Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I want to use some thing unique for a licensing system. i decided to use ProcessorID from Win32\_Processor Management class.
I tried on two different systems with same processor type..
It shows me same processorID for both system. i am using this code
```
public static String GetCPUId()
{
String processorID = "";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(
"Select * FROM WIN32_Processor");
ManagementObjectCollection mObject = searcher.Get();
foreach (ManagementObject obj in mObject)
{
processorID = obj["ProcessorId"].ToString();
}
return processorID;
}
``` | No, it can't be guaranteed that it will be unique, as the processor might not even support the CPUID instruction, in which case, the call can't be guaranteed to succeed.
Also, you are neglecting that a machine might have multiple processors in it, so getting the id of a single processor doesn't help.
---
As others have indicated, if you want to get a unique id for the system, your best bet is to create an id which is an amalgam of various component ids on the system.
A hash (and not just any, but one that has *very* few collisions) of various values of the hardware *could* suffice. You'd probably want to use things that are fairly embedded in the system, such as the processor, motherboard info, but not things easily detached/changed, such as USB drives/hubs/etc. | Most licensing systems rely on multiple hardware components to create a fingerprint. No single component is used as the only unique key. So you might take the following into consideration:
* MAC Addresses of all network adapters (Can get tricky if they have a docking station or enable/disable their wireless on a laptop)
* CPUID
* Motherboard component part numbers (like the IDE or SCSI controllers)
* Serial number of system drive (NOT Volume ID which is easy to change)
* etc.
When combined as a whole you'll get a unique representation of the machine. The danger of course comes when the user changes something on their machine. Do they lose their license? Do they have to contact you?
Also note that WMI classes often require admin rights to read the kind of information that you're looking for which would be a real hassle for Vista & Windows 7 users.
Doing hardware locking is very difficult to get right. So I'd recommend either 1. don't do it or 2. purchase a commercial library that already does this. | WIN32_Processor::Is ProcessorId Unique for all computers | [
"",
"c#",
"winapi",
"wmi",
""
] |
I have a RichTextBox which contains links posted by the users.
The problem is that my RTB makes the color of the links black, and the background color is also black. This leads to the links being invisible.
How do I change the color of the links in the RTB? | Phoexo:
Have a look at the following CodeProject article. This fellow provides a way to create arbitrary links in the text that work, *while the DetectUrls property is set to false*. With a small amount of hacking, you should have full control of the formatting of your links.
Links with arbitrary text in a RichTextBox
<http://www.codeproject.com/KB/edit/RichTextBoxLinks.aspx?display=Print> | ```
string str = richTextBox1.Text;
Regex re = new Regex("^((ht|f)tp(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?", RegexOptions.None);
MatchCollection mc = re.Matches(str);
foreach (Match ma in mc)
{
richTextBox1.Select(ma.Index, ma.Length);
richTextBox1.SelectionColor = Color.Red;
}
```
<http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/1f757f8c-427e-4042-8976-9ac4fd9caa22> | Change link color in RichTextBox | [
"",
"c#",
"winforms",
"colors",
"hyperlink",
"richtextbox",
""
] |
cgi.escape seems like one possible choice. Does it work well? Is there something that is considered better? | [`html.escape`](http://docs.python.org/3/library/html.html#html.escape) is the correct answer now, it used to be [`cgi.escape`](http://docs.python.org/library/cgi.html#cgi.escape) in python before 3.2. It escapes:
* `<` to `<`
* `>` to `>`
* `&` to `&`
That is enough for all HTML.
EDIT: If you have non-ascii chars you also want to escape, for inclusion in another encoded document that uses a different encoding, like *Craig* says, just use:
```
data.encode('ascii', 'xmlcharrefreplace')
```
Don't forget to decode `data` to `unicode` first, using whatever encoding it was encoded.
However in my experience that kind of encoding is useless if you just work with `unicode` all the time from start. Just encode at the end to the encoding specified in the document header (`utf-8` for maximum compatibility).
Example:
```
>>> cgi.escape(u'<a>bá</a>').encode('ascii', 'xmlcharrefreplace')
'<a>bá</a>
```
Also worth of note (thanks Greg) is the extra *`quote`* parameter `cgi.escape` takes. With it set to `True`, `cgi.escape` also escapes double quote chars (`"`) so you can use the resulting value in a XML/HTML attribute.
EDIT: Note that cgi.escape has been deprecated in Python 3.2 in favor of [`html.escape`](http://docs.python.org/3/library/html.html#html.escape), which does the same except that *`quote`* defaults to True. | In Python 3.2 a new [`html`](https://docs.python.org/3/library/html.html) module was introduced, which is used for escaping reserved characters from HTML markup.
It has one function `escape()`:
```
>>> import html
>>> html.escape('x > 2 && x < 7 single quote: \' double quote: "')
'x > 2 && x < 7 single quote: ' double quote: "'
``` | What's the easiest way to escape HTML in Python? | [
"",
"python",
"html",
""
] |
Basically, I want to have my program retrieve various variables from the hard drive disk for use in the program. I guess, before asking for details, I should verify that is even possible. Is it?
If it is, what is the best way? I've seen the use of .ini files, but I don't know how to retrieve data specifically from .ini files. Is it the same as a text file that you have messed with to make sure variables will always be on x line? For instance:
```
ifstream variables("variables.ini");
//some code later
//assume line 'x' holds a variable
if(variables.good())
{
variables.get(x);
}
//or whatever =/
```
I'm kind of at a loss for what to do here.
Edit: my language of choice is C++. | The first questions you need to address are the who and the why. Your options on the *how* will follow from those.
So who (or what) will be accessing the data? If it is just the program itself then you can store the data however you want - binary file, xml, database, ini file, whatever. However if the data needs to be easily accessible to the user so they can change it prior to a run then a text file like an ini, which can be easily edited, makes sense. In order to edit the data stored in other formats you may have to write an entirely separate program just to manipulate the stored parameters. Maybe that makes sense in your situation or maybe not but it will be more work.
If you choose to go the ini route then you are on the right track. They are just text files. A common format is to have sections (usually in brackets), and then key/value pairs within the sections. Usually comment lines start with semicolon, a nice touch for the users who may want to flip back and forth between settings.
So something like this:
```
[System]
datapath = /home/me/data
[Application]
start_count = 12
; start_count = 20 //this is a comment
```
You don't have to worry about specific lines for your data. You just read through the file line by line. Empty or comment lines get tossed. You take note of what section you are in and you process the key/value pairs.
There are many ways to store the parsed file in your program. A simple one may be to concatenate the section name and key into a key for a map. The value (of the key/value pair) would be the data for the map.
So "Systemdatapath" could be one map key and its value would be "/home/me/data". When your program needs to use the values it just looks it up by key.
That's the basics. Ultimately you will want to embellish it. For instance, methods to retrieve values by type. E.g. getString(), getInteger(), getFloat(), etc. | You decide the format of the .ini file of your application. I usually work with XML because then you can organize your information by scope and there is already a bunch of libs to handle storing and retrieving information from XML trees.
Edit: for C++ - <http://xerces.apache.org/xerces-c/> | How do you farm out variables to persistent data? | [
"",
"c++",
"ini",
"persistent-data",
""
] |
For Javascript some testing-frameworks exist, like JSUnit or js-test-driver. They are fine, but they run the tests in a browser. That's fine, especially to verify your webapp is running in different browsers. But on out continuous-integration-server no window-system (and no browser) is installed. So is there a way to run the tests without the usage of a browser? The best would be to use one of the existing frameworks, so that developers can locally run the tests in their browsers and the continuous-integration-system runs them browserless. | You may be interested in [HtmlUnit](http://htmlunit.sourceforge.net/) which is used by several UI-testing framework like [WebDriver](http://code.google.com/p/webdriver/) | [jsTest](http://thinkpond.org/articles/2008/jstest-intro.shtml) can be run command line or as an eclipse plugin.
However, be careful, you will not get 100% code coverage using a tool like this if you need to support multiple browsers. Each browser implements JavaScript differently (i.e.: IE). Therefore, the only way to fully test your JavaScript is to run the tests in all browsers that you support. | Which testing-framework for Javascript supports Testing without a browser? | [
"",
"javascript",
"unit-testing",
"testing",
"continuous-integration",
""
] |
I have a program in C++, using the standard socket API, running on Ubuntu 7.04, that holds open a socket to a server. My system lives behind a router. I want to figure out how long it could take to get a socket error once my program starts sending AFTER the router is cut off from the net.
That is, my program may go idle (waiting for the user). The router is disconnected from the internet, and then my program tries to communicate over that socket.
Obviously it's not going to know quickly, because TCP is quite adept at keeping a socket alive under adverse network conditions. This causes TCP to retry a lot of times, a lot of ways, before it finally gives up.
I need to establish some kind of 'worst case' time that I can give to the QA group (and the customer), so that they can test that my code goes into a proper offline state.
(for reference, my program is part of a pay at pump system for gas stations, and the server is the system that authorizes payment transactions. It's entirely possible for the station to be cut off from the net for a variety of reasons, and the customer just wants to know what to expect).
EDIT: I wasn't clear. There's no human being waiting on this thing, this is just for a back office notation of system offline. When the auth doesn't come back in 30 seconds, the transaction is over and the people are going off to do other things.
EDIT: I've come to the conclusion that the question isn't really answerable in the general case. The number of factors involved in determining how long a TCP connection takes to error out due to a downstream failure is too dependent on the exact equipment and failure for there to be a simple answer. | You should be able to use:
<http://linux.die.net/man/2/getsockopt>
with:
SO\_RCVTIMEO and SO\_SNDTIMEO
to determine the timeouts involved.
This link: <http://linux.die.net/man/7/socket>
talks about more options that may be of interest to you.
In my experience, just picking a time is usually a bad idea. Even when it sounds reasonable, arbitrary timeouts usually misbehave in practice. The general result is that the application becomes unusable when the environment falls outside of the norm.
Especially for financial transactions, this should be avoided. Perhaps providing a cancel button and some indication that the transaction is taking longer than expected would be a better solution. | I would twist the question around the other way: how long is a till operator prepared to stand there looking stupid in front of the customer before they say, of it must not be working lets to this the manual way.
So pick some time like 1 minute (assuming your network is not auto disconnect, and thus will reconnect when traffic occurs)
Then use that time for how long your program waits before giving up. Closing the socket etc. Displays error message. Maybe even a count down timer while waiting, so the till operator has an idea how much long the system is going to wait...
Then they know the transaction failed, and that it's manual time.
Otherwise depending on you IP stack, the worse case time-out could be 'never times-out'. | How do I determine a maximum time needed for TCP socket to die due to intermediate network disconnect? | [
"",
"c++",
"tcp",
""
] |
Looking for something like:
```
$("input:radio:checked").previous("name", "original_name").attr("name","new_name");
```
I tried a few different seen around here but mostly get the error: Object Expected
Any help is appreciated. | As Ben S wrote in the comment to your original question, why do you need to change the name?
Let's say you have
```
<input type="radio" name="myRadio" id="radioChoice1" value="radioChoice1Value" />
<input type="radio" name="myRadio" id="radioChoice2" value="radioChoice2Value" />
```
If user selects 'radioChoice1' and clicks submit, browser will send
**myRadio=radioChoice1Value** to your CGI script. You can process this as you desire.
In case you insist on changing the name attribute, I am not sure what is the 'previous' method in your code.
Can you try,
```
$("input:radio:checked").attr("name","new_name");
```
And see if it works?
I can imagine that there could be cross browser problems if you try to change the name attribute.
You can create a hidden input and store the name of the radio button selected by the user.
```
<input type="hidden" id="selectedRadioButton" />
$('#selectedRadioButton').val($("input:radio:checked").attr('name'));
```
**EDIT:**
Please post your HTML so that I can tell you what kind of values will be posted to CGI.
For example if you have
```
<input type="radio" name="transactionType" id="buy" value="buy" />
<input type="radio" name="transactionType" id="sell" value="sell" />
```
If user clicks on the first radio button 'buy', then in your CGI script value for 'transactionType' will be 'buy'. | Here's a jQuery script that does the job requested. I'm using it to rename all the input=text fields on a form. Though I'm not doing anything with radio or checkbox, I added the relevant case statements. Insert your radio/checkbox transforms as needed.
```
function renameTextInputFields(ele) {
var i = 0;
$(ele).find(':input').each(function() {
switch(this.type) {
case 'text':
$(this).attr("name","textFieldNumber"+(++i));
break;
case 'checkbox':
case 'radio':
});
}
```
Call this method on a DOM element. Myself, I'm making a clone of a div within a form. The div has lots of text fields. I get the base element like so.
```
var clone = $('.classAssignedToMyDiv').clone();
```
It runs fine in both IE 8.x and Firefox 3.x | jQuery, dynamic name change of radio button | [
"",
"javascript",
"jquery",
"html",
"dom",
"radio-button",
""
] |
Are there any libraries for connecting as a client via Remote Desktop Protocol (RDP) in Linux? The language used is secondary to the issue of existence. Any mainstream language would do (e.g. C++, Perl, Java, Ruby, PHP, Python), and even less popular ones like OCaml or Scheme.
Is there any option available other than taking the rdesktop source and hacking a library out of that? | There is a set of cross-platform open source RDP libraries available in FreeRDP project. They are written in C and under Apache Licence 2.0. See <http://www.freerdp.com> | Typing rdp into my Mandriva Software Managment tool revealed libxrdp which is a library that xrdp depends on but I don't know the details so it may not be what you want.
The project website is [xrdp.sourceforge.net](http://xrdp.sourceforge.net). | Does an RDP client library under Linux exist? | [
"",
"c++",
"linux",
"remote-desktop",
"rdp",
""
] |
I have a small Python program, which uses a Google Maps API secret key. I'm getting ready to check-in my code, and I don't want to include the secret key in SVN.
In the canonical PHP app you put secret keys, database passwords, and other app specific config in LocalSettings.php. Is there a similar file/location which Python programmers expect to find and modify? | No, there's no standard location - on Windows, it's usually in the directory `os.path.join(os.environ['APPDATA'], 'appname')` and on Unix it's usually `os.path.join(os.environ['HOME'], '.appname')`. | A user must configure their own secret key. A configuration file is the perfect place to keep this information.
You several choices for configuration files.
1. Use [`ConfigParser`](http://docs.python.org/library/configparser.html) to parse a config file.
2. Use a simple Python module as the configuration file. You can simply [`execfile`](http://docs.python.org/library/functions.html#execfile) to load values from that file.
3. Invent your own configuration file notation and parse that. | Where to store secret keys and password in Python | [
"",
"python",
"configuration",
"google-maps",
""
] |
I'm trying to use JMX API to get active session counts for a web application.
1. Is it possible to use JMX API to get this kind of information?
2. If yes, how reliable would it be?
3. Any example code on how to get this done?
I've been reading JMX tutorial and documentation, but they are giving me the overview of what the technology is. I just can't pinpoint to what I need, yet. | You can accomplish this by using something like JConsole or JVisualVM once you configure your app server to expose a JMX port. You don't mention which app server you're using but for Tomcat, it's described here: <http://tomcat.apache.org/tomcat-5.5-doc/monitoring.html>. Once you connect with JConsole, Tomcat exposes an MBean which has session information but again it depends which container you use. | ```
ObjectName name = new ObjectName("Catalina:type=Manager,path=/NAME_OF_APP,host=localhost");
ManagementFactory.getPlatformMBeanServer().getAttribute(name, "activeSessions");
``` | Getting Active Session counts with JMX (Java Management Extensions) API | [
"",
"java",
"web-applications",
"jboss",
"jmx",
""
] |
For a project I am working on, I have been asked to create an audit trail of all changes that have been made to records. This is the first time I have had to create an audit trail, so I have been doing a lot of research on the subject.
The application will be developed in PHP/MSSQL, and will be low-traffic.
From my reading, I have pretty much decided to have an audit table and use triggers to record the changes in the table.
The two requirements for display in the application are as follows:
1. Be able to see a log of all changes made to a field (I pretty much know how to do this)
2. Be able to see, when viewing a record in the application, an indicator next to any field in the record that has ever been changed (and possibly other info like the date of the last change).
Item #2 is the one that is currently giving me grief. Without doing a separate query for each field (or a very long nested query that will take ages to execute), does anyone have suggestions for an optimal way to do this? (I have thought of adding an extra "ModifiedFlag" field for each field in the table, that will act as boolean indicator if the field has ever been edited, but that seems like a lot of overhead. | I would treat the audit information separately from the actual domain information as much as possible.
**Requirement #1:**
I think you will create additional audit tables to record the changes.
Eric suggestion is a good one, creating the audit information using triggers in the SQL database. This way your application needs not be aware of the audit logic.
If your database does not support triggers, then perhaps you are using some kind of persistence or database layer. This would also be a good place to put this kind of logic, as again you minimize any dependencies between *normal* application code and the audit code.
**Requirement #2:**
As for showing the indicators: I would not create boolean fields in the table that stores the actual. (This would cause all sorts of dependencies to exist between your *normal* application code and your *audit trail* code.)
I would try to let the code responsible for displaying the form also be responsible for showing audit data on field level. This will cause query overhead, but that is the cost for displaying this extra layer of information. Perhaps you can minimize the database overhead by adding metadata to the audit information that allows for easy retrieval.
Some big Enterprisy application that I maintain uses roughly the following structure:
* A change header table corresponding to a change of a record in a table.
Fields:
```
changeId, changeTable, changedPrimaryKey, userName, dateTime
```
- A change field table corresponding to a field that is changed.
Fields:
```
changeId, changeField, oldValue, NewValue
```
**Sample content:**
Change Header:
```
'1', 'BooksTable', '1852860138', 'AdamsD', '2009-07-01 15:30'
```
Change Item:
```
'1', 'Title', 'The Hitchhiker's Guide to the Gaxaly', 'The Hitchhiker's Guide to the Galaxy'
'1', 'Author', 'Duglas Adasm', 'Douglas Adams'
```
This structure allows both easy viewing of audit trails as well as easy retrieval for showing the desired indicators. One query (inner join in the Header and Items table) would be enough to retrieve all information to show in a single form. (Or even a table when you have a list of shown Id's) | As a general requirement flagging changed field "smells" slightly odd. If records are long lived and subject to change over time then eventually all fields will tend to get so flagged. Hence I wonder how any user could make sense of a simple set of indicators per field.
That line of thinking makes me suspect that the data you store needs to be, as you've described, a true audit trail with all the changes recorded, and the first real challenge is to decide how the info should be presented to the user.
I think your idea of preparing some kind of aggregateOfTheAuditTrail data is likely to be very useful. The question would be is a single flag per record enough? If the User's primary access is through list then maybe it's enough just to highlight the changed records for later drill down. Or a date of last change of the record value, so that only recently changed records are highlighted - all back to what the user's real needs are. I find it hard to imagine that records changed 3 years ago are as intersting as those changed last week.
Then when we come to the drill down to a single record. Again a simple flag per field doesn't sound useful (though your domain, your requirements). If it is, then your summary idea is fine. My guess is that a sequence of changes to a field, and the sequence of overall changes to the record, are much more interesting. Employee had pay rise, employee moved department, employee was promoted = three separate business events or one?
If anything more than a simple flag is needed then I suspect that you just need to return the whole (or recent) audit trail for the record and let the UI figure out how to present that.
So, my initial thought: Some kind of rolling-maintenance of a summary record sounds like a good idea. If necessary maintained in background threads or batch jobs. We deisgn that to be business-useful without going to the full audit trail each time. Then for detailed analyses we allow some or all of the trail to be retrieved. | How would I use an audit trail to display which fields have ever been edited? | [
"",
"php",
"sql-server",
"audit-trail",
""
] |
I've been writing some jQuery functions that have JavaScript variables and looping, etc inside them - they're becoming long and hard to read. If I want to break them up, how would I do that?
```
$(".x").click(function ()
{
var i=0;
for (i=0;i<50;i++)
{
if ($("#x"+i).is(':hidden'))
{
$("#x"+i).show();
}
else
{
$("#x"+i).hide();
}
}
});
```
For example, in the code above, if I want to move the contents of the loop to a separate function and then call that function from inside the loop, what would that need to look like? | There is no such thing as "jQuery functions", the jQuery code just usually uses an anonymous JavaScript function.
To move the contents of the loop into a named function would look like this:
```
$(".x").click( function() {
for (var i=0; i<50; i++) toggleItem(i)
});
function toggleItem(i) {
if ($("#x"+i).is(':hidden')) {
$("#x"+i).show();
} else {
$("#x"+i).hide();
}
}
```
However, you could use the cascading properties of CSS to toggle all the items with a simple JavaScript statement instead of looping through all the elements. Example:
CSS:
```
<style type="text/css">
.StateOne .InitiallyHidden { display: none; }
.StateTwo .InitiallyVisible { display: none; }
</style>
```
HTML:
```
<div class="StateOne" id="StateContainer">
<div class="InitiallyVisible">Visible first</div>
<div class="InitiallyHidden">Visible second</div>
<div class="InitiallyVisible">Visible first</div>
<div class="InitiallyHidden">Visible second</div>
<div class="InitiallyVisible">Visible first</div>
<div class="InitiallyHidden">Visible second</div>
<div class="InitiallyVisible">Visible first</div>
<div class="InitiallyHidden">Visible second</div>
</div>
```
JavaScript:
```
$('.x').click(function() {
var s = document.getElementById('StateContainer');
s.className = (s.className == 'StateOne' ? 'StateTwo' : 'StateOne');
});
``` | jQuery is JavaScript, so you can pass functions around just like you would normally do.
```
// First refactor - separate the function out
$(".x").click(myfunc);
function myfunc() {
{
var i=0;
for (i=0;i<50;i++)
{
if ($("#x"+i).is(':hidden'))
{
$("#x"+i).show();
}
else
{
$("#x"+i).hide();
}
}
}
```
Although looking at your code it is screaming for all x1 to x50 elements to have the same class applied to it. like so...
```
<div id='x1' class='xClass'></div>
<div id='x2' class='xClass'></div>
<div id='x3' class='xClass'></div>
.....
<div id='x50' class='xClass'></div>
```
Then you could do something like
```
var currentHidden = $('.xClass:hidden')
var currentVisible = $('.xClass:visible')
currentHidden.show();
currentVisible.show();
```
And yes, toggle is even better:
```
$('.xClass').toggle();
```
Then you don't have to loop, which is one of the beauties of using jQuery! =) | To break up your jQuery code into functions, do you do it the same way as in JavaScript? | [
"",
"javascript",
"jquery",
"function",
""
] |
I can't get my progress bar to work. Any help is much appreciated!
Here's the code:
```
<Window x:Class="BulkSAConfigureControl.BulkSaProgressBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Please Wait.." Height="60" Width="300" WindowStyle="ToolWindow" ResizeMode="NoResize" WindowStartupLocation="CenterScreen">
<ProgressBar Name="progressBar" IsIndeterminate="True">
<ProgressBar.Resources>
<ResourceDictionary Source="/PresentationFramework.Aero;v3.0.0.0;31bf3856ad364e35;component/themes/aero.normalcolor.xaml" />
</ProgressBar.Resources>
</ProgressBar>
```
.
```
public class ProgressBarClass : Window
{
public ProgressBarClass()
{
InitializeComponent();
}
public void StartProgressBar()
{
Duration d = new Duration(TimeSpan.FromSeconds(5));
DoubleAnimation anim = new DoubleAnimation(100.0, d);
progressBar.BeginAnimation(ProgressBar.ValueProperty, anim);
this.Show();
}
public void StopProgressBar()
{
this.Close();
}
}
```
.
```
public class DoSomething : UserControl
{
public void DoSomeStuff()
{
ProgressBarClass pBar = new ProgressBarClass();
pBar.StartProgressBar();
// Do some stuff here
pBar.StopProgressBar();
}
}
``` | To add what Mark says, there are two ways to fix the problem. The hack way and the proper way.
The proper way is to use threading, such as a BackgroundWorker. You will likely end up using control.BeginInvoke to handle updating the GUI thread.
The hack way is to call Application.DoEvents in your loop. I call this the hack because it only partially works. For example, if you're doing a tight loop that has lots of little quick instructions then it will work fine'ish. If you're doing a loop in which your instructions take a while, this will not work (such as making a huge sql query to a database).
[Here](http://msdn.microsoft.com/en-us/magazine/cc300429.aspx#S3 "Here") is a good link to learn about this particular example. I think WPF handles things only slightly different than regular WinForms. | This answer isn't specific to C# or WPF, but with Windows in general. A progress bar will only update if you are processing Windows messages. If you're running a tight CPU loop with no UI interaction, the progress bar never gets a chance to repaint. | Why won't my progress bar work? | [
"",
"c#",
"wpf",
"progress-bar",
""
] |
We have a large internal data collection website. I don't have time to create form based data collection pages for every department. I was thinking that there might be some kind of WYSIWYG forms creation module that could be run on top of our website. System would be like a cms, but one that allows custom pages to be created. All the form page setup is run from the database. So when a department head needs to implement a forms data collection page they can go in and create a page, and drag and drop all the form fields and position the elements. Then all form submission data is saved to one primary set of tables that I can query and generate custom reports on the data or utilize for custom page processing.
System should allow:
Choose the names of fields on the form
Choose the field type: textbox, checkbox, radio buttons, dropdown
Choose the validation: required, max length, data type, as well as the error message shown when validation fails
Choose the order in which the fields are displayed
To be able to add conditional logic to the fields (i.e. if this is yes, then that is required or hide that field)
Choose to capture data into a database when the form is submitted
To retrieve the data stored in the database so it can be transformed into something meaningful
To be able to create forms by copying other forms and editing them
To be able to reuse the forms in many pages
To be able to add pagination to the forms (so the form isn't soooo long)
To be able to display a customized message when the form is submitted. | Check the BizForms functionality in [Kentico](http://www.kentico.com). I have used Kentico for a bit, just getting into the forms part, but seems like it will meet most, maybe even all of your requirements. | [Kentico CMS](http://kenticocms.com/free-cms-asp-net.aspx) might be what you're looking for. Alternatively, you might want to look into [DotNetNuke](http://www.dotnetnuke.com/). | Anyone know of an Asp.Net C# CMS type system with a Forms Module | [
"",
"c#",
"asp.net",
"content-management-system",
"content-management",
""
] |
I am doing an archive service for logs. Since some files are open and in use I can't archive them until they are not in use anymore. The only way I can figure out how to see if the file is open by another process is the code below.
I ***hate*** the code there must be a better way. Is there a better way?
```
try
{
using (FileStream stream = File.Open("SomeFile.txt", FileMode.Open, FileAccess.ReadWrite))
{
// Do nothing just seeing if I could open it.
return true;
}
}
catch (IOException)
{
// Exception so File is in use and can't open
return false;
}
```
**EDIT:** Please note, that I do not want to catch the exception. I would rather avoid the exception entirely. I would rather have some magic function for example IsFileInUser(string fileName) that would return a boolean WITHOUT catching exceptions underneath.
A way I have see is using [OpenFile of PInvoke](http://www.pinvoke.net/default.aspx/kernel32.OpenFile). | Here is what I came up with.
First here is the bad way of doing it by exception.
```
public static bool IsFileInUseBadMethod(string filePath)
{
if (!File.Exists(filePath))
{
return false;
}
try
{
using (StreamReader reader = new StreamReader(File.Open(filePath, FileMode.Open, FileAccess.ReadWrite)))
{
return false;
}
}
catch (IOException)
{
return true;
}
}
```
On my machine this method took about 10 million ticks when the file was in use.
The other way is using the kernel32.dll
```
// Need to declare the function from the kernel32
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern Microsoft.Win32.SafeHandles.SafeFileHandle CreateFile(string lpFileName, System.UInt32 dwDesiredAccess, System.UInt32 dwShareMode, IntPtr pSecurityAttributes, System.UInt32 dwCreationDisposition, System.UInt32 dwFlagsAndAttributes, IntPtr hTemplateFile);
private static readonly uint GENERIC_WRITE = 0x40000000;
private static readonly uint OPEN_EXISTING = 3;
```
Here is the function
```
public static bool IsFileInUse(string filePath)
{
if (!File.Exists(filePath))
{
return false;
}
SafeHandle handleValue = null;
try
{
handleValue = FileHelper.CreateFile(filePath, FileHelper.GENERIC_WRITE, 0, IntPtr.Zero, FileHelper.OPEN_EXISTING, 0, IntPtr.Zero);
bool inUse = handleValue.IsInvalid;
return inUse;
}
finally
{
if (handleValue != null)
{
handleValue.Close();
handleValue.Dispose();
handleValue = null;
}
}
}
```
This ran in about 1.8 million ticks. *Over an 8 million ticks difference* from the exception method.
However when file it not in use meaning no exception is thrown the speed of the "BAD" method is 1.3 million and the kernel32.dll is 2 million. About an 800k ticks better. So using the Exception method would be better if I knew the file would be not be in use about 1/10th of the time. However the one time it is, it is an extremely expensive ticks operation compared to the kernel32.dll. | The only thing I would improve on in your code example is catching the few specific exceptions that would be thrown by File.Open. You'll need to catch IOException and UnauthorizedAccessException at a minimum.
By putting in `catch`, you catch *any* exception that might be thrown, which is bad practice. | Is there a better way to determine if a file is open by another application in .NET? | [
"",
"c#",
".net",
"file-io",
""
] |
I hear a lot about [Spring](https://spring.io/), people are saying all over the web that Spring is a good framework for web development. What exactly is Spring Framework for in a nutshell? Why should I used it over just plain Java. | Basically Spring is a framework for [dependency-injection](/questions/tagged/dependency-injection "show questions tagged 'dependency-injection'") which is a pattern that allows building very decoupled systems.
## The problem
For example, suppose you need to list the users of the system and thus declare an interface called `UserLister`:
```
public interface UserLister {
List<User> getUsers();
}
```
And maybe an implementation accessing a database to get all the users:
```
public class UserListerDB implements UserLister {
public List<User> getUsers() {
// DB access code here
}
}
```
In your view you'll need to access an instance (just an example, remember):
```
public class SomeView {
private UserLister userLister;
public void render() {
List<User> users = userLister.getUsers();
view.render(users);
}
}
```
Note that the code above hasn't initialized the variable `userLister`. What should we do? If I explicitly instantiate the object like this:
```
UserLister userLister = new UserListerDB();
```
...I'd couple the view with my implementation of the class that access the DB. What if I want to switch from the DB implementation to another that gets the user list from a comma-separated file (remember, it's an example)? In that case, I would go to my code again and change the above line to:
```
UserLister userLister = new UserListerCommaSeparatedFile();
```
This has no problem with a small program like this but... What happens in a program that has hundreds of views and a similar number of business classes? The maintenance becomes a nightmare!
## Spring (Dependency Injection) approach
What Spring does is to *wire* the classes up by using an XML file or annotations, this way all the objects are instantiated and initialized by Spring and *injected* in the right places (Servlets, Web Frameworks, Business classes, DAOs, etc, etc, etc...).
Going back to the example in Spring we just need to have a setter for the `userLister` field and have either an XML file like this:
```
<bean id="userLister" class="UserListerDB" />
<bean class="SomeView">
<property name="userLister" ref="userLister" />
</bean>
```
or more simply annotate the filed in our view class with `@Inject`:
```
@Inject
private UserLister userLister;
```
This way when the view is created it *magically* will have a `UserLister` ready to work.
```
List<User> users = userLister.getUsers(); // This will actually work
// without adding any line of code
```
It is great! Isn't it?
* *What if you want to use another implementation of your `UserLister` interface?* Just change the XML.
* *What if don't have a `UserLister` implementation ready?* Program a temporal mock implementation of `UserLister` and ease the development of the view.
* *What if I don't want to use Spring anymore?* Just don't use it! Your application isn't coupled to it. [Inversion of Control](http://en.wikipedia.org/wiki/Inversion_of_control) states: "The application controls the framework, not the framework controls the application".
There are some other options for Dependency Injection around there, what in my opinion has made Spring so famous besides its simplicity, elegance and stability is that the guys of SpringSource have programmed many many POJOs that help to integrate Spring with many other common frameworks without being intrusive in your application. Also, Spring has several good subprojects like Spring MVC, Spring WebFlow, Spring Security and again a loooong list of etceteras.
Anyway, I encourage you to read [Martin Fowler's article](http://martinfowler.com/articles/injection.html) about Dependency Injection and Inversion of Control because he does it better than me. ~~After understanding the basics take a look at [Spring Documentation](http://static.springframework.org/spring/docs/2.5.x/reference/index.html)~~, in my opinion, it ~~is~~ **used to be** the best Spring book ever. | Spring *contains* (*as Skaffman rightly pointed out*) a MVC framework. To explain in short here are my inputs.
Spring supports segregation of service layer, web layer and business layer, but what it really does best is "injection" of objects. So to explain that with an example consider the example below:
```
public interface FourWheel
{
public void drive();
}
public class Sedan implements FourWheel
{
public void drive()
{
//drive gracefully
}
}
public class SUV implements FourWheel
{
public void drive()
{
//Rule the rough terrain
}
}
```
Now in your code you have a class called RoadTrip as follows
```
public class RoadTrip
{
private FourWheel myCarForTrip;
}
```
Now whenever you want a instance of Trip; sometimes you may want a SUV to initialize FourWheel or sometimes you may want Sedan. It really depends what you want based on specific situation.
To solve this problem you'd want to have a Factory Pattern as creational pattern. Where a factory returns the right instance. So eventually you'll end up with lots of glue code just to instantiate objects correctly. Spring does the job of glue code best without that glue code. You declare mappings in XML and it initialized the objects automatically. It also does lot using singleton architecture for instances and that helps in optimized memory usage.
This is also called Inversion Of Control. Other frameworks to do this are Google guice, Pico container etc.
Apart from this, Spring has validation framework, extensive support for DAO layer in collaboration with JDBC, iBatis and Hibernate (and many more). Provides excellent Transactional control over database transactions.
There is lot more to Spring that can be read up in good books like "Pro Spring".
Following URLs may be of help too.
<http://static.springframework.org/docs/Spring-MVC-step-by-step/>
<http://en.wikipedia.org/wiki/Spring_Framework>
<http://www.theserverside.com/tt/articles/article.tss?l=SpringFramework> | What exactly is Spring Framework for? | [
"",
"java",
"spring",
"frameworks",
""
] |
How do I programmatically save an image from a URL? I am using C# and need to be able grab images from a URL and store them locally. ...and no, I am not stealing :) | It would be easier to write something like this:
```
WebClient webClient = new WebClient();
webClient.DownloadFile(remoteFileUrl, localFileName);
``` | You just need to make a basic http request using **HttpWebRequest** for the URI of the image then grab the resulting byte stream then save that stream to a file.
Here is an example on how to do this...
'As a side note if the image is very large you may want to break up **br.ReadBytes(500000)** into a loop and grab n bytes at a time writing each batch of bytes as you retrieve them.'
```
using System;
using System.IO;
using System.Net;
using System.Text;
namespace ImageDownloader
{
class Program
{
static void Main(string[] args)
{
string imageUrl = @"http://www.somedomain.com/image.jpg";
string saveLocation = @"C:\someImage.jpg";
byte[] imageBytes;
HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
WebResponse imageResponse = imageRequest.GetResponse();
Stream responseStream = imageResponse.GetResponseStream();
using (BinaryReader br = new BinaryReader(responseStream ))
{
imageBytes = br.ReadBytes(500000);
br.Close();
}
responseStream.Close();
imageResponse.Close();
FileStream fs = new FileStream(saveLocation, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
try
{
bw.Write(imageBytes);
}
finally
{
fs.Close();
bw.Close();
}
}
}
}
``` | How do I programmatically save an image from a URL? | [
"",
"c#",
".net",
"image",
""
] |
I was trying to figure out what happens when a derived class declares a virtual function as private. The following is the program that I wrote
```
#include <iostream>
using namespace std;
class A
{
public:
virtual void func() {
cout<<"A::func called"<<endl;
}
private:
};
class B:public A
{
public:
B()
{
cout<<"B constructor called"<<endl;
}
private:
void func() {
cout<<"B::func called"<<endl;
}
};
int main()
{
A *a = new B();
a->func();
return 0;
}
```
Surprisingly (for me) the output was:
```
B constructor called
B::func called
```
Isn't this violating the private access set for that function. Is this the expected behavior? Is this is a standard workaround or loophole? Are access levels bypassed when resolving function calls through the VTABLE?
Any insight in to this behavior would be greatly helpful.
Further it was mentioned that a privately overriding a virtual member would prevent further classes from inheriting it. Even this is having problems. Modifying the above program to include:
```
class C: public B
{
public:
void func() {
cout<<"C::func called"<<endl;
}
};
```
and the main test program to:
```
int main()
{
A *a = new C();
a->func();
return 0;
}
```
output is:
```
C::func called
``` | The behavior is correct. Whenever you declare your function as "virtual", you instruct the compiler to generate a virtual call, instead of the direct call to this function. Whenever you override the virtual function in the descendant class, you specify the behavior of this function (you do not change the access mode for those clients, who rely on the "parent's" interface).
Changing the access mode for the virtual function in the descendant class means that you want to hide it from those clients, who use the descendant class directly (who rely on the "child's" interface).
Consider the example:
```
void process(const A* object) {
object->func();
}
```
"process" function relies on the parent's interface. It is expected to work for any class, public-derived from A. You cannot public-derive B from A (saying "every B is A"), but hide a part of its interface. Those, who expect "A" must receive a fully functional "A". | This is well-defined behavior. If `a` were a `B*` this wouldn't compile. The reason is that member access is resolved statically by the compiler, not dynamically at run-time. Many C++ books suggest that you avoid coding like this because it confuses less experienced coders. | Public virtual function derived private in C++ | [
"",
"c++",
"inheritance",
"virtual-functions",
""
] |
I have a C# Windows application that I want to ensure will show up on a second monitor if the user moves it to one. I need to save the main form's size, location and window state - which I've already handled - but I also need to know which screen it was on when the user closed the application.
I'm using the Screen class to determine the size of the current screen but I can't find anything on how to determine which screen the application was running on.
Edit: Thanks for the responses, everyone! I wanted to determine which monitor the window was on so I could do proper bounds checking in case the user accidentally put the window outside the viewing area or changed the screen size such that the form wouldn't be completely visible anymore. | You can get an array of Screens that you have using this code.
```
Screen[] screens = Screen.AllScreens;
```
You can also figure out which screen you are on, by running this code (**this** is the windows form you are on)
```
Screen screen = Screen.FromControl(this); //this is the Form class
```
in short check out the Screen class and static helper methods, they might help you.
[MSDN Link](http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.aspx), doesn't have much..I suggest messing around in the code by yourself. | If you remember the window's location and size, that will be enough. When you set the position to the previously used position, if it happened to be on the second monitor it will go back there.
For example, if you have 2 monitors, both sized 1280x1024 and you set your window's left position to be 2000px, it will appear on the second monitor (assuming the second monitor is to the right of the first.) :)
If you are worried about the second monitor not being there when the application is started the next time, you can use this method to determine if your window intersects any of the screens:
```
private bool isWindowVisible(Rectangle rect)
{
foreach (Screen screen in Screen.AllScreens)
{
if (screen.Bounds.IntersectsWith(rect))
return true;
}
return false;
}
```
Just pass in your window's desired location and it will tell you if it will be visible on one of the screens. Enjoy! | How do I determine which monitor my .NET Windows Forms program is running on? | [
"",
"c#",
".net",
"windows",
"winforms",
"screen",
""
] |
I'm developing a sim game based on Theme Hospital, which is quite an old game.
I've made lots of progress on the underlying workings, however now I am coming to the GUI elements, which I haven't done alot of before. I am still rather new to java.
The effect I am trying to create is like shown here...
<http://www.tubechop.com/watch/18438>
Click on a button, opens up a panel with tabs to select from different selections, and then click a button to build a room. I believe for the "tabs" I can use a card layout? For the actual building of rooms, I am pretty much sorted. The main problem I have right now, is getting the panel to open up on the click of a button.
At current, I have 1 JFrame and 2 JPanels ontop, the main game panel and the control panel with a few buttons.
Can anyone show me some simple example of how I would do such a thing? I know its probably really simple, and I bet some of you could even write the code off the top of your head, but I am new to java, and have been taught more about the logical elements of programming so far rather than how to build a more complex multi layered GUI like required in a game.
I know it's an ambitious project, but I have come a long way, and have even implemented custom path finding using A\*, which I'm happy about (All thanks to you people here at StackOverflow!)
Thank you in advance for your help. | JDialogs would work, but they're going to pop up new top level windows over your game window. You could implement your main game display and control panel as the background of a JDesktopPane(which extends JLayeredPane), and could make the pop ups JInternalFrames.
Contrived (but working) example:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
public class DesktopTest extends JFrame {
private JDesktopPane desktop;
private JPanel background;
private JInternalFrame firstFrame;
private JInternalFrame secondFrame;
public DesktopTest() {
super("DesktopTest");
desktop = new JDesktopPane();
setContentPane(desktop);
background = new JPanel(new BorderLayout());
JToolBar toolbar = new JToolBar();
toolbar.add(new AbstractAction("1") {
public void actionPerformed(ActionEvent actionEvent) {
firstFrame.setVisible(true);
}
});
toolbar.add(new AbstractAction("2") {
public void actionPerformed(ActionEvent actionEvent) {
secondFrame.setVisible(true);
}
});
AddPanel addPanel = new AddPanel();
background.add(addPanel, BorderLayout.CENTER);
background.add(toolbar, BorderLayout.SOUTH);
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent componentEvent) {
background.setSize(desktop.getSize());
background.revalidate();
background.repaint();
}
public void componentShown(ComponentEvent componentEvent) {
background.setSize(desktop.getSize());
background.revalidate();
background.repaint();
}
});
desktop.add(background);
firstFrame = new TermFrame("First Term", "Update First Term: ", addPanel) {
protected int getValue() {
return addPanel.getFirst();
}
protected void update(int value) {
addPanel.setFirst(value);
}
};
firstFrame.pack();
firstFrame.setBounds(10, 10, 200, 150);
desktop.add(firstFrame);
secondFrame = new TermFrame("Second Term", "Update Second Term: ", addPanel){
protected int getValue() {
return addPanel.getSecond();
}
protected void update(int value) {
addPanel.setSecond(value);
}
};
secondFrame.pack();
secondFrame.setBounds(200, 200, 200, 150);
desktop.add(secondFrame);
}
public static void main(String[] args) {
JFrame f = new DesktopTest();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 400);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
static class AddPanel extends JPanel {
private JLabel first;
private JLabel second;
private JLabel result;
public AddPanel() {
first = new JLabel("0");
second = new JLabel("0");
result = new JLabel("0");
Box vertical = Box.createVerticalBox();
vertical.add(Box.createVerticalGlue());
Box horizontal = Box.createHorizontalBox();
horizontal.add(Box.createHorizontalGlue());
horizontal.add(first);
horizontal.add(new JLabel("+"));
horizontal.add(second);
horizontal.add(new JLabel("="));
horizontal.add(result);
horizontal.add(Box.createHorizontalGlue());
vertical.add(horizontal);
vertical.add(Box.createVerticalGlue());
setLayout(new BorderLayout());
add(vertical, BorderLayout.CENTER);
}
public void setFirst(int i) {
first.setText(Integer.toString(i));
updateResult();
}
public int getFirst() {
return Integer.parseInt(first.getText());
}
public void setSecond(int j) {
second.setText(Integer.toString(j));
updateResult();
}
public int getSecond() {
return Integer.parseInt(second.getText());
}
private void updateResult() {
int i = Integer.parseInt(first.getText());
int j = Integer.parseInt(second.getText());
result.setText(Integer.toString(i + j));
revalidate();
}
}
static abstract class TermFrame extends JInternalFrame {
protected AddPanel addPanel;
private JFormattedTextField termField;
public TermFrame(String title, String message, AddPanel addPanel) {
super(title, true, true, true);
this.addPanel = addPanel;
NumberFormat format = NumberFormat.getNumberInstance();
format.setMaximumFractionDigits(0);
termField = new JFormattedTextField(format);
termField.setColumns(3);
termField.setValue(getValue());
JPanel content = new JPanel(new FlowLayout());
content.add(new JLabel(message));
content.add(termField);
JButton apply = new JButton("apply");
apply.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
Integer value = Integer.parseInt(termField.getText());
update(value);
}
});
content.add(apply);
setContentPane(content);
setDefaultCloseOperation(JInternalFrame.HIDE_ON_CLOSE);
}
protected abstract int getValue();
protected abstract void update(int value);
}
}
``` | > The main problem I have right now, is
> getting the panel to open up on the
> click of a button.
You don't open up another panel. You would probably use a JDialog that contains another panel. You could then use a CardLayout or you could use a JTabbedPane on the dialog. The design choices are up to you.
I suggest you start by reading the [Swing tutorial](http://java.sun.com/docs/books/tutorial/uiswing/TOC.html) for examples of all the components. I can't really offer any advice on the graphics of the program. For that you need to start asking specific questions. But building dialogs, with panels and components is straight forward. | Layering many JPanels and adding them on the fly | [
"",
"java",
"jframe",
"jpanel",
"layer",
""
] |
I work in the technical group at a large Architecture firm. While there are a number of people here that are very proficient at various programing and scripting languages, it's far from the environment of the development environment of a software company. Rarely are there ever more then one or two people working on a development project, most of which are just automation scripts. There's no source control, or version control setup or anything like that.
My academic background is engineering but not CS or CE. So I've taking a number of programing classes in school, and actually tinkered a lot with VB back when I was a little kid. Yet it wasn't until this past year at my current job have I really had the opportunity to do any real development outside of homework problems in school. In the past year I've transitions from making simple automation scripts to full blow plug-in applications in C#.NET.
I have family and friends that are CS or CE majors, and work for companies whose main product is software. While have no interest in actually working for a software company, but it seems like they do have a major advantage over me. At their work they have people with more experience that can look over their should and give them suggestions to improve their code or logic. Sites like Stack Overflow are great for solving bugs and getting advice, but only when you know you need the advice. I'm sure there are many times when I'm taking the completely wrong approach to something.
What are some of the best ways to improve these real life programing skills? Is there a way to find open source projects (preferably .Net based) that I can help work on, so I can gain some experience working with other (more experienced) programmers? I've also been looking into design patterns, but have a hard time recognizing when to use certain patterns. | Find a coding hobby project that **interests** you. If you find it interesting you will spend way more time working on the code than if you are doing it simply to learn.
As far as
> Is there a way to find open source
> projects (preferably .Net based)
go to SourceForge and find something that looks **interesting** to you and get involved. Again emphasis on interesting. Don't worry too much about how practical it is. | I'm going to go out on a limb here and suggest that you *write some code*.
Read [Code Complete](https://rads.stackoverflow.com/amzn/click/com/0735619670). Look at other questions about this topic here at StackOverflow. Find an open source project and contribute to it. Start your own pet project that focuses on the skills you're interested in.
[When to use Design patterns](https://stackoverflow.com/questions/85272/how-do-you-know-when-to-use-design-patterns)
[How to get into C# Open Source projects](https://stackoverflow.com/questions/392947/what-is-a-good-open-source-c-project-for-me-to-get-involved-in) | How to gain real world programming skills when you don't work for a software company | [
"",
"c#",
".net",
""
] |
I have a table of suppliers, and tables Computers, Cameras, Displays all containing the SupplierID field.
I am trying to do a T-SQL that will list all the suppliers, with a count of all rows. I can do them one at a time with:
```
SELECT SupplierID, COUNT(dbo.Computers.ComputerID) as Computers
FROM Supplier INNER JOIN
Computers ON Supplier.SupplierID = Computers.SupplierID
GROUP BY SupplierID
```
How can I change this to include the other tables - like cameras, displays etc... | Assuming that a suppliers may not supply each type of product, you will want to use outer joins.
If you use inner joins you will only get back suppliers that supply at least one of each production.
You also want to count the distinct ProductId for each product type. Otherwise you will get a
mulitplication affect. (For example Supplier 1 provides Computers 1 & 2 and Displays 10 & 11,
you will get back four rows of Computer 1 Display 10, Computer 1 Display 11, Computer 4 and Display 11.)
Building on gbn's answer:
```
SELECT
Supplier.SupplierID,
COUNT(distinct Computers.ComputerID) as Computers,
COUNT(distinct Displays.DisplayID) as Displays,
COUNT(distinct Foos.FooID) as Foos,
COUNT(distinct Bars.BarID) as Bars
FROM Supplier
LEFT OUTER JOIN Computers
ON Supplier.SupplierID = Computers.SupplierID
LEFT OUTER JOIN Displays
ON Supplier.SupplierID = Displays.SupplierID
LEFT OUTER JOIN Foos
ON Supplier.SupplierID = Foos.SupplierID
LEFT OUTER JOIN Bars
ON Supplier.SupplierID = Bars.SupplierID
GROUP BY
Supplier.SupplierID
``` | I don't want to repeat with others have posted, but I agree that you join all the tables and do the counts.
the thing you need to consider (and this is a individual schema consideration) is that you may **need to** `left join` the tables. **If you inner join them, you may lose rows** if you have `NULL`s in other fields. These fields would be optional fields to the table. | How do I use T-SQL Group By with multiple tables? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm writing a program which has both an ASP.NET configuration system and a Silverlight application. Most users will remain on the Silverlight page and not visit the ASP.NET site except for logging in, etc.
The problem is, I need the session to remain active for authentication purposes, but the session will timeout even if the user is using the features of the silverlight app.
Any ideas? | On the page hosting the silverlight control, you could setup a javascript timer and do an ajax call to an Http Handler (.ashx) every 5 minutes to keep the session alive. Be sure to have your Handler class implement `IRequiresSessionState`.
I recommend the Handler because it is easier to control the response text that is returned, and it is more lightweight then an aspx page.
You will also need to set the response cache properly to make sure that the browser makes the ajax call each time.
**UPDATE**
Here is the sample code for an HttpHandler
```
public class Ping : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "text/plain";
context.Response.Write("OK");
}
public bool IsReusable
{
get { return true; }
}
}
```
Then if you use jQuery, you can put this on your host aspx page
```
setInterval(ping, 5000);
function ping() {
$.get('/Ping.ashx');
}
```
The interval is in milliseconds, so my sample will ping every 5 seconds, you probably want that to be a larger number. Fiddler is a great tool for debugging ajax calls, if you don't use it, start. | I've actually found a pretty cool hack which essentially embeds an iframe on the same page as the silverlight application. The iframe contains an aspx webpage which refreshes itself every (Session.Timeout - 1) minutes. This keeps the session alive for however long the silverlight app is open.
To do this:
Create an asp.net page called "KeepAlive.aspx". In the head section of that page, add this:
```
<meta id="MetaRefresh" http-equiv="refresh" content="18000;url=KeepAlive.aspx" runat="server" />
<script language="javascript" type="text/javascript">
window.status = "<%= WindowStatusText%>";
</script>
```
In the code behind file, add this:
```
protected string WindowStatusText = "";
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
// Refresh this page 60 seconds before session timeout, effectively resetting the session timeout counter.
MetaRefresh.Attributes["content"] = Convert.ToString((Session.Timeout * 60) - 60) + ";url=KeepAlive.aspx?q=" + DateTime.Now.Ticks;
WindowStatusText = "Last refresh " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
}
}
```
Now, on the same page as the silverlight app, add this:
```
<iframe id="KeepAliveFrame" src="KeepAlive.aspx" frameborder="0" width="0" height="0" runat="server" />
```
Now the asp.net session will remain active while the silverlight app is being used! | Preventing an ASP.NET Session Timeout when using Silverlight | [
"",
"c#",
"asp.net",
"silverlight",
"authentication",
"session",
""
] |
I've created a javascript function that will take a hidden span, copy the text within that span and insert it into a single textarea tag on a website. I've written a function in JavaScript that does this (well, kinda, only after a few clicks), but I know there's a better way - any thoughts? The behavior is similar to a Retweet for twitter, but using sections of a post on a blog instead. Oh, and I'm also calling out to jquery in the header.
```
<script type="text/javascript">
function repost_submit(postID) {
$("#repost-" + postID).click(function(){
$("#cat_post_box").empty();
var str = $("span#repost_msg-" + postID).text();
$("#cat_post_box").text(str);
});
}
</script>
``` | ```
$("#repost-" + postID).click(function(){
$("#cat_post_box").val(''); // Instead of empty() - because empty remove all children from a element.
$("#cat_post_box").text($("#repost_msg-" + postID).text());//span isn't required because you have and id. so the selector is as efficient as it can be.
});
```
And wrap everything in a $(document).ready(function(){ /*Insert the code here*/ }) so that it will bind to $("#repost-" + postID) button or link when the DOM is loaded. | Based on the comment in your question, I am assuming you have something like this in your HTML:
```
<a href="#" onclick="repost_submit(5);">copy post</a>
```
And I am also assuming that because you are passing a post ID there can be more than one per page.
Part of the beauty of jQuery is that you can do really cool stuff to sets of elements without having to use inline Javascript events. These are considered a bad practice nowadays, as it is best to separate Javascript from your presentation code.
The proper way, then, would be to do something like this:
```
<a href="#" id='copy-5' class='copy_link'>copy post</a>
```
And then you can have many more that look similar:
```
<a href="#" id='copy-5' class='copy_link'>copy post</a>
<a href="#" id='copy-6' class='copy_link'>copy post</a>
<a href="#" id='copy-7' class='copy_link'>copy post</a>
```
Finally, you can write code with jQuery to do something like this:
```
$(function() { // wait for the DOM to be ready
$('a.copy_link').click(function() { // whenever a copy link is clicked...
var id = this.id.split('-').pop(); // get the id of the post
var str = $('#repost_msg-' + id); // span not required, since it is an ID lookup
$('#cat_post_box').val(str); // empty not required, and val() is the proper way to change the value of an input element (even textareas)
return false;
});
});
```
This is the best way to do it even if there is only one post in the page. Part of the problem with your code is that on the first click it BINDS the function, and in the subsequent clicks is when it finally gets called. You could go for a quick and dirty fix by changing that around to just be in document.ready. | JQuery Copy text & paste into textarea | [
"",
"javascript",
"jquery",
""
] |
I am hosting the IMsRdpClient6 ActiveX control in my WinForms application in order to make connections to remote machines.
I have setup a terminal services gateway machine, and I can successfully use it.
I want to get my ActiveX control to use this gateway. I have set the Gateway options, but connection fails with no error that I can see. Here is the code that I am using:
```
MSTSCLib6.IMsRdpClient6 client6 = RdpClient.GetOcx() as MSTSCLib6.IMsRdpClient6;
if (client6 != null)
{
MSTSCLib6.IMsRdpClientTransportSettings2 transport = client6.TransportSettings2;
if (Convert.ToBoolean(transport.GatewayIsSupported) == true)
{
client6.TransportSettings.GatewayHostname = "mygateway";
client6.TransportSettings.GatewayUsageMethod = 2;
client6.TransportSettings.GatewayCredsSource = 0;
client6.TransportSettings.GatewayUserSelectedCredsSource = 0;
client6.TransportSettings2.GatewayDomain = "mydomain";
client6.TransportSettings2.GatewayPassword = "mypassword";
client6.TransportSettings2.GatewayUsername = "myusername";
}
}
``` | The answer to this was to omit the GatewayUserSelectedCredsSource and to include GatewayProfileUsageMethod = 1;
```
MSTSCLib6.IMsRdpClient6 client6 = RdpClient.GetOcx() as MSTSCLib6.IMsRdpClient6;
if (client6 != null)
{
MSTSCLib6.IMsRdpClientTransportSettings2 transport = client6.TransportSettings2;
if (Convert.ToBoolean(transport.GatewayIsSupported) == true)
{
client6.TransportSettings.GatewayHostname = "mygateway";
client6.TransportSettings.GatewayUsageMethod = 1;
client6.TransportSettings.GatewayCredsSource = 0;
client6.TransportSettings.GatewayProfileUsageMethod = 1;
client6.TransportSettings2.GatewayDomain = "mydomain";
client6.TransportSettings2.GatewayPassword = "mypassword";
client6.TransportSettings2.GatewayUsername = "myusername";
}
}
``` | Just tried adding this code and got a field not valid error. I'm guessing it has something to do with not setting the server name, but it is not set in you example. Can you explain how to get around this.
regards Andrew. Will post code if needed. | How to use Terminal Services Gateway with the IMsRdpClient6 ActiveX Control? | [
"",
"c#",
"winforms",
"activex",
"terminal-services",
"terminal-services-gateway",
""
] |
Hi I have to store some hidden information in Isolated space. For that I am using System.IO.Isolated class like
```
IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
Stream writer = new IsolatedStorageFileStream(filename, FileMode.Create, isf);
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(writer, appCollection.ToString());
writer.Close();
```
It works fine in Windows XP but on production server that is windows 2003 it shows exception
System.IO.IsolatedStorage.IsolatedStorageException: Unable to create the store directory.
I have a Everyone full control permissions in my asp.net project folder. Attention CSoft.Core is a personal Framework created by me.
This is my Stack Trace:
> [IsolatedStorageException: Unable to create the store directory.
> (Exception from HRESULT: 0x80131468)]
> System.IO.IsolatedStorage.IsolatedStorageFile.nGetRootDir(IsolatedStorageScope
> scope) +0
> System.IO.IsolatedStorage.IsolatedStorageFile.InitGlobalsNonRoamingUser(IsolatedStorageScope
> scope) +97
> System.IO.IsolatedStorage.IsolatedStorageFile.GetRootDir(IsolatedStorageScope
> scope) +137
> System.IO.IsolatedStorage.IsolatedStorageFile.GetGlobalFileIOPerm(IsolatedStorageScope
> scope) +213
> System.IO.IsolatedStorage.IsolatedStorageFile.Init(IsolatedStorageScope
> scope) +56
> System.IO.IsolatedStorage.IsolatedStorageFile.GetStore(IsolatedStorageScope
> scope, Type domainEvidenceType, Type assemblyEvidenceType) +59
> CSoft.Core.IO.StorageHelper.Save(String fileName, String content) in
> c:\Projectos\FrameworkCS\CSoft.Core\IO\StorageHelper.cs:18
> CSoft.Web.UI.ViewStateHelper.SerializeViewState(HttpContext context,
> Object state) in
> c:\Projectos\FrameworkCS\CSoft.Web.Controls\Web\UI\ViewStateHelper.cs:65
> CSoft.Web.UI.Page.SavePageStateToPersistenceMedium(Object state) in
> c:\Projectos\FrameworkCS\CSoft.Web.Controls\Web\UI\Page.cs:302
> System.Web.UI.Page.SaveAllState() +236
> System.Web.UI.Page.ProcessRequestMain(Boolean
> includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
> +1099 | I changed IsolatedStorage file to
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetMachineStoreForAssembly())
{ }
And this work. | If it's running on IIS and application pool identity is NetworkService, You can try to go to advanced settings of application pool and set "Load user profile" value to "True". Worked for me. | IsolatedStorageException: Unable to create the store directory | [
"",
"c#",
"asp.net",
"visual-studio",
"isolatedstorage",
""
] |
In the end, I have decided that this isn't a problem that I particularly need to fix, however it bothers me that I don't understand why it is happening.
Basically, I have some checkboxes, and I only want the users to be able to select a certain number of them. I'm using the code below to achieve that effect.
```
$j( function () {
$j('input[type=checkbox].vote_item').click( function() {
var numLeft = (+$j('#vote_num').text());
console.log(numLeft);
if ( numLeft == 0 && this.checked ) {
alert('I\'m sorry, you have already voted for the number of items that you are allowed to vote for.');
return false;
} else {
if ( this.checked == true ) {
$j('#vote_num').html(numLeft-1);
} else {
$j('#vote_num').html(numLeft+1);
}
}
});
});
```
And when I was testing it, I noticed that if I used:
```
$j('input[type=checkbox]').each( function () {
this.click()
});
```
The JavaScript reacted as I would expect, however when used with:
```
$j('input[type=checkbox]').each( function () {
$j(this).click()
});
```
It would actually make the counter count UP.
I do realize that it isn't the most secure way to keep count using the counter, however I do have server side error-checking that prevents more than the requisite amount from being entered in the database, that being the reason that I have decided that it doesn't actually need fixing.
Edit: The `$j` is due to the fact that I have to use jQuery in `noConflict` mode... | The fact that counter is going up gave me the clue that there is a link between checked attribute, which you are using, and firing the click event manually.
I searched Google for 'jquery checkbox click event raise' and found this link, where author faces the exact same problem and the workaround he used.
<http://www.bennadel.com/blog/1525-jQuery-s-Event-Triggering-Order-Of-Default-Behavior-And-triggerHandler-.htm>
On a side note, I think you can simplify your code further:
```
$j('input[type=checkbox].vote_item').click(
function()
{
var maxNumberOfChoices = 5;
//get number of checked checkboxes.
var currentCheckedCount = $j('input[type=checkbox].vote_item :checked');
if(currentCheckedCount > maxNumberOfChoices)
{
//It's useful if you show how many choices user can make. :)
alert('You can only select maximum ' + maxNumberOfChoices + ' checkboxes.');
return false;
}
return true;
});
``` | $(this) contains a jQuery wrapper (with lots of functions) whereas this is solely the DOM object. | What is the difference between this.click() and $(this).click()? | [
"",
"javascript",
"jquery",
"jquery-events",
""
] |
I want to use a hardware cursor for a computer game I am making, AWT allows me to do so, and specify an image to use, however it only accepts 2 colours and transparency, which is fairly limiting.
I'm fairly certain that it's possible to use a greater colour depth on most current systems, is there any way to achieve that in AWT? What about other ways? | If you call Toolkit.getMaximumCursorColors and that returns a maximum of 2 - then that's all that AWT's going to use to render the cursor. To get around this, you can make a completely transparent image and set that as the cursor. Then, add a MouseListener to whatever component you're using to paint the game and just draw or paint whatever cursor image you want at the current mouse coordinates. | Drawing on an image didn't work for me.
image loaded as normal, then:
```
Cursor cursor = Toolkit.getDefaultToolkit().createCustomCursor(bufferedImage, new Point(0,0), "transparent");
Graphics graphics = bufferedImage.getGraphics();
graphics.drawImage(image, 0,0, null);
frame.setCursor(cursor);
```
it's still got the Toolkit's 2-colour limitation :( | How do I use more than two colors using an AWT hardware cursor? | [
"",
"java",
"colors",
"cursor",
"awt",
""
] |
I have a very simple WPF user control that is mixed in with a windows forms app. It has a list box that renders its scroll bar without **the thumb** (image below). I narrowed it down to a plugin in my app that uses Managed DirectX (MDX). If I remove the plugin, the scroll bar is just fine. I know MDX is deprecated, but I don't think today is the day to consider an upgrade. Has anyone ever seen their **scroll bar get messed up**, or has any idea what I should do?
And I should add, that this control also lives in a plugin. There is no way for the 2 plugins to reference each other.
[](https://i.stack.imgur.com/JtQJD.png)
```
<UserControl x:Class="MAAD.Plugins.Experiment.Visual.TestEditor"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="403" Width="377">
<ListBox Margin="12" Name="listBox1" />
</UserControl>
```
Update: You can read about the solution below. | As it turns out, I stumbled on the solution today while working with a client. If you add the CreateFlags.FpuPreserve flag to your device creation, the scrollbar should go back to normal. | I've seen this bug too. It is not a SlimDX issue per se, but rather due to DirectX using 32-bit math on the x87 FP stack.
Use the FpuPreserve flag when initializing your device and the problem should go away. | MDX/SlimDX messes up WPF scrollbars? | [
"",
"c#",
"wpf",
"winforms",
"interop",
"directx",
""
] |
I'm working on a small django project that will be deployed in a servlet container later. But development is much faster if I work with cPython instead of Jython. So what I want to do is test if my code is running on cPython or Jython in my settiings.py so I can tell it to use the appropriate db driver (postgresql\_psycopg2 or doj.backends.zxjdbc.postgresql). Is there a simple way to do this? | if you're running Jython
```
import platform
platform.system()
```
return 'Java'
[here has some discussion](https://stackoverflow.com/questions/1086000/), hope this helps. | The most clear-cut way is:
> > > import platform
> > >
> > > platform.python\_implementation()
'CPython'
By default, most of the time the underlying interpreter is CPython only which is also arguably the most efficient one :) | Can I detect if my code is running on cPython or Jython? | [
"",
"python",
"django",
"jython",
""
] |
How do you find the range of page n in Microsoft Word using office automation? There appears to be no getPageRange(n) function and it is unclear how they are divided. | This is how you do it from VBA, should be fairly trivial to convert to Matlab COM calls.
```
Public Sub DemoPerPageText()
Dim i As Integer
Dim totalPages As Integer
Dim bmRange As Range
totalPages = Selection.Information(wdNumberOfPagesInDocument)
For i = 1 To totalPages
Set bmRange = ActiveDocument.Bookmarks("\Page").Range
Debug.Print CStr(i) & " : " & bmRange.Text & vbCrLf
Next i
End Sub
``` | You can use the Matlab OfficeDoc utility for reading/writing Word contents from Matlab: <http://www.mathworks.com/matlabcentral/fileexchange/15192-officedoc-readwriteformat-ms-office-docs-xlsdocppt> | How To Get the Range of a Page Using Word Automation | [
"",
"c#",
"matlab",
"automation",
"ms-word",
"ms-office",
""
] |
I have a `List<MyObj>` with the `class MyObj : IComparable`. I wrote the method `CompareTo` in the `MyObj` class per the `IComparable` interface, but when I use the `List<MyObj>.Contains(myObjInstance)` it returns `false` when it should be `true`.
I'm not sure I'm understanding how I need to proceed to make sure the `List` uses my custom comparison method when calling then `Contains` function.
Here is my compareTo implementation:
```
#region IComparable Members
public int CompareTo(object obj)
{
MyObj myObj = (MyObj)obj;
return String.Compare(this.Symbol, myObj.Symbol, true);
}
#endregion
```
Note the Symbol property is a string.
To clarify I've put a stopping point in that compareTo method and it doesn't even go in there.
Anyone has ever tried that?
Thanks. | The absolute easiest way to find out whether your CompareTo method is called is to set a breakpoint in it and hit F5 to run your program. But I believe that `List<T>.Contains` looks for the [`IEquatable<T>`](http://msdn.microsoft.com/en-us/library/ms131187.aspx) interface for making the comparison. | According to the [documentation](http://msdn.microsoft.com/en-us/library/bhkz42b3.aspx) for `List<T>.Contains`, it uses either your implementation of `IEquatable` interface or `object.Equals`, that you can override as well. | Modify List.Contains behavior | [
"",
"c#",
"list",
"contains",
"icomparable",
"icomparer",
""
] |
I'm completely new to Visual Studio and I'm having some trouble getting a project started with Visual Studio 2008. I'm experimenting with MAPI, and I'm getting error messages like this when I go to build the project:
"unresolved external symbol \_MAPIUninitialize@0 referenced in function \_main"
I know I need to link to MAPI32.lib, but the guides I have found thus far have indicated going to the "Visual Studio settings **link** tab" and adding it there (which was - apparently - from an older version of Visual Studio). I can't find anything like that in the project properties linker or C/C++ sections of VS 2008.
Where do I need to tell Visual Studio to use that library?
Thanks | It's under Project Properties / Configuration Properties / Linker / Input / Additional Dependencies.
The help tip at the bottom of the screen says *"Specifies additional items add to the line line (ex: kernel32.lib)"*. | Project Properties->Linker->Input->Additional Dependencies
You can also use
`#pragma comment( lib, "mapi32" )`
in one of your source files. As noted MSDN here is a similar library addition using the pragma technique [MSDN - Creating a Basic Winsock Application](http://msdn.microsoft.com/en-us/library/windows/desktop/ms737629%28v=vs.85%29.aspx)
```
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#pragma comment(lib, "Ws2_32.lib")
int main() {
return 0;
}
``` | Add Library to Visual Studio 2008 C++ Project | [
"",
"c++",
"visual-studio-2008",
"mapi",
""
] |
```
SELECT
*
FROM
myTable
WHERE
field1 LIKE 'match0' AND
myfunc(t1.hardwareConfig) LIKE 'match1'
```
Here is my question,
the matching of field1 is fast and quick, but myfunc takes forever to return and I want to make sure that if field1 doesn't match that it doesn't even attempt to do myfunc.
Will SQL just know this or can I make it explicit in my query?
I'm on MSSQL 2000, 2005 and 2008, hopefully there's a common answer. | To enforce the order in which conditions are evaluated, use the following approach, because it is documented that CASE preserves the order in which conditions are evaluated.
```
SELECT
*
FROM
myTable
WHERE
CASE WHEN field1 LIKE 'match0' THEN
CASE WHEN myfunc(t1.hardwareConfig) LIKE 'match1'
THEN 1
END
END = 1
```
The following article explains it in good detail: [Predicates in SQL](http://pratchev.blogspot.com/2008/10/predicates-in-sql.html) | There's a lot that goes on behind the scenes to determine how a query is executed, but in this situation I would *expect* for it to filter on the field1 first. Note that this isn't a guarantee - the query optimizer can make some strange choices now and then. Additionally, you can improve your chances by using the '=' operator rather than the 'LIKE' operator. | How will SQL Server perform this query behind the scenes | [
"",
"sql",
"sql-server",
"performance",
""
] |
I want to have a small text box with a scroll bar that will hold frequent outputs from PHP based on server-side activity. How do I set up formatting like this? | I would either use a `<pre>` or multiple `<div>`s (one per line) instead of an input element. That way, you don't have to deal with making the input element read-only. If you use `<div>`s, then you can also add classes to each line to style messages of different severity differently (for example, errors are red, warnings are orange etc.) | The box:
```
<iframe style="overflow:auto; width:100px" src="status.php"/>
```
And in status.php you parse a log file, as explained here
[How can I parse Apache's error log in PHP?](https://stackoverflow.com/questions/159393/how-can-i-parse-apaches-error-log-in-php)
And you log interesting events/errors/warnings/debug in the log file. | Formatting PHP Echo | [
"",
"php",
"html",
"css",
""
] |
Is there a way to use ASP.NET in browsers that javascript is not enabled?
Whereas all buttons/actions do a postback using javascript by default, i guess that isn't possible, but using ASP.NET MVC could be a solution?
**What do you think is the best way to deal if the user's browser is with javascript disabled?** Block the page access telling that the user need enabled?
**So, is this really necessary?**
A lot of large sites do nothing to handle that. | > A lot of large sites do nothing to handle that.
A lot of large sites are rubbish created by incompetents.
Apply the techniques of [Progressive Enhancement](http://en.wikipedia.org/wiki/Progressive_enhancement): create a functional application or site that works without scripting, even though it may be clunky and long-winded to navigate. Then use scripting to enhance that basic version by adding the stuff that makes it slick and easy to use.
Try going to something like Google Maps with JS disabled; you still get a basic site you can use to search and view static map images. That's the professional approach. | Yes, asp.net will downgrade itself to not use javascript for validation of a browser doesn't have it enabled.
Well it depends on who your audience is. If you have visually impared people accessing the site you need to have a non-js enabled site, because their readers (browsers) can't handle javascript.
There are also a lot of people who have js turned off for security reasons, and unless they have a reason to trust your site, they won't turn it on.
If you don't mind people in demographics like these, then sure you can just tell them they need a browser with it turned on. | Using ASP.NET in browsers that not support javascript | [
"",
"asp.net",
"javascript",
""
] |
> **Possible Duplicate:**
> [CSV File Imports in .Net](https://stackoverflow.com/questions/1898/csv-file-imports-in-net)
In .net, is there a standard library that should be used to read in csv files? All the samples on the web roll their own csv reader / parser, or use OleDb.
It's not a problem using any of these solutions, I was just wondering if there is a generally accepted library (not that I can find), or any other "proper" way to do it? | [CsvReader](http://www.codeproject.com/KB/database/CsvReader.aspx) is a pretty good one... it isn't Microsoft, but it works very well, and is a lot faster than some of the alternatives (legacy OleDb etc). | One of the reasons that many people write their own is that **CSV isn't quite so simple**. For example:
1. Does the first row contain field names, or not?
2. Do you support dates? If, so, are they quoted, surrounded by # marks, in a certain day-month-year order?
3. Does it support linefeeds that occur inside quoted text values? Or does that split the record?
4. How do you escape a quote inside of a quoted string? Do you double the quote, or use a backslash or other escape character?
5. What character encoding(s) are supported?
6. How does it handle escaped control characters? &#XX; or \uXXXX or some other method?
These are *some* of the reasons people write their own parsers, *because they're stuck reading files created with all these different settings*. Or they write their own serializers, *because the target system has a bunch of these idiosyncrasies*.
If you don't care about these issues, just use the most convenient library. But understand they are there. | Is there a "proper" way to read CSV files | [
"",
"c#",
".net",
"csv",
"oledb",
""
] |
I'm getting the error "**T does not contain a definition for Id**" below in the specified line, even though when I debug, I see that "item" **does indeed** have a property "Id" in its ***base class***.
**How do I specify here that I want C# to look in the item's base class for Id (and why doesn't it do this automatically?)?**
```
//public abstract class Items<T> : ItemBase (causes same error)
public abstract class Items<T> where T : ItemBase
{
public List<T> _collection = new List<T>();
public List<T> Collection
{
get
{
return _collection;
}
}
public int GetNextId()
{
int highestId = 0;
foreach (T item in _collection)
{
//ERROR: "T does not contain a definition for Id
if (item.Id > highestId) highestId = item.Id;
}
return highestId;
}
}
```
Here's how the classes are being defined:
```
public class SmartForm : Item
{
public string IdCode { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int LabelWidth { get; set; }
public int FormWidth { get; set; }
...
public abstract class Item : ItemBase
{
public int Id { get; set; }
public DateTime WhenCreated { get; set; }
public string ItemOwner { get; set; }
public string PublishStatus { get; set; }
public int CorrectionOfId { get; set; }
...
``` | Your problem is that there is no constraint on T, so, at compile time, all the compiler knows is that T is some sort of object. If you know what type T will always inherit off, you can add a generic constraint to the class definition:
```
public abstract class Items<T> : ItemBase where T : Item
{
//....
}
```
When you're debugging, T is instantiated to an Item (or subclass of) that does have an Id property, but the compiler doesn't know that at compile time, hence the error. | You got your generic constraint wrong.
```
public abstract class Items<T> : ItemBase
```
should be:
```
public abstract class Items<T> where T : ItemBase
```
What happened is that while your class has a collection of items, your `ItemBase` is not associated with `T` | How to tell C# to look in an object's base class for a property? | [
"",
"c#",
"generics",
"inheritance",
""
] |
I create some dynamic textbox's and a button in a placeholder and would like to save info in textbox's when button is clicked but not sure how to retrieve data from the textbox
```
LiteralControl spacediv3 = new LiteralControl("  ");
Label lblComText = new Label();
lblComTitle.Text = "Comment";
TextBox txtComment = new TextBox();
txtComment.Width = 200;
txtComment.TextMode = TextBoxMode.MultiLine;
phBlog.Controls.Add(lblComText);
phBlog.Controls.Add(spacediv3);
phBlog.Controls.Add(txtComment);
Button btnCommentSave = new Button();
btnCommentSave.ID = "mySavebtnComments" ;
btnCommentSave.Text = "Save ";
phBlog.Controls.Add(btnCommentSave);
btnCommentSave.CommandArgument = row["ID"].ToString();
btnCommentSave.Command += new CommandEventHandler(btnSave_Click);
protected void btnSave_Click(object sender, CommandEventArgs e)
{
firstelement.InnerText = txtComment.text // this gives error on txtComment.text
}
``` | You need to get a reference to your control in btnSave\_Click. Something like:
```
protected void btnSave_Click(object sender, CommandEventArgs e)
{
var btn = (Button)sender;
var container = btn.NamingContainer;
var txtBox = (TextBox)container.FindControl("txtComment");
firstelement.InnerText = txtBox.text // this gives error on txtComment.text
}
```
You also need to set the ID on txtComment and recreate any dynamically created controls at postback. | You will need some mechanism to create a relation between the Button and the TextBox obviously. In winforms this would be easy, where each control has a Tag property, which can contain a reference to pretty much anything. The web controls don't have such a property (that I know of), but it is still easy to maintain such relations. One approach would be to have `Dictionary` in the page storing button/textbox relations:
```
private Dictionary<Button, TextBox> _buttonTextBoxRelations = new Dictionary<Button, TextBox>();
```
When you create the button and textbox controls, you insert them in the dictionary:
```
TextBox txtComment = new TextBox();
// ...
Button btnCommentSave = new Button();
// ...
_buttonTextBoxRelations.Add(btnCommentSave, txtComment);
```
...and then you can look up the text box in the button's click event:
```
protected void btnSave_Click(object sender, CommandEventArgs e)
{
TextBox commentTextBox = _buttonTextBoxRelations[(Button)sender];
firstelement.InnerText = txtComment.text // this gives error on txtComment.text
}
``` | How can I read a dynamically created textbox | [
"",
"c#",
"asp.net",
"dynamic",
"controls",
""
] |
I have a collection like this
```
List<int> {1,15,17,8,3};
```
how to get a flat string like "1-15-17-8-3" through LINQ query?
thank you | something like...
```
string mystring = string.Join("-", yourlist.Select( o => o.toString()).toArray()));
```
(Edit: Now its tested, and works fine) | You can write an extension method and then call .ToString("-") on your IEnumerable object type as shown here:
```
int[] intArray = { 1, 2, 3 };
Console.WriteLine(intArray.ToString(","));
// output 1,2,3
List<string> list = new List<string>{"a","b","c"};
Console.WriteLine(intArray.ToString("|"));
// output a|b|c
```
Examples of extension method implementation are here:
<http://coolthingoftheday.blogspot.com/2008/09/todelimitedstring-using-linq-and.html>
<http://www.codemeit.com/linq/c-array-delimited-tostring.html> | Simple LINQ query | [
"",
"c#",
".net",
"linq",
"generics",
""
] |
```
class Foo(){
public List<string> SomeCollection;
}
```
I need to implement an event which can fires when something added or removed from the Collection. How to do this? | `List<T>` has no notification support. You could look at `BindingList<T>`, which has events - or `Collection<T>`, which can be inherited with override methods.
If you want to expose the event at the `Foo` level, perhaps something like below - but it may be easier to leave it on the list:
```
class Foo{
public event EventHandler ListChanged;
private readonly BindingList<string> list;
public Foo() {
list = new BindingList<string>();
list.ListChanged += list_ListChanged;
}
void list_ListChanged(object sender, ListChangedEventArgs e) {
EventHandler handler = ListChanged;
if (handler != null) handler(this, EventArgs.Empty);
}
public IList<string> SomeCollection {get {return list;}}
}
``` | Take a look at the [`BindingList`](http://msdn.microsoft.com/en-us/library/ms132679.aspx) and [`ObservableCollection`](http://msdn.microsoft.com/en-us/library/ms668604.aspx) classes (in the `System.ComponentModel` and `System.Collections.ObjectModel` namespaces respectively) - either one should do the job well for you.
Note that the two classes generally provide the same functionality, but they do *differ slightly*. `BindingList` is typically more suitable for data-binding/UI purposes (hence it's name), since it allows the option to cancel updates and such. However, `ObservableCollection` is possibly more appropiate in your case, since you're just interested in being notified of changes (it would seem), and the class was designed purely from that perspective. The fact that they exist in very different namespaces sort of hints at this. If you want the precise details on the similarities and differences, I recommend you inspect the linked MSDN docs. | How to implement event | [
"",
"c#",
"events",
"collections",
""
] |
Suppose I have the following types of data:
```
class Customer {
String id; // unique
OtherCustData someOtherData;
}
class Service {
String url; // unique
OtherServiceData someOtherData;
}
class LastConnection {
Date date;
OtherConnData someOtherData; // like request or response
}
```
Now I need to remember when each of the customers connected to each of the services.
I would make the structure:
```
Map<Customer, Map<Service, LastConnection>> lastConnections;
```
Or, to be able to search by ids and not have to write all the equal() and hashCode():
```
Map<String, Map<String, LastConnection>> lastConnections;
```
Now I could access the LastConnection data by
```
LastConnection connection = lastConnections.get(custId).get(srvUrl);
```
All this seems ugly, especially that I have to pass it as parameters to tens of methods expecting map of maps of LastConnections, so I'm thinking of creating my own classes which would look something like that:
```
class CustomerConnections extends HashMap<String, LastConnection> {
}
class AllConnections extends HashMap<String, CustomerConnections> {
public LastConnection get(String custId, String srvUrl) {
return get(custId).get(srvUrl);
}
}
```
Ok, I learned already that inheritance is 3v1l, so let's try composition:
```
class CustomerConnections {
Map<String, LastConnection> customerConnections;
LastConnection get(String srvUrl) {
return customerConnections.get(srvUrl);
}
... // all other needed operations;
}
class AllConnections {
Map<String, CustomerConnections> allConnections;
public LastConnection get(String custId, String srvUrl) {
return get(custId).get(srvUrl);
}
public CustomerConnection get(String custId) {
return allConnections.get(custId);
}
... // all other needed operations;
}
```
The problem is that I'm not sure what would be the best approach respecting SOLID principles and all the best practices. Creating classes that do nothing except extending already existing collections seems like multiplying entities beyond necessity, but would make my code more clear (Especially when there are next levels - like Map of AllConnections by month and so on). Any directions? | > Creating classes that do nothing
> except extending already existing
> collections seems like multiplying
> entities beyond necessity
I would change extend to encapsulate. You are hiding the details of how this information is stored. Clients of your class don't need to know how you are providing them with the Customer connection history. I think this is a good idea since you can change the underlying model without having clients of the api change their code.
> but would make my code more clear
This is great and is a good reason to do this. YourClass.getCustomerConnection(cId) is much clearer than yourCollection.get(id).get(id).getConnection(). You need to make the life of the people using this code easier, even if you are that person.
> (Especially when there are next levels - like Map of AllConnections by month and so on)
Good, then you are planning ahead and making your code extensible. Which is good OO practice. In my opinion the conculsion you have reached on your own is what I would do. | I think that you should also consider how the collections are going to be used and how the data is obtained:
* If they are simple result sets to be displayed on a page (for example), then using standard collections seems reasonable - and you can then use lots of standard libraries to manipulate them.
* On the other hand, if they are mutable and any changes need to be persisted (for example), then encapsulating them within your own classes might be preferable (which can then write changes to databases, etc).
How do you get and persist your data? If it is stored in a database, then maybe you can use SQL to select LastConnections by customer and/or service and/or month, rather than having to maintain the datastructures yourself (and just return simple lists or maps of connections or counts of connections). Or maybe you don't want to run a query for each request, so do need to keep the whole datastructure in memory.
Encapsulation is generally a good thing though, particularly as it can help you to adhere to the [Law of Demeter](http://en.wikipedia.org/wiki/Law_Of_Demeter) - maybe you can push some of the operations that you will perform on the collections back into the AllConnections class (which is effectively a DAO). This can often help unit testing.
Also, why is extending HashMap considered evil here, considering that you only want to add a trivial helper method? In your code for AllConnections, AllConnections will always behave in the same way as a HashMap - it is polymorphically substitutable. Of course, you are potentially locking yourself into using HashMap (rather than TreeMap, etc), but that probably doesn't matter since it has the same public methods as Map. However, whether you would actually want to do this really does depend upon how you intend to use the collections - I just don't think that you should automatically discount implementation inheritance as *always* bad (it just usually is!)
```
class AllConnections extends HashMap<String, CustomerConnections> {
public LastConnection get(String custId, String srvUrl) {
return get(custId).get(srvUrl);
}
}
``` | Inheriting and encapsulating collection classes in Java | [
"",
"java",
"inheritance",
"collections",
"encapsulation",
""
] |
I currently have a website that I am trying to optimize in terms of SEO.
I've got the site working with URLs such as:
> domain.com/?app=about
In my app, `$_GET[app]` is set to 'about', as expected.
Now, I want to make it so that a URL like `domain.com/about` is treated as if it were `domain.com/?app=about`.
How can I do this in an Apache .htaccess file? | These are known as `RewriteRule`s, and they are fairly straightforward:
```
RewriteEngine on
RewriteRule ^about$ /index.php?app=about
```
[Here's the documentation](http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html)
As far as making it more generic, how about this:
```
RewriteEngine on
RewriteRule ^([A-Za-z]+)$ /index.php?app=$1
```
This will make any request to something like /staff or /contact redirect to index.php?app=[staff|contact] | Use this in your .htaccess
```
RewriteEngine on
RewriteBase /your-site # only if neccessary
RewriteRule ^([^/])$ index.php?app=$1 [R,L]
```
**EDIT**
I added the L flag meaning process this as the last rule, and the R flag which by itself does not change the URL .. just rewrites internally. Doing R=301 will forward the browser to the rewritten page, which is useful for debugging. | How can I rewrite query parameters to path parameters in Apache? | [
"",
"php",
"apache",
".htaccess",
"url-rewriting",
""
] |
I am just wondering how i can get the error causing LoginUser function to fail in my C++ program and return it as a String?
```
JNIEXPORT jstring JNICALL Java_com_entrust_adminservices_urs_examples_authn_LdapAuthenticator2_takeInfo(JNIEnv *env, jobject obj, jstring domain, jstring id, jstring idca, jstring password)
{
const char *nt_domain;
const char *nt_id;
const char *nt_password;
nt_domain = env->GetStringUTFChars(domain, NULL);
nt_id = env->GetStringUTFChars(id, NULL);
nt_password = env->GetStringUTFChars(password, NULL);
HANDLE hToken = 0;
char *otherString;
bool aut = true;
aut = LogonUser(nt_id, nt_domain, nt_password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &hToken );
if(aut)
{
otherString = "true";
}
else
{
otherString = //how would i get the last error here?
}
jstring newString = env->NewStringUTF((const char*)otherString);
return newString;
}
int main()
{
return 0;
}
```
Thanks
-Pete
Edit:
Thanks guys, did it with:
```
DWORD dwError = GetLastError();
LPVOID lpMsgBuf;
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT ), (LPTSTR) &lpMsgBuf, 0, NULL );
otherString = (char*)lpMsgBuf;
``` | In Windows, you can use [GetLastError](http://msdn.microsoft.com/en-us/library/ms679360(VS.85).aspx) to retrieve the error, and then [FormatMessage](http://msdn.microsoft.com/en-us/library/ms679351(VS.85).aspx) to turn that into a string you can use. | Use [`GetLastError`](http://msdn.microsoft.com/en-us/library/ms679360(VS.85).aspx) to retrieve the error code. Use [`FormatMessage`](http://msdn.microsoft.com/en-us/library/ms679351(VS.85).aspx) to get its textual description (there's an example at the bottom of the page). | Get Last Error from LogonUser function and return it as a String? | [
"",
"c++",
"string",
"error-handling",
""
] |
Duplicate of [Encrypting config files for deployment .NET](https://stackoverflow.com/questions/559995/encrypting-config-files-for-deployment-net) and [Encrypting config files for deployment](https://stackoverflow.com/questions/563717/encrypting-config-files-for-deployment)
---
What is the best approach and tools for encrypting information in web.config file? | I believe there are two ways of doing this:
using aspnet\_regiis using [DPAPI](http://msdn.microsoft.com/en-us/library/ms998280.aspx) or [RSA](http://msdn.microsoft.com/en-us/library/ms998283.aspx), or [doing it programmatically](http://www.dotnetcurry.com/ShowArticle.aspx?ID=185&AspxAutoDetectCookieSupport=1).
The programmatic way can be handy, particularly if you also like to encrypt app.config.
From my experiences of using this, if you write a custom configuration section, you have install the DLL containing the classes for that section into the GAC. For a project I was working I basically scripted the following approach:
* Copy config DLL to GAC.
* Perform encryption.
* Remove config DLL from GAC.
Chances are if you are just encrypting connection strings then this won't be a problem. You also need to be bear in mind whether you want to encrypt on a machine wide basis or to a specific user account- both options can be useful depending on your scenario. For simplicity I stuck to machine wide encryption. The links I have provided explain the merits of both approaches. | Here are the commands to encrypt web.config file without any programming...
For encryption
```
aspnet_regiis -pef "Section" "Path exluding web.config"
```
For Decryption
```
aspnet_regiis -pdf "Section" "Path exluding web.config"
```
From this commands you can encrypt or decrypt all the section. | Encrypting Web.Config | [
"",
"c#",
".net",
"asp.net",
"encryption",
"web-config",
""
] |
At our shop, we are maintaining roughly 20 Java EE web applications. Most of these applications are fairly CRUD-like in their architecture, with a few of them being pretty processor intensive calculation applications.
For the deployment of these applications we have been using Hudson set up to monitor our CVS repository. When we have a check-in, the projects are set to be compiled and deployed to our Tomcat 6.0 server (*Solaris 10, sparc Dual-core 1.6 GHz processor, 2 GB RAM...not the beefiest machine by any stretch of the imagination...*) and, if any unit-tests exist for the project, those are executed and the project is only deployed if the unit-tests pass. This works great.
Now, over time, I've noticed myself that a lot of the projects I create utilize the same .jar files over and over again (Hibernate, POI (Excel output), SQL Server JDBC driver, JSF, ICEFaces, business logic .jar files, etc.). Our practice has been to just keep a folder on our network drive stocked with all the default .jar files we have been using, and when a new project is started we copy this set of .jar files into the new project and go from there...and I feel so *dirty* every time this happens it has started to keep me up at night. I have been told by my co-workers that it is "extremely difficult" to set up a .jar repository on the tomcat server, which I don't buy for a second...I attribute it to pure laziness and, probably, no desire to learn the best practice. I could be wrong, however, I am just stating my feelings on the matter. This seems to bloat the size of our .war files that get deployed to the server as well.
From my understanding, Tomcat itself has a set of .jar files that are accessible to all applications deployed to it, so I would think we would be able to consolidate all of these duplicate .jar files in all our projects and move them onto the tomcat server. This would involve only updating one .jar file on the server if, for example, we need to update the ICEFaces .jar files to a new version.
Another part of me says that by including only one copy of the .jar files on the server, I might need to keep a copy of the server's lib directory in my development environment as well (i.e. include those .jar files in eclipse dependency).
My gut instinct tells me that I want to move those duplicated .jar files onto the server...will this work? | I think Maven and Ivy were born to help manage JAR dependencies. Maybe you'll find that those are helpful.
As far as the debate about duplicating the JARs in every project versus putting them in the server/lib, I think it hinges on one point: How likely is it that you'll want to upgrade every single application deployed on Tomcat at the same time? Can you ever envision a time where you might have N apps running on that server, and the (N+1)th app could want or require a newer version of a particular JAR?
If you don't mind keeping all the apps in synch, by all means have them use a common library base.
Personally, I think that disk space is cheap. My preference is to duplicate JARs for each app and put them in the WAR file. I like the partitioning. I'd like to see more of it when OSGi becomes more mainstream. | It works most of the time, but you can get into annoying situations where the jar that you have moved into tomcat is trying to make an instance of a class in one of your web application jars, leading to ClassNotFoundException s being thrown. I used to do this, but stopped because of these problems. | Java EE Jar file sharing | [
"",
"java",
"tomcat",
"jsf",
"jakarta-ee",
""
] |
I've got this table. The table has a bunch of char fields, but the field in question (expiredate) contains a char on the test\_tmp table, and a datetime on the test table. (Table names have been changed to protect the clients.)
In the test\_tmp table, the field contains a Month-Date pair, like 'Aug 10' or 'Feb 20'. The code I'm using to insert the data is:
```
INSERT IGNORE INTO test (RECNUM, ORDERNUM, CREATEDATE, EXPIREDATE, FNAME, LNAME)
SELECT RECNUM, ORDERNUM, CREATEDATE,
CAST(CASE WHEN str_to_date(concat(expiredate, ' ', year(now())), '%b %d %Y') <= CURDATE()
THEN str_to_date(concat(expiredate, ' ', 1+year(now())), '%b %d %Y')
ELSE str_to_date(concat(expiredate, ' ', year(now())), '%b %d %Y') END AS DATETIME) AS EXPIREDATE, FNAME, LNAME FROM test_tmp
```
What's really puzzing is that if I run the 'SELECT' section of the query everything looks fine. But if I run the whole thing (truncating the test table first), every row contains NULL in expiredate. | Well, I just found the answer to my own question, finally.
Notice how I put the 'drupal' tag on the question? The query was going through Drupal... which requires you to escape the % character if you don't want it used to replace data. So, `str_to_date(concat(expiredate, ' ', year(now())), '%b %d %Y')` actually needed to be `str_to_date(concat(expiredate, ' ', year(now())), '%%b %%d %%Y')`.
Thanks for the suggestions, folks. | Sadly I can not set comments yet. That's why I have to write it here.
At the end of the SQL statement you have a ')' to much. Is there maybe more cut out while you copy/pasted this code? | Why is this mysql table producing a NULL in the datetime field? | [
"",
"sql",
"mysql",
"drupal",
"null",
""
] |
which is the best framework to develop a community web site.
For the MVC architecture, is there any disadvantage while using frameworks.
or is it better to develop that in a pure php with OOPs concept?
thanks in advance!! | Do you want an MVC framework or a CMS?
For MVC frameworks, there isn't simply the best. It's always about what you need, but here is a short overview of the most common [frameworks.](http://www.phpit.net/demo/framework%20comparison/chart.php)
If you're looking for a CMS I'd suggest [Drupal](http://www.drupal.org) for community like functionality.
> or is it better to develop that in a
> pure php with OOPs concept?
If you really need that last little bit of speed, do it in pure php...
I'd suggest, use a good stable Framework like [CakePHP](http://cakephp.org/), [symfony](http://www.symfony-project.org/) or [CodeIgniter](http://codeigniter.com/). It'll help you avoid a lot of mistakes you'd make if you do it all by yourself and it makes development (not the page) a lot faster. | I switched from pure PHP to [Django](http://www.djangoproject.com) (python) and I cannot tell you enough good stuff about it. Using an ORM and automatic admin system was key for me and have saved me tons and tons of tedious work.
If you don't want to learn a new language there're probably some very nice frameworks for PHP as well. | which is best framework or technolgy for a community site development? | [
"",
"php",
"frameworks",
""
] |
I have inherited an application that logs the results of certain daily commands that run on multiple hosts to an MS-SQL table. Now I've been asked to provide a view/query that displays the last log line per host to get an overview of the last results.
The table is similar to this:
```
------------------------------
|HOST |LAST_RUN |RESULT |
------------------------------
|SERVER1 |13-07-2009 |OK |
|SERVER2 |13-07-2009 |Failed |
|SERVER1 |12-07-2009 |OK |
|SERVER2 |12-07-2009 |OK |
|SERVER3 |11-07-2009 |OK |
------------------------------
```
In this case the query should output:
```
------------------------------
|HOST |LAST_RUN |RESULT |
------------------------------
|SERVER1 |13-07-2009 |OK |
|SERVER2 |12-07-2009 |Failed |
|SERVER3 |11-07-2009 |OK |
------------------------------
```
...as these are the last lines for each of the hosts.
I realise that it might be something simple I'm missing, but I just can't seem to get it right :-(
Thanks,
Mark. | Here's a quick version:
```
SELECT lt.Host, lt.Last_Run, lt.Results
from LogTable lt
inner join (select Host, max(Last_Run) Last_Run
from LogTable
group by Host) MostRecent
on MostRecent.Host = lt.Host
and MostRecent.Last_run = lt.Last_Run
```
This should work in most any SQL system. The ranking functions in SQL Server 2005 or 2008 might work a bit better. | ```
Select Host, Last_Run, Result from
(
select ROW_NUMBER() OVER (PARTITION BY Host ORDER BY Last_Run DESC) AS row_number,
Host, Last_Run, Result from Table1
) tempTable
where row_number = 1
``` | Get last log line per unique host from table | [
"",
"sql",
"sql-server-2005",
"t-sql",
""
] |
I'm making some controls which all have to share the same look and some common behavior, although they are meant for different kind of inputs. So I made a BaseClass which inherit from UserControl, and all my controls inherit from BaseClass.
However, if i add controls for BaseClass in the designer, such as a TableLayoutPanel, i can't access them when I'm designing the inherited classes. I see the TableLayoutPanel, but even though he is "protected", i can't modify it or put controls in it through the designer. I've no trouble accesing it by code, but i don't want to lose the ability to use the designer.
Right now, i simply removed all controls from BaseClass, added the layout and all the common controls in each of the inherited class, then use references to manipulate them inside BaseClass. But that doesn't satisfy me at all. Is there a way to make the designer work with inherited protected member controls ?
Environment : C#, .NET 3.5, Visual Studio 2008
EDIT to answer SLaks's suggestion. I tried setting a property, and although I'm not used to use them it doesn't seem to work. Here is the code i tried :
```
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public TableLayoutPanel TableLayoutPanel1
{
get { return tableLayoutPanel1;}
set { tableLayoutPanel1 = value;}
}
}
public partial class UserControl2 : UserControl1
{
public UserControl2()
{
InitializeComponent();
}
}
``` | When you try to access from the inherited control with the designer to the TableLayoutPanel declared in the base control, you're using a feature in WinForms called "Visual Inheritance".
Unfortunately TableLayoutPanel doesn't support visual inheritance:
<http://msdn.microsoft.com/en-us/library/ms171689%28VS.80%29.aspx>
That's why the TableLayoutPanel appears blocked in the inherited controls. | Try adding this attribute to the definition of the panel (this may or may not help):
```
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
``` | How to access inherited controls in the winforms designer | [
"",
"c#",
"winforms",
"visual-studio-2008",
""
] |
I'm currently writing about dynamic typing, and I'm giving an example of Excel interop. I've hardly done any Office interop before, and it shows. The [MSDN Office Interop tutorial](http://msdn.microsoft.com/en-us/library/dd264733(VS.100).aspx) for C# 4 uses the `_Worksheet` interface, but there's also a `Worksheet` interface. I've no idea what the difference is.
In my absurdly simple demo app (shown below) either works fine - but if best practice dictates one or the other, I'd rather use it appropriately.
```
using System;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
class DynamicExcel
{
static void Main()
{
var app = new Excel.Application { Visible = true };
app.Workbooks.Add();
// Can use Excel._Worksheet instead here. Which is better?
Excel.Worksheet workSheet = app.ActiveSheet;
Excel.Range start = workSheet.Cells[1, 1];
Excel.Range end = workSheet.Cells[1, 20];
workSheet.get_Range(start, end).Value2 = Enumerable.Range(1, 20)
.ToArray();
}
}
```
I'm trying to avoid doing a full deep-dive into COM or Office interoperability, just highlighting the new features of C# 4 - but I don't want to do anything really, really dumb.
(There may be something really, really dumb in the code above as well, in which case please let me know. Using separate start/end cells instead of just "A1:T1" is deliberate - it's easier to see that it's genuinely a range of 20 cells. Anything else is probably accidental.)
So, should I use `_Worksheet` or `Worksheet`, and why? | If I recall correctly -- and my memory on this is a bit fuzzy, it has been a long time since I took the Excel PIA apart -- it's like this.
An event is essentially a method that an object calls when something happens. In .NET, events are delegates, plain and simple. But in COM, it is very common to organize a whole bunch of event callbacks into interfaces. You therefore have two interfaces on a given object -- the "incoming" interface, the methods you expect other people to call on you, and the "outgoing" interface, the methods you expect to call on other people when events happen.
In the unmanaged metadata -- the type library -- for a creatable object there are definitions for three things: the incoming interface, the outgoing interface, and the coclass, which says "I'm a creatable object that implements this incoming interface and this outgoing interface".
Now when the type library is automatically translated into metadata, those relationships are, sadly, preserved. It would have been nicer to have a hand-generated PIA that made the classes and interfaces conform more to what we'd expect in the managed world, but sadly, that didn't happen. Therefore the Office PIA is full of these seemingly odd duplications, where every creatable object seems to have two interfaces associated with it, with the same stuff on them. One of the interfaces represents the interface to the coclass, and one of them represents the incoming interface to that coclass.
The \_Workbook interface is the incoming interface on the workbook coclass. The Workbook interface is the interface which represents the coclass itself, and therefore inherits from \_Workbook.
Long story short, I would use Workbook if you can do so conveniently; \_Workbook is a bit of an implementation detail. | If you look at the PIA assembly (Microsoft.Office.Interop.Excel) in [`Reflector`](http://www.red-gate.com/products/reflector/), the `Workbook` interface has this definition ...
```
public interface Workbook : _Workbook, WorkbookEvents_Event
```
`Workbook` is `_Workbook` but adds events. Same for `Worksheet` (sorry, just noticed you were not talking about `Workbooks`) ...
```
public interface Worksheet : _Worksheet, DocEvents_Event
```
`DocEvents_Event` ...
```
[ComVisible(false), TypeLibType((short) 0x10), ComEventInterface(typeof(DocEvents),
typeof(DocEvents_EventProvider))]
public interface DocEvents_Event
{
// Events
event DocEvents_ActivateEventHandler Activate;
event DocEvents_BeforeDoubleClickEventHandler BeforeDoubleClick;
event DocEvents_BeforeRightClickEventHandler BeforeRightClick;
event DocEvents_CalculateEventHandler Calculate;
event DocEvents_ChangeEventHandler Change;
event DocEvents_DeactivateEventHandler Deactivate;
event DocEvents_FollowHyperlinkEventHandler FollowHyperlink;
event DocEvents_PivotTableUpdateEventHandler PivotTableUpdate;
event DocEvents_SelectionChangeEventHandler SelectionChange;
}
```
I would say it's best bet to use `Worksheet`, but that's the difference. | Excel interop: _Worksheet or Worksheet? | [
"",
"c#",
"excel",
"com",
"interop",
""
] |
I'm trying to get the principles of doing jQuery-style function chaining straight in my head. By this I mean:
```
var e = f1('test').f2().f3();
```
I have gotten one example to work, while another doesn't. I'll post those below. I always want to learn the first principle fundamentals of how something works so that I can build on top of it. Up to now, I've only had a cursory and loose understanding of how chaining works and I'm running into bugs that I can't troubleshoot intelligently.
What I know:
1. Functions have to return themselves, aka "return this;"
2. Chainable functions must reside in a parent function, aka in jQuery, .css() is a sub method of jQuery(), hence jQuery().css();
3. The parent function should either return itself or a new instance of itself.
This example worked:
```
var one = function(num){
this.oldnum = num;
this.add = function(){
this.oldnum++;
return this;
}
if(this instanceof one){
return this.one;
}else{
return new one(num);
}
}
var test = one(1).add().add();
```
But this one doesn't:
```
var gmap = function(){
this.add = function(){
alert('add');
return this;
}
if(this instanceof gmap) {
return this.gmap;
} else{
return new gmap();
}
}
var test = gmap.add();
``` | In JavaScript Functions are first class Objects. When you define a function, it is the constructor for that function object. In other words:
```
var gmap = function() {
this.add = function() {
alert('add');
return this;
}
this.del = function() {
alert('delete');
return this;
}
if (this instanceof gmap) {
return this.gmap;
} else {
return new gmap();
}
}
var test = new gmap();
test.add().del();
```
By assigning the
```
new gmap();
```
to the variable test you have now constructed a new object that "inherits" all the properties and methods from the gmap() constructor (class). If you run the snippet above you will see an alert for "add" and "delete".
In your examples above, the "this" refers to the window object, unless you wrap the functions in another function or object.
Chaining is difficult for me to understand at first, at least it was for me, but once I understood it, I realized how powerful of a tool it can be. | Sadly, the direct answer has to be 'no'. Even if you can override the existing methods (which you probably can in many UAs, but I suspect cannot in IE), you'd still be stuck with nasty renames:
```
HTMLElement.prototype.setAttribute = function(attr) {
HTMLElement.prototype.setAttribute(attr) //uh-oh;
}
```
The best you could probably get away with is using a different name:
```
HTMLElement.prototype.setAttr = function(attr) {
HTMLElement.prototype.setAttribute(attr);
return this;
}
``` | How does basic object/function chaining work in javascript? | [
"",
"javascript",
"methods",
"chaining",
"method-chaining",
""
] |
Here is the thing. Right now I have this e-commerce web site where people can send a lot of pictures for their products. All the images are stored at Amazon's S3. When we need a thumbnail or something, I check over S3 if there is one available. If not, I process one and send it to S3 and display it on the browser. Every different sized thumbnail gets stored at S3, and checking the thumbnail availability at every request is kind of money consuming. I'm afraid I'll pay a lot once the site starts to get more attention (if it gets...).
Thinking about alternatives, I was thinking on keeping only the original images at S3 and process the images on the fly at every request. I imagine that in that way I would by on CPU usage, but I hasn't made any benchmarks to see how far can I go. The thing is that I wouldn't expend money making requests and storing more images on S3 and I could cache everything on the user's browser. I know it's not that safe to do that, so that is why I'm bringing this question here.
What do you think? How do you think I could solve this? | Keep a local cache of:
1. Which images are in S3
2. A cache of the most popular images
Then in both circumstances you have a local reference. If the image isn't in the local cache, you can check a local cache to see if it is in S3. Saves on S3 traffic for your most popular items and saves on latency when checking S3 for an item not in the local cache. | I would resize at the time of upload and store all version in S3.
For example if you have a larger image ( 1200x1200 ~200kb ) and create 3 resized version ( 300x300, 120x120, and 60x60 ) you only add about 16% or 32kb ( for my test image, YMMV ). Lets say you need to store a million images; that is roughly 30 GB more, or $4.5 extra a month. Flickr reported to have 2 billion images ( in 2007 ) that is ~$9k extra a month, not too bad if you are that big.
Another major advantage is you will be able to use Amazon's CloudFront. | Image caching vs. image processing in PHP and S3 | [
"",
"php",
"image",
"caching",
"amazon-s3",
"amazon-web-services",
""
] |
I am writing a plain vanilla c++ console app using VS 2008. When I create the project, the IDE gives me a choice of .net versions. There is no option for 'none'. When I look at the project properties page, the Targeted Framework has whatever value I chose and is greyed out.
When I try and run the app on a windows machine without the clr, it gives me a setup error and quits.
There is nothing in my code that has anything to do with .net. How can I escape the clutches of .net and the clr? | Make sure that you chose the "Win32 Console Application" project type. This will give you a C++ only project. Most of the other console options will bind the project to .Net. | How are you creating the project? If I start Visual Studio 2008 and go File / New / Project... / Other languages / Visual C++ / Win32 / Win32 Console Application, I get a plain old C++ project with no .net dependency. | VS 2008 C++ how to make a project without .net dependency | [
"",
"c++",
"visual-studio",
"visual-studio-2008",
""
] |
Normally in a C or C++ program there's a main loop/function, usually `int main ()`. Is there a similar function that I can use in android Java development? | As far as an Android program is concerned there is no `main()`.
There is a UI loop that the OS runs that makes calls to methods you define or override in your program. These methods are likely called from/defined in `onCreate()`, `onStart()`, `onResume()`, `onReStart()`, `onPause()`, `onStop()`, or `onDestroy()`. All these methods may be overriden in your program.
The fundamental issue is that the OS is designed to run in a resource constrained environment. Your program needs to be prepared to be halted and even completely stopped whenever the OS needs more memory (this is a multitasking OS). In order to handle that your program needs to have some of all of the functions listed above.
The [Activity lifecycle](http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle) describes this best (your program is one or more Activities, think of an Activity as a screen).
Bottom line: Your program 'starts' at `onCreate()` through `onResume()` but the OS is running the loop. Your program provides callbacks to the OS to handle whatever the OS sends to it. If you put a long loop at any point in your program it will appear to freeze because the OS (specifically the UI thread) is unable to get a slice of time. Use a thread for long loops. | In Android environment, there is no main(). The OS relies on the manifest file to find out the entry point, an activity in most case, into your application.
You should read <http://developer.android.com/guide/topics/fundamentals.html> for more detail. | Is there a function in Android analogous to "int main" in C/C++ which contains the program's main loop? | [
"",
"java",
"android",
"activity-lifecycle",
""
] |
How can I display a newline in `JLabel`?
For example, if I wanted:
> Hello World!
> blahblahblah
This is what I have right now:
```
JLabel l = new JLabel("Hello World!\nblahblahblah", SwingConstants.CENTER);
```
This is what is displayed:
> Hello World!blahblahblah
Forgive me if this is a dumb question, I'm just learning some Swing basics... | Surround the string with `<html></html>` and break the lines with `<br/>`.
```
JLabel l = new JLabel("<html>Hello World!<br/>blahblahblah</html>", SwingConstants.CENTER);
``` | You can try and do this:
```
myLabel.setText("<html>" + myString.replaceAll("<","<").replaceAll(">", ">").replaceAll("\n", "<br/>") + "</html>")
```
The advantages of doing this are:
* It replaces all newlines with `<br/>`, without fail.
* It automatically replaces eventual `<` and `>` with `<` and `>` respectively, preventing some render havoc.
What it does is:
* `"<html>" +` adds an opening `html` tag at the beginning
* `.replaceAll("<", "<").replaceAll(">", ">")` escapes `<` and `>` for convenience
* `.replaceAll("\n", "<br/>")` replaces all newlines by `br` (HTML line break) tags for what you wanted
* ... and `+ "</html>"` closes our `html` tag at the end.
P.S.: I'm very sorry to wake up such an old post, but whatever, you have a reliable snippet for your Java! | Newline in JLabel | [
"",
"java",
"user-interface",
"swing",
"formatting",
"jlabel",
""
] |
If I have two `byte[]` arrays, is there a built-in function to compare them ala C's `memcmp()` ? | There's Arrays.equals().
I don't know whether the JVM implementation actually optimizes this if a corresponding instruction exists in the hardware, but I doubt it.
Also, if I remember my C correctly, strcmp works up to a null terminator (making it useful for C strings), The Arrays version will compare the entire array since Java programmers rarely bother with null-terminated arrays. You could easily write your own function, though, if you care about the null-terminator. | Memcmp returns an int, less than, equal to, or greater than zero if the first n bytes of s1 is found, respectively, to be less than, to match, or be greater than the first n bytes of s2. Equals returns a boolean. It's not the same function. In addition, memcmp compares bytes as unsigned chars.
I think this could work:
```
public int memcmp(byte b1[], byte b2[], int sz){
for(int i = 0; i < sz; i++){
if(b1[i] != b2[i]){
if(b1[i] >= 0 && b2[i] >= 0)
return b1[i] - b2[i];
if(b1[i] < 0 && b2[i] >= 0)
return 1;
if(b2[i] < 0 && b1[i] >= 0)
return -1;
if(b1[i] < 0 && b2[i] < 0){
byte x1 = (byte) (256 + b1[i]);
byte x2 = (byte) (256 + b2[i]);
return x1 - x2;
}
}
}
return 0;
}
```
(edit)
In fact, the 2's complement part is not necessary:
```
public static int memcmp(byte b1[], byte b2[], int sz){
for(int i = 0; i < sz; i++){
if(b1[i] != b2[i]){
if((b1[i] >= 0 && b2[i] >= 0)||(b1[i] < 0 && b2[i] < 0))
return b1[i] - b2[i];
if(b1[i] < 0 && b2[i] >= 0)
return 1;
if(b2[i] < 0 && b1[i] >=0)
return -1;
}
}
return 0;
}
``` | equivalent of memcmp() in Java? | [
"",
"java",
"c",
"posix",
"libc",
"memcmp",
""
] |
I need to get the last day of the month given as a date in SQL. If I have the first day of the month, I can do something like this:
```
DATEADD(DAY, DATEADD(MONTH,'2009-05-01',1), -1)
```
But does anyone know how to generalize it so I can find the last day of the month for any given date? | Here's my version. No string manipulation or casting required, just one call each to the `DATEADD`, `YEAR` and `MONTH` functions:
```
DECLARE @test DATETIME
SET @test = GETDATE() -- or any other date
SELECT DATEADD(month, ((YEAR(@test) - 1900) * 12) + MONTH(@test), -1)
```
---
This works by taking the number of months that have passed since the initial date in SQL's date system (1/1/1990), then adding that number of months to the date "-1" (12/31/1899) using the DATEADD function, which returns a proper datetime at the corresponding month's end (that of the date you specified). It relies on the fact that December always ends on the 31st and there are no months longer than that. | From SQL Server 2012 you can use the [EOMONTH](https://msdn.microsoft.com/library/hh213020.aspx) function.
> Returns the last day of the month that contains the specified date,
> with an optional offset.
**Syntax**
```
EOMONTH ( start_date [, month_to_add ] )
```
> How ... I can find the last day of the month for any given date?
```
SELECT EOMONTH(@SomeGivenDate)
``` | Get the last day of the month in SQL | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm setting up a C++ project, on Ubuntu x64, using Eclipse-CDT. I'm basically doing a hello world and linking to a commerical 3rd party library.
I've included the header files, linked to their libraries, but I still get linker errors. Are there some possible problems here other than the obvious (e.g. I am 99% sure I'm linking to the correct library).
1. Is there a way to confirm the static libraries I am linking to are 64bit?
2. Is there a way to confirm that the library has the class (and methods) I am expecting it to have?
Eclipse says:
```
Building target: LinkProblem
Invoking: GCC C++ Linker
g++ -L/home/notroot/workspace/somelib-3/somelib/target/bin -o"LinkProblem" ./src/LinkProblem.o -lsomelib1 -lpthread -lsomelib2 -lsomelib3
./src/LinkProblem.o: In function `main':
/home/notroot/workspace/LinkProblem/Debug/../src/LinkProblem.cpp:17: undefined reference to `SomeClass::close()'
./src/LinkProblem.o: In function `SomeOtherClass':
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:148: undefined reference to `SomeClass::SomeClass()'
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:148: undefined reference to `vtable for SomeOtherClass'
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:151: undefined reference to `SomeClass::~SomeClass()'
./src/LinkProblem.o: In function `~SomeOtherClass':
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:140: undefined reference to `vtable for SomeOtherClass'
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:140: undefined reference to `SomeClass::~SomeClass()'
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:140: undefined reference to `SomeClass::~SomeClass()'
collect2: ld returned 1 exit status
make: *** [LinkProblem] Error 1
``` | Assuming those methods are in one of the libs it looks like an ordering problem.
When linking libraries into an executable they are done in the order they are declared.
Also the linker will only take the methods/functions required to resolve currently outstanding dependencies. If a subsequent library then uses methods/functions that were not originally required by the objects you will have missing dependencies.
How it works:
* Take all the object files and combine them into an executable
* Resolve any dependencies among object files.
* For-each library in order:
+ Check unresolved dependencies and see if the lib resolves them.
+ If so load required part into the executable.
Example:
Objects requires:
* Open
* Close
* BatchRead
* BatchWrite
Lib 1 provides:
* Open
* Close
* read
* write
Lib 2 provides
* BatchRead (but uses lib1:read)
* BatchWrite (but uses lib1:write)
If linked like this:
> gcc -o plop plop.o -l1 -l2
Then the linker will fail to resolve the read and write symbols.
But if I link the application like this:
> gcc -o plop plop.o -l2 -l1
Then it will link correctly. As l2 resolves the BatchRead and BatchWrite dependencies but also adds two new ones (read and write). When we link with l1 next all four dependencies are resolved. | This linker error usually (in my experience) means that you've overridden a virtual function in a child class with a declaration, but haven't given a definition for the method. For example:
```
class Base
{
virtual void f() = 0;
}
class Derived : public Base
{
void f();
}
```
But you haven't given the definition of f. When you use the class, you get the linker error. Much like a normal linker error, it's because the compiler knew what you were talking about, but the linker couldn't find the definition. It's just got a very difficult to understand message. | GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()' | [
"",
"c++",
"linker",
"g++",
"eclipse-cdt",
""
] |
I'm new to Scala, so I may be off base on this, I want to know if the problem is my code. Given the Scala file httpparse, simplified to:
```
object Http {
import java.io.InputStream;
import java.net.URL;
def request(urlString:String): (Boolean, InputStream) =
try {
val url = new URL(urlString)
val body = url.openStream
(true, body)
}
catch {
case ex:Exception => (false, null)
}
}
object HTTPParse extends Application {
import scala.xml._;
import java.net._;
def fetchAndParseURL(URL:String) = {
val (true, body) = Http request(URL)
val xml = XML.load(body) // <-- Error happens here in .load() method
"True"
}
}
```
Which is run with (URL doesn't matter, this is a joke example):
```
scala> HTTPParse.fetchAndParseURL("http://stackoverflow.com")
```
The result invariably:
```
java.io.IOException: Server returned HTTP response code: 503 for URL: http://www.w3.org/TR/html4/strict.dtd
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1187)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:973)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startEntity(XMLEnti...
```
I've seen the [Stack Overflow thread](https://stackoverflow.com/questions/998280/dtd-download-error-while-parsing-xhtml-document-in-xom) on this with respect to Java, as well as the [W3C's System Team Blog entry](http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic) about not trying to access this DTD via the web. I've also isolated the error to the XML.load() method, which is a Scala library method as far as I can tell.
**My Question: How can I fix this?** Is this something that is a by product of my code (cribbed from [Raphael Ferreira's post](http://blogs.oracle.com/rafaelferreira/entry/pragmatic_scala)), a by product of something Java specific that I need to address as in [the previous thread](https://stackoverflow.com/questions/998280/dtd-download-error-while-parsing-xhtml-document-in-xom), or something that is Scala specific? Where is this call happening, and is it a bug or a feature? (*"Is it me? It's her, right?"*) | It works. After some detective work, the details as best I can figure them:
Trying to parse a developmental RESTful interface, I build the parser and get the above (rather, a similar) error. I try various parameters to change the XML output, but get the same error. I try to connect to an XML document I quickly whip up (cribbed stupidly from the interface itself) and get the same error. Then I try to connect to anything, just for kicks, and get the same (again, likely only similar) error.
I started questioning whether it was an error with the sources or the program, so I started searching around, and it looks like an ongoing issue- with many Google and SO hits on the same topic. This, unfortunately, made me focus on the upstream (language) aspects of the error, rather than troubleshoot more downstream at the sources themselves.
Fast forward and the parser suddenly works on the *original* XML output. I confirmed that there was some additional work has been done server side (just a crazy coincidence?). I don't have either earlier XML but suspect that it is related to the document identifiers being changed.
Now, the parser works fine on the RESTful interface, as well any well formatted XML I can throw at it. It also fails on all XHTML DTD's I've tried (e.g. www.w3.org). This is contrary to what @SeanReilly expects, but seems to jive with [what the W3 states](http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic).
I'm still new to Scala, so can't determine if I have a special, or typical case. Nor can I be assured that this problem won't re-occur for me in another form down the line. It does seem that pulling XHTML will continue to cause this error unless one uses a solution similar to those suggested by @GClaramunt $ @J-16 SDiZ have used. I'm not really qualified to know if this is a problem with the language, or my implementation of a solution (likely the later)
For the immediate timeframe, I suspect that the best solution would've been for me to ensure that it was *possible* to parse that XML source-- rather than see that other's have had the same error and assume there was a functional problem with the language.
Hope this helps others. | I've bumped into the SAME issue, and I haven't found an elegant solution (I'm thinking into posting the question to the Scala mailing list) Meanwhile, I found a workaround: implement your own SAXParserFactoryImpl so you can set the f.setFeature("<http://apache.org/xml/features/disallow-doctype-decl>", true); property. The good thing is it doesn't require any code change to the Scala code base (I agree that it should be fixed, though).
First I'm extending the default parser factory:
```
package mypackage;
public class MyXMLParserFactory extends SAXParserFactoryImpl {
public MyXMLParserFactory() throws SAXNotRecognizedException, SAXNotSupportedException, ParserConfigurationException {
super();
super.setFeature("http://xml.org/sax/features/validation", false);
super.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false);
super.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
super.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
}
}
```
Nothing special, I just want the chance to set the property.
**(Note: that this is plain Java code, most probably you can write the same in Scala too)**
And in your Scala code, you need to configure the JVM to use your new factory:
```
System.setProperty("javax.xml.parsers.SAXParserFactory", "mypackage.MyXMLParserFactory");
```
Then you can call XML.load without validation | Is Scala/Java not respecting w3 "excess dtd traffic" specs? | [
"",
"java",
"xml",
"scala",
"w3c",
"dtd",
""
] |
I want to get the list of removable disk in c#. I want to skip the local drives.
Because i want the user to save the file only in removable disk. | You will need to reference `System.IO` for this method.
```
var driveList = DriveInfo.GetDrives();
foreach (DriveInfo drive in driveList)
{
if (drive .DriveType == DriveType.Removable)
{
//Add to RemovableDrive list or whatever activity you want
}
}
```
Or for the LINQ fans:
```
var driveList = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Removable);
```
**Added**
As for the Saving part, as far as I know I don't think you can restrict where the user is allowed to save to using a SaveFileDialog, but you could complete a check after you have shown the SaveFileDialog.
```
if(saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (CheckFilePathIsOfRemovableDisk(saveFileDialog.FileName) == true)
{
//carry on with save
}
else
{
MessageBox.Show("Must save to Removable Disk, location was not valid");
}
}
```
**OR**
The best option would be to create your own Save Dialog, which contains a tree view, only showing the removable drives and their contents for the user to save to! I would recommend this option.
Hope this helps | How about:
```
var removableDrives = from d in System.IO.DriveInfo.GetDrives()
where d.DriveType == DriveType.Removable;
``` | How to get the list of removable disk in c#? | [
"",
"c#",
".net",
"removable-storage",
"driveinfo",
""
] |
[using SQL Server 2005]
I have a table full of users, I want to assign every single user in the table (16,000+) to a course by creating a new entry in the assignment table as well as a new entry in the course tracking table so their data can be tracked. The problem is I do no know how to do a loop in SQL because I don't think you can but there has got to be a way to do this...
FOR EACH user in TABLE
write a row to each of the two tables with userID from user TABLE...
how would I do this? please help! | Something like:
```
insert into CourseAssignment (CourseId, StudentId)
select 1 -- whatever the course number is
, StudendId
from Student
``` | You'd do this with 2 insert statements. You'd want to wrap this with a [transaction](http://msdn.microsoft.com/en-us/library/ms188929(SQL.90).aspx) to ensure consistency, and may want to double-check our [isolation level](http://msdn.microsoft.com/en-us/library/ms173763(SQL.90).aspx) to make sure that you get a consistent read from the users table between the 2 queries (take a look at SNAPSHOT or SERIALIZABLE to avoid phantom reads).
```
BEGIN TRAN
INSERT Courses
(UserID, CourseNumber, ...)
SELECT UserID, 'YourCourseNumberHere', ...
FROM Users
INSERT Assignments
(UserID, AssignmentNumber, ...)
SELECT UserID, 'YourAssignmentNumberHere', ...
FROM Users
COMMIT TRAN
``` | Help me with this SQL: 'DO THIS for ALL ROWS in TABLE' | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
I need to implement something. Something that could do some certain task in my program. For example every ten seconds, write something into a log in a file.
Of course it suppose to run in a background thread.
Where should I dig? I am not so familiar with multithreading. I've heard about BackgroundWorker class, but I'm not sure if it is appropriate here.. | Use System.Threading.Timer, it will run a task in a ThreadPoool thread. That is the most efficient way for this.
Here is an example, every 10 seconds:
```
Timer aTimer = new System.Threading.Timer(MyTask, null, 0, 10000);
static void MyTask(object state)
{
...
}
``` | Actually for WPF DispatcherTimer would be much better than the Async timer. | Sort of scheduler | [
"",
"c#",
"wpf",
"backgroundworker",
""
] |
Is System.currentTimeMillis() the best measure of time performance in Java? Are there any gotcha's when using this to compare the time before action is taken to the time after the action is taken? Is there a better alternative? | I hope not - it's what I use when i don't use [`nanoTime()`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#nanoTime()). | besides `System.nanoTime()`, JMX is probably the best viable option:
```
java.lang.management.ManagementFactory.getThreadMXBean()
```
you can query current thread cpu time (measured in nano seconds but not with nano seconds precision, as for `System.nanoTime`()) | Is System.currentTimeMillis() the best measure of time performance in Java? | [
"",
"java",
"performance",
"big-o",
""
] |
vs2005 support
::stdext::hash\_map
::std::map.
however it seems ::stdext::hash\_map's insert and remove OP is slower then ::std::map in my test.
( less then 10000 items)
Interesting....
Can anyone offored a comparision article about them? | It is not just about insertion and removal. You must consider that memory is allocated differently in a hash\_map vs map and you every time have to calculate the hash of the value being searched.
I think this Dr.Dobbs article will answer your question best:
[C++ STL Hash Containers and Performance](http://www.ddj.com/cpp/198800559?pgno=1) | Normally you look to the complexities of the various operations, and that's a good guide: amortized O(1) insert, O(1) lookup, delete for a hashmap as against O(log N) insert, lookup, delete for a tree-based map.
However, there are certain situations where the complexities are misleading because the constant terms involved are extreme. For example, suppose that your 10k items are keyed off strings. Suppose further that those strings are each 100k characters long. Suppose that different strings typically differ near the beginning of the string (for example if they're essentially random, pairs will differ in the first byte with probability 255/256).
Then to do a lookup the hashmap has to hash a 100k string. This is O(1) in the size of the collection, but might take quite a long time since it's probably O(M) in the length of the string. A balanced tree has to do log N <= 14 comparisons, but each one only needs to look at a few bytes. This might not take very long at all.
In terms of memory access, with a 64 byte cache line size, the hashmap loads over 1500 sequential lines, and does 100k byte operations, whereas the tree loads 15 random lines (actually probably 30 due to the indirection through the string) and does 14 \* (some small number) byte operations. You can see that the former might well be slower than the latter. Or it might be faster: how good are your architecture's FSB bandwidth, stall time, and speculative read caching?
If the lookup finds a match, then of course in addition to this both structures need to perform a single full-length string comparison. Also the hashmap might do additional failed comparisons if there happens to be a collision in the bucket.
So assuming that failed comparisons are so fast as to be negligible, while successful comparisons and hashing ops are slow, the tree might be roughly 1.5-2 times as fast as the hash. If those assumptions don't hold, then it won't be.
An extreme example, of course, but it's pretty easy to see that on your data, a particular O(log N) operation might be considerably faster than a particular O(1) operation. You are of course right to want to test, but if your test data is not representative of the real world, then your test results may not be representative either. Comparisons of data structures based on complexity refer to behaviour in the limit as N approaches infinity. But N doesn't approach infinity. It's 10000. | hash_map and map which is faster? less than 10000 items | [
"",
"c++",
"stl",
"dictionary",
"hashmap",
""
] |
I am currently writing an application where the user has, at some point, to click a button which have been generated at run time. I know how to do it when writing all my swing code from scratch, but I'd like to take advantage of Netbeans' visual editor.
The generated UI code goes into an initComponents() method I can't modify since it is regenerated automatically from the visual form.
I'd like to have a panel I place at design time using the visual editor in which I could add the buttons at run time so that they fit nicely in the layout, but I don't know how to access the panel in a convenient way. Besides, there may be another method than using a panel.
So basically :
* How do I locate a Swing component at run time ?
* Is there a better way of integrating components created at run time in a generated Swing UI ?
Thanks for your help. | NetBeans-generated GUI classes store all the components in private variables. You can add a method into the generated class that returns the panel, and it will remain even as you do additional design.
If you're going to use a generated UI, then it's probably best to use a JPanel within that UI to "carve out" space for your own components. Otherwise, you'll have to worry about how your components affect the layout of the components placed by the UI. | Just because you are using NetBeans generated GUI classes doesn't mean that you have to use the Group layout for the panels. I find that switching it to a BorderLayout helps especially in cases where I want to add some dynamic user interface code. | How do I add components at run time to a Swing UI created with Netbeans visual editor? | [
"",
"java",
"swing",
"netbeans",
"runtime",
""
] |
I was wondering if I could do pre/post function call in C++ somehow. I have a wrapper class with lots of functions, and after every wrapper function call I should call another always the same function.
So I do not want to put that postFunction() call to every single one of the functions like this:
```
class Foo {
f1();
f2();
f3();
.
.
.
fn();
}
void Foo::f1() {
::f1();
postFunction();
}
void Foo::f2() {
::f2();
postFunction();
}
etc.
```
Instead I want that postFunction call to come automatically when I call some Foo's member function. Is it possible? It would help maintenance.. | Might be a case for [RAII](http://en.wikipedia.org/wiki/RAII)! Dun-dun-dunnn!
```
struct f1 {
f1(Foo& foo) : foo(foo) {} // pre-function, if you need it
void operator()(){} // main function
~f1() {} // post-function
private:
Foo& foo;
}
```
Then you just have to make sure to create a new temporary f1 object every time you wish to call the function. Reusing it will obviously mean the pre/post functions don't get called every time.
Could even wrap it like this:
```
void call_f1(Foo& foo) {
f1(foo)(); // calls constructor (pre), operator() (the function itself) and destructor (post)
}
```
You might experiment a bit with other ways of structuring it, but in general, see if you can't get constructors/destructors to do the heavy lifting for you.
Roman M's approach might be a good idea as well. Write one generic wrapper, which takes a functor or function pointer as its argument. That way, it can call pre/post functions before and after calling its argument | Implement a wrapper that will take a function pointer as an argument, and will call pre\post function before the function call.
```
Foo::caller ( function* fp ) {
preCall ();
fp (...);
postCall ();
}
``` | Pre/Post function call implementation | [
"",
"c++",
"function",
""
] |
I have a **large list** of email addresses, and I need to determine which of them are *not* already in my database. Can I construct a query that will tell me this information?
I am using **SQL Server 2000**, if it requires non-standard extensions | make a temporary table, load the e-mailaddresses into the temporary table and then do a NOT IN query such as
```
SELECT emailaddress FROM temp_table WHERE emailaddress NOT IN (SELECT emailaddress FROM table)
```
you could extend that with an INSERT INTO | For a huge list, I would recommend loading that list into a second table (e.g., `TEMP_EMAIL_ADDRESS`), then use:
```
SELECT
EMAIL
FROM
TEMP_EMAIL_ADDRESS
WHERE
EMAIL NOT IN (SELECT EMAIL FROM EMAIL_ADDRESS)
```
**Data Transformation**
If your data is in a text file named **emails.txt** (one row per line), you can create the insert statements using the following DOS command:
```
FOR /F %i IN (emails.txt) DO echo INSERT INTO TEMP_EMAIL_ADDRESS (EMAIL) VALUES ('%i') >> insert-email.sql
```
That command will create a new file called **insert-email.sql** in the current directory, containing all the inserts you need to inject the existing list of e-mail addresses into the database. | SQL Query for information *not* in database | [
"",
"sql",
"sql-server",
""
] |
I'm using Eclipse to learn to develop Android applications in Java. I haven't used Eclipse before.
The project I'm trying to use (supplied by OReilly as part of 'Android Application Development') is MJAndroid. When attempting to run the project, the Run fails, and the Problems tab mentions com.java.Object can't be found, and Eclipse asks me to check the build path. Clicking
Properties -> Java Build Path -> Libraries, the message 'Unable to get system library for the project' is displayed.
On a working project, Properties -> Java Build Path -> Libraries has an entry for Android 1.1, which if I click Edit, has the classpath container path of com.android.ide.eclipse.adt.ANDROID\_FRAMEWORK.
It seems a simple matter of adding the correct container path to my non-working project. However Eclipse seems determined to make this as difficult as possible. No matter what I chose to add - jars, externals jars, variables, libraries, class folders, external class folders, nothing seems to take the form of 'com.android.ide.eclipse.adt.ANDROID\_FRAMEWORK' that the 'Android 1.1' entry on the working app has.
How can I add this namespace to my project so it resembles the working one?
I'm quite sure it's a problem with Eclipse's somewhat odd user interface. Frankly there' nothing I'd prefer more than a file to modify and set such information - my background is in Python, and the whole eclipse environment seems an unnecessary burden. | I had faced the same issue when I imported a sample code downloaded from the internet. I am using android sdk 1.5 with 0.9 ADT plugins. Here is a simpler way to fix the andoid library reference issues
* Right click on the project which has
issues and select properties
* Select the appropriate Android build
(1.1, 1.5 or 1.5 with google api) and
say ok
* Again right click on the project and
select "Android Tools > Fix Project
Properties"
* Fix the imports once (if required)
* Refresh the project and you should be
ready to go without any manual
editing | I faced this same problem after importing a project through GIT. The problem was that I didn't have the same target android platform installed, and the build path somehow got corrupted.
The first obvious thing i did was changing the target sdk in the project.properties, but even after cleaning up the project and Android Tools > Fix Project Properties, it didn't help and I was still getting the build error.
My solution after wasting close to 1 hour trying to figure this out?
```
RESTART ECLIPSE
```
Everything worked fine after that. Eclipse is pretty fickle. Only through years of experience you'll then understand her well. :) | Android Eclipse Classpath - want to add classpath container path but eclipse won't let me | [
"",
"java",
"android",
"eclipse",
"classpath",
""
] |
How do I get the version attribute of a file?
I tried the "Version" prop but it gives me the same number for all files
My Code:
```
while (getNextEntry)
{
ZipEntry entry = inStream.GetNextEntry();
getNextEntry = (entry != null);
if (getNextEntry)
{
string fileType = Path.GetExtension(entry.Name);
string version = "unavailable"; // entry.Version.ToString();
// etc ...
}
}
``` | This is correct behavior. I am not familiar with SharpZipLib, but in .zip format itself, field version contains version of PkZip software needed to extract this particular file (or version of software that created this file). And, as usually, entire zip file created with one tool, so such field will contain the same version.
Again, version in zip is not file version, but version of software that packed this file.
You can read more about zip format [here](http://www.pkware.com/documents/casestudies/APPNOTE.TXT) (Main source of information about zip format). | The version in the zip entry is the "version needed to extract", and it refers to the version of the ZIP spec that the unzipping tool must support, in order to properly extract that entry. This is different than the version of the tool that packed the zip. Also, this number is often the same for all entries in a zip archive, but that isn't a requirement. Different entries can have different features enabled - the most common variations are encryption and zip64 encoding. The first entry may be unencrypted in which case the version-needed-to-extract will be 20. The next entry may use zip64 extensions, in which case the version-needed-to-extract will be 45.
This version number is mostly interesting when building a tool or libbrary that packs or unpacks zips. If you are *using* a zip library, you shouldn't have to care about it. The library should take care of it for you. | SharpZipLib ~ File Version | [
"",
"c#",
"zip",
"sharpziplib",
""
] |
What is the best way to name variables which contain multiple words? After going through lots of projects available in the [CakePHP forge](http://cakeforge.org/), I have noticed people use either camelCase, underscores or camelCase for variables and underscores for data sent to the view.
An example of the last one would be:
```
$activeSites = $this->Site->find('all',array('conditions'=>array('Site.active' => '1'), 'recursive' => -1));
$this->controller->set('active_sites', activeSites);
``` | As most people will tell you, there is not "best way" to name variables, other than to be consistent. Decide the naming convention you like the most, and stick to it. If you're continuing on a project, keep the naming convention that is already there. That is all the advice I can give you. | According to the naming conventions used for CakePHP itself (<http://book.cakephp.org/view/509/Coding-Standards#Variables-609>), variables are named in the following way:
> Normal variables should start with a lowercase letter, and should be written in camelBack in case of multiple words. | Variable naming conventions in CakePHP | [
"",
"php",
"cakephp",
"naming-conventions",
""
] |
After three years working on a C++ project, the executable has grown to 4 MB. I'd like to see where all this space is going. Is there a tool that could report what the biggest space hogs are? It would be nice to see the size by class (all functions in a class), by template (all instantiations), and by library (how much belongs to the C standard library and STL? how much for each library in the exe?)
Edit: Note, I am using Visual C++ on Windows. | **In Linux**, you can use [`nm`](http://linux.die.net/man/1/nm) to show all symbols in the executable and to sort them in reverse order by size:
```
$ nm -CSr --size-sort <exe>
```
Options:
* **`-C`** demangles C++ names.
* **`-S`** shows size of symbols.
* **`--size-sort`** sorts symbols by size.
* **`-r`** reverses the sort.
If you want to get the results per namespace or per class, you can just `grep` the output for '`namespace::`', '`namespace::class_name::`', *etc.*.
If you only want to see symbols that are defined *in* the executable (not ones defined elsewhere, like in libraries) then add `--defined-only`. Sorting by size should take care of this, though, since undefined symbols aren't going to have a size.
**For Windows**, you should still be able to use `nm` on your binary files, since `nm` supports [COFF](http://en.wikipedia.org/wiki/COFF) binaries. You can install `nm` via cygwin, or you could copy your windows executable to a linux box and run `nm` on it there.
You could also try [`dumpbin`](http://msdn.microsoft.com/en-us/library/c1h23y6c(VS.71).aspx), which dumps info about a binary on Windows. You can get info on symbols with the `/SYMBOLS` switch, but it doesn't look like it directly provides information about their size. | In Windows under Visual Studio compiles, this information is in your .map file (it'll be near the .pdb).
**ADDED**: To convert the decorated names found in the .map file to something more human-readable, you can use the [undname.exe](http://msdn.microsoft.com/en-us/library/5x49w699.aspx) utility included with Visual Studio. It accepts individual names on the commandline or you can feed it a .map file.
For example,
```
Microsoft (R) C++ Name Undecorator
Copyright (C) Microsoft Corporation. All rights reserved.
Undecoration of "?push_back@?$mini_vector@U?$Point@U?$FixedPoint@$0O@H@Math@@@Math@@$05@@QAAXABU?$Point@U?$FixedPoint@$0O@H@Math@@@Math@@@Z" is
"public: void __cdecl mini_vector<struct Math::Point<struct Math::FixedPoint<14,int> >,6>::push_back(struct Math::Point<struct Math::FixedPoint<14,int> > const &)"
``` | Is there a "function size profiler" out there? | [
"",
"c++",
"function",
"size",
"profiler",
""
] |
I'm trying to follow Java's JDBC tutorials to write a Java program that can connect to SQL Server 2008. I'm getting lost at the point of making a connection.
The following snippet is from the tutorial:
```
InitialContext ic = new InitialContext();
DataSource ds = ic.lookup("java:comp/env/jdbc/myDB");
Connection con = ds.getConnection();
DataSource ds = (DataSource) org.apache.derby.jdbc.ClientDataSource()
ds.setPort(1527);
ds.setHost("localhost");
ds.setUser("APP")
ds.setPassword("APP");
Connection con = ds.getConnection();
```
There's no explanation of what comp/env/jdbc/myDB should point to, and I don't know how I should choose a port. Also, the object ds seems to be defined twice.
I'm using the `JSQLDataSource` driver, for the record. Can anyone point me in the right direction here?
<http://java.sun.com/docs/books/tutorial/jdbc/basics/connecting.html> | Start with the [JDBC tutorial](http://java.sun.com/docs/books/tutorial/jdbc/index.html) or the [Microsoft docs](http://support.microsoft.com/kb/313100).
and this:
```
String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
Class.forName(driver);
String url = "jdbc:microsoft:sqlserver://host:1433/database";
Connection conn = DriverManager.getConnection(url, "username", "password");
```
Fill in your values for host, database, username, and password. The default port for SQL server is 1433.
UPDATE: Good point below. JDBC drivers can be had from both Microsoft and jTDS. I prefer the latter.
JNDI lookups have to do with Java EE app servers that support connection pooling. You can ask the app server to create a pool of connections, which can be an expensive thing to do, and loan them out to clients like library books as needed.
If you aren't using a Java EE app server or connection pooling, you have to create the connection on your own. That's where manual processes and DriverManager come in.
EXPLANATION: As for why the Sun tutorial shows DataSource twice, I'd say it's a case of poor editing. If you look above the code sample it says you can get a DataSource "by lookup or manually". The code snippet below shows both together, when it should be one or the other.
You know it's an inadvertent error because there's no way the code as written could compile. You have "ds" declared twice.
So it should read "...lookup", followed by its code snippet, and then "...manually", followed by its code snippet. | I'm not sure anyone above has really answered the question.
I found [this microsoft sample useful](http://technet.microsoft.com/en-us/library/aa342342.aspx).
The key information in there is really that the class you need is **SQLServerDataSource**
that is basically a configuration object - you use it something like this:
```
SQLServerDataSource dataSource = new SQLServerDataSource();
dataSource.setUser("aUser");
dataSource.setPassword("password");
dataSource.setServerName("hostname");
dataSource.setDatabaseName("db");
```
You would then call
```
dataSource.getConnection();
```
to get a connection object which is basically the thing you use to talk to the database.
Use
```
connection.prepareStatement("some sql with ? substitutions");
```
to make something for firing off sql and:
```
connection.prepareCall
```
for calling stored procedures. | How do you configure a DataSource in Java to connect to MS SQL Server? | [
"",
"java",
"sql-server",
"datasource",
""
] |
I am checking out the code in the reflector, but I haven't yet found out how it can enumerate through a collection backwards?
Since there is no count information, and enumeration always starts from the "start" of the collection, right?
Is it a drawback in the .NET framework? Is the cost higher than regular enumeration? | In short, it buffers everything and then walks through it backwards. Not efficient, but then, neither is OrderBy from that perspective.
In LINQ-to-Objects, there are buffering operations (Reverse, OrderBy, GroupBy, etc) and non-buffering operations (Where, Take, Skip, etc).
---
As an example of a non-buffering `Reverse` implementation using `IList<T>`, consider:
```
public static IEnumerable<T> Reverse<T>(this IList<T> list) {
for (int i = list.Count - 1; i >= 0; i--) {
yield return list[i];
}
}
```
Note that this is still a little susceptible to bugs if you mutate the list while iterating it... so don't do that ;-p | It works by copying the underlying IEnumerable<T> to an array, then enumerating over that array backward. If the underlying IEnumerable<T> implements ICollection<T> (like T[], List<T>, etc.), then the copy step is skipped and the enumerator just iterates over the underlying collection directly.
For more information, check out System.Linq.Buffer<TElement> in Reflector.
Edit: The underlying collection is always copied, even if it's an ICollection<TElement>. This prevents changes in the underlying collection from being propagated by the Buffer<TElement>. | How does IEnumerable<T>.Reverse work? | [
"",
"c#",
".net",
"linq",
"collections",
""
] |
I have a set of .NET components that were developed long ago (1.1). I would like to continue to provide them for 1.1 for any clients that need that version, but also offer versions - in some cases the same code, in some cases with enhancements - for .NET 2 and for .NET 3(.5). In each later case, I might want to take advantages of newer features of the platform for certain components.
I'm looking for guidance as to what the best practice is in this situation.
In the case where I am not looking to make *any* changes to a component, then I imagine I could still supply it as 1.1 and later libraries/applications could just consume the 1.1 assemblies as is. I suspect there might still be good reasons to provide assemblies built with later versions of .NET - e.g. performance - but my understanding is that I *could* just supply the 1.1. Is this correct?
In the case where I want to keep the bulk of a component's code working with 1.1, but also add features for later versions of .NET, what's the best approach?
* Separate branches of code
* C# pre-processor
* Supply the functionality in separate (new) classes for the .NET 2+ versions, and use the original via, say, composition
* some other advanced .NET trick I don't yet know about
Also, any advice on what to do with the assembly signing would be greatly appreciated.
Thanks in advance | In my rather harsh opinion, it's way past time to stop supporting .NET 1.1. The only good reason I can think of for still using .NET 1.1 is if you still have to support hardware that .NET 2.0 does not support - and at this late date, I'm not sure we can call that a good reason.
In fact, aside from hardware support, I don't think I've heard of any valid reasons for a machine to not be upgraded to .NET 3.5 SP1. As far as .NET 2.0 applications are concerned, .NET 3.5 SP1 is just .NET 2.0 SP2. You've got to wonder why someone doesn't want to implement a service pack that's been out there almost a year now.
All the rest of .NET 3.0 and .NET 3.5 is just additional assemblies that can have no affect on code that does not use them.
So I'd balance my desire to serve all my customers against the continued cost of supporting .NET 1.1. Maybe you do continue to support it, but charge extra for support, and a *lot* more for any new features. Same thing, to a lesser extent, with .NET 2.0.
Another wilder thought: are we not enabling the .NET 1.1 companies by continuing to support them as though there were no additional expense in doing so? Are we really doing them any favors by helping them to keep their heads in the sand? Even if they're too busy to see it, it can't be long before some startup begins competing with them and winning a lot of their business away, not because they're a better company, but because they're using WCF and ASP.NET MVC and AJAX and all the cool features that the .NET 1.1 people can only dream about. | I maintain a project for .NET 2.0, .NET 3.0, .NET 3.5 CF 2.0, CF 3.5, Mono 2.x and Silverlight 2.0 - I do most of this using a combination of project (build) files and #if directives, to minimise/localise the amount of duplicated code.
Mostly I output the same dlls - although I have created some 3.5-specific dlls to cover things like extension methods.
An important job is to make sure you set this up so that you can build/test them all quickly - for example, I have a single "build.bat" that will check that it compiles in all of them (it is really easy to introduce illegal syntax).
For 1.1, I imagine you could use MSBee, but you might need a "csc" - but there are some pretty fundamental changes (such as no generics), so it might be an order of magnitude harder... | How to evolve a .NET codebase over versions of .NET | [
"",
"c#",
".net",
".net-3.5",
".net-2.0",
""
] |
How do I convert 6 bytes representing a MAC address into a string that displays the address as colon-separated hex values?
Thanks | You probably want a sequence of six bytes to be formatted like so:
```
aa:bb:cc:dd:ee:ff
```
where `aa` is the first byte formatted in hex.
Something like this should do:
```
char MAC[6]; //< I am assuming this has real content
std::ostringstream ss;
for (int i=0; i<6; ++i) {
if (i != 0) ss << ':';
ss.width(2); //< Use two chars for each byte
ss.fill('0'); //< Fill up with '0' if the number is only one hexadecimal digit
ss << std::hex << (int)(MAC[i]);
}
return ss.str();
```
If you dearly want to do this in a cast-like style (guessing from your title here), you can create a MAC class, implement the ostream-operator for it (like my given code) and use `boost::lexical_cast`. | Not sure if you mean cast or convert. If convert, then it depends in what form you want it. You might want Hex, base-64, octal, ...
If you want hex, consider [STLSoft](http://www.stlsoft.org/)'s [`format_bytes()`](http://www.stlsoft.org/doc-1.9/byte__format__functions_8hpp.html) function, which can do all kinds of ordering and grouping.
If you want base-64, consider the [b64 library](http://www.synesis.com.au/software/b64.html).
HTH
[EDIT] In line with the edit on the OP, the full impl would be:
```
#include <stlsoft/conversion/byte_format_functions.hpp>
#include <stdio.h>
int main()
{
unsigned char mac[6];
char result[STLSOFT_NUM_ELEMENTS(mac) * 3];
stlsoft::format_bytes(mac, sizeof(mac), &result[0], STLSOFT_NUM_ELEMENTS(result), 1, ":");
puts(result);
return 0;
}
```
There's no need *in this case* to check the return value from `format_bytes()` because you're passing in enough write buffer. In a real case you'd want to check | C++ Casting a byte binary value into a string | [
"",
"c++",
""
] |
I have a pretty monstrous Java app in development here. As of now, it's only ever been deployed on my locally installed Tomcat/MySQL setup.
For completeness, the app is an online game server written using Spring, Hibernate with MySQL currently on the backend.
Now, I can easily package up the WAR and get that on the remote server.. The problem is the database. Right now it's generated with an ANT script that uses Hibernate (specifically, the HBM2DDL Ant task) to generate the schema, and then populates the db with a combination of static SQL and a couple of ant-based parsers that read from other data (XML mostly). After that, I have a fully created DB populated with the game servers "starting" data set.
The issue is being a bit green in Java I have no idea what the right way to deploy this is.
Should I:
1. Export the SQL from my local MySQL and manually import it on the new server? Eww.
2. Make the ANT script less grody (it's got lots of hardcoded directories in it right now) and run it on the server?
3. The elegant option I don't know about?
The other complication is that the WAR will be going to different server(s) than the MySQL db will be on. Is there a Java book or web resource that comprehensively addresses these kinds of deployment issues? | I think there are 3 options:
1. Change your ANT script to target the DB on the remote machine. You can run it on your local machine, so you don't have to change it: It will find the necessary files in the same places. The main drawback of this method is that executing a lot of SQL over a network (internet) can be slow).
2. Export the schema from your local (build) database to the new database. It doesn't have to be SQL, if your database supports some binary format. Usually this is the fastest and least error prone way of doing it, although there might be some very subtle issues if the configuration of the remote DB is just slightly different from your local setup (e.g. character set).
3. Run the ANT script on your server. The biggest problem with this is that your database server will have to have all the necessary tools (like ant and java) but also all source files (hibernate mappings), which it usually (being a database server) has no need for. | I've done something similar by creating ant targets to push an ant script to the remote machine, that ant script having a target to generate the DB. Since you already have ant targets to generate the schema and initialize the DB, you can just push your existing ant script to the remote machine (assuming the remote machine has the same set of tools).
You can use the **scp** ant task to do the remote copy, and **sshexec** to do the remote invocation of ant and the script. | The proper way to deploy a Hibernate-based J2EE app to a remote server | [
"",
"java",
"hibernate",
"spring",
"deployment",
""
] |
When creating a new Java project in IntelliJ IDEA, the following directories and files are created:
```
./projectname.iml
./projectname.ipr
./projectname.iws
./src/
```
I want to configure IntelliJ IDEA to include my dependency JARs in `./lib/*.jar` to the project.
What is the correct way to achieve this in IntelliJ IDEA? | [](https://i.stack.imgur.com/ZlENo.png)
Steps for adding external jars in **IntelliJ IDEA**:
1. Click **File** from the toolbar
2. Select **Project Structure** option (`CTRL` + `SHIFT` + `ALT` + `S` on Windows/Linux, `⌘` + `;` on Mac OS X)
3. Select **Modules** at the left panel
4. Select **Dependencies** tab
5. Select **+** icon
6. Select **1 JARs or directories** option | ### IntelliJ IDEA 15 & 2016
1. **File** > **Project Structure...**

or press `Ctrl` + `Alt` + `Shift` + `S`
2. **Project Settings** > **Modules** > **Dependencies** > "**+**" sign > **JARs or directories...**

3. Select the jar file and click on OK, then click on another OK button to confirm


4. You can view the jar file in the "External Libraries" folder
 | Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project | [
"",
"java",
"intellij-idea",
"build",
"dependency-management",
""
] |
I have a file in .gz format. The java class for reading this file is GZIPInputStream.
However, this class doesn't extend the BufferedReader class of java. As a result, I am not able to read the file line by line. I need something like this
```
reader = new MyGZInputStream( some constructor of GZInputStream)
reader.readLine()...
```
I though of creating my class which extends the Reader or BufferedReader class of java and use GZIPInputStream as one of its variable.
```
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.util.zip.GZIPInputStream;
public class MyGZFilReader extends Reader {
private GZIPInputStream gzipInputStream = null;
char[] buf = new char[1024];
@Override
public void close() throws IOException {
gzipInputStream.close();
}
public MyGZFilReader(String filename)
throws FileNotFoundException, IOException {
gzipInputStream = new GZIPInputStream(new FileInputStream(filename));
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
// TODO Auto-generated method stub
return gzipInputStream.read((byte[])buf, off, len);
}
}
```
But, this doesn't work when I use
```
BufferedReader in = new BufferedReader(
new MyGZFilReader("F:/gawiki-20090614-stub-meta-history.xml.gz"));
System.out.println(in.readLine());
```
Can someone advice how to proceed .. | The basic setup of decorators is like this:
```
InputStream fileStream = new FileInputStream(filename);
InputStream gzipStream = new GZIPInputStream(fileStream);
Reader decoder = new InputStreamReader(gzipStream, encoding);
BufferedReader buffered = new BufferedReader(decoder);
```
The key issue in this snippet is the value of `encoding`. This is the character encoding of the text in the file. Is it "US-ASCII", "UTF-8", "SHIFT-JIS", "ISO-8859-9", …? there are hundreds of possibilities, and the correct choice usually cannot be determined from the file itself. It must be specified through some out-of-band channel.
For example, maybe it's the platform default. In a networked environment, however, this is extremely fragile. The machine that wrote the file might sit in the neighboring cubicle, but have a different default file encoding.
Most network protocols use a header or other metadata to explicitly note the character encoding.
In this case, it appears from the file extension that the content is XML. XML includes the "encoding" attribute in the XML declaration for this purpose. Furthermore, XML should really be processed with an XML parser, not as text. Reading XML line-by-line seems like a fragile, special case.
Failing to explicitly specify the encoding is [against the second commandment.](http://cafe.elharo.com/programming/the-ten-commandments-of-unicode/) *Use the default encoding at your peril!* | ```
GZIPInputStream gzip = new GZIPInputStream(new FileInputStream("F:/gawiki-20090614-stub-meta-history.xml.gz"));
BufferedReader br = new BufferedReader(new InputStreamReader(gzip));
br.readLine();
``` | GZIPInputStream reading line by line | [
"",
"java",
"file-io",
"filereader",
"gzipinputstream",
""
] |
I'm trying to write a C# unit test with VS 2008's built-in unit testing framework and the method I'm testing calls `Environment.Exit(0)`. When I call this method in my unit test, my unit test is Aborted. The method should indeed be calling `Exit`, and I want a way to test that it does, and also to test the exit code that it uses. How might I do this? I looked at [Microsoft.VisualStudio.TestTools.UnitTesting Namespace](http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.aspx) but didn't see anything that looked relevant.
```
[TestMethod]
[DeploymentItem("myprog.exe")]
public void MyProgTest()
{
// Want to ensure this Exit's with code 0:
MyProg_Accessor.myMethod();
}
```
Meanwhile, here's the gist of the code that I want to test:
```
static void myMethod()
{
Environment.Exit(0);
}
```
**Edit:** here's the solution I used in my test method, thanks to [RichardOD](https://stackoverflow.com/questions/1121655/vs2008-unit-tests-assert-method-exits/1121669#1121669):
```
Process proc;
try
{
proc = Process.Start(path, myArgs);
}
catch (System.ComponentModel.Win32Exception ex)
{
proc = null;
Assert.Fail(ex.Message);
}
Assert.IsNotNull(proc);
proc.WaitForExit(10000);
Assert.IsTrue(proc.HasExited);
Assert.AreEqual(code, proc.ExitCode);
``` | This sounds like an incredibly bad idea. Environment.Exit(0), will obviously do as prescribed, hence why your unit testings are breaking.
If you really want to still test this you can by launching a seperate process and checking the return code- have a look at wrapping it up in [Process.Start](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx).
I guess another option is factoring this code out and injecting a [test spy](http://xunitpatterns.com/Test%20Spy.html), or using a mock object to verify correct behaviour.
Perhaps you can do something with Typemock Isolator- I believe this lets you [mock static methods](http://weblogs.asp.net/nunogomes/archive/2009/07/02/typemock-isolator-faking-an-internal-static-type-and-overriding-a-static-method.aspx). | You'll need to create a wrapper for the Environment class, then use the wrapper in your code. For your unit tests, inject a mock version of the wrapper. The following example uses RhinoMocks to verify that the method calls the wrapper with the expected argument.
```
public class EnvironmentWrapper
{
public virtual void Exit( int code )
{
Environment.Exit( code );
}
}
public class MyClass
{
private EnvironmentWrapper Environment { get; set; }
public MyClass() : this( null ) { }
public MyClass( EnvironmentWrapper wrapper )
{
this.Environment = wrapper ?? new EnvironmentWrapper();
}
public void MyMethod( int code )
{
this.Environment.Exit( code )
}
}
[TestMethod]
public void MyMethodTest()
{
var mockWrapper = MockRepository.GenerateMock<EnvironmentWrapper>();
int expectedCode = 5;
mockWrapper.Expect( m => m.Exit( expectedCode ) );
var myClass = new MyClass( mockWrapper );
myclass.MyMethod( expectedCode );
mockWrapper.VerifyAllExpectations()
}
``` | VS2008 unit tests - assert method exits | [
"",
"c#",
"visual-studio-2008",
"unit-testing",
"exit",
""
] |
I'm currently writing an app in Android that works with the GPS. At the moment I'm able to work out whether the GPS is enabled. My problem is that I want to enable the GPS on app startup if it is disabled. How can I do this programmaticaly? | You can't, starting with Android 1.5. The most you can do is pop open the activity to allow the user to toggle it on/off. Use the action held in `android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS` to craft an Intent to open this activity. | ```
if(!LocationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER ))
{
Intent myIntent = new Intent( Settings.ACTION_SECURITY_SETTINGS );
startActivity(myIntent);
}
``` | How to programmatically enable GPS in Android Cupcake | [
"",
"java",
"android",
"gps",
"android-1.5-cupcake",
""
] |
I'm trying to create a list of tasks that I've read from some text files and put them into lists. I want to create a master list of what I'm going to do through the day however I've got a few rules for this.
One list has separate daily tasks that don't depend on the order they are completed. I call this list 'daily'. I've got another list of tasks for my projects, but these do depend on the order completed. This list is called 'projects'. I have a third list of things that must be done at the end of the day. I call it 'endofday'.
So here are the basic rules.
A list of randomized tasks where daily tasks can be performed in any order, where project tasks may be randomly inserted into the main list at any position but must stay in their original order relative to each other, and end of day tasks appended to the main list.
I understand how to get a random number from random.randint(), appending to lists, reading files and all that......but the logic is giving me a case of 'hurty brain'. Anyone want to take a crack at this?
EDIT:
Ok I solved it on my own, but at least asking the question got me to picture it in my head. Here's what I did.
```
random.shuffle(daily)
while projects:
daily.insert(random.randint(0,len(daily)), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
```
Thanks for the answers, I'll give ya guys some kudos anyways!
EDIT AGAIN:
Crap I just realized that's not the right answer lol
LAST EDIT I SWEAR:
```
position = []
random.shuffle(daily)
for x in range(len(projects)):
position.append(random.randint(0,len(daily)+x))
position.sort()
while projects:
daily.insert(position.pop(0), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
```
I LIED:
I just thought about what happens when position has duplicate values and lo and behold my first test returned 1,3,2,4 for my projects. I'm going to suck it up and use the answerer's solution lol
OR NOT:
```
position = []
random.shuffle(daily)
for x in range(len(projects)):
while 1:
pos = random.randint(0,len(daily)+x)
if pos not in position: break
position.append(pos)
position.sort()
while projects:
daily.insert(position.pop(0), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
``` | First, copy and shuffle daily to initialize master:
```
master = list(daily)
random.shuffle(master)
```
then (the interesting part!-) the alteration of master (to insert projects randomly but without order changes), and finally `random.shuffle(endofday); master.extend(endofday)`.
As I said the alteration part is the interesting one -- what about:
```
def random_mix(seq_a, seq_b):
iters = [iter(seq_a), iter(seq_b)]
while True:
it = random.choice(iters)
try: yield it.next()
except StopIteration:
iters.remove(it)
it = iters[0]
for x in it: yield x
```
Now, the mixing step becomes just `master = list(random_mix(master, projects))`
Performance is not ideal (lots of random numbers generated here, we could do with fewer, for example), but fine if we're talking about a few dozens or hundreds of items for example.
This insertion randomness is not ideal -- for that, the choice between the two sequences should not be equiprobable, but rather with probability proportional to their lengths. If that's important to you, let me know with a comment and I'll edit to fix the issue, but I wanted first to offer a simpler and more understandable version!-)
**Edit**: thanks for the accept, let me complete the answer anyway with a different way of "random mixing preserving order" which does use the right probabilities -- it's only slightly more complicated because it cannot just call `random.choice`;-).
```
def random_mix_rp(seq_a, seq_b):
iters = [iter(seq_a), iter(seq_b)]
lens = [len(seq_a), len(seq_b)]
while True:
r = random.randrange(sum(lens))
itindex = r < lens[0]
it = iters[itindex]
lens[itindex] -= 1
try: yield it.next()
except StopIteration:
iters.remove(it)
it = iters[0]
for x in it: yield x
```
Of course other optimization opportunities arise here -- since we're tracking the lengths anyway, we could rely on a length having gone down to zero rather than on try/except to detect that one sequence is finished and we should just exhaust the other one, etc etc. But, I wanted to show the version closest to my original one. Here's one exploiting this idea to optimize and simplify:
```
def random_mix_rp1(seq_a, seq_b):
iters = [iter(seq_a), iter(seq_b)]
lens = [len(seq_a), len(seq_b)]
while all(lens):
r = random.randrange(sum(lens))
itindex = r < lens[0]
it = iters[itindex]
lens[itindex] -= 1
yield it.next()
for it in iters:
for x in it: yield x
``` | Use random.shuffle to shuffle a list
random.shuffle(["x", "y", "z"]) | Random list with rules | [
"",
"python",
"random",
""
] |
why is this not ok?
```
aContract = function(){};
aContract.prototype = {
someFunction: function() {
alert('yo');
},
someOtherFunction: some$Other$Function
};
var some$Other$Function = function() {
alert('Yo yo yo');
};
var c = new aContract();
c.someFunction();
c.someOtherFunction();
```
Firebug says c.someOtherFunction is not a function
But this works just fine
```
aContract = function(){};
aContract.prototype = {
someFunction: function() {
alert('yo');
},
someOtherFunction: some$Other$Function
};
function some$Other$Function() {
alert('Yo yo yo');
};
var c = new aContract();
c.someFunction();
c.someOtherFunction();
```
What am I missing here??? I prefer to code in javascript using the first method, which usually works fine, but doesn't seem to work correctly when I prototype.
Thanks,
~ck in Sandy Eggo | You have assigned `some$Other$Function` to `aContract.prototype.someOtherFunction` before you actually create `some$Other$Function`. The order of statements matters. If you switch the order of things you'll be good:
```
var some$Other$Function = function() {
alert('Yo yo yo');
};
aContract = function(){};
aContract.prototype = {
someFunction: function() {
alert('yo');
},
someOtherFunction: some$Other$Function
};
``` | At the time this is evaluated:
```
aContract.prototype = { ... }
```
this has not yet been evaluated:
```
var some$Other$Function = function() { ... }
```
Thus `aContract.prototype.someOtherFunction` is set to `undefined`.
The reason the second works is because function **declarations** (which the second is, the first is an expression) are evaluated before any other statements. There are more details here: [Named function expressions demystified](http://yura.thinkweb2.com/named-function-expressions/) | Why does it say xxx is not a function | [
"",
"javascript",
"closures",
"unobtrusive-javascript",
""
] |
How do I get the file size and date stamp of a file on Windows in C++, given its path? | You can use `FindFirstFile()` to get them both at once, without having to open it (which is required by `GetFileSize()` and `GetInformationByHandle()`). It's a bit laborious, however, so a little wrapper is helpful
```
bool get_file_information(LPCTSTR path, WIN32_FIND_DATA* data)
{
HANDLE h = FindFirstFile(path, &data);
if(INVALID_HANDLE_VALUE != h) {
return false;
} else {
FindClose(h);
return true;
}
}
```
Then the file size is available in the `nFileSizeHigh` and `nFileSizeLow` members of [WIN32\_FIND\_DATA](http://msdn.microsoft.com/en-us/library/aa365740(VS.85).aspx), and the timestamps are available in the `ftCreationTime`, `ftLastAccessTime` and `ftLastWriteTime` members. | [GetFileSize](http://msdn.microsoft.com/en-us/library/aa364955(VS.85).aspx)/[GetFileSizeEx](http://msdn.microsoft.com/en-us/library/aa364957(VS.85).aspx) and [GetFileInformationByHandleEx](http://msdn.microsoft.com/en-us/library/aa364953(VS.85).aspx) with FileBasicInfo can be used to retrieved this information.
Both functions take a handle, so you need to use CreateFile on the path prior to calling these functions.
```
// Error handling removed for brevity
HANDLE hFile = CreateFile(path, GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
LARGE_INTEGER fileSize;
GetFileSizeEx(hFile, &fileSize);
FILE_BASIC_INFO fileInfo);
GetFileInformationByHandle(hFile, FileBasicInfo, fileInfo, sizeof(fileInfo));
// fileInfo.CreationTime is when file was created.
``` | VC++: How to get the time and date of a file? | [
"",
"c++",
"windows",
"file",
"date",
"size",
""
] |
I want to trim the column headers of a CSV file, fields below is an array that contains the header names, where would I place trim()? I've placed it with the foreach loop but VS tells me "cannot assign field because it is a foreach iteration variable". What am I doing wrong?
```
while ((fields = csv.GetCSVLine()) != null)
{
if (header)
{
foreach (string field in fields)
{
//field = field.trim(); //VS: "cannot assign field because it is a foreach iteration variable"
headers.Add(field);
}
}
``` | You can do it on the same line as the `Add()` call. No need to overwrite the variable `field` if you pass the result of `Trim()` directly to `Add()`.
```
foreach (string field in fields)
{
headers.Add(field.Trim());
}
``` | You're trying to change the value of the item you're working on.
Just do
```
var trimmedField=field.Trim();
headers.Add(trimmedField);
``` | C# "cannot assign field because it is a foreach iteration variable" | [
"",
"c#",
"foreach",
""
] |
This is something that's I've wanted to know recently, mostly out of curiousity. I'm in the mood to learn some old coding styles, and FORTRAN seems like a good place to start.
I guess I should help you guys out by providing a good starting point.
So how would this C procedure be written in FORTRAN?
```
int foo ( int x , int y )
{
int tempX = x ;
x += y / 2 ;
y -= tempX * 3 ; // tempX holds x's original value.
return x * y ;
}
```
I know the entire function could be a single line:
```
return ( x + ( y / 2 ) ) * ( y - ( x * 3 ) ) ;
```
But the point of me asking this question is to see how those four statements would be written individually in FORTRAN, not neccessarily combined into a single statement. | Where do you learn FORTRAN from? Just take a look at the [wikibooks](http://en.wikibooks.org/wiki/Fortran/Fortran_procedures_and_functions)!
Derived from the example, I'd say:
```
function func(x, y) result(r)
integer, intent(in) :: x, y
integer :: r
integer :: tempX
tempX = x
x = x / 2
y = y - tempX * 3
r = x * y
end function foo
``` | Don't blame me - you said *old* coding styles:
```
C234567
SUBROUTINE FOO(I,J,K)
C SAVE THE ORIGINAL VALUES
IORIG = I
JORIG = J
C PERFORM THE COMPUTATION
I = I + J/2
J = J - IORIG*3
K = I * J
C RESTORE VALUES
I = IORIG
J = JORIG
END SUBROUTINE FOO
```
I shudder as I write this, but
* all variables are implicitly integers, since they start with letters between I and N
* FORTRAN passes by reference, so reset `I` and `J` at the end to give the same effect as the original function (i.e. pass-by-value, so `x` and `y` were unchanged in the calling routine)
* Comments start in column 1, actual statements start in column 7
Please, please, please never write new code like this unless as a joke. | What is the Basic Structure of a Function in FORTRAN? | [
"",
"c++",
"c",
"function",
"fortran",
""
] |
I am a pretty good programmer(IMO only, of course. Know Python, Java well. Tried my hands at Lisp, Ruby, Haskell). I also know how to use Jquery reasonable well, so I know Dom manipulation.
I want a recommendation on a Javascript book, which teaches the Language. My criteria are,
1. Fast paced and for programmers who know programming. Dont tell me what loops are.
2. Teaches the language not the Dom manipulation.
3. Preferable ebook. Non free is fine. | JavaScript: The Good Parts.
[](https://i.stack.imgur.com/uELfe.jpg) | Like others I'd firstly recommend JavaScript the good parts. Another option to consider is JavaScript the definitive guide by David Flanagan. This is also a good book that covers the language well- certainly enough depth for a programmer interested in particular features of javascript. The language part is seperate from the client side stuff- so you can just read the bits that interest you.
Update- I've just checked the book on Amazon it has a whopping 286 customer reviews! | Javascript book which teaches javascript the language, not dom | [
"",
"javascript",
""
] |
How can I retrieve the links of a webpage and copy the url address of the links using Python? | Here's a short snippet using the SoupStrainer class in BeautifulSoup:
```
import httplib2
from bs4 import BeautifulSoup, SoupStrainer
http = httplib2.Http()
status, response = http.request('http://www.nytimes.com')
for link in BeautifulSoup(response, parse_only=SoupStrainer('a')):
if link.has_attr('href'):
print(link['href'])
```
The BeautifulSoup documentation is actually quite good, and covers a number of typical scenarios:
<https://www.crummy.com/software/BeautifulSoup/bs4/doc/>
Edit: Note that I used the SoupStrainer class because it's a bit more efficient (memory and speed wise), if you know what you're parsing in advance. | For completeness sake, the BeautifulSoup 4 version, making use of the encoding supplied by the server as well:
```
from bs4 import BeautifulSoup
import urllib.request
parser = 'html.parser' # or 'lxml' (preferred) or 'html5lib', if installed
resp = urllib.request.urlopen("http://www.gpsbasecamp.com/national-parks")
soup = BeautifulSoup(resp, parser, from_encoding=resp.info().get_param('charset'))
for link in soup.find_all('a', href=True):
print(link['href'])
```
or the Python 2 version:
```
from bs4 import BeautifulSoup
import urllib2
parser = 'html.parser' # or 'lxml' (preferred) or 'html5lib', if installed
resp = urllib2.urlopen("http://www.gpsbasecamp.com/national-parks")
soup = BeautifulSoup(resp, parser, from_encoding=resp.info().getparam('charset'))
for link in soup.find_all('a', href=True):
print link['href']
```
and a version using the [`requests` library](https://requests.readthedocs.io), which as written will work in both Python 2 and 3:
```
from bs4 import BeautifulSoup
from bs4.dammit import EncodingDetector
import requests
parser = 'html.parser' # or 'lxml' (preferred) or 'html5lib', if installed
resp = requests.get("http://www.gpsbasecamp.com/national-parks")
http_encoding = resp.encoding if 'charset' in resp.headers.get('content-type', '').lower() else None
html_encoding = EncodingDetector.find_declared_encoding(resp.content, is_html=True)
encoding = html_encoding or http_encoding
soup = BeautifulSoup(resp.content, parser, from_encoding=encoding)
for link in soup.find_all('a', href=True):
print(link['href'])
```
The `soup.find_all('a', href=True)` call finds all `<a>` elements that have an `href` attribute; elements without the attribute are skipped.
BeautifulSoup 3 stopped development in March 2012; new projects really should use BeautifulSoup 4, always.
Note that you should leave decoding the HTML from bytes *to BeautifulSoup*. You can inform BeautifulSoup of the characterset found in the HTTP response headers to assist in decoding, but this *can* be wrong and conflicting with a `<meta>` header info found in the HTML itself, which is why the above uses the BeautifulSoup internal class method `EncodingDetector.find_declared_encoding()` to make sure that such embedded encoding hints win over a misconfigured server.
With `requests`, the `response.encoding` attribute defaults to Latin-1 if the response has a `text/*` mimetype, even if no characterset was returned. This is consistent with the HTTP RFCs but painful when used with HTML parsing, so you should ignore that attribute when no `charset` is set in the Content-Type header. | retrieve links from web page using python and BeautifulSoup | [
"",
"python",
"web-scraping",
"hyperlink",
"beautifulsoup",
""
] |
Given two methods on the same class in Java :
```
public void doSomething( Person person );
public void doSomething( Employee employee );
```
where
```
Employee extends Person
```
If I call:
```
doSomething( employee )
```
I find that `doSomething( Person )` gets invoked.
I'd have expected the overload with the closest matching contract be invoked, not with the most abstract (which is what I'm finding)
Could someone explain why? | The most specific applicable overload is used - but that overload is determined at *compile*-time, based on the compile time type of the `employee` variable.
In other words:
```
Employee employee = new Employee();
doSomething(employee); // Calls doSomething(Employee)
```
but:
```
Person employee = new Employee();
doSomething(employee); // Calls doSomething(Person)
```
Note that this is unlike *overriding* where it's the *execution time* type of the target object which is important. | How was `employee` declared? If it was declared as `Person employee = new Employee();`, then `doSomething(Person)` is indeed the closest matching overload.
Unlike overrides, overloads are determined at compile time. Therefore, even though the runtime type of `employee` is `Employee`, the `Person` overload has already been chosen to be executed.
See the [JLS §8.4.9 Overloading](http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.9):
> When a method is invoked [(§15.12)](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#20448), the number of actual arguments (and any explicit type arguments) and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked [(§15.12.2)](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#292575). If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup [(§15.12.4)](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#45677). | Type order with overloaded methods in Java | [
"",
"java",
"types",
""
] |
I'm looking for ways to express this Python snippet in Perl:
```
data = {"A": None, "B": "yes", "C": None}
key_list = [k for k in data if data[k]]
# in this case the same as filter(lambda k: data[k], data) but let's ignore that
```
So looking at it one way, I just want the keys where the values are *None* or *undef*. Looking at it another way, what I want is the concise perl equivalent of a [list comprehension with conditional](http://docs.python.org/tutorial/datastructures.html#list-comprehensions). | I think you want [`grep`](http://perldoc.perl.org/functions/grep.html):
```
#!/usr/bin/env perl
use strict;
use warnings;
my %data = ( A => undef, B => 'yes', C => undef );
my @keys = grep { defined $data{$_} } keys %data;
print "Key: $_\n" for @keys;
```
I also think that I type too slowly, and that I should reload the page before posting answers. By the way, either a value of `0` or `undef` can be a good way to handle *null* values, but make sure you remember which you're using. A false value and and undefined value aren't the same thing in Perl. To clarify: `undef` returns false in a boolean test, but so does `0`. If `0` is a valid value, then you want to explicitly test for definedness, not simply truth. (I mention it because James went for `0` and I went the other way, and you may or may not know if it matters.) | Use [grep](http://perldoc.perl.org/functions/grep.html):
```
#!/usr/bin/perl
use strict;
use warnings;
my %data = ("A" => 0, "B" => "yes", "C" => 0 );
my @keys = grep { $data{$_} } keys %data;
```
Grep returns the values from the list on the right-hand side for which the expression in braces evaluates to a true value. As [telemachus](https://stackoverflow.com/users/26702/telemachus) points out, you want to make sure you understand true/false values in Perl. [This question](https://stackoverflow.com/questions/1036347/how-do-i-use-boolean-variables-in-perl/) has a good overview of truth in Perl.
You'll likely want a look at [map](http://perldoc.perl.org/functions/map.html), which applies an expression in braces to each element of a list and returns the result. An example would be:
```
my @data = ("A" => 0, "B" => 1, "C" => 0 );
my @modified_data = map { $data{$_} + 1 } @data;
print join ' ', @data, "\n";
print join ' ', @modified_data, "\n";
``` | Perl equivalent of (Python-) list comprehension | [
"",
"python",
"perl",
"list-comprehension",
""
] |
I'm taking an vanilla WPF application and converting it to use the MVVM pattern. During my evaluation of the code, I made up a list of topics that I'd need to know about before converting the application. My list looks kinda like this:
* dynamically loading xaml (although this is specific to my app)
* binding xaml to view model commands (buttons, toolbars, menu items)
* hotkeys
* binding view model commands to events (window size changes, mouse events, etc)
* handling dialogs (message boxes, file dialogs, user-designed dialogs, etc)
I already have various solutions for each item, so I'm not asking about how to do them. My actual question is: am I missing anything? What else is there that I'd need to know about?
Another way to see it is if I were making a WPF WVVM toolkit. What kind of features and functionality would it need so that developers can create MVVM apps?
Thanks! | I think you've got the basic MVVM issues. What you might still need is "What do I do when my app becomes too complex for MVVM?" That happens fairly quickly--more than a couple of views, and you get a view-model explosion, or you get monolithic view models that become cumbersome and very difficult to maintain.
I'd suggest looking into the Composite WPF (Prism) framework as one solution to that problem. Prism is an architectural framework that simplifies partitioning an application into modules that are more-or-less independent of each other. Each module can have a view or two (one is probably most common), and each view can have its own view model. It does a great job of organizing communications among modules in a very loosely-coupled way. The modules load into a Shell window that can be configured however you need.
Hope that helps! | You might also want to set infrastructure for some common functionality like copy/paste search buttons etc. | General checklist of things that have to know when converting a WPF app to MVVM | [
"",
"c#",
"wpf",
"mvvm",
""
] |
Is there a simple way or method to convert a `Stream` into a `byte[]` in C#? | Call next function like
```
byte[] m_Bytes = StreamHelper.ReadToEnd (mystream);
```
Function:
```
public static byte[] ReadToEnd(System.IO.Stream stream)
{
long originalPosition = 0;
if(stream.CanSeek)
{
originalPosition = stream.Position;
stream.Position = 0;
}
try
{
byte[] readBuffer = new byte[4096];
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}
byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
if(stream.CanSeek)
{
stream.Position = originalPosition;
}
}
}
``` | The shortest solution I know:
```
using(var memoryStream = new MemoryStream())
{
sourceStream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
``` | How do I convert a Stream into a byte[] in C#? | [
"",
"c#",
"arrays",
"inputstream",
""
] |
This is **very basic stuff**, but here goes. I find that I am never able to agree with myself whether the way I **split large classes into smaller ones** make things more maintainable or less maintainable. I am familiar with **design patterns**, though not in detail, and also with the concepts of **object oriented design**. All the fancy rules and guidelines aside, I am looking to pick your brains with regards to what I am missing with a very simple, sample scenario. Essentially along the lines of: "...this design will make it more difficult to", etc... All the things I don't anticipate because of lack of experience essentially.
Say you need to write a basic "file reader / file writer" style class to process a certain type of file. Let's call the file a **YadaKungFoo file**. The contents of YadaKungFoo files is essentially similar to INI Files, but with subtle differences.
There are sections and values:
```
[Sections]
Kung,Foo
Panda, Kongo
[AnotherSection]
Yada,Yada,Yada
Subtle,Difference,Here,Yes
[Dependencies]
PreProcess,SomeStuffToPreDo
PreProcess,MoreStuff
PostProcess,AfterEight
PostProcess,TheEndIsNear
PostProcess,TheEnd
```
OK, so this can yield 3 basic classes:
```
public class YadaKungFooFile
public class YadaKungFooFileSection
public class YadaKungFooFileSectionValue
```
The two latter classes are essentially only data structures with a ToString() override to spit out a string list of values stored using a couple of Generic lists. This is sufficient to implement the YadaKungFooFile save functionality.
So over time the YadaYadaFile starts growing. Several overloads to save in different formats, including XML etc, and the file starts pushing towards 800 lines or so. **Now the real question**: We want to add a feature to validate the contents of a YadaKungFoo file. The first thing that comes to mind is obviously to add:
```
var yada = new YadaKungFooFile("C:\Path");
var res = yada .Validate()
```
And we're done (we can even call that method from the constructor). Trouble is the validation is quite complicated, and makes the class very large, so we decide to create a new class like this:
```
var yada = new YadaKungFooFile("C:\Path");
var validator = new YadaKungFooFileValidator(yada);
var result = validator.Validate();
```
Now this sample is obviously **terribly simple, trivial and insignificant**. Either of the two ways above probably won't make too much difference, but what I don't like is:
1. The **YadaKungFooFileValidator** class and the **YadaKungFooFile** class seem to be very strongly coupled by this design. It seems a change in one class, would likely trigger changes in the other.
2. I am aware that phrases such as "Validator", "Controller", "Manager" etc... indicates a class that is concerned with the state of other objects as opposed to its "own business", and hence violates separation of concern principles and message sending.
All in all I guess I feel that I don't have the experience to understand all the aspects of why a design is bad, in what situations it doesn't really matter and what concern carries more weight: smaller classes or more cohesive classes. They seem to be contradictive requirements, but perhaps I am wrong. Maybe the validator class should be a composite object?
Essentially I am asking for comments on likely benefits / problems that could result from the above design. What could be done differently? (base FileValidator class, FileValidator Interface, etc.. u name it). Think of the YadaKungFooFile functionality as ever growing over time. | Bob Martin wrote a series of articles on class design, which he refers to as the SOLID principles:
<http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod>
The principles are:
1. The Single Responsibility Principle: *A class should have one, and only one, reason to change.*
2. The Open-Closed Principle: *You should be able to extend a classes behavior, without modifying it.*
3. The Liskov Substitution Principle: *Derived classes must be substitutable for their base classes.*
4. The Interface Segregation Principle: *Make fine grained interfaces that are client specific.*
5. The Dependency Inversion Principle: *Depend on abstractions, not on concretions.*
So in light of those, let's look at some of the statements:
> So over time the YadaYadaFile starts growing. Several overloads to save in different formats, including XML etc, and the file starts pushing towards 800 lines or so
This is a first Big Red Flag: YadaYadaFile starts out with two responsibilities: 1) maintaining a section/key/value data structure, and 2) knowing how to read and write an INI-like file. So there's the first problem. Adding more file formats compounds the issue: YadaYadaFile changes when 1) the data structure changes, or 2) a file format changes, or 3) a new file format is added.
Similarly, having a single validator for all three of those responsibilities puts too much responsibility on that single class.
A large class is a "code smell": it's not bad in and of itself, but it very often results from something that really is bad--in this case, a class that tries to be too many things. | I don't think the size of a class is a concern. The concern is more cohesion and coupling. You want to design objects that are loosely coupled and cohesive. That is, they should be concerned with one well defined thing. So if the thing happens to be very complicated then the class will grow.
You can use various design patterns to help manage the complexity. One thing you can do for instance is to create a Validator interface and have the YadaKunfuFile class depend on the interface rather than the Validator. This way you can change the Validator class without changes to the YadaKungfuFile class as long as the interface does not change. | How to split code into components... big classes? small classes? | [
"",
"c#",
".net",
""
] |
I am not sure if Exceptions work the same way in each language, but I am using PHP and I was wondering when I'm doing something like this:
```
if (!$this->connection[0]->query($this->query))
throw new QueryFailedException($this->connection[0]->error);
```
Is there a need to supply a code in the second parameter? For example:
```
if (!$this->connection[0]->query($this->query))
throw new QueryFailedException($this->connection[0]->error,123);
```
Now the code is 123... I can't think of a need for this. Is there one? In this case the message contains the query, exception name is QueryFailedException which explains the exception type, the exception itself contains file, line and stack trace, so, I can't think of anything where you could use the code for something useful. | The error code was a feature used when there was no object oriented language. The only thing that could aid you to understand what went wrong was the error code. In an object oriented language, the object IS your error code.
Unless, in specific cases, more than one thing can throw the exact same error AND they are treated in different ways, drop it.
Also, you would provide much better explanation to whomever is debugging your code if you left a message instead of a meaningless error code, so if you feel like the exception needs more information, fill the Error Message field instead. | The error code is a field that can be used to provide more detailed information. If for example you have two things that can generate the same exception, the code could be used to give more detail. | Using a code for an exception. Useful? | [
"",
"php",
"exception",
""
] |
I don't get it. I created this regular expression:
```
<span class="copy[Green|Red].*>[\s]*(.*)[\s]*<\/span>
```
to match certain parts of HTML code (a part between spans). For instance the following:
```
<span class="copyGreen">0.12</span>
<span class="copyRed"> 0.12 </span>
```
Now, this works beautifully with RegexBuddy and others, but with Boost::regex
I have an issue. It doesn't match up.
EDIT: To be more precise, I want to capture the number between the spans. Before and after
the number, there can be white spaces as well (\n, \r, etc.).
Here's the code I've been done:
```
try {
const boost::regex e("<span class=\"copy[Green|Red].*>[\\s]*(.*)[\\s]*<\\/span>");
boost::smatch matches;
std::string html("<span class=\"copyGreen\"> 0.12 </span>");
if (boost::regex_match(html, matches, e)) {
// Works... (not).
} else {
throw std::runtime_error("Couldn't match the regex against HTML-source!");
}
} catch (boost::regex_error& e) {
std::cout << e.what() << std::endl;
}
```
What am I doing wrong here? Thanks in advance!
EDIT:
It seems, that the correct expression would be
```
boost::regex("<span class=\"copy(?:Green|Red)[^>]*>\\s*(.*?)\\s*<\\/span>"); // Thanks chaos!.
```
This actually matches up with Boost. However, I needed to enable boost::match\_extra
in order to get all the captures I needed. This was done by defining
```
BOOST_REGEX_MATCH_EXTRA
```
in boost\regex\user.hpp
Thank you once again. | For one thing, this:
```
[Green|Red]
```
doesn't do what you think it does. You want:
```
(?:Green|Red)
```
`[Green|Red]` is a character class made up of the letters `GRred|`, not a way of alternating between matches. The way you've written it, it will match exactly one of those characters followed by any number of other characters.
This:
```
[\s]
```
is redundant and maybe hazardous (depending on interpretation it could be what's actually making your match not work). It can be just
```
\s
```
In order for your second `\s` to work, the capturing expression probably needs to be
```
(.*?)
```
I also recommend making your first `.*` into `[^>]*`, to avoid the problem you'll get if you ever apply this to actual HTML documents, where it will suck in arbitrary amounts of HTML. | There's a couple of problems with your regex.
First is this bit: `[Green|Red]`
which maches a set of characters, that set is **`G`**, **`r`**, **`e`**, **`n`**, **`|`**, **`R`** and **`d`**.
you need to do this using parenthises, like `(Green|Red)`. now this matches either the string **`Green`** or **`Red`**.
EDIT: if you don't want this to capture anything, you can use a non-capturing group, which in boost::regex is done by including a `?:` after the first parenthesis: `(?:Green|Red)`. Now the regex has the grouping behavior of parentheses, but there is no capturing.
The second problem is the `(.*)`
This doesn't seem like much, but it matches too much, including patterns like consecutive spans. This will consume the end of one span and the start of the next, all the way to the last span on the page. You need to make this non-greedy. In boost::regex, you do that by following the `*` with a `?`. change it to look like `(.*?)` (and do similar with the other \*'s.
The thing is, XML and HTML are very hard to get anything more than trivially simple regexes to work correctly. You should really be using a library that is meant for working with that format. There are plenty of [options](http://www.google.com/search?q=c%2B%2B+html+parser). This way you can be sure that you are handling HTML correctly, no matter how contorted the input might be. | Boost::regex issue, Matching an HTML span element | [
"",
"c++",
"regex",
"boost",
""
] |
I am going to be coding up a windows service to add users to a computer (users with no rights, ie just for authentication). (As a side note, I plan to use [this method](http://www.codeproject.com/KB/dotnet/addnewuser.aspx).)
I want to be able to call this windows service from another computer.
How is this done? Is this a tall order? Would I be better off just creating a Web Service and hosting it in IIS?
I have some WCF services hosted in IIS on the calling computer (they will do the calling to the proposed windows service). I have found that Hosting in IIS is somewhat problematic, so I would rather not have a second IIS instance to manage unless I need to.
(I will be using Visual Studio 2008 SP1, C# and Windows Server 2003 (for both caller and service host).
Thanks for the help | If you are thinking of hosting a web service in IIS just to communicate with an NT-service on that same machine, that is **definitely** more trouble than it is worth in this case.
As other answers have indicated you can make a WCF service with the operations you need and host that within the same NT-service that you want to interact with. You can easily secure this with certificates, or user accounts to make sure it is only controlled by the right people/machines.
If you need to control the NT-service itself, there are existing programs such as [sc.exe](http://msdn.microsoft.com/en-us/library/ms810435.aspx) to start, stop, configure, or query the status of your NT-service remotely.
However, you may want to consider seeking a solution without the overhead of creating an custom NT-service and a custom WCF service to interact with it. If you do, the **Net User** commands (sorry no link - new user limitation) or the **AddUsers** (see kb 199878/en-us) utility may be sufficient. If your remote "controller" can invoke these commands directly against the target machine you may not have to create any custom software address this need. Additionally you would have less software to maintain and administer on the target machine. You would just be using the built-in OS capabilities and admin utilities.
Finally, you will need to think about the security aspect, NT-services and IIS are usually run under very restricted accounts, many auditors would flip-out over any service running with sufficient permission to create or modify users locally, and especially on other machines. You'll want to make sure that the service could never be used to create users that do have more than the "authenticate" permission you indicated.
Edit: The **net user** command may not work against another machine's local users, but check out. [pspasswd](http://technet.microsoft.com/en-us/sysinternals/bb897543.aspx) that along with PsExec to create users, should do what you need remotely. | Simply host a WCF service in the Windows Service. You'll then be able to call it remotely. | Call A Windows Service from a remote computer | [
"",
"c#",
"wcf",
"web-services",
"windows-services",
""
] |
I am trying to teach myself MySQL/PHP from the very beginning. The following code was lifted from various tutorial sites. I'm using phpMyAdmin provided by my webhost.
I made a table with an auto-incrementing field called "ID" and another field called "first" (varchar, limit 30, not null). Then I made a simple form with one text field named "first" and a Submit button. I type my name into the box and click Submit. This does create a row in the database with an ID, but the "first" field is always blank.
I tried replacing '$\_POST[first]' with some straight-up words, and that worked - the words appeared in the table with an ID number just fine. That's how I know it is indeed managing to talk to the database, it's just not picking up the text field
After the INSERT statement runs, I have it display all the records in the table. It shows all of the ID numbers and then blank where "first" should be.
I also have it echo the INSERT statement. This is what the echo displays:
INSERT INTO tblHurray(ID, first) VALUES ('','')
When I substitute words for '$\_POST[first]', the echo looks like this:
INSERT INTO tblHurray(ID, first) VALUES ('','words')
This is my first question so please let me know if I've left out any pertinent information! And thanks in advance for your help.
This is the form:
```
<form action="run_input.php" method="post">
Name: <input type="text" name="first">
<input type="Submit">
</form>
```
This is what runs when "Submit" is clicked:
```
<?
include("run_connect.php"); // this connects to the database, this works
$step1 = "INSERT INTO tblHurray(ID, first) VALUES ('','$_POST[first]')";
mysql_query($step1);
echo "$step1";
echo "<b><center>Database Output</center></b><br><br>";
$step2=mysql_query("SELECT * FROM tblHurray");
$num=mysql_numrows($step2);
$i=0;
while ($i < $num) {
$firstname=mysql_result($step2,$i,"first");
$ID=mysql_result($step2,$i,"ID");
echo "$ID: $firstname<br />";
$i++;
}
?>
``` | This line
```
$step1 = "INSERT INTO tblHurray(ID, first) VALUES ('','$_POST[first]')";
```
needs to look like this:
```
$step1 = "INSERT INTO tblHurray(ID, first) VALUES ('','" . mysql_escape_string($_POST['first']) . "')";
```
It's a good habit to always quote your array keys (['first'] rather than [first]).
Plus it's good to get used to always escaping user input before inserting into the database to prevent SQL injection.
Also double-check to make sure the name of the input on your HTML form matches your PHP code.
```
$_POST['first']
```
is **not** the same as
```
$_POST['First']
``` | Try
```
$step1 = "INSERT INTO tblHurray(ID, first) VALUES ('','".$_POST['first']."')";
```
Although, if you're really going learn it, then start with
[PHP PDO](http://php.net/manual/en/book.pdo.php). It will save you ALOT of trouble in the long run, especially with parametrized queries. | MySQL: Why is it ignoring the text in the form field? | [
"",
"php",
"mysql",
"forms",
"insert",
""
] |
I am trying to write a query that will return only the most recent results. The table I am pulling information from has no uniqiue columns, and contains information on rate changes so for any particular client there can be several rate changes - I only want the most recent rate change for each client.
The structure is:
```
mrmatter VARCHAR(14)
mrtk VARCHAR(14)
mreffdate DATETIME
mrtitle VARCHAR(100)
mrrate INT
mrdevper INT
```
Some sample data is:
```
mrmatter mrtk mreffdate mrtitle mrrate mrdevper
184-00111 0005 2001-03-19 00:00:00.000 ! 250 NULL
184-00111 0259 2001-03-19 00:00:00.000 ! 220 NULL
184-00111 9210 2001-03-19 00:00:00.000 ! 220 NULL
184-00111 0005 2007-07-01 00:00:00.000 ! NULL NULL
```
From the data above you can see there is two mrtk (0005), from these results it should only return three instead of the four rows.
The query isnt just on mrtk, instead of mrtk there could be a mrtitle in which case I would need to find the most recent date, when there is multiples.
I have tried the following query, it returns the results sorted in newest to oldest, but it returns four rows (two 0005) instead of only the three. I have tried different ways of doing the same query but it all returns the same results.
```
SELECT mrmatter,mrtk,mrrate,MAX(mreffdate) AS 'MostRecent'
FROM mexrate
WHERE mrmatter='184866-00111'
GROUP BY mrmatter,mrtk,mrrate
```
Any assistance that can be provided would be greatly appreciated.
**UPDATE:**
The mrrate column can contain nulls, and the nulls can be the most recent entry. What I am after is the most recent entry for the same mrmatter AND (mrtk OR mrtitle).
Some more sample data is:
```
mrmatter mrtk mrtk mrrate mreffdate
100626-01406 Senior Assoc ! 235.000 2006-01-25 00:00:00.000
100626-01406 Solicitor ! 235.000 2006-01-25 00:00:00.000
100626-01407 Associate ! 265.000 2006-01-30 00:00:00.000
100626-01407 Associate ! 276.000 2007-07-01 00:00:00.000
100626-01407 Partner ! 265.000 2006-01-30 00:00:00.000
100626-01407 Partner ! 276.000 2007-07-01 00:00:00.000
100626-01407 Senior Assoc ! 265.000 2006-01-30 00:00:00.000
100626-01407 Senior Assoc ! 276.000 2007-07-01 00:00:00.000
```
Matt | I was able to achieve what I was after by using this query:
```
SELECT t1.mrmatter,t2.mrtk,t1.mrrate,t2.MostRecent
FROM mexrate t1
INNER JOIN
(
SELECT DISTINCT(mrtk),MAX(mreffdate) AS MostRecent
FROM mexrate
WHERE mrmatter='184866-00111'
GROUP BY mrtk
) t2 ON t1.mrtk=t2.mrtk AND t1.mreffdate=t2.MostRecent
WHERE mrmatter='184866-00111'
```
Thanks everyone for your assistance with this problem, it is, as always, greatly appreciated.
Matt | The group by clause have mrrate column as well. For the two rows of mrtk(0005), first row have mrrate as 250 and second row have mrrate as NULL. This will certainly result in two rows of 0005.
The query is working fine. You may remove mrrate from group by but probably there is some functionality attached to it which is not clear. | Select most recent dates | [
"",
"sql",
"sql-server",
"sql-server-2000",
""
] |
I was told that in Java, unchecked exceptions can be caught in a try block, but if it's caught, isn't it called a checked exception? | Unchecked exceptions are exceptions that don't need to be caught in a `try`-`catch` block. Unchecked exceptions are subclasses of the [`RuntimeException`](http://java.sun.com/javase/6/docs/api/java/lang/RuntimeException.html) or [`Error`](http://java.sun.com/javase/6/docs/api/java/lang/Error.html) classes.
Checked exceptions are exceptions that need to be caught in a `try`-`catch` block.
The definition of checked and unchecked exceptions can be found in [Section 11.2: Compile-Time Checking of Exceptions](http://java.sun.com/docs/books/jls/second_edition/html/exceptions.doc.html#44121) of [The Java Language Specification](http://java.sun.com/docs/books/jls/second_edition/html/jTOC.doc.html):
> The unchecked exceptions classes are
> the class `RuntimeException` and its
> subclasses, and the class `Error` and
> its subclasses. All other exception
> classes are checked exception classes.
Just because an unchecked exception is caught in a `catch` block does not make it a checked exception -- it just means that the unchecked exception was caught, and was handled in the `catch` block.
One could `catch` an unchecked exception, and then `throw` a new checked exception, so any methods calling that method where an unchecked exception could occur and force an method that calls it to handle some kind of exception.
For example, a `NumberFormatException` which can be thrown when handling some unparsable `String` to the `Integer.parseInt` method is an unchecked exception, so it does not need to be caught. However, the method calling that method may want its caller to properly handle such a problem, so it may throw another exception which is checked (not a subclass of `RuntimeException`.):
```
public int getIntegerFromInput(String s) throws BadInputException {
int i = 0;
try {
i = Integer.parseInt(s);
catch (NumberFormatException e) {
throw new BadInputException();
}
return i;
}
```
In the above example, a `NumberFormatException` is caught in the `try`-`catch` block, and a new `BadInputException` (which is intended to be a checked exception) is thrown.
Any caller to the `getIntegerFromInput` method will be forced to catch a `BadInputException`, and forced to deal with bad inputs. If the `NumberFormatException` were not to be caught and handled, any callers to this method would have to handle the exception correctly.
(Also, it should be noted, eating an exception and doing something that is not really meaningful is not considered a good practice -- handle exceptions where meaningful exception handling can be performed.)
From The Java Tutorials:
* [Lessons: Exceptions](http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html)
+ [The Catch or Specify Requirement](http://java.sun.com/docs/books/tutorial/essential/exceptions/catchOrDeclare.html) - discusses checked exceptions.
+ [Chained Exceptions](http://java.sun.com/docs/books/tutorial/essential/exceptions/chained.html) - the practice of catching an exception and throwing a new one, as the example above.
+ [Unchecked Exceptions — The Controversy](http://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.html) | No, it's not called a checked exception just because it is caught. A catch block can be written to catch any kind of Exception or Error. Checked exceptions are those that are subject to the [Catch or Specify Requirement](http://java.sun.com/docs/books/tutorial/essential/exceptions/catchOrDeclare.html), meaning that you are *required* to either catch them or declare that your method may throw them. You can think of the term *checked* as meaning that the compiler will check to make sure you adhere to the catch or specify requirement. Errors and RuntimeExceptions are called *unchecked* exceptions because the compiler does not enforce this requirement on them. | Isn't an unchecked exception that is caught in a try block a checked exception in Java? | [
"",
"java",
"exception",
"checked-exceptions",
""
] |
I am starting to migrate a custom serialization mechanism to Protocol Buffers. One data type that will be used particularly regularly is `BigDecimal`.
Does anyone know of a good way of serializing this within Protocol Buffers? Our current serialization routine uses `BigDecimal.toPlainString()` for serialization, and `new BigDecimal(String)` for deserialization - I'm assuming there's a better way.
My guess is to define a `BigDecimal` as:
```
message BDecimal {
required int32 scale = 1;
required BInteger int_val = 2;
}
```
But I am not too sure how to define `BigInteger` - perhaps using its `toByteArray()` method? | Yes. You should define BigInteger as BigInteger.toByteArray() .
My guess is that BigDecimal would be:
```
message BDecimal {
required int32 scale = 1;
required BInteger int_val = 2;
}
```
while BigInteger may be defined as
```
message BInteger {
required bytes value = 1;
}
```
The code to handle BigInteger would be:
```
BInteger write(BigInteger val) {
BInteger.Builder builder = BInteger.newBuilder();
ByteString bytes = ByteString.copyFrom(val.toByteArray());
builder.setValue(bytes);
return builder.build();
}
BigInteger read(BInteger message) {
ByteString bytes = message.getValue();
return new BigInteger(bytes.toByteArray());
}
``` | I have recently had the same need as OP, and used a similar solution to the one proposed by @notnoop. Posting it here after seeing this comment from @stikkos:
> How would you convert a BigDecimal to a BigInteger and scale? And back ?
According to the `BigDecimal` class [documentation](https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html#BigDecimal-java.math.BigInteger-int-java.math.MathContext-):
> The value of the `BigDecimal` is (`unscaledVal` × 10-`scale`), rounded according to the precision and rounding mode settings.
So, a `java.math.BigDecimal` can be serialized considering three properties:
* [`unscaledValue`](https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html#unscaledValue--)
* `scale`
* `precision`
---
Now, the code.
1. Protobuf v3 message definition:
```
syntax = "proto3";
message DecimalValue {
uint32 scale = 1;
uint32 precision = 2;
bytes value = 3;
}
```
2. How to serialize a `java.math.BigDecimal` to a Protobuf message:
```
import com.google.protobuf.ByteString;
import DecimalValue;
java.math.BigDecimal bigDecimal = new java.math.BigDecimal("1234.56789");
DecimalValue serialized = DecimalValue.newBuilder()
.setScale(bigDecimal.scale())
.setPrecision(bigDecimal.precision())
.setValue(ByteString.copyFrom(bigDecimal.unscaledValue().toByteArray()))
.build();
```
3. How to deserialize the Protobuf message back to a `java.math.BigDecimal`:
```
java.math.MathContext mc = new java.math.MathContext(serialized.getPrecision());
java.math.BigDecimal deserialized = new java.math.BigDecimal(
new java.math.BigInteger(serialized.getValue().toByteArray()),
serialized.getScale(),
mc);
```
4. We can check the obtained `java.math.BigDecimal` yields the same original value as follows:
```
assert bigDecimal.equals(deserialized);
```
---
Note: OP assumed there is a better way to serialize a `java.math.BigDecimal` than using a plain `String`. In terms of storage, this solution is better.
For example, to serialize the first 100 decimals of π:
```
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679
```
```
System.out.println("DecimalValue: " + serialized.getSerializedSize());
System.out.println("String: " + StringValue.of(pi).getSerializedSize());
```
This yields:
```
DecimalValue: 48
String: 104
``` | What is the best approach for serializing BigDecimal/BigInteger to ProtocolBuffers | [
"",
"java",
"protocol-buffers",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.