Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I've got a case statement in c#. I would like to chose the values for the cases from a configuration file at run time. Is this possible? | Not with a switch statement, no. The case labels have to be compile-time constants.
Marc Gravell has a switch-like construct you could use, somewhere... I'll try to find it. It may well not be suitable for your particular usage though.
Otherwise, a sequence of if/else if/else if [...] /else is the way to go. | As the values being used in a case statement in C# are expected to be constants I don't think it is possible to set these at runtime from a config file. | Switch Over Value Determined at Runtime in c# | [
"",
"c#",
"runtime",
"case-statement",
""
] |
How can I get all the options of a select through jQuery by passing on its ID?
I am only looking to get their values, not the text. | Use:
```
$("#id option").each(function()
{
// Add $(this).val() to your list
});
```
[.each() | jQuery API Documentation](https://api.jquery.com/each/) | [Without jQuery](http://youmightnotneedjquery.com/)
I do know that the [`HTMLSelectElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement) element contains an [`options`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/options) property, which is a [`HTMLOptionsCollection`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionsCollection).
```
const myOpts = document.getElementById('yourselect').options;
console.log(myOpts[0].value) //=> Value of the first option
```
A 12 year old answer. Let's modernize it a bit (using `.querySelectorAll`, [spreading](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) the resulting `HTMLOptionsCollection` to `Array` and map the values).
```
// helper to retrieve an array of elements using a css selector
const nodes = selector => [...document.querySelectorAll(selector)];
const results = {
pojs: nodes(`#demo option`).map(o => o.value),
jq: $(`#demo option`).toArray().map( o => o.value ),
}
console.log( `pojs: [${results.pojs.slice(0, 5)}]` );
console.log( `jq: [${results.jq.slice(0, 5)}]` );
```
```
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="demo">
<option value="Belgium">Belgium</option>
<option value="Botswana">Botswana</option>
<option value="Burkina Faso">Burkina Faso</option>
<option value="Burundi">Burundi</option>
<option value="China">China</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
<option value="India">India</option>
<option value="Japan">Japan</option>
<option value="Malaysia">Malaysia</option>
<option value="Mali">Mali</option>
<option value="Namibia">Namibia</option>
<option value="Netherlands">Netherlands</option>
<option value="North Korea">North Korea</option>
<option value="South Korea">South Korea</option>
<option value="Spain">Spain</option>
<option value="Sweden">Sweden</option>
<option value="Uzbekistan">Uzbekistan</option>
<option value="Zimbabwe">Zimbabwe</option>
</select>
``` | How to get all options of a select using jQuery? | [
"",
"javascript",
"jquery",
"jquery-selectors",
""
] |
i am reading this page <http://www.cplusplus.com/doc/tutorial/exceptions.html>
it says if i write function() throw(); no exceptions can be thrown in that function. I tried in msvc 2005 writing throw(), throw(int), throw() and nothing at all. each had the exact same results. Nothing. I threw int, char\*, another type and it was all caught the same way. It looks like throw doesnt affect it at all. What does function() throw() actually do? | See [this article](http://www.codeproject.com/KB/cpp/stdexceptionspec.aspx) for details on C++ exception specifications and Microsoft's implementation:
> Microsoft Visual C++ 7.1 ignores exception specifications unless they are empty. Empty exception specifications are equivalent to `__declspec(nothrow)`, and they can help the compiler to reduce code size.
>
> [...] If it sees an empty exception specification, it will assume you know what you are doing and optimize away the mechanics for dealing with exceptions. If your function throws anyway - well, shame on you. Use this feature only if you are 100% positive your function does not throw and never will. | What you're finding is that that version of VC++ didn't enforce specification exceptions. I believe that was documented as a variance from the standard.
However, exception specifications are usually not a good idea. If a program violates them in a standards-conforming implementation (which the VC++ from VS 2005 was not in this case), the system is supposed to catch it. This means that the specification is not a compiler optimization hint, but rather forces the compiler to go to extra lengths, and sometimes produce suboptimal code.
See [the Boost rationale](http://www.boost.org/development/requirements.html#Exception-specification) for reasons why the highly regarded Boost project does not use exception specifications. This is Boost, which is something of the poster child for doing weird and useful things with advanced parts of the language. | about c++ exceptions. func() throw() | [
"",
"c++",
"exception",
"throw",
""
] |
I have the following query:
```
select count(L.ID)
from LA inner join L on (LA.leadid = L.ID)
where L.status = 5
and L.city = "cityname"
and Date(LA.Datetime) < Date_Sub(Now(), INTERVAL 6 MONTH);
```
which looks for records with status 5 in a particular city that are older than 6 months (the date for which is stored in LA). This returns about 4k results. I would like to update the value of the status to 1 on each of those records, and so my update looks like:
```
update L, LA
set L.status = 1
where L.status = 5
and L.city = "cityname"
and Date(LA.SomeDatetime) < Date_Sub(Now(), INTERVAL 6 MONTH);
```
but it stalls out and locks the db. I suspect there is a problem because there is no join, but I try something like:
```
update L, LA
from L inner join LA on (L.OID = LA.leadid)
set L.status = 1
where L.status = 5
and L.syscity = "cityname"
and Date(LA.SomeDatetime) < Date_Sub(Now(), INTERVAL 6 MONTH);
```
and it obviously won't work because there is no 'from' in an update.
edit> I'm using MySQL | ```
update L
set L.status = 1
where L.status = 5
and L.city = "cityname"
and EXISTS (
select * from LA
where Date(LA.SomeDatetime) < Date_Sub(Now(), INTERVAL 6 MONTH)
and LA.leadid = L.ID
)
``` | For `MySQL`, you may use old join syntax:
```
UPDATE l, la
SET l.status = 1
WHERE l.status = 5
AND l.city = "cityname"
AND la.leadid = l.id
AND DATE(la.datetime) < DATE_SUB(NOW(), INTERVAL 6 MONTH)
``` | How do I join tables on an update | [
"",
"mysql",
"sql",
"join",
"sql-update",
""
] |
I think the title sums it up. I just want to know why one or the other is better for continous integration builds of Java projects from Svn. | As a long time CruiseControl committer **and** someone who has never used Hudson I'm pretty biased, but my take on it is:
Hudson is much easier to get up and running (in large part from a nice web interface) and has a very active plugin development community.
CruiseControl has support from lots of [3rd party stuff](http://confluence.public.thoughtworks.org/display/CC/3rdPartyCCStuff) and has the benefit of doing some neat tricks with the xml configuration like plugin preconfiguration and include.projects which lets you version the configuration information with the project.
If you're only going to have a few builds I think Hudson is the clear winner. If you're going to have lots -- and don't mind the xml -- then I think CruiseControl's xml configuration tricks become a real strength. | I agree with [this answer](https://stackoverflow.com/questions/604385/what-is-the-difference-between-hudson-and-cruisecontrol-for-java-projects/604419#604419), but wanted to add a few points.
In short, **Hudson** (update: **[Jenkins](http://jenkins-ci.org/)**) is likely the better choice now. First and foremost because creating and configuring jobs ("projects" in CC vocabulary) is just *so much faster* through Hudson's web UI, compared to editing CruiseControl's XML configuration file (which we used to keep in version control just to keep track of it better). The latter is not especially difficult - it simply is slower and more tedious.
CruiseControl has been great, but as noted in Dan Dyer's aptly-named blog post, *[Why are you still not using Hudson?](http://blog.uncommons.org/2008/05/09/why-are-you-still-not-using-hudson/)*, it suffers from being first. (Um, like Britain, if you will, later into the industrial revolution, when others started overtaking it with newer technologies.)
We used CruiseControl heavily and have gradually switched over to Hudson, finally using it exclusively. And *even more* heavily: in the process we've started using the CI server for many other things than before, because setting up and managing Hudson jobs is so handy. (We now have some 40+ jobs in Hudson: the usual build & test jobs for stable and development branches; jobs related to releasing (building installers etc); jobs that run some (experimental) metrics against the codebase; ones that run (slow) UI or integration tests against a specific database version; and so on.)
From this experience I'd argue that even if you have lots of builds, including complicated ones, Hudson is a pretty safe choice because, like CC, you can use it to do *anything*, basically. Just configure your job to run whatever Ant or Maven targets, Unix shell scripts, or Windows .bat scripts, in the order you wish.
As for the 3rd party stuff ([mentioned here by Jeffrey Fredrick](https://stackoverflow.com/questions/604385/what-is-the-difference-between-hudson-and-cruisecontrol-for-java-projects/605452#605452)) - that is a good point, but my impression is that Hudson is quickly catching up, and that there's already a very large number of [plugins available](http://wiki.hudson-ci.org/display/HUDSON/Plugins) for it.
For me, the two things I can name that I miss about CruiseControl are:
1. Its warning emails about broken builds were more informative than those of Hudson. In most cases the root cause was evident from CC's nicely formatted HTML mail itself, whereas with Hudson I usually need to follow the link to Hudson web UI, and click around a little to get the details.
2. The [CruiseControl dashboard](http://cruisecontrol.sourceforge.net/dashboard.html) is better suited, out of the box, as an "[information radiator](http://www.agileadvice.com/archives/2005/05/information_rad.html)" (shown on a public monitor, or projected on a wall, so that you can always quickly see the status of all projects). With Hudson's front page, we needed some Greasemonkey tricks to get job rows all nicely green/red.
Minor disclaimer: I haven't been following the CC project closely for the last year or so. (But from a [quick look](http://cruisecontrol.sourceforge.net/download.html), it has not changed in any dramatic way.)
**Note** (2011-02-03): Hudson has been [renamed/forked](http://jenkins-ci.org/content/hudsons-future) as [Jenkins](http://jenkins-ci.org/) (by Hudson creator [Kohsuke Kawaguchi](http://kohsuke.org/2011/01/11/bye-bye-hudson-hello-jenkins/) and others). It looks as if Oracle—which controls the Hudson name—will keep "[Hudson](http://hudson-ci.org/)" around too, but my personal recommendation is to go with **Jenkins**, no matter what Oracle says. | What is the difference between Hudson and CruiseControl for Java projects? | [
"",
"java",
"continuous-integration",
"hudson",
"jenkins",
"cruisecontrol",
""
] |
As the title says, given the year and the week number, how do I get the month number?
edit: if a week crosses two months, I want the month the first day of the week is in.
edit(2): This is how I get the week number:
```
CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
```
I'm just trying to do the reverse. | This is what I ended up doing:
```
static int GetMonth(int Year, int Week)
{
DateTime tDt = new DateTime(Year, 1, 1);
tDt.AddDays((Week - 1) * 7);
for (int i = 0; i <= 365; ++i)
{
int tWeek = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
tDt,
CalendarWeekRule.FirstDay,
DayOfWeek.Monday);
if (tWeek == Week)
return tDt.Month;
tDt = tDt.AddDays(1);
}
return 0;
}
```
I would have preferred something simpler, but it works :) | If you assume that the first day of your definition of week is the same day as the 1st day of the year, then this will work:
```
int year = 2000;
int week = 9;
int month = new DateTime(year, 1, 1).AddDays(7 * (week - 1)).Month;
```
Obviously, a *true* answer would depend on how you define the first day of the week, and how you define how a week falls into a month when it overlaps more than one. | How do I get the month number from the year and week number in c#? | [
"",
"c#",
"datetime",
""
] |
C++ file I/O is tougher than C file I/O.
So in C++, creating a new library for file I/O is useful or not? I mean `<fstream>`
Can anyone please tell are there any benefits in C++ file I/O ? | **Opinion**
I don't know of any real project that uses C++ streams. They are too slow and difficult to use. There are several newer libraries like [FastFormat](http://www.fastformat.org/) and the [Boost](http://www.boost.org/doc/libs/1_38_0/libs/format/index.html) version that claim to be better there was a piece in the last ACCU Overload magazine about them. Personally I have used the c FILE library for the last 15 years or so in C++ and I can see no reason yet to change.
**Speed**
Here is small test program (I knock together quickly) to show the basic speed problem:
```
#include <stdio.h>
#include <time.h>
#include<iostream>
#include<fstream>
using namespace std;
int main( int argc, const char* argv[] )
{
const int max = 1000000;
const char* teststr = "example";
int start = time(0);
FILE* file = fopen( "example1", "w" );
for( int i = 0; i < max; i++ )
{
fprintf( file, "%s:%d\n", teststr, i );
}
fclose( file );
int end = time(0);
printf( "C FILE: %ds\n", end-start );
start = time(0);
ofstream outdata;
outdata.open("example2.dat");
for( int i = 0; i < max; i++ )
{
outdata << teststr << ":" << i << endl;
}
outdata.close();
end = time(0);
printf( "C++ Streams: %ds\n", end-start );
return 0;
}
```
And the results on my PC:
```
C FILE: 5s
C++ Streams: 260s
Process returned 0 (0x0) execution time : 265.282 s
Press any key to continue.
```
As we can see just this simple example is 52x slower. I hope that there are ways to make it faster!
*NOTE:* changing endl to '\n' in my example improved C++ streams making it only 3x slower than the FILE\* streams (thanks [jalf](https://stackoverflow.com/users/33213/jalf)) there may be ways to make it faster.
**Difficulty to use**
I can't argue that printf() is not terse but it is more flexible (IMO) and simpler to understand, once you get past the initial WTF for the macro codes.
```
double pi = 3.14285714;
cout << "pi = " << setprecision(5) << pi << '\n';
printf( "%.5f\n", pi );
cout << "pi = " << fixed << showpos << setprecision(3) << pi << '\n';
printf( "%+.3f\n", pi );
cout << "pi = " << scientific << noshowpos << pi<< '\n';
printf( "%e\n", pi );
```
**The Question**
Yes, may be there is need of a better C++ library, may be [FastFormat](http://www.fastformat.org/) is that library, only time will tell.
dave | In response to David Allan Finch's answer, I fixed an error in his benchmarking code (he flushed the stream in the C++ version after every single line), and reran the test:
The C++ loop now looks like this:
```
start = time(0);
{
ofstream outdata("example2.txt");
for( int i = 0; i < max; i++ )
{
outdata << teststr << ":" << i << "\n"; // note, \n instead of endl
}
}
end = time(0);
```
I run 10000000 iterations (10 times more than in the original code, because otherwise, the numbers are just too small for time()'s lousy resolution to give us anything meaningful))
And the output is:
```
G++ 4.1.2:
C FILE: 4s
C++ Streams: 6s
MSVC9.0:
C FILE: 10s
C++ Streams: 23s
```
(note, the MSVC version was run on my laptop with a significantly slower harddrive)
But this gives us a performance difference of 1.5-2.3x, depending on the implementation. and other external factors. | C++ and C file I/O | [
"",
"c++",
"file",
"io",
""
] |
How do i create a db file in C#? a friend told me it was in the toolbox and not to use sqlite. I dont see anything that could be it, nor what it is called. google didnt help:( | There is no file-based database provider built in to c# or the .NET Framework. There are of course pre-existing connectors for using SQL Server (which includes [SQL Express](http://www.microsoft.com/express/sql/)), but if you need a fully functional RDBMS that is file-based, you need to use something like [SQLite](http://www.sqlite.org/) or [Firebird](http://www.firebirdsql.org/) (also a fan of [VistaDB](http://www.vistadb.net/), not free or open source but VERY solid and pretty affordable). | Could it be...
[SQL Server Compact Edition](http://www.microsoft.com/Sqlserver/2005/en/us/compact.aspx) – A lightweight, in-process database engine designed to run on devices and desktops and is geared toward local data storage. Compact Edition includes a subset of SQL Server 2005 data types and shares common elements of the Transact-SQL (T-SQL) language with the data service engines. | C# database in a file | [
"",
"c#",
"database",
"file",
""
] |
1. Is this guaranteed to be always true:
```
std::numeric_limits<int>::max() == INT_MAX
```
What does C++ standard say about it? I could not find any reference in the standard that would explicitly state this, but I keep reading that those should be equivalent.
2. What about C99 types that are not in C++98 standard for compilers that implement both C99 (at least `long long` part) and C++98? I am not sure whether there is any guarantee that this always holds true:
```
std::numeric_limits<unsigned long long>::max() == ULLONG_MAX
```
Is this a reasonable assumption? | My copy of the C++ 2003 standard says that the `numeric_limits<>::max()` and `min()` templates will return values:
> Equivalent to `CHAR_MIN, SHRT_MIN, FLT_MIN, DBL_MIN,` etc.
>
> Equivalent to `CHAR_MAX, SHRT_MAX, FLT_MAX, DBL_MAX,` etc
However, those are in footnotes. ISO/IEC Directives Part 3: "[Footnotes] shall not contain requirements." Though footnotes to tables or figures may be requirements. | The first should be guaranteed to be true: `std::numeric_limits<int>::max() == INT_MAX`.
However, for unsigned long long, there are no guarantees since the compiler/libraries are not required to support them. But...
If your compiler and libs support unsigned long long, it should be equal since the limits for the types will be the same regardless of how you ask.
yes, it is this a reasonable assumption. | Equivalence of <limits> and <climits> | [
"",
"c++",
"c",
"stl",
"standards",
"limits",
""
] |
public static void Refer(ref int a,ref int b)
in this how do i find that these variables are reference variable programatically ..how do i find their type | Do you mean you want to know via reflection that the method parameters are by-ref?
You use [`MethodBase.GetParameters`](http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getparameters.aspx) to get the parameters for the method, and then [`ParameterInfo.ParameterType`](http://msdn.microsoft.com/en-us/library/system.reflection.parameterinfo.parametertype.aspx) to find the type of the parameter and [`Type.IsByRef`](http://msdn.microsoft.com/en-us/library/system.type.isbyref.aspx) to check whether or not it's passed by reference.
Here's a quick example:
```
using System;
using System.Reflection;
public class Test
{
public static void Refer(ref int a,ref int b)
{
}
static void Main()
{
MethodInfo method = typeof(Test).GetMethod("Refer");
ParameterInfo[] parameters = method.GetParameters();
foreach (ParameterInfo parameter in parameters)
{
Console.WriteLine("{0} is ref? {1}",
parameter.Name,
parameter.ParameterType.IsByRef);
}
}
}
```
You can't do this in a "strong" way for a variable using `a.GetType()` or `typeof(a)` etc. `GetType()` finds the type of the *value* of `a`, which is just an `int`. | Since C# is strongly typed, you can use any `int` methods safely since `a` and `b` have to be `ints`. But if you need the `Type` during runtime, use the [`typeof`](http://msdn.microsoft.com/en-us/library/58918ffs.aspx) operator.
```
Type intType = typeof(a);
``` | how to find a reference datatype | [
"",
"c#",
""
] |
Is there any good and free Date AND Time Picker available for Java Swing?
There are a lot date pickers available but no date AND time picker. This is the closest I came across so far: [Looking for a date AND time picker](http://forum.worldwindcentral.com/showthread.php?t=15566)
Anybody? | For a time picker you can use a JSpinner and set a JSpinner.DateEditor that only shows the time value.
```
JSpinner timeSpinner = new JSpinner( new SpinnerDateModel() );
JSpinner.DateEditor timeEditor = new JSpinner.DateEditor(timeSpinner, "HH:mm:ss");
timeSpinner.setEditor(timeEditor);
timeSpinner.setValue(new Date()); // will only show the current time
``` | You can extend the swingx JXDatePicker component:
> "JXDatePicker only handles dates without time. Quite often we need to let the user choose a date and a time. This is an example of how to make use JXDatePicker to handle date and time together."
<http://wiki.java.net/twiki/bin/view/Javadesktop/JXDateTimePicker>
EDIT: This article disappeared from the web, but as SingleShot discovered, it is still available in an internet archive. Just to be sure, here is the full working example:
```
import org.jdesktop.swingx.calendar.SingleDaySelectionModel;
import org.jdesktop.swingx.JXDatePicker;
import javax.swing.*;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.DateFormatter;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.*;
import java.awt.*;
/**
* This is licensed under LGPL. License can be found here: http://www.gnu.org/licenses/lgpl-3.0.txt
*
* This is provided as is. If you have questions please direct them to charlie.hubbard at gmail dot you know what.
*/
public class DateTimePicker extends JXDatePicker {
private JSpinner timeSpinner;
private JPanel timePanel;
private DateFormat timeFormat;
public DateTimePicker() {
super();
getMonthView().setSelectionModel(new SingleDaySelectionModel());
}
public DateTimePicker( Date d ) {
this();
setDate(d);
}
public void commitEdit() throws ParseException {
commitTime();
super.commitEdit();
}
public void cancelEdit() {
super.cancelEdit();
setTimeSpinners();
}
@Override
public JPanel getLinkPanel() {
super.getLinkPanel();
if( timePanel == null ) {
timePanel = createTimePanel();
}
setTimeSpinners();
return timePanel;
}
private JPanel createTimePanel() {
JPanel newPanel = new JPanel();
newPanel.setLayout(new FlowLayout());
//newPanel.add(panelOriginal);
SpinnerDateModel dateModel = new SpinnerDateModel();
timeSpinner = new JSpinner(dateModel);
if( timeFormat == null ) timeFormat = DateFormat.getTimeInstance( DateFormat.SHORT );
updateTextFieldFormat();
newPanel.add(new JLabel( "Time:" ) );
newPanel.add(timeSpinner);
newPanel.setBackground(Color.WHITE);
return newPanel;
}
private void updateTextFieldFormat() {
if( timeSpinner == null ) return;
JFormattedTextField tf = ((JSpinner.DefaultEditor) timeSpinner.getEditor()).getTextField();
DefaultFormatterFactory factory = (DefaultFormatterFactory) tf.getFormatterFactory();
DateFormatter formatter = (DateFormatter) factory.getDefaultFormatter();
// Change the date format to only show the hours
formatter.setFormat( timeFormat );
}
private void commitTime() {
Date date = getDate();
if (date != null) {
Date time = (Date) timeSpinner.getValue();
GregorianCalendar timeCalendar = new GregorianCalendar();
timeCalendar.setTime( time );
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, timeCalendar.get( Calendar.HOUR_OF_DAY ) );
calendar.set(Calendar.MINUTE, timeCalendar.get( Calendar.MINUTE ) );
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date newDate = calendar.getTime();
setDate(newDate);
}
}
private void setTimeSpinners() {
Date date = getDate();
if (date != null) {
timeSpinner.setValue( date );
}
}
public DateFormat getTimeFormat() {
return timeFormat;
}
public void setTimeFormat(DateFormat timeFormat) {
this.timeFormat = timeFormat;
updateTextFieldFormat();
}
public static void main(String[] args) {
Date date = new Date();
JFrame frame = new JFrame();
frame.setTitle("Date Time Picker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DateTimePicker dateTimePicker = new DateTimePicker();
dateTimePicker.setFormats( DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.MEDIUM ) );
dateTimePicker.setTimeFormat( DateFormat.getTimeInstance( DateFormat.MEDIUM ) );
dateTimePicker.setDate(date);
frame.getContentPane().add(dateTimePicker);
frame.pack();
frame.setVisible(true);
}
}
``` | Is there any good and free Date AND Time Picker available for Java Swing? | [
"",
"java",
"swing",
"datepicker",
"datetimepicker",
""
] |
Is there a way to immediately stop execution of a SQL script in SQL server, like a "break" or "exit" command?
I have a script that does some validation and lookups before it starts doing inserts, and I want it to stop if any of the validations or lookups fail. | **The [raiserror](http://msdn.microsoft.com/en-us/library/ms178592.aspx) method**
```
raiserror('Oh no a fatal error', 20, -1) with log
```
This will terminate the connection, thereby stopping the rest of the script from running.
Note that both severity level 20 or higher and the `WITH LOG` option are necessary for it to work this way.
This even works with GO statements, eg.
```
print 'hi'
go
raiserror('Oh no a fatal error', 20, -1) with log
go
print 'ho'
```
Will give you the output:
```
hi
Msg 2745, Level 16, State 2, Line 1
Process ID 51 has raised user error 50000, severity 20. SQL Server is terminating this process.
Msg 50000, Level 20, State 1, Line 1
Oh no a fatal error
Msg 0, Level 20, State 0, Line 0
A severe error occurred on the current command. The results, if any, should be discarded.
```
Notice that 'ho' is not printed.
CAVEATS:
* This only works if you are logged in as admin ('sysadmin' role), and also leaves you with no database connection.
* If you are NOT logged in as admin, the RAISEERROR() call itself will fail *and the script will continue executing*.
* When invoked with sqlcmd.exe, exit code 2745 will be reported.
Reference: <http://www.mydatabasesupport.com/forums/ms-sqlserver/174037-sql-server-2000-abort-whole-script.html#post761334>
**The noexec method**
Another method that works with GO statements is `set noexec on` ([docs](https://learn.microsoft.com/en-us/sql/t-sql/statements/set-noexec-transact-sql?view=sql-server-ver15)). This causes the rest of the script to be skipped over. It does not terminate the connection, but you need to turn `noexec` off again before any commands will execute.
Example:
```
print 'hi'
go
print 'Fatal error, script will not continue!'
set noexec on
print 'ho'
go
-- last line of the script
set noexec off -- Turn execution back on; only needed in SSMS, so as to be able
-- to run this script again in the same session.
``` | Just use a RETURN (it will work both inside and outside a stored procedure). | SQL Server - stop or break execution of a SQL script | [
"",
"sql",
"sql-server",
"scripting",
"exit",
""
] |
Is `filter_var` any good for filtering data? What kind of bad data will it filter? I do use `mysql_real_escape_string` but I wonder if adding `filter_var` will help? | To defend from SQL injection use prepared statements if possible. If not, use mysql\_real\_escape\_string for strings, (int) casting or intval() for integers, (float) or floatval() for floats and addcslashes($input, '%\_') for strings to be used inside LIKE statements. Things get even more complicated when trying to escape strings to be used inside RLIKE statements.
For filtering HTML content, the best would be strip\_tags (without passing $allowable\_tags), but... you may not like/want it, in which case the most affordable solution is:
```
$escaped = htmlspecialchars($input, ENT_QUOTES, $your_charset);
```
A more reliable solution would be to use a library like [HTML Purifier](http://htmlpurifier.org/)
Filter functions are OK, but some of them are more validators than filters. Depending on your needs you may find some of them useful. | You adjust `filter_var` by using it with the [`FILTER_*` constants](http://www.php.net/manual/en/filter.filters.php). It sounds like you're looking for [sanitisation](https://www.php.net/manual/en/filter.filters.sanitize.php) of data (actually adjusting the data to make it safe\*) rather than [validation](https://www.php.net/manual/en/filter.filters.validate.php) (checking the data is safe).
Different filters can help with different tasks. While `mysql_real_escape_string` is ok for sanitising data to prevent SQL injection it's no good for outputting data that may contain HTML. Here's a couple of filter's I'd use for everyday tasks:
* `FILTER_SANITIZE_SPECIAL_CHARS` - useful for displaying (not removing) HTML code, preventing XSS attacks and converting symbols to HTML entities.
* `FILTER_SANITIZE_STRING` with the `STRIP_LOW/HIGH` flags - actually removes HTML (see `strip_tags`).
* `FILTER_SANITIZE_URL` - makes URLs safe\*.
* `FILTER_SANITIZE_EMAIL` - makes email addresses safe, although I'd prefer to use it's validation cousin before storing the address.
> \* I use safe loosely, I'm of the opinion that you can never be too sure. | Is filter_var a good way to go? | [
"",
"php",
"security",
""
] |
How are CLR (.NET) objects managed in SQL Server?
The entry point to any CLR code from SQL Server is a static method. Typically you'll only create objects that exist within the scope of that method. However, you could conceivably store references to objects in static members, letting them escape the method call scope. If SQL Server retains these objects in memory across multiple stored procedure/function calls, then they could be useful for caching applications -- although they'd be more dangerous too.
How does SQL Server treat this? Does it even allow (non-method) static members? If so, how long does it retain them in memory? Does it garbage collect everything after every CLR call? How does it handle concurrency? | In "Pro SQL Server 2005 Assemblies" by Robin Dewson and Julian Skinner, it says that "Assemblies loaded into a database, like other database objects, are owned by a database user. All assemblies owned by the same user in the same database will run within the same AppDomain. Assemblies owned by a different user will run within a separate AppDomain."
What this tells me is that if you're working with a single database and all the assemblies you load in with the CREATE ASSEMBLY statement have the same owner, then your assemblies will all run in the same app domain. However, being in the same AppDomain does not mean using the same code-base, so even the same dll can be loaded into the same application domains multiple times, and it's types will not match up, even though they have the same name. When same-named types are from different code-bases, their static variables will be different instances as well.
The only way I can see to use static variables safely in SQL Server CLR environment with multiple assemblies is to actually just use a single assembly. You can use the ILMerge utility with the "UnionMerge" option to pack all your assemblies into one and merge classes with the same name. This should guarantee that for a given database, in your sole assembly, your static variables will work just like they would in a stand-alone application. I think it's safe to assume the application domain isn't unloaded and reloaded at every request, but you can't depend on it never being unloaded, since that will happen whenever there is an unhandled error (at least if it's running in unsafe mode). | SQL Server allows static readonly members if assembly is deployed with Unsafe permission level.
Practically objects are retained in memory until SQL service is stopped/restarted.
Regarding concurrency, your object and methods should be thread-safe as everywhere else.
For example:
```
public static class MyCLRClass
{
private static readonly ReaderWriterLock rwlock = new ReaderWriterLock();
private static readonly ArrayList list = new ArrayList();
private static void AddToList(object obj)
{
rwlock.AcquireWriterLock(1000);
try
{
list.Add(obj);
}
finally
{
rwlock.ReleaseLock();
}
}
[SqlProcedure(Name="MyCLRProc")]
public static void MyCLRProc()
{
rwlock.AcquireReaderLock(1000);
try
{
SqlContext.Pipe.Send(string.Format("items in list: {0}", list.Count));
}
finally
{
rwlock.ReleaseLock();
}
}
}
```
I use such things in SQL CLR and it works. | What is the SQL Server CLR Integration Life Cycle? | [
"",
"c#",
".net",
"sql-server",
"sql-server-2005",
"stored-procedures",
""
] |
XPath (v1) contains no way to encode expressions.
If you only have single OR double quotes then you can use expressions such as
```
//review[@name="Bob's Pizza"]
//review[@name='"Pizza" Pam']
```
But if you have BOTH e.g [Fred's "Fancy Pizza"] then you have to use something like this [Escaping Strings in XPath (C++)](http://www.deez.info/sengelha/category/programming/xml/xpath/) to generate
```
//review[@name=Concat("Fred's ",'"Fancy Pizza"')]
```
Anyone have a function in c# to do this?
Some links that are close
* [Use the MVP.XML library and XPathVariable](http://www.tkachenko.com/blog/archives/000627.html) (a very good solution but a bit heavyweight for my needs).
* [Doesn't encode where both " and ' are present](http://www.webtips.co.in/c/c-sharp-function-to-escape-single-quote-on-xpath-expression.aspx)
* [Adds more arguments to the Concat operation than is necessary](http://kushalm.com/the-perils-of-xpath-expressions-specifically-escaping-quotes)
e.g. would return
//review[@name=concat('Fred', "'", 's ', '"', 'Fancy Pizza', '"', '')]
EDIT: A few answers have suggested escaping ' with `'` and " with `"` but although this makes sense it does not work; try it using the XML fragment:
```
<review name="Bob's Pizza"/>
```
and the xpath
```
//review[@name='Bob's Pizza']
``` | Wow, you all sure are making this complicated. Why not just do this?
```
public static string XpathExpression(string value)
{
if (!value.Contains("'"))
return '\'' + value + '\'';
else if (!value.Contains("\""))
return '"' + value + '"';
else
return "concat('" + value.Replace("'", "',\"'\",'") + "')";
}
```
[.NET Fiddle & test](https://dotnetfiddle.net/hDFP1E) | Though it certainly won't work in all circumstances, here's a way to sidestep the problem:
```
doc.DocumentElement.SetAttribute("searchName", name);
XmlNode n = doc.SelectNodes("//review[@name=/*/@searchName]");
``` | Encoding XPath Expressions with both single and double quotes | [
"",
"c#",
"xml",
"xpath",
"xpath-1.0",
""
] |
I'm a C# .NET developer and I work on mostly ASP.NET projects.
I want to learn a new programming language,
* to improve my programming skills by experiencing a new language,
* to see something different then microsoft environment,
* and maybe to think in a different way.
I focus on two languages for my goal. **Python** and **Ruby**.
* Which one do you offer for me ?
* Pros and cons of them on each other?
* Is it worth learning them ?
**EDIT :** Sorry I editted my post but not inform here,
Ruby on Rails replaced with Ruby. | Both languages are powerful and fun. Either would be a useful addition to your tool box.
Python has a larger community and probably more mature documentation and libraries. Its object-orientation is a little inconsistent and feels (to me, IMHO) like something that was bolted on to the language. You can alter class behaviour at runtime (monkey-patching) but not for the precompiled classes and it's generally frowned-upon.
Ruby might be a little more different to your current experience: it has some flavour of Smalltalk (method-calling is more correctly message-sending for example). Its object-orientation is built-in from scratch, all classes are open to modification and it's an accepted - if slightly scary - practise. The community is smaller, the libraries less mature and documentation coverage is less.
Both languages will have some level of broken backward compatibility in their next majopr releases, both have .Net implementations (IronPython is production, IronRuby getting there). Both have web frameworks that reflect their strengths (search SO for the Django/Rails debate).
If I'd never seen Ruby, I'd be very happy working in Python, and have done so without suffering when necessary. I always found myself wishing I could do the work in Ruby. But that's my opinion, YMMV.
Edit: Come to think of it, and even though it pains me, if you're seeking to leverage your knowledge of the .Net framework, you might be best off looking at IronPython, as it's more mature than the Ruby equivalent. | First... good for you for wanting to broaden your knowledge! Second, you are comparing a language (Python) with a web framework (Ruby on Rails).
I think your best option is to try a few different frameworks in both Python *and* Ruby, do the same fairly simple task in each, and only then pick which one you'd like to learn more about. Rails is nice for Ruby, but it's not the only one out there. For Python I like Pylons and Django.
Pros and cons: Ruby is a little cleaner, language-wise, than Python. Python has a much larger set of modules.
Is it worth learning? Yes, to both Python and Ruby. | Python or Ruby for a .NET developer? | [
"",
"python",
"ruby-on-rails",
"ruby",
"comparison",
""
] |
After reading the faq's and everything else I can find, I'm still confused. If I have a char pointer that is initialised in this fashion:
`char *s = "Hello world!"`
The string is in read-only memory and I cannot change it like this:
```
*s = 'W';
```
to make "Wello world!". This I understand, but I can't, for the life of me, understand how to make it NOT read-only. Do I have to use an array instead of a pointer? Like [here](https://stackoverflow.com/questions/164194/why-does-simple-c-code-receive-segmentation-fault)?
This is my code:
```
char *s = str;
char *e = s;
while (*e != '\0')
e++;
e--;
char *temp;
//Swop the string around
while (s <= e) {
*temp = *s;
*s = *e;
*e = *temp;
e--;
s++;
}
```
The error message is just a segmentation fault. Apologies in advance if this is a really stupid question.
Thanks so much for all the help. After taking all your advice, I get this:
```
void something(char * str) {
char *store = str;
char *s = new char[strlen(str) + 1]; //Allocate memory. Nice one.
strcpy(s, str);
char *e = new char[strlen(str) + 1];
strcpy(e, str);
while (*e != '\0')
e++;
e--;
char temp; //no longer a pointer
while (s <= e) {
cout << *e;
temp = *s;
*s = *e;
*e = temp;
e--;
s++;
}
delete [] e;
delete [] s;
}
```
however, the deletes at the end of the function seem to be causing their own segmentation faults. Why?
For interest's sake: The faults were due to accessing the e and s pointers after they were incremented. A much simpler solution followed from that:
```
void something(char * str) {
char *s = new char[strlen(str) + 1];
strcpy(s, str);
char temp;
int j = strlen(str) - 1;
for (int i = 0; i <= strlen(str)/2; i++) {
cout << s << endl;
temp = s[i];
s[i] = s[j];
s[j] = temp;
j--;
}
delete [] s;
}
``` | The easiest way to modify it is to create an array for your storage, and then copy the string into it.
For example:
```
char buf[128];
const char *src = "Hello World";
strncpy(buf, src, 127); // one less - we always 0-terminate
buf[127] = '\0';
// you can now modify buf
buf[0] = 'W';
```
The reason your code doesn't work is that you haven't allocated any memory for the copy of the string - you've just made a second pointer to the same read-only memory. (And then tried to copy it? I'm not quite sure what the rest of the code is doing.) You need to get some non-read-only memory somewhere, and it's much easier to use the standard library to copy it into that new memory, rather than writing the loop yourself.
In the case when you don't know the length of the string beforehand, you can also use malloc (or, even better, do what drschnz's answer says and use *new char[]*):
```
const char *src = "Hello world";
char *buf = malloc(strlen(src) + 1); // or = new char[strlen(src) + 1];
strcpy(buf, src);
// you can now modify buf
// later, you need to free it
free(buf); // or delete [] buf;
```
Also, if you're using C++, you can just use a std::string:
```
std::string myString("Hello world");
myString[0] = "W";
```
Hope that helps. | Try:
```
char src[] = "Hello world";
src[6] = 'W';
-- // or
char buffer[] = "Hello world";
char* src = buffer;
src[6] = 'W';
```
If you want to copy a string into a buffer then use strcpy() or strncpy()
```
char buffer[20];
char const* s = "Hello World"
strcpy(s,buffer);
```
If you must write your own string copy then it should look like this:
```
char buffer[20];
char const* s = "Hello World";
// OK this is not the perfect solution but it is easy to read.
for(int loop = 0;s[loop] != '\0';++loop)
{
buffer[loop] = s[loop];
}
buffer[loop] = '\0';
``` | Why can't I assign values to pointers? | [
"",
"c++",
"pointers",
"segmentation-fault",
"readonly",
""
] |
I am trying to build a count-down widget.
Given a certain date, whats the easiest way in PHP to determine how many days until that date? | ```
<?php
$cdate = mktime(0, 0, 0, 12, 31, 2009);
$today = time();
$difference = $cdate - $today;
if ($difference < 0) { $difference = 0; }
echo floor($difference/60/60/24)." days remaining";
?>
``` | Expanding on schnaader's answer, here is a one-liner function that takes a date string as a parameter but only returns the number of days:
```
<?php
function days_until($date){
return (isset($date)) ? floor((strtotime($date) - time())/60/60/24) : FALSE;
}
?>
``` | How many days until X-Y-Z date? | [
"",
"php",
"datetime",
""
] |
I'm planning to use [jBCrypt](http://www.mindrot.org/projects/jBCrypt/) for password hashing in a new web application, as it is supposed to be the best from what I've read. As I haven't used it before I'm looking into if there is any reason not to use it.
I have this:
* I haven't found it in the Maven repository (searched for jbcrypt and bcrypt at mvnrepository.org) which is a downer as I'd like to have my dependencies managed using a Maven repository if possible. If jBCrypt is the best of breed solution for password hashing I'd have to setup my own local repository and have it available that way. Or have I just missed it? Maybe it's in there somewhere?
* It's only at version 0.2, but maybe it's stable anyway and the reason for a low version number has some other cause? | jBcrypt is probably fine as a crypto algorithm for your passwords; blowfish is relatively strong. Although there have been some reported implementation flaws in Blowfish itself, I don't find anything much reported about jBcrypt. On the other hand, Blowfish hasn't been tested nearly as heavily as other algorithms have, and a [crack](http://www.crypticide.com/alecm/security/c50-faq.html)-style known-plaintxt attack often works better than expected, surprising crypto geeks.
So here's what I'd suggest:
* go ahead and use jBcrypt but protect your encrypted password files to the extent you reasonably can -- as you would using /etc/shadow on a UNIX system.
* Contrary to Nikhil's suggestion, I *would* pull the sources into your version control, for two reasons: (1) where else would you keep them, since you need them whenever you build, and (2) because there's always the *chance* the person doing jBcrypt will move on to other things, and you don't want to find yourself left dangling just before a delivery (which is inevitably when you'd find out.) In this kind of situation, I'd put the sources into your version control as if they were your on code, and then any changes can be inserted as if you'd built a new version yourself. No need to be more complicated than you normally would be. | As far as your concern that it's not mature, I was going to suggest that you set up your own JUnit tests comparing the results of jBcrypt and the more proven Bcrypt, to see if you get the same results, and then contribute those to the jBcrypt project.
But that's already been done:
> ... ships with a set of JUnit unit
> tests to verify correct operation of
> the library and compatibility with the
> canonical C implementation of the
> bcrypt algorithm.
Perusing the JUnit tests to see if they meet your level of satisfaction is where I'd start... | What to use for password hashing? Any reason not to use jBCrypt? | [
"",
"java",
"hash",
"crypt",
"bcrypt",
"jbcrypt",
""
] |
I need to write a very simple 3D physics simulator in Java, cube and spheres bumping into each other, not much more. I've never did anything like that, where should I start? Any documentation on how it is done? any libraries I could re-use? | [Physics for Game Programmers By Grant Palmer](http://books.google.com/books?id=oVLDoO-V67cC&printsec=frontcover&dq=physics+for+game+programmers#PPP5,M1) (not Java)
[Phys2D](http://www.cokeandcode.com/phys2d/) (Java code) | NeHe's lesson 39 is a good starting point, it's in C++ but the theory is pretty easy to understand. | Where do I start to write/use a 3D physics simulation engine? | [
"",
"java",
"simulation",
"physics-engine",
""
] |
In my webservice, I need to place some HTTP calls. Is it possible to do some connection pooling, like I do JDBC connection pooling?
In the Admin Console of GlassFish I see the configuration items `Connector Connection Pool` and `Connector Resources`. Can I use these? | No. For HTTP you don't actually need connection pooling (except if you are a browser). A HTTP connection is much cheaper than a database connection.
However, You can use a custom resource, so you can configure the connection in JNDI. [This article](http://blogs.oracle.com/chengfang/entry/how_to_create_custom_resources) helped me out. [There are](http://blogs.oracle.com/chengfang/entry/how_to_inject_and_look) [also three](http://blogs.oracle.com/chengfang/entry/how_to_parameterize_and_configure) [follow up posts](http://blogs.oracle.com/chengfang/entry/a_generic_beanfactory_class_for). | doekman's answer is one possible approach.
Over in my company, we just use Apache Commons' HTTPClient library, which has its own connection pool manager. This link below should start you off easy.
<http://hc.apache.org/httpclient-3.x/performance.html>
It's your own value judgement whether or not you want to pull in another external dependency. Having migrated our applications from Tomcat, we chose to retain the dependency on HTTPClient just 'cos it's easy to use while alleviating the need to build (**and** maintain) another factory class. | HTTP Connection Pooling in GlassFish | [
"",
"java",
"http",
"jakarta-ee",
"glassfish",
""
] |
We are seeing frequent but intermittent `java.net.SocketException: Connection reset` errors in our logs. We are unsure as to where the `Connection reset` error is actually coming from, and how to go about debugging.
The issue appears to be unrelated to the messages we are attempting to send.
Note that the message is **not** `connection reset by peer`.
Any suggestions on what the typical causes of this exception might be, and how we might proceed?
Here is a representative stack trace (`com.companyname.mtix.sms` is our component):
```
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:168)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
at java.io.BufferedInputStream.read(BufferedInputStream.java:235)
at org.apache.commons.httpclient.HttpParser.readRawLine(HttpParser.java:77)
at org.apache.commons.httpclient.HttpParser.readLine(HttpParser.java:105)
at org.apache.commons.httpclient.HttpConnection.readLine(HttpConnection.java:1115)
at org.apache.commons.httpclient.HttpMethodBase.readStatusLine(HttpMethodBase.java:1832)
at org.apache.commons.httpclient.HttpMethodBase.readResponse(HttpMethodBase.java:1590)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:995)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:397)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:170)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:324)
at com.companyname.mtix.sms.services.impl.message.SendTextMessage.sendTextMessage(SendTextMessage.java:127)
at com.companyname.mtix.sms.services.MessageServiceImpl.sendTextMessage(MessageServiceImpl.java:125)
at com.companyname.mtix.sms.services.remote.MessageServiceRemoteImpl.sendTextMessage(MessageServiceRemoteImpl.java:43)
at sun.reflect.GeneratedMethodAccessor203.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.apache.axis.providers.java.RPCProvider.invokeMethod(RPCProvider.java:397)
at org.apache.axis.providers.java.RPCProvider.processMessage(RPCProvider.java:186)
at org.apache.axis.providers.java.JavaProvider.invoke(JavaProvider.java:323)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.handlers.soap.SOAPService.invoke(SOAPService.java:453)
at org.apache.axis.server.AxisServer.invoke(AxisServer.java:281)
at org.apache.axis.transport.http.AxisServlet.doPost(AxisServlet.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
at org.apache.axis.transport.http.AxisServletBase.service(AxisServletBase.java:327)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at com.companyname.mtix.sms.http.filters.NoCacheFilter.doFilter(NoCacheFilter.java:63)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at com.companyname.mtix.sms.http.filters.MessageFilter.doFilter(MessageFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:61)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:77)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.ajaxanywhere.AAFilter.doFilter(AAFilter.java:46)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:541)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Thread.java:595)
```
---
Our component is a web application, running under Tomcat, that calls a third party Web service that sends SMS messages, it so happens. The line of our code on which the exception gets thrown from is the last line in the code snippet below.
```
String aggregatorResponse = null;
HttpClient httpClient = prepareHttpClient( username, password );
PostMethod postMethod = preparePostMethod( textUrl );
try {
SybaseTextMessageBuilder builder = new SybaseTextMessageBuilder();
URL notifyUrl = buildNotificationUrl( textMessage, codeSetManager );
String smsRequestDocument = builder.buildTextMessage( textMessage, notifyUrl );
LOG.debug( "Sybase MT document created as: \n" + smsRequestDocument );
postMethod.setRequestEntity( new StringRequestEntity( smsRequestDocument ) );
LOG.debug( "commiting SMS to aggregator: " + textMessage.toString() );
int httpStatus = httpClient.executeMethod( postMethod );
``` | The javadoc for SocketException states that it is
> Thrown to indicate that there is an error in the underlying protocol such as a TCP error
In your case it seems that the connection has been closed by the server end of the connection. This could be an issue with the request you are sending or an issue at their end.
To aid debugging you could look at using a tool such as [Wireshark](http://www.wireshark.org) to view the actual network packets. Also, is there an alternative client to your Java code that you could use to test the web service? If this was successful it could indicate a bug in the Java code.
As you are using Commons HTTP Client have a look at the [Common HTTP Client Logging Guide](http://hc.apache.org/httpclient-3.x/logging.html). This will tell you how to log the request at the HTTP level. | This error **happens on your side** and NOT the other side. If the other side reset the connection, then the exception message should say:
```
java.net.SocketException reset by peer
```
The cause is the connection inside `HttpClient` is stale. Check stale connection for SSL does not fix this error. Solution: dump your client and recreate. | What's causing my java.net.SocketException: Connection reset? | [
"",
"java",
"sockets",
"socketexception",
"connection-reset",
""
] |
I have a Custom Control (Windows Form) that is a lookup text box. A property on the Control is Current Selection which is a Custom Object containing "Identifier", "Code" and "Description". This property is Databound using a BindingSource.
Displaying the information works great. On the other hand regardless of whether I set the Update to OnValidate or OnValueChange it never updates the BindingSource. Is there something I'm missing to get this to auto update?
```
private System.Windows.Forms.BindingSource buildPlanComponentDataBindingSource;
public void LoadBuildPlan(string itemNumber)
{
var buildPlanComponents = BuildPlan.LoadBuildPlanComponents(itemNumber, AutomaticPrice);
buildPlanComponentDataBindingSource.DataSource = buildPlanComponents;
AssemblyNumber = itemNumber;
}
[Bindable(true)]
[DefaultValue(null)]
public ILookupSelection CurrentSelection
{
get
{
if (currentSelection == null)
currentSelection = new LookupSelection {Code = txtLookup.Text};
return currentSelection;
}
set
{
if (value == null) return;
currentSelection = value;
SetText(currentSelection, DisplayText);
SetDescription(currentSelection, DisplayDescription);
}
}
``` | Implementing INotifyPropertyChanged seems to be the solution!
```
#region IPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (null != PropertyChanged)
{
PropertyChanged(this, e);
}
}
#endregion
``` | > Displaying the information works
> great. On the other hand regardless of
> whether I set the Update to OnValidate
> or OnValueChange it never updates the
> BindingSource.
Looking at your code I'm actually not sure of this. In your set, you test for null and abandon; if the data actually contains null (which is what you're describing) your control will be out of synch. I wonder if perhaps that check is masking the underlying problem. | Databinding a Custom Control | [
"",
"c#",
"winforms",
"controls",
""
] |
I see loads of code snippets with the following Syntax
```
using (RandomType variable = new RandomType(1,2,3))
{
// A bunch of code here.
}
```
why not just declare the variable and use it?
This Using syntax seems to just clutter the code and make it less readable. And if it's so important that that varible is only available in that scope why not just put that block in a function? | Using has a very distinct purpose.
It is designed for use with types that implement IDisposable.
In your case, if RandomType implements IDisposable, it will get .Dispose()'d at the end of the block. | ```
using (RandomType variable = new RandomType(1,2,3))
{
// A bunch of code here.
}
```
is pretty much the same (with a few subtle differences) as:
```
RandomType variable = new RandomType(1,2,3);
try
{
// A bunch of code
}
finally
{
if(variable != null)
variable.Dispose()
}
```
Note that when calling "Using", you can cast anything as IDisposable:
```
using(RandomType as IDisposable)
```
The null check in the finally will catch anything that doesn't actually implement IDisposable. | What is the point of having using blocks in C# code? | [
"",
"c#",
"using-statement",
""
] |
I'm going to retrofit my custom graphics engine so that it takes advantage of multicore CPUs. More exactly, I am looking for a library to parallelize loops.
It seems to me that both OpenMP and Intel's Thread Building Blocks are very well suited for the job. Also, both are supported by Visual Studio's C++ compiler and most other popular compilers. And both libraries seem quite straight-forward to use.
So, which one should I choose? Has anyone tried both libraries and can give me some cons and pros of using either library? Also, what did you choose to work with in the end?
Thanks,
Adrian | I haven't used TBB extensively, but my impression is that they complement each other more than competing. TBB provides threadsafe containers and some parallel algorithms, whereas OpenMP is more of a way to parallelise existing code.
Personally I've found OpenMP very easy to drop into existing code where you have a parallelisable loop or bunch of sections that can be run in parallel. However it doesn't help you particularly for a case where you need to modify some shared data - where TBB's concurrent containers might be exactly what you want.
If all you want is to parallelise loops where the iterations are independent (or can be fairly easily made so), I'd go for OpenMP. If you're going to need more interaction between the threads, I think TBB may offer a little more in that regard. | From Intel's software blog: [Compare Windows\* threads, OpenMP\*, Intel® Threading Building Blocks for parallel programming](http://software.intel.com/en-us/blogs/2008/12/16/compare-windows-threads-openmp-intel-threading-building-blocks-for-parallel-programming/)
It is also the matter of style - for me TBB is very C++ like, while I don't like OpenMP pragmas that much (reeks of C a bit, would use it if I had to write in C).
I would also consider the existing knowledge and experience of the team. Learning a new library (especially when it comes to threading/concurrency) does take some time. I think that for now, OpenMP is more widely known and deployed than TBB (but this is just mine opinion).
Yet another factor - but considering most common platforms, probably not an issue - portability. But the license might be an issue.
* TBB incorporates some of nice research originating from academic research, for example [recursive data parallel approach](http://software.intel.com/en-us/blogs/2007/09/28/hierarchically-tiled-arrays-and-threading-building-blocks/).
* There is some work on cache-friendliness, for [example](http://software.intel.com/en-us/blogs/2007/09/25/cache-affinity-support-for-tbb-2/).
* Lecture of the Intel blog seems really interesting. | C++ Parallelization Libraries: OpenMP vs. Thread Building Blocks | [
"",
"c++",
"multithreading",
"multicore",
"openmp",
"tbb",
""
] |
I was just dealing with strings, and I find myself annoyed that strings can be nullable. So, I have to have
```
if((teststring??string.Empty)==string.Empty)
```
all over the place. Would string? have been so hard for allowing nullability in the relatively few cases where it is needed (dbs, idiot user inputs, etc.). I also find myself irritated with having to export readonly interfaces in the cases where I want some form of const correctness. So, what C# language construct/decision annoys you?
EDIT: Thanks for the isnullorempty function, I hadn't seen that before! Still doesn't lessen my annoyance at it being nullable :D | Making string a reference type seems entirely reasonable to me.
It's a shame that one can't declare a variable/parameter/return type to be *non-nullable* though - e.g.
```
// Never returns null
public string! Foo()
{
}
```
Code contracts in .NET 4.0 will help with this, I believe - but it's a bit late to make it pervasive.
A while ago I wrote a [blog entry on the mistakes of C#](http://msmvps.com/blogs/jon_skeet/archive/2008/02/05/c-4-part-1-looking-back-at-the-past.aspx). To summarise that post:
**C# 1:**
* Lack of separate getter/setter access for properties.
* Lack of generics. Life would have been a lot sweeter with generics from the start.
* Classes not being sealed by default.
* Enums just being named numbers.
* The "\x" character escape sequence.
* Various things about the switch statement :)
* Some odd overload resolution rules
* The "lock" keyword, instead of "using" with a lock tocken.
**C# 2:**
* Lack of partial methods (came in C# 3)
* Lack of generic variance (coming in C# 4)
* The `System.Nullable` class (not `Nullable<T>` - that's fine!)
* InternalsVisibleTo requiring the whole public key for strongly signed assemblies instead of the public key token.
**C# 3:**
* Lack of support for immutability - lots of changes improved opportunities for mutating types (automatic properties, object and collection initializers) but none of these really work for mutable types
* Extension method discovery | Testing strings for Null or Empty is best done using:
```
if (string.IsNullOrEmpty(testString))
{
}
``` | What language decision in C# annoys you? | [
"",
"c#",
""
] |
So in my `persistence.xml` I turned on `hibernate.generate_statistics`.
```
<property name="hibernate.generate_statistics">true</property>
```
My question is how do I access them? Where do the statistics go? | In your dao service you can go:
```
Session session = this.sessionFactory.getCurrentSession();
SessionStatistics sessionStats = session.getStatistics();
Statistics stats = this.sessionFactory.getStatistics();
``` | i would rather use [Hibernate Statistics published via JMX](http://www.hibernate.org/216.html) if you use spring you can make it real easy with [Hibernate Statistics MBean with Spring](http://raibledesigns.com/wiki/Wiki.jsp?page=HibernateJMX) | How to get access to the Hibernate Statistics | [
"",
"java",
"hibernate",
"jpa",
"jboss",
"jakarta-ee",
""
] |
Is there a way to figure out if every function defined in code is called somewhere?
I have been doing a major code update to a large project of mine and I want to make sure the old functions that are no longer used are removed from the code.
Is there a better way then searching for each function in the solution? | Mark each method you are trying to remove as [Obsolete](http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.iserror.aspx) with `IsError` set to `true`.
When you mark a method as such, you will get a compilation error and will be able to find out if you can *safely* remove the method.
```
[Obsolete("Don't use this method", /* IsError */ true)]
public void Foo () {}
``` | [FxCop](http://msdn.microsoft.com/en-us/library/bb429476.aspx) should be able to find orphaned/unused methods. I think static analysis is what you're looking for, not code coverage. | Is there a way to check if all defined functions are called? | [
"",
"c#",
"visual-studio-2005",
""
] |
I am creating a simple 2D OpenGL application but I seem to be experiencing some camera issues. When I draw a rectangle at (20,20) it is drawn at (25,20) or so. When I draw it at (100, 20) it is drawn at 125 or so. For some reasons everything is being shifted to the right by a few %.
I have pasted a trimmed down version here
<http://pastebin.com/m56491c4c>
Is there something wrong with the way I am setting up GLUT? I know it's not my objects doing anything weird since the same thing happens when I disable them.
Thanks in advance. | You need to set the projection matrix inside the reshape function (`resize()`), which also automatically solves the problem of the user resizing the window:
```
void resize(int w, int h)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, w, h, 0);
}
```
And then in your draw function, make sure that the matrix mode is model-view:
```
void draw()
{
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
...
}
```
Other problems with your code:
* You probably shouldn't be calling `glutPostRedisplay()` at the end of `draw()`. This is going to make your CPU run at 100%. You can instead use `glutTimerFunc()` to still have updates every some number of milliseconds.
* In `processMouse()`, you're using `wsprintf()` on an array of `char`s: `wsprintf()` takes an array of wide characters (`wchar_t`), so you should make the local variable `s` of type `wchar_t[]`, or use `sprintf()` and `MessageBoxA()` instead of `wsprintf()` and `MessageBoxW()` (to which `MessageBox()` expands as a macro when compiling a Unicode application, which I'm assuming you're doing). You're also vulnerable to a buffer overflow -- you should use a buffer of at least 12 characters, even though realistically you'll never be passed a very large `x` value. Finally, you should also use `snprintf()/wsnprintf()` instead of `sprintf()/wsprintf()` to protect against the buffer overflow. | You seem to be calling your glOrtho2D on your ModelView matrix. I doubt that that's the problem (since I guess in this case, your Projection should be the identity), but you should still call it on your Projection matrix instead.
You should also print out w and h in your resize call, just to make sure that your window size is actually what you think it is (I don't know how glut works, but glutInitWindowSize() may include borders, which would mess things up). | OpenGL coordinate problem | [
"",
"c++",
"opengl",
"glut",
""
] |
I have a method called funct which i want to have as my callback function when i am using the beingreceive socket method in c#.
```
s.BeginReceive(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None,
new AsyncCallback(funct), null);
```
The error that am getting is:
> No overload for 'funct' matches delegate 'System.AsyncCallback'
What might be the problem here? | "funct" must be a method with the following signature:
```
void funct(IAsyncResult ar) { }
``` | You can't just use *any* method for your callback. The function has to have a specific signature (parameter list). | Callback Function | [
"",
"c#",
".net",
"delegates",
"callback",
""
] |
I have a float value set to NaN (seen in the Watch Window), but I can't figure out how to detect that in code:
```
if (fValue == float.NaN) // returns false even though fValue is NaN
{
}
``` | You want `float.IsNaN(...)`. Comparisons to `NaN` always return false, no matter what the value of the float is. It's one of the quirks of floating points.
That means you can do this:
```
if (f1 != f1) { // This conditional will be true if f1 is NaN.
```
In fact, that's exactly how IsNaN() works. | Try this:
```
if (float.IsNaN(fValue))
{
}
``` | How can I compare a float to NaN if comparisons to NaN always return false? | [
"",
"c#",
""
] |
I would like to do some experimenting with javascript and encryption and I got curious as to how unpredictable the implementation of the random function is. Has anyone done any hard tests?
Clearly browsers have the ability to generate strong randomness (for ssl). The questions is do they give javascript access to the same strength. | Generally, the random function is not cryptographically strong, for that you need to make sure you are using a cryptographic pseudo-random-number generator.
Generic random functions generally don't use cryptographically strong generation methods because they take longer than simple ones, (eg. Yarrow is more complicated than Mersenne Twister) and require careful management of the entropy pool, which is not a guarantee that Mozilla, cstdlib, etc. want to make to you.
If you need access to cryptographically strong random number generators, I'd look into getting access to the underlying SSL implementation (which a given browser may or may not allow access to). | Recent browsers expose [`window.crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues) which is cryptographically strong.
There are also JS libraries that implement strong RNGs but without `getRandomValues()` it's very hard part to collect entropy. It [can be done from mouse & keyboard](https://www.clipperz.com/security_privacy/crypto_algorithms/#prng) though it may take a long time.
`Math.random()` was weak in most browsers in 2008 - [Amit Klein's paper](https://dl.packetstormsecurity.net/papers/general/Temporary_User_Tracking_in_Major_Browsers.pdf) goes into excellent detail - and sadly is almost as weak today.
**UPDATE: It seems practically all browsers switched in 2015–2016 to [XorShift128+](https://en.wikipedia.org/wiki/Xorshift#xorshift.2B)** — a fast variant on LFSR tuned to good statistical properties but also very weak cryptographically: <https://lwn.net/Articles/666407/>,
<https://security.stackexchange.com/questions/84906/predicting-math-random-numbers>. Details below are out of date.
* Firefox used a very weak "our own homebrew LFSR" algorithm; they've been discussing switching to a stronger algoritm and entropy source since 2006 ([bug 322529](https://bugzilla.mozilla.org/show_bug.cgi?id=322529)). UPDATE: in 2015 they switched to XorShift128+.
In May 2013 they at least switched the seed from current time to good entropy sources ([bug 868860](https://bugzilla.mozilla.org/show_bug.cgi?id=868860)), also removing(?) cross-tab leakage.
* Webkit uses a weak fast algorithm ([GameRand](http://www.redditmirror.cc/cache/websites/mjolnirstudios.com_7yjlc/mjolnirstudios.com/IanBullard/files/79ffbca75a75720f066d491e9ea935a0-10.html)) [since 2009](https://trac.webkit.org/changeset/50789) but seeds [since 2010](https://bugs.webkit.org/show_bug.cgi?id=36673#c4) (in each context) from a strong RNG initialized from strong OS sources.
(I presume this is what Safari uses but I may be confused about the various WebKit ports...)
* Chrome doesn't use WebKit's random, does its own in V8, [a weak linear thing](https://code.google.com/p/v8/codesearch#v8/trunk/src/v8.cc&q=random_base&sq=package:v8&l=149).
There is no agreement whether Math.random() should be strong ([bug 246054](https://code.google.com/p/chromium/issues/detail?id=246054)).
Not sure how it's seeded. V8 has SetEntropySource() hook, but apparently it was only [introduced for unit testing](https://code.google.com/p/chromium/issues/detail?id=90224), not called by Chrome. If not called, `random()` is used for seeding.
State became per-context [in 2011](https://code.google.com/p/v8/issues/detail?id=864) but that's not very useful with weak seeding.
* Opera declared it [fixed in Jan 2009](http://www.opera.com/security/advisory/928) and [say here](https://github.com/cryptocat/cryptocat/issues/190) that their Math.random() is cryptographically strong.
* Didn't find documentation on what IE does nowdays. They had a weak linear PRNG in 2008 (see paper).
They did tell Amit they'll fix it in a service pack, so there might be an advisory somewhere... | How trustworthy is javascript's random implementation in various browsers? | [
"",
"javascript",
"math",
"random",
""
] |
Are Debug.Assert/Debug.Fail automatically conditionally compiled #if "DEBUG"? Or is it more like if there is no debugger attached (even in release) it just doesn't do much of anything? If so, are there performance implications of leaving them in your code? Or are they really not meant to be in production code, only test or Conditional code? | No, the whole call, incuding any expression evaluation is removed from compilation if the symbol isn't defined. This is very important - if there are any side-effects in the expression, they *won't* occur if DEBUG isn't defined. Here's a short but complete program to demonstrate:
```
using System;
using System.Diagnostics;
class Test
{
static void Main()
{
int i = 0;
Debug.Assert(i++ < 10);
Console.WriteLine(i);
}
}
```
If `DEBUG` is defined this prints out 1, otherwise it prints 0.
Due to this kind of behaviour, you can't have an `out` parameter on a conditionally-compiled method:
```
using System;
using System.Diagnostics;
class Test
{
static void Main()
{
int i ;
MethodWithOut(out x);
}
[Conditional("FOO")]
static void MethodWithOut(out int x)
{
x = 10;
}
}
```
This gives the error:
> Test.cs(13,6): error CS0685: Conditional member 'Test.MethodWithOut(out int)' cannot
> have an out parameter | The Debug.Assert/Fail API's contain a ConditionalAttribute attribute with the value "DEBUG" like so
```
[Conditional("DEBUG")]
public void Assert(bool condition)
```
The C# and VB compiler will only actually include a call to the is method if the constant DEBUG is defined when the method call is compiled in code. If it's no there, the method call will be ommitted from the IL | Are Debug.Assert/Debug.Fail automatically conditionally compiled #if "DEBUG" | [
"",
"c#",
".net",
"debugging",
""
] |
I extracted, configured and used make for the installation package in my server.
However, I could not use *make install*. I get the error
```
[~/wepapps/python/Python-2.6.1]# make install
/usr/bin/install -c python /usr/local/bin/python2.6
/usr/bin/install: cannot create regular file `/usr/local/bin/python2.6': Permission denied
make: *** [altbininstall] Error 1
```
I run the folder with
```
chmod +x Python-2.6.1
```
I get still the same error.
How can I run *make install* without sudo access? | > How can I install to a path under my home directory?
```
mkdir /home/masi/.local
cd Python-2.6.1
make clean
./configure --prefix=/home/masi/.local
make
make install
```
Then run using:
```
/home/masi/.local/bin/python
```
Similarly if you have scripts (eg. CGI) that require your own user version of Python you have to tell them explicitly:
```
#!/home/masi/.local/bin/python
```
instead of using the default system Python which “#!/usr/bin/env python” will choose.
You can alter your PATH setting to make just typing “python” from the console run that version, but it won't help for web apps being run under a different user.
If you compile something that links to Python (eg. mod\_wsgi) you have to tell it where to find your Python or it will use the system one instead. This is often done something like:
```
./configure --prefix=/home/masi/.local --with-python=/home/masi/.local
```
For other setup.py-based extensions like MySQLdb you simply have to run the setup.py script with the correct version of Python:
```
/home/masi/.local/bin/python setup.py install
``` | As of year 2020, [`pyenv`](https://github.com/pyenv/pyenv) is the best choice for installing Python without sudo permission, supposing the system has necessary build dependencies.
```
# Install pyenv
$ curl https://pyenv.run | bash
# Follow the instruction to modify ~/.bashrc
# Install the latest Python from source code
$ pyenv install 3.8.3
# Check installed Python versions
$ pyenv versions
# Switch Python version
$ pyenv global 3.8.3
# Check where Python is actually installed
$ pyenv prefix
/home/admin/.pyenv/versions/3.8.3
# Check the current Python version
$ python -V
Python 3.8.3
``` | Unable to install Python without sudo access | [
"",
"python",
"installation",
"sudo",
""
] |
I have to map two simple table with a foreign key relationship. One of the tables is **Contact** containing columns **id** (primary key of type int),**name**, **address** and **guid** (newly added and is not the primary key). The other one is **phone\_\_number** containing columns **id** (primary key of type int), **contact\_\_\_id** (foreign key of id in contact table) and **phone\_\_number**.
The mapping file for Contact table is as below :
```
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="OfflineDbSyncWithNHibernate" default-lazy="true" namespace="OfflineDbSyncWithNHibernate.Models">
<class name="Contact" table="Contact">
<id name="Id" column="Id" type="int">
<generator class="native" />
</id>
<property name="Name" column="name" type="string"/>
<property name="Address" column="address" type="string"/>
<property name="Guid" column="guid" type="string"/>
<set lazy="true" batch-size="6" table="phone_number" name="PhoneNumbers" fetch="join" inverse="false" cascade="all" >
<key foreign-key="FK_contact_phone_number" column="contact_id"/>
<one-to-many class="PhoneNumber" />
</set>
</class>
</hibernate-mapping>
```
The mapping file for Phone\_number table is :
```
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="OfflineDbSyncWithNHibernate" default-lazy="true" namespace="OfflineDbSyncWithNHibernate.Models">
<class name="PhoneNumber" table="phone_number">
<id name="Id" column="Id" type="int">
<generator class="native" />
</id>
<property name="ContactId" column="contact_id" />
<property name="Number" column="phone_number" />
</class>
</hibernate-mapping>
```
The Contact and PhoneNumber classes are :
```
namespace OfflineDbSyncWithNHibernate.Models
{
public class Contact
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Address { get; set; }
public virtual string Guid { get; set; }
public virtual PhoneNumbers PhoneNumbers { get; set; }
}
}
namespace OfflineDbSyncWithNHibernate.Models
{
public class PhoneNumber
{
public virtual int Id { get; set; }
public virtual int ContactId { get; set; }
public virtual string Number { get; set; }
}
}
namespace OfflineDbSyncWithNHibernate.Models
{
public class PhoneNumbers : List<PhoneNumber>
{
}
}
```
When I load the contact and phone\_numbers separately it works, but after adding the set element to get a one-to-many relationship nhibernate is giving an error :
NHibernate.MappingException: Invalid mapping information specified for type OfflineDbSyncWithNHibernate.Models.Contact, check your mapping file for property type mismatches
I am new to nHibernate so I am not sure if there is a mistake in the set element or I should not even be using it. Any help will be appreciated. | Just remeber this
* Bag is implemented using IList
* Set is implemented using ISet
* List is implemented using ArrayList or List
* Map is implemented using HashedTable or IDictionary
If you want to use IList use first rule i.e change your hbm.xml to use Bag instead of Set also your Phonenumbers class should inherit from IList not List, if you want to use List you will need to change your mapping file to use List instead of Set. | I think your PhoneNumbers class needs to inherit from a subtype of `Iesi.Collections.ISet`. I don't think there is a "Set" type provided in .NET by default. See hibernate [FAQ](http://www.hibernate.org/359.html)
> The <set> maps to an
> Iesi.Collections.ISet. That interface
> is part of the Iesi.Collections
> assembly distributed with NHibernate. | NHibernate one-to-many mapping problem | [
"",
"c#",
".net",
"nhibernate",
"nhibernate-mapping",
"one-to-many",
""
] |
I'm storing a bunch of supposedly-unique item IDs as a key and the file locations as the value in a hash table while traversing a table. While I am running through it, I need to make sure that they key/location pair is unique or throw an error message. I have the hashtable set up and am loading the values, but am not sure what to test:
```
Hashtable check_for_duplicates = new HashTable();
foreach (object item in items)
{
if (check_for_duplicates.ContainsKey(item["ItemID"]) &&
//what goes here? Would be contains item["Path"] as the value for the key)
{
//throw error
}
}
``` | Try this:
```
Hashtable check_for_duplicates = new HashTable();
foreach (object item in items)
{
if (check_for_duplicates.ContainsKey(item["ItemID"]) &&
check_for_duplicates[item["ItemID"]].Equals(item["Path"]))
{
//throw error
}
}
```
Also, if you're using .NET 2.0 or higher, consider using Generics, like this:
```
List<Item> items; // Filled somewhere else
// Filters out duplicates, but won't throw an error like you want.
HashSet<Item> dupeCheck = new HashSet<Item>(items);
items = dupeCheck.ToList();
```
Actually, I just checked, and it looks like HashSet is .NET 3.5 only. A Dictionary would be more appropriate for 2.0:
```
Dictionary<int, string> dupeCheck = new Dictionary<int, string>();
foreach(Item item in items) {
if(dupeCheck.ContainsKey(item.ItemID) &&
dupeCheck[item.ItemID].Equals(item.Path)) {
// throw error
}
else {
dupeCheck[item.ItemID] = item.Path;
}
}
``` | If you were using `Dictionary` instead, the `TryGetValue` method would help. I don't think there is a really better way for the pretty much deprecated `Hashtable` class.
```
object value;
if (dic.TryGetValue("key", out value) && value == thisValue)
// found duplicate
``` | How to test if a C# Hashtable contains a specific key/value pair? | [
"",
"c#",
"hashtable",
""
] |
I have a table full of tracking data for as specific course, course number 6.
Now I have added new tracking data for course number 11.
Each row of data is for one user for one course, so for users assigned to both course 6 and course 11 there are two rows of data.
The client wants all users who have completed course number 6 any time after August 1st 2008 to also have completion marked for course 11. However I can't just convert the 6 to 11 because they want to preserve their old data for course 6.
So for every row that has a course number of 6, is marked as complete, and is greater than the date August 1st 2008, I want to write the completion data over the row that contains the tracking for course 11 for that specific user.
I would need to carry over the data from the course 6 row to the course 11 row so things like user score and date of posted completion is moved over.
Here is the structure of the table:
```
userID (int)
courseID (int)
course (bit)
bookmark (varchar(100))
course_date (datetime)
posttest (bit)
post_attempts (int)
post_score (float)
post_date (datetime)
complete (bit)
complete_date (datetime)
exempted (bit)
exempted_date (datetime)
exempted_reason (int)
emailSent (bit)
```
Some values will be NULL and userID/courseID obviously won't be carried over as that is already in the right place. | Maybe I read the problem wrong, but I believe you already have inserted the course 11 records and simply need to update those that meet the criteria you listed with course 6's data.
If this is the case, you'll want to use an `UPDATE`...`FROM` statement:
```
UPDATE MyTable
SET
complete = 1,
complete_date = newdata.complete_date,
post_score = newdata.post_score
FROM
(
SELECT
userID,
complete_date,
post_score
FROM MyTable
WHERE
courseID = 6
AND complete = 1
AND complete_date > '8/1/2008'
) newdata
WHERE
CourseID = 11
AND userID = newdata.userID
```
[See this related SO question for more info](https://stackoverflow.com/questions/2334712/update-from-select-using-sql-server) | ```
UPDATE c11
SET
c11.completed= c6.completed,
c11.complete_date = c6.complete_date,
-- rest of columns to be copied
FROM courses c11 inner join courses c6 on
c11.userID = c6.userID
and c11.courseID = 11 and c6.courseID = 6
-- and any other checks
```
I have always viewed the From clause of an update, like one of a normal select. Actually if you want to check what will be updated before running the update, you can take replace the update parts with a select c11.\*. See my comments on the lame duck's answer. | Copy data from one existing row to another existing row in SQL? | [
"",
"sql",
"insert",
"copy",
"row",
""
] |
Question based on [MSDN example](https://web.archive.org/web/20170228051218/https://msdn.microsoft.com/en-us/library/aa288454(VS.71).aspx).
Let's say we have some C# classes with HelpAttribute in standalone desktop application. Is it possible to enumerate all classes with such attribute? Does it make sense to recognize classes this way? Custom attribute would be used to list possible menu options, selecting item will bring to screen instance of such class. Number of classes/items will grow slowly, but this way we can avoid enumerating them all elsewhere, I think. | Yes, absolutely. Using Reflection:
```
static IEnumerable<Type> GetTypesWithHelpAttribute(Assembly assembly) {
foreach(Type type in assembly.GetTypes()) {
if (type.GetCustomAttributes(typeof(HelpAttribute), true).Length > 0) {
yield return type;
}
}
}
``` | Well, you would have to enumerate through all the classes in all the assemblies that are loaded into the current app domain. To do that, you would call the [`GetAssemblies` method](https://learn.microsoft.com/en-us/dotnet/api/system.appdomain.getassemblies) on the [`AppDomain`](https://learn.microsoft.com/en-us/dotnet/api/system.appdomain) instance for the current app domain.
From there, you would call [`GetExportedTypes`](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.getexportedtypes) (if you only want public types) or [`GetTypes`](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.gettypes) on each [`Assembly`](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly) to get the types that are contained in the assembly.
Then, you would call the [`GetCustomAttributes` extension method](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.customattributeextensions.getcustomattributes) on each [`Type`](https://learn.microsoft.com/en-us/dotnet/api/system.type) instance, passing the type of the attribute you wish to find.
You can use LINQ to simplify this for you:
```
var typesWithMyAttribute =
from a in AppDomain.CurrentDomain.GetAssemblies()
from t in a.GetTypes()
let attributes = t.GetCustomAttributes(typeof(HelpAttribute), true)
where attributes != null && attributes.Length > 0
select new { Type = t, Attributes = attributes.Cast<HelpAttribute>() };
```
The above query will get you each type with your attribute applied to it, along with the instance of the attribute(s) assigned to it.
Note that if you have a large number of assemblies loaded into your application domain, that operation could be expensive. You can use [Parallel LINQ](https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/parallel-linq-plinq) to reduce the time of the operation (at the cost of CPU cycles), like so:
```
var typesWithMyAttribute =
// Note the AsParallel here, this will parallelize everything after.
from a in AppDomain.CurrentDomain.GetAssemblies().AsParallel()
from t in a.GetTypes()
let attributes = t.GetCustomAttributes(typeof(HelpAttribute), true)
where attributes != null && attributes.Length > 0
select new { Type = t, Attributes = attributes.Cast<HelpAttribute>() };
```
Filtering it on a specific `Assembly` is simple:
```
Assembly assembly = ...;
var typesWithMyAttribute =
from t in assembly.GetTypes()
let attributes = t.GetCustomAttributes(typeof(HelpAttribute), true)
where attributes != null && attributes.Length > 0
select new { Type = t, Attributes = attributes.Cast<HelpAttribute>() };
```
And if the assembly has a large number of types in it, then you can use Parallel LINQ again:
```
Assembly assembly = ...;
var typesWithMyAttribute =
// Partition on the type list initially.
from t in assembly.GetTypes().AsParallel()
let attributes = t.GetCustomAttributes(typeof(HelpAttribute), true)
where attributes != null && attributes.Length > 0
select new { Type = t, Attributes = attributes.Cast<HelpAttribute>() };
``` | How enumerate all classes with custom class attribute? | [
"",
"c#",
"class",
"attributes",
"custom-attributes",
"enumerate",
""
] |
I'm running Python 2.5, so this question may not apply to Python 3. When you make a diamond class hierarchy using multiple inheritance and create an object of the derived-most class, Python does the Right Thing (TM). It calls the constructor for the derived-most class, then its parent classes as listed from left to right, then the grandparent. I'm familiar with Python's [MRO](http://www.python.org/download/releases/2.3/mro/); that's not my question. I'm curious how the object returned from super actually manages to communicate to calls of super in the parent classes the correct order. Consider this example code:
```
#!/usr/bin/python
class A(object):
def __init__(self): print "A init"
class B(A):
def __init__(self):
print "B init"
super(B, self).__init__()
class C(A):
def __init__(self):
print "C init"
super(C, self).__init__()
class D(B, C):
def __init__(self):
print "D init"
super(D, self).__init__()
x = D()
```
The code does the intuitive thing, it prints:
```
D init
B init
C init
A init
```
However, if you comment out the call to super in B's init function, neither A nor C's init function is called. This means B's call to super is somehow aware of C's existence in the overall class hierarchy. I know that super returns a proxy object with an overloaded get operator, but how does the object returned by super in D's init definition communicate the existence of C to the object returned by super in B's init definition? Is the information that subsequent calls of super use stored on the object itself? If so, why isn't super instead self.super?
Edit: Jekke quite rightly pointed out that it's not self.super because super is an attribute of the class, not an instance of the class. Conceptually this makes sense, but in practice super isn't an attribute of the class either! You can test this in the interpreter by making two classes A and B, where B inherits from A, and calling `dir(B)`. It has no `super` or `__super__` attributes. | I have provided a bunch of links below, that answer your question in more detail and more precisely than I can ever hope to. I will however give an answer to your question in my own words as well, to save you some time. I'll put it in points -
1. super is a builtin function, not an attribute.
2. Every *type* (class) in Python has an `__mro__` attribute, that stores the method resolution order of that particular instance.
3. Each call to super is of the form super(type[, object-or-type]). Let us assume that the second attribute is an object for the moment.
4. At the starting point of super calls, the object is of the type of the Derived class (**say DC**).
5. super looks for methods that match (in your case `__init__`) in the classes in the MRO, after the class specified as the first argument (in this case classes after DC).
6. When the matching method is found (say in class **BC1**), it is called.
(This method should use super, so I am assuming it does - See Python's super is nifty but can't be used - link below)
That method then causes a search in the object's class' MRO for the next method, to the right of **BC1**.
7. Rinse wash repeat till all methods are found and called.
**Explanation for your example**
```
MRO: D,B,C,A,object
```
1. `super(D, self).__init__()` is called. isinstance(self, D) => True
2. Search for **next method** in the MRO in classes to the right of D.
`B.__init__` found and called
---
3. `B.__init__` calls `super(B, self).__init__()`.
isinstance(self, B) => False
isinstance(self, D) => True
4. Thus, the MRO is the same, but the search continues to the right of B i.e. C,A,object are searched one by one. The next `__init__` found is called.
5. And so on and so forth.
**An explanation of super**
<http://www.python.org/download/releases/2.2.3/descrintro/#cooperation>
**Things to watch for when using super**
<http://fuhm.net/super-harmful/>
**Pythons MRO Algorithm:**
<http://www.python.org/download/releases/2.3/mro/>
**super's docs:**
<http://docs.python.org/library/functions.html>
**The bottom of this page has a nice section on super:**
<http://docstore.mik.ua/orelly/other/python/0596001886_pythonian-chp-5-sect-2.html>
I hope this helps clear it up. | Change your code to this and I think it'll explain things (presumably `super` is looking at where, say, `B` is in the `__mro__`?):
```
class A(object):
def __init__(self):
print "A init"
print self.__class__.__mro__
class B(A):
def __init__(self):
print "B init"
print self.__class__.__mro__
super(B, self).__init__()
class C(A):
def __init__(self):
print "C init"
print self.__class__.__mro__
super(C, self).__init__()
class D(B, C):
def __init__(self):
print "D init"
print self.__class__.__mro__
super(D, self).__init__()
x = D()
```
If you run it you'll see:
```
D init
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>)
B init
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>)
C init
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>)
A init
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>)
```
Also it's worth checking out [Python's Super is nifty, but you can't use it](http://fuhm.net/super-harmful/). | How does Python's "super" do the right thing? | [
"",
"python",
"constructor",
"multiple-inheritance",
"super",
"python-2.5",
""
] |
I have a single table and it contains 4 columns:
```
Id|Hospital| Doctor|patient
1 A D1 P11
2 B D6 P61
3 A D2 P21
4 A D1 P12
5 B D7 P71
6 B D6 P62
7 B D6 P63
```
Doctors are unique to the Hospital. They don't work in other hospitals. Patients are unique to the doctor. They don't visit any other doctor. Each hospital has multiple Doctors.
If you observe there are multiple patients for each doctor.
Now the question is, How can I get "only one patient" related to each doctor? It can be any patient from the record.
I am looking forward to seeing something like this:
```
Hospital Doctor Patient
A D1 P11
A D2 P21
B D6 P61
B D7 P71
```
How do I get the id also in the above table like:
```
id Hospital Doctor Patient
1 A D1 P11
3 A D2 P21
2 B D6 P61
5 B D7 P71
```
Thanks in advance | Like this:
```
SELECT Hospital, Doctor, MAX(Patient)
FROM table
GROUP BY Hospital, Doctor
ORDER BY Hospital, Doctor
```
Since you said you don't care which patient, I just used MAX, but you could use MIN or some other grouping function as well. | I can't help but ask if this shouldn't be three tables, not one. Certainly there's a 1:m relationship between Hospital and Doctor, and another 1:m between Doctor and Patient. Each entity must have other attributes. Why are all these in a single table? I'd normalize it.
I don't understand the requirement that would say P61 or P63 should be preferred for D6 in hospital B, but I'm sure you do. | Getting the data out of one-many relation ship from same table | [
"",
"sql",
""
] |
I have a service, say foo, written in C++, that runs as root. There is the usual scrip, /etc/init.d/foo start|stop|restart.
At certain times, foo needs to reload itself. Normally after an upgrade has finished. But doing things like:
```
system("/etc/init.d/foo restart")
```
doesn't work since as soon as restart kills foo, the system() call obviously gets killed as well, and the restart script never executes to completion.
Is there another call I can use instead of system() that runs asynchronously as a sibling to the calling process, instead of creating a synchronous child?
Thanks! | Have you considered the `exec[*]` family yet? Here's one -- [`execve`](http://linux.die.net/man/2/execve). | You could put it in inittab and let init worry about restarting the process when it exits for any reason. That would also take care of automatic restarts if your process happens to crash or assert() or otherwise exit unexpectedly.
Then, to handle your use case, the process would simply terminate itself. | how do I get a process to reload itself in linux? | [
"",
"c++",
"linux",
"process",
"reload",
"restart",
""
] |
I'm just starting with NumPy so I may be missing some core concepts...
What's the best way to create a NumPy array from a dictionary whose values are lists?
Something like this:
```
d = { 1: [10,20,30] , 2: [50,60], 3: [100,200,300,400,500] }
```
Should turn into something like:
```
data = [
[10,20,30,?,?],
[50,60,?,?,?],
[100,200,300,400,500]
]
```
I'm going to do some basic statistics on each row, eg:
```
deviations = numpy.std(data, axis=1)
```
Questions:
* What's the best / most efficient way to create the numpy.array from the dictionary? The dictionary is large; a couple of million keys, each with ~20 items.
* The number of values for each 'row' are different. If I understand correctly numpy wants uniform size, so what do I fill in for the missing items to make std() happy?
Update: One thing I forgot to mention - while the python techniques are reasonable (eg. looping over a few million items is fast), it's constrained to a single CPU. Numpy operations scale nicely to the hardware and hit all the CPUs, so they're attractive. | You don't need to create numpy arrays to call numpy.std().
You can call numpy.std() in a loop over all the values of your dictionary. The list will be converted to a numpy array on the fly to compute the standard variation.
The downside of this method is that the main loop will be in python and not in C. But I guess this should be fast enough: you will still compute std at C speed, and you will save a lot of memory as you won't have to store 0 values where you have variable size arrays.
* If you want to further optimize this, you can store your values into a list of numpy arrays, so that you do the python list -> numpy array conversion only once.
* if you find that this is still too slow, try to use psycho to optimize the python loop.
* if this is still too slow, try using [Cython](http://www.cython.org/) together with the numpy module. This [Tutorial](http://wiki.cython.org/tutorials/numpy) claims impressive speed improvements for image processing. Or simply program the whole std function in Cython (see [this](http://prabhuramachandran.blogspot.com/2008_09_01_archive.html) for benchmarks and examples with sum function )
* An alternative to Cython would be to use [SWIG](http://www.swig.org/) with [numpy.i](http://projects.scipy.org/scipy/numpy/browser/trunk/doc/swig/numpy.i).
* if you want to use only numpy and have everything computed at C level, try grouping all the records of same size together in different arrays and call numpy.std() on each of them. It should look like the following example.
example with O(N) complexity:
```
import numpy
list_size_1 = []
list_size_2 = []
for row in data.itervalues():
if len(row) == 1:
list_size_1.append(row)
elif len(row) == 2:
list_size_2.append(row)
list_size_1 = numpy.array(list_size_1)
list_size_2 = numpy.array(list_size_2)
std_1 = numpy.std(list_size_1, axis = 1)
std_2 = numpy.std(list_size_2, axis = 1)
``` | While there are already some pretty reasonable ideas present here, I believe following is worth mentioning.
Filling missing data with any default value would spoil the statistical characteristics (std, etc). Evidently that's why Mapad proposed the nice trick with grouping same sized records.
The problem with it (assuming there isn't any a priori data on records lengths is at hand) is that it involves even more computations than the straightforward solution:
1. at least *O(N\*logN)* 'len' calls and comparisons for sorting with an effective algorithm
2. *O(N)* checks on the second way through the list to obtain groups(their beginning and end indexes on the 'vertical' axis)
Using Psyco is a good idea (it's strikingly easy to use, so be sure to give it a try).
It seems that the optimal way is to take the strategy described by Mapad in bullet #1, but with a modification - not to generate the whole list, but iterate through the dictionary converting each row into numpy.array and performing required computations. Like this:
```
for row in data.itervalues():
np_row = numpy.array(row)
this_row_std = numpy.std(np_row)
# compute any other statistic descriptors needed and then save to some list
```
In any case a few million loops in python won't take as long as one might expect. Besides this doesn't look like a routine computation, so who cares if it takes extra second/minute if it is run once in a while or even just once.
---
A generalized variant of what was suggested by Mapad:
```
from numpy import array, mean, std
def get_statistical_descriptors(a):
if ax = len(shape(a))-1
functions = [mean, std]
return f(a, axis = ax) for f in functions
def process_long_list_stats(data):
import numpy
groups = {}
for key, row in data.iteritems():
size = len(row)
try:
groups[size].append(key)
except KeyError:
groups[size] = ([key])
results = []
for gr_keys in groups.itervalues():
gr_rows = numpy.array([data[k] for k in gr_keys])
stats = get_statistical_descriptors(gr_rows)
results.extend( zip(gr_keys, zip(*stats)) )
return dict(results)
``` | Best way to create a NumPy array from a dictionary? | [
"",
"python",
"numpy",
""
] |
When using objects that have a capacity, what are some guidelines that you can use to ensure the best effeciency when using to collections? It also seems like .NET framework has set some of these capacities low. For example, I think StringBuilder has an intial capacity of 16. Does this mean that after 16 strings are inserted into the StringBuilder, the StringBuilder object is reallocated and doubled in size? | With `StringBuilder`, it isn't the number of *strings*, but the number of *characters*. In general; if you can predict the length, go ahead and tell it - but since it uses doubling, there isn't a *huge* overhead in reallocating occasionally if you need to juts use `Add` etc.
In most cases, the difference will be trivial and a micro-optimisation. The biggest problem with not telling it the size is that unless the collection has a "trim" method, you might have nearly double the size you really needed (if you are very unlucky). | If you know how large a collection or StringBuilder will be up front, it is good practice to pass that as the capacity to the constructor. That way, only one allocation will take place. If you don't know the precise number, even an approximation can be helpful. | What is the best way to determine the initial capacity for collection objects? | [
"",
"c#",
"collections",
""
] |
I have a tuple of tuples containing strings:
```
T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
```
I want to convert all the string elements into integers and put them back into a list of lists:
```
T2 = [[13, 17, 18, 21, 32],
[7, 11, 13, 14, 28],
[1, 5, 6, 8, 15, 16]]
``` | [`int()`](https://docs.python.org/3/library/functions.html#int) is the Python standard built-in function to convert a string into an integer value. You call it with a string containing a number as the argument, and it returns the number converted to an integer:
```
>>> int("1") + 1
2
```
If you know the structure of your list, T1 (that it simply contains lists, only one level), you could do this in Python 3:
```
T2 = [list(map(int, x)) for x in T1]
```
In Python 2:
```
T2 = [map(int, x) for x in T1]
``` | You can do this with a list comprehension:
```
T2 = [[int(column) for column in row] for row in T1]
```
The inner list comprehension (`[int(column) for column in row]`) builds a `list` of `int`s from a sequence of `int`-able objects, like decimal strings, in `row`. The outer list comprehension (`[... for row in T1])`) builds a list of the results of the inner list comprehension applied to each item in `T1`.
The code snippet will fail if any of the rows contain objects that can't be converted by `int`. You'll need a smarter function if you want to process rows containing non-decimal strings.
If you know the structure of the rows, you can replace the inner list comprehension with a call to a function of the row. Eg.
```
T2 = [parse_a_row_of_T1(row) for row in T1]
``` | How do I convert all strings in a list of lists to integers? | [
"",
"python",
"string",
"integer",
""
] |
I have a "generate website" command, that parses through all the tables to republish an entire website into fixed html pages. That's a heavy process, at least on my local machine (the CPU rises up). On the production server it does not seem to be a problem so far but i would like to keep it future proof. Therefore i'm considering using the php sleep() function between each step of the heavy script so that the server has time to "catch its breath" between the heavy steps.
Is that a good idea or will it be useless? | If you're running php5, and it's being used in CGI (rather than mod\_php) mode, then you could consider using `proc_nice` instead.
This could allow the "generate website" command to use as much CPU as it wants while no-one else is trying to use the site. | I would simply not do this on the Production Server, the steps I have followed before:
1. Rent a low cost PHP server - or get a proper Dev server setup that replicates the production
2. All Dynamic files are copied to DEV - they dont even need to be on the production
3. Run the HTMLizer script - no sleep just burn it out
4. Validate the ouput and then RSYNC this to the live server - backing up the live directory as you do it so you can safely fall back
Anyway since Caching / Memcaching came up to speed I havent had to do this at all - use Zend Framework and Zend Cache and you basically have a dynamic equivalent to what you need to do automatically. | Is using php sleep() function a good idea to keep CPU load down with heavy script? | [
"",
"php",
"sleep",
""
] |
It's time for my first question now. How do you cross assignments operators between two classes?
```
class B;
class A {
public:
A &operator = ( const B &b );
friend B &B::operator = ( const A &a ); //compiler error
};
class B {
public:
B &operator = ( const A &a );
friend A &A::operator = ( const B &b );
};
```
I searched for how to forward declare a member function like:
```
class B;
B &B::operator = ( const A &a ); //error
```
But I didn't find anything. And I don't want to make the classes all-out friends with each other. How do I do this? | The reason for the compiler error is a circular dependency. Each of your operator=() functions require knowledge of the operator=() function inside the other class, so no matter which order you define your classes in, there will always be an error.
Here is one way to sort it out. It isn't very elegant, but it will do what you want:
```
class A;
class B;
A & set_equal(A & a, const B & b);
B & set_equal(B & a, const A & a);
class A
{
private:
int x;
public:
A & operator=(const B & b) { return set_equal(*this, b); }
friend B & set_equal(B & b, const A & a);
friend A & set_equal(A & a, const B & b);
};
class B
{
private:
int y;
public:
B & operator=(const A & a) { return set_equal(*this, a); }
friend A & set_equal(A & a, const B & b);
friend B & set_equal(B & b, const A & a);
};
A & set_equal(A & a, const B & b) { a.x = b.y; return a; }
B & set_equal(B & b, const A & a) { b.y = a.x; return b; }
```
You may also be able to solve this problem with inheritance.
**edit:** here is an example using inheritance. This will work if the copying procedure only needs access to some common data shared by both A and B, which would seem likely if the = operator is to have any meaning at all.
```
class A;
class B;
class common
{
protected:
int x;
void copyFrom(const common & c) { x = c.x; }
};
class A : public common
{
public:
A & operator=(const common & c) { copyFrom(c); return *this; }
};
class B : public common
{
public:
B & operator=(const common & c) { copyFrom(c); return *this; }
};
``` | There is no way to forward-declare member functions. I'm not sure if there is a more elegant way than this to get what you want (I've never had reason to do something like this), but what would work would be to make for the second class a non-member function that is a friend to both classes, and delegate copying to it. Note that operator= cannot be itself a non-member, but something like this should work:
```
class B;
class A {
public:
A& operator = ( const B &b );
friend B& do_operator_equals ( B& b, const A& b);
};
class B {
public:
B &operator = ( const A &a );
friend A& A::operator = ( const B &b );
friend B& do_operator_equals ( B& b, const A& a);
};
```
And then in your implementation file
```
A& A::operator= (const B& b) {
// the actual code to copy a B into an A
return *this;
}
B& B::operator= (const A& a) {
return do_operator_equals(*this, a);
}
B& do_operator_equals(B& b, const A& a) {
// the actual code to copy an A into a B
return b;
}
```
**Edit:** Got the A's and B's backwards, oops. Fixed. | Crossing assignment operators? | [
"",
"c++",
""
] |
I made the following code example to learn how to use a generics method signature.
In order to get a **Display() method** for both Customer and Employee, I actually began replacing my **IPerson interface** with an **Person abstract class**.
But then I stopped, remembering a podcast in which Uncle Bob was telling Scott Hanselman about the **Single Responsibility Principle** in which you should have lots of little classes each doing one specific thing, i.e. that a Customer class should not have a **Print()** and **Save()** and **CalculateSalary()** method but that you should have a ***CustomerPrinter class*** and a ***CustomerSaver class*** and a ***CustomerSalaryCalculator class***.
That seems an odd way to program. However, **getting rid of my interface also felt wrong** (since so many IoC containers and DI examples use them inherently) so I decided to give the Single Responsibility Principle a try.
So **the following code is different than I have programmed in the past** (I would have made an abstract class with a Display() method and got rid of the interface) but based on what I have heard about decoupling and the S.O.L.I.D. principles, **this new way of coding** (the interface and the PersonDisplayer class) **I think this is the right way to go**.
I would **like to hear if others think the same way** on this issue or have experienced positive or negative effects of this (e.g. an unwieldy number of classes each doing one particular thing, etc.).
```
using System;
namespace TestGeneric33
{
class Program
{
static void Main(string[] args)
{
Container container = new Container();
Customer customer1 = container.InstantiateType<Customer>("Jim", "Smith");
Employee employee1 = container.InstantiateType<Employee>("Joe", "Thompson");
Console.WriteLine(PersonDisplayer.SimpleDisplay(customer1));
Console.WriteLine(PersonDisplayer.SimpleDisplay(employee1));
Console.ReadLine();
}
}
public class Container
{
public T InstantiateType<T>(string firstName, string lastName) where T : IPerson, new()
{
T obj = new T();
obj.FirstName = firstName;
obj.LastName = lastName;
return obj;
}
}
public interface IPerson
{
string FirstName { get; set; }
string LastName { get; set; }
}
public class PersonDisplayer
{
private IPerson _person;
public PersonDisplayer(IPerson person)
{
_person = person;
}
public string SimpleDisplay()
{
return String.Format("{1}, {0}", _person.FirstName, _person.LastName);
}
public static string SimpleDisplay(IPerson person)
{
PersonDisplayer personDisplayer = new PersonDisplayer(person);
return personDisplayer.SimpleDisplay();
}
}
public class Customer : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Company { get; set; }
}
public class Employee : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int EmployeeNumber { get; set; }
}
}
``` | I like to think of the [Single Responsibility Principle](http://en.wikipedia.org/wiki/Single_responsibility_principle) as an implementation of [separation of duties](http://en.wikipedia.org/wiki/Separation_of_duties). Before I start splitting my classes as you have, I try to think of what each class should be responsible for.
Your classes are quite simple and lend themselves well to an abstract class with an implemented `Print()` and `Save()` functions as you mentioned. I would tend to keep that design over your current one.
However, if printing and saving were more complicated tasks which might be performed in different ways then a dedicated `Printer` or `Saver` class would be warranted, since that responsibility is now more complex. The 'complexity' threshold for making a new class is very subjective and will depend on the exact situation, but in the end, the code is just an abstraction for us lowly humans to understand, so make it such that it's the most intuitive.
You `Container` class is a little misleading. It doesn't actually 'contain' anything. It actually implements the [Factory Method Pattern](http://en.wikipedia.org/wiki/Factory_method) and would benefit from being named a factory.
Also, your `PersonDisplayer` is never instantiated and can provide all of its functionality through static methods, so why not make it a static class? It's not uncommon for [utility classes](http://en.wikipedia.org/wiki/Utility_pattern) such as Printers or savers to be static. Unless you have a need to have separate instances of a printer with different properties, keep it static. | I think you're on the right track. I'm not entirely sure about the Container class though. I'd generally stick with the simpler solution of just using "new" for these objects unless you have some business-driven need for that interface. (I don't consider "neat" to be a business requirement in this sense)
But the separation of "being" a customer responsibility from "displaying a customer" is nice. Stick with that, it's nice interpretation of SOLID principles.
Personally I have now *completely* stopped used any kind of static methods in this kind of code, and I rely on DI to get all the right service objects at the right place & time. Once you start elaborating further on the SOLID principles you'll find you're making a lot more classes. Try to work on those naming conventions to stay consistent. | It this an example of the Single Responsibility Principle? | [
"",
"c#",
"design-patterns",
"solid-principles",
""
] |
I have been looking for C# examples to transform a DAG into a Tree.
Does anyone have an examples or pointers in the right direction?
**Clarification Update**
I have a graph that contains a list of modules that my application is required to load. Each module has a list of modules it depends on. For example here are my modules, A, B C, D and E
* A has no dependencies
* B depends on A, C and E
* C depends on A
* D depends on A
* E depends on C and A
I want resolve dependencies and generate a tree that looks like this...
--A
--+--B
-----+--C
---------+--D
--+--E
**Topological Sort**
Thanks for the information, if I perform a Topological sort and reverse the output i will have the following order
* A
* B
* C
* D
* E
I want to maintain the hierarchical structure so that my modules are loaded into the correct context, for example... module E should be in the same container as B
Thanks
Rohan | There's the graph theoretical answer and the programmer's answer to this. I assume you can handle the programmers part yourself. For the graph theorethical answer:
* A DAG is a set of modules where it never happens that A needs B, and at the same time, B (or one of the modules B needs) needs A, in modules-speak: no circular dependency. I've seen circular dependencies happen (search the Gentoo forums for examples), so you can't even be 100% sure you have a DAG, but let's assume you have. It it not very hard to do a check on circular dependencies, so I'd recommend you do so somewhere in your module loader.
* In a tree, something that never can happen is that A depends on B and C and that both B and C depend on D (a diamond), but this can happen in a DAG.
* Also, a tree has exactly one root node, but a DAG can have multiple "root" nodes (i.e. modules that nothing depends on). For example a program like the GIMP, the GIMP program will be the root node of the set of modules, but for GENTOO, almost any program with a GUI is a "root" node, while the libraries etc are dependencies of them. (I.E. both Konqueror and Kmail depend on Qtlib, but nothing depends on Konqueror, and nothing depends on Kmail)
The Graph theorethical answer to your question, as others pointed out, is that a DAG can't be converted to a tree, while every tree is a DAG.
However, (high-level programmers answer) if you want the tree for graphical representations, you're only interested in the dependencies of a specific module, not what's depending on that module. Let me give an example:
```
A depends on B and C
B depends on D and E
C depends on D and F
```
I can't show this as an ASCII-art tree, for the simple reason that this can't be converted into a tree.
However, if you want to show what A depends on, you can show this:
```
A
+--B
| +--D
| +--E
+--C
+--D
+--F
```
As you see, you get double entries in your tree - in this case "only" D but if you do an "expand all" on the Gentoo tree, I guarantee you that your tree will have at least 1000 times the amount of nodes as there are modules. (there are at least 100 packages that depend on Qt, so everything Qt depends on will be present at least 100 times in the tree).
If you have a "large" or "complex" tree, It might be best to expand the tree dynamically, not in advance, otherwise you might have a very memory-intensive process.
The disadvantage of the tree above is that if you click open B, then D, you see that A and B depend on D, but not that also C depends on D. However, depending on your situation, this might not be important at all - if you maintain a list of loaded modules, on loading C you see that you have loaded D already, and it doesn't matter it wasn't loaded for C, but for B. It is loaded, that's all that matters. If you dynamically maintain what directly depends on a certain module, you can handle the opposite problem (unloading) as well.
However, what you can't do with a tree is what's in your final sentence: preserve topological order, i.e. if B gets loaded in the same container as C, you'll never get to load C in the same container as well. Or you might have to be put up with putting everything in one container (not that I fully understand what you mean with "loading into the same container")
Good luck! | A DAG and a tree are not the same thing mathematically. Thus, any conversion introduces ambiguity. A tree by definition has no cycles, period. | How to convert Directed Acyclic Graph (DAG) to Tree | [
"",
"c#",
"data-structures",
"tree",
"directed-acyclic-graphs",
""
] |
I want to ensure certain input into my webapp contains only characters that can represented as ascii (it's for tagging and I'm trying to save space in the database column by using varchar instead of nvarchar)
Is there a framework feature to do this in .net or should I check the character codes one by one to ensure they're in the correct range?
EDIT:
I just wrote this extension method but it seems too cumbersome for something so simple.
```
public static bool IsAscii(this string value)
{
if (value != null)
for (int current = 0; current < value.Length; current++)
{
if ((int)value[current] > 127)
return false;
}
return true;
}
``` | Given that you're using an extension method, you're presumably using C# 3 and .NET 3.5. In that case I'd use:
```
using System.Linq;
...
public static bool IsPrintableAscii(this string value)
{
return value != null && value.All(c => c >= 32 && c < 127);
}
```
This will check that every character is in the range [U+0020-U+007E] which only contains printable characters. Is that what you're after?
As other comments have said, that will exclude everything with accents etc - are you sure that's okay? This also rejects carriage return, linefeed and tab. Again, is that all right? | You can run the text through a System.Text.ASCIIEncoding which will make sure everything is ASCII (any character that doesn't map to an ASCII character will be converted to a '?'). | Ensure ascii values | [
"",
"c#",
".net",
""
] |
Say I have an enum which is just
```
public enum Blah {
A, B, C, D
}
```
and I would like to find the enum value of a string, for example `"A"` which would be `Blah.A`. How would it be possible to do this?
Is the [`Enum.valueOf()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Enum.html#valueOf(java.lang.Class,java.lang.String)) the method I need? If so, how would I use this? | Yes, `Blah.valueOf("A")` will give you `Blah.A`.
Note that the name must be an *exact* match, including case: `Blah.valueOf("a")` and `Blah.valueOf("A ")` both throw an `IllegalArgumentException`.
The static methods `valueOf()` and `values()` are created at compile time and do not appear in source code. They do appear in Javadoc, though; for example, [`Dialog.ModalityType`](http://docs.oracle.com/javase/7/docs/api/java/awt/Dialog.ModalityType.html) shows both methods. | Another solution if the text is not the same as the enumeration value:
```
public enum Blah {
A("text1"),
B("text2"),
C("text3"),
D("text4");
private String text;
Blah(String text) {
this.text = text;
}
public String getText() {
return this.text;
}
public static Blah fromString(String text) {
for (Blah b : Blah.values()) {
if (b.text.equalsIgnoreCase(text)) {
return b;
}
}
return null;
}
}
``` | How to get an enum value from a string value in Java | [
"",
"java",
"enums",
""
] |
An extremely secure ASP.NET application is having to be written at my work and instead of trawling through the Internet looking for best practices I was wondering as to what considerations and generally what things should be done to ensure a public web application is safe.
Of course we've taken into consideration user/pass combinations but there needs to be a much deeper level than this. I'm talking about every single level and layer of the application i.e.
* Using URL rewrites
* Masterpages
* SiteMaps
* Connection pooling
* Session data
* Encoding passwords.
* Using stored procedures instead of direct SQL statements
I'm making this a community wiki as there wouldn't be one sole answer which is correct as it's such a vast topic of *discussion*. I will point out also that this is not my forte by any means and previous security lockdown has been reached via non-public applications. | That's a bigger toppic than I think you perhaps realise. The best advice is to get someone that already knows who can advise you. Failing that I would start by reading the Microsoft document "[Improving Web Application Security: Threats and Countermeasures](http://msdn.microsoft.com/en-us/library/ms994921.aspx)" but be warned that runs to 919 printed pages. | You should refine the idea of "stored procedures" into just using parameterized queries. That will take care of most of your problems there. You can also restrict fields on the UI and strip out or encode damaging characters like the pesky ';'... | Public ASP.NET Application Security Considerations | [
"",
"asp.net",
"sql",
"security",
""
] |
I'm trying to get to the bottom of a problem with our Java applet based program. It quite regularly seizes up with an unresponsive GUI (or a white screen). This of course only happens when deployed at a customer site :-(. They are running a version of the Sun JVM in 1.5 series (not sure the exact release).
We have a theory that it's to do with the applet running out of heap space - does that sound plausible? The other thing that I have set up on my machine is disabling direct draw, but that was mainly to avoid weird artefacts on other applications.
They are seeing the problem on Citrix and on regular PCs, but obviously there is a limit to what the users on Citrix can do.
Any suggestions? | Running out of heap space should cause an `OutOfMemoryError` to be thrown. This case sounds like a typical deadlock. To find where that is you want a stack dump of all the threads. IIRC< you can do it through the console, or from IIRC 1.6 the JDK includes `jps` and `jstack`. | First of all ensure the customer uses the latest release of the JVM they are using, and make them enable the Java console inside their browser (this requires some research from you).
Then when it happens again, tell them to look at the console window and cut-paste the contents in a mail to you. | Java applet white screen | [
"",
"java",
"applet",
""
] |
I have this idea that using SQL VIEWS to abstract simple database computations (such as a count on a relation) is sufficient, and you don't need procedures (== procedural code)
A simple sql ***view*** + a ***where*** clause >> a stored procedure with parameters sometimes
While making this point I imagined a way of retrieving table/view data without writing SQL and without writing the where clause..
But, to my surprise, there does not seem a way to accomplish this in ADO.NET 2.0 or later.
Let me tell you what I tried:
* SqlDataAdapter + SqlCommandBuilder still requires you to write "SELECT ... FROM" and the **WHERE CLAUSE** in strings (plus, if you put the 'where', you dont have much use of Update/Insert/DeleteCommand)
* typed DataSets only allow you to retrieve \_entire DataTable\_s and then applying filters to them. Filters are strings, without escaping aid... (must double the single quote!)
* SQL to Entities looked promising but they seem to: be limited to MSSQL, generate bloated SQL queries, generate a whole new stack of DAOs (besides the existing Domain Model classes), reqiuire .net 3.5+ for all this etc. (that is, all these are disadvantages for me)
Other ORMs have similar problems as SQL to Entities.
What I'm looking for is a strong-typed method of accessing database tables/***views*** that:
* doesn't come with another set of DAOs (K.I.S.S)
* allows me to query a table without writing "SELECTs" in strings (strong-typed)
* allows me to filter(***WHERE***) a table with properly-escaped parameters (and without retrieving the whole data beforehand)
* can later issue updates/inserts/deletes
I am fairly new to .Net but not stupid: does this exist?
Thanks. | [Subsonic](http://subsonicproject.com) has a fairly lightweight [query tool](http://subsonicproject.com/docs/Simple_Query_Tool) that you can use to directly query against the database with a Query object that abstracts the SQL. If you want to, you can also use its code generation facility to map your database tables to POCOs, or to only create a strongly typed schema (for column/table names and so on). | [FluentADO](http://fluentado.codeplex.com/) | ADO.net without writing SQL (esp. WHERE) | [
"",
"sql",
"stored-procedures",
"ado.net",
"datatable",
"view",
""
] |
I have a function for which I cannot change the function parameters. I need to return a const reference to a std::string created in this function. I tried to use boost shared\_ptr, but this doesn't work. Why? How do I make this work?
```
const std::string& getVal(const std::string &key) {
boost::shared_ptr<std::string> retVal(new std::string());
... //build retVal string with += operator based on key
return *retVal;
}
``` | You can't return a reference to a local variable from a function with c++. Although in c++0x this is possible.
**Allocate the string on the heap and manually cleanup later:**
If you cannot change the function's interface, then you will need to create it on the heap and then manually delete it after.
```
//Remember to free the address that getVal returns
const std::string& getVal(const std::string &key) {
std::string *retVal = new std::string();
... //build retVal string with += operator based on key
return *retVal;
}
```
**Same solution but not manually:**
Since the above will eventually lead to a memory leak if you forget to free it manually. I would recommend to wrap this call into a class and use RAII. I.e. in the constructor, call getVal and set a member of this class to point to it. In the destructor of your class you would delete it.
**Why the code you gave with shared\_ptr does not work:**
shared\_ptr works via reference counting. Since you are destroying the only shared\_ptr object (by scope), there are no references left and the memory will be freed. To get this to work you'd have to return a shared\_ptr, but you said you cannot do this. | You would need to return a boost shared\_ptr, not a std::string. As soon as the function exits that shared\_ptr on the stack will go out of scope and because there's only one reference it will be deleted. You would also need to return a copy not a reference.
You should never return a reference to a stack variable because again, as soon as the function exists it will be deleted.
If you cannot change the return type then the only (icky) option would be to allocate the string on the heap, return a reference to the pointer, and make sure the calling code knows it's a pointer and later deletes it.
E.g.
```
const std::string& getVal(const std::string &key) {
return *(new std::string("Something"));
}
// get the val, remember we must delete this pointer!
std::string* pString = &getVal("SomeKey");
delete pString;
``` | How can I return a const ref a to local variable in C++? | [
"",
"c++",
"boost",
""
] |
I want to read unsigned bytes from a binary file.
So I wrote the following code.
```
#include <iostream>
#include <fstream>
#include <vector>
#include <istream>
std::string filename("file");
size_t bytesAvailable = 128;
size_t toRead = 128;
std::basic_ifstream<unsigned char> inf(filename.c_str(), std::ios_base::in | std::ios_base::binary) ;
if (inF.good())
{
std::vector<unsigned char> mDataBuffer;
mDataBuffer.resize(bytesAvailable) ;
inF.read(&mDataBuffer[0], toRead) ;
size_t counted = inF.gcount() ;
}
```
This results in reading in always 0 bytes as shown by the variable counted.
There seem to be references on the web saying that I need to set the locale to make this work. How to do this exactly is not clear to me.
The same code works using the data type 'char' instead of 'unsigned char'
The above code using unsigned char seems to work on Windows but fails running in a colinux Fedora 2.6.22.18 .
What do I need to do to get it to work for linux? | C++ does require the implementation only to provide explicit specializations for two versions of character traits:
```
std::char_traits<char>
std::char_traits<wchar_t>
```
The streams and strings use those traits to figure out a variety of things, like the EOF value, comparison of a range of characters, widening of a character to an int, and such stuff.
If you instantiate a stream like
```
std::basic_ifstream<unsigned char>
```
You have to make sure that there is a corresponding character trait specialization that the stream can use and that this specialization does do useful things. In addition, streams use facets to do actual formatting and reading of numbers. Likewise you have to provide specializations of those too manually. The standard doesn't even require the implementation to have a complete definition of the primary template. So you could aswell get a compile error:
> error: specialization std::char\_traits could not be instantiated.
I would use `ifstream` instead (which is a `basic_ifstream<char>`) and then go and read into a `vector<char>`. When interpreting the data in the vector, you can still convert them to `unsigned char` later. | Don't use the basic\_ifstream as it requires specializtion.
Using a static buffer:
```
linux ~ $ cat test_read.cpp
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main( void )
{
string filename("file");
size_t bytesAvailable = 128;
ifstream inf( filename.c_str() );
if( inf )
{
unsigned char mDataBuffer[ bytesAvailable ];
inf.read( (char*)( &mDataBuffer[0] ), bytesAvailable ) ;
size_t counted = inf.gcount();
cout << counted << endl;
}
return 0;
}
linux ~ $ g++ test_read.cpp
linux ~ $ echo "123456" > file
linux ~ $ ./a.out
7
```
using a vector:
```
linux ~ $ cat test_read.cpp
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main( void )
{
string filename("file");
size_t bytesAvailable = 128;
size_t toRead = 128;
ifstream inf( filename.c_str() );
if( inf )
{
vector<unsigned char> mDataBuffer;
mDataBuffer.resize( bytesAvailable ) ;
inf.read( (char*)( &mDataBuffer[0]), toRead ) ;
size_t counted = inf.gcount();
cout << counted << " size=" << mDataBuffer.size() << endl;
mDataBuffer.resize( counted ) ;
cout << counted << " size=" << mDataBuffer.size() << endl;
}
return 0;
}
linux ~ $ g++ test_read.cpp -Wall -o test_read
linux ~ $ ./test_read
7 size=128
7 size=7
```
using reserve instead of resize in first call:
```
linux ~ $ cat test_read.cpp
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main( void )
{
string filename("file");
size_t bytesAvailable = 128;
size_t toRead = 128;
ifstream inf( filename.c_str() );
if( inf )
{
vector<unsigned char> mDataBuffer;
mDataBuffer.reserve( bytesAvailable ) ;
inf.read( (char*)( &mDataBuffer[0]), toRead ) ;
size_t counted = inf.gcount();
cout << counted << " size=" << mDataBuffer.size() << endl;
mDataBuffer.resize( counted ) ;
cout << counted << " size=" << mDataBuffer.size() << endl;
}
return 0;
}
linux ~ $ g++ test_read.cpp -Wall -o test_read
linux ~ $ ./test_read
7 size=0
7 size=7
```
As you can see, without the call to .resize( counted ), the size of the vector will be wrong. Please keep that in mind.
it is a common to use casting see [cppReference](http://www.cppreference.com/wiki/io/read) | C++ reading unsigned char from file stream | [
"",
"c++",
"file-io",
"stream",
"ifstream",
""
] |
I am reading data from serial port. The data comes off the scale. I am now using `Readline()` and getting data dropped even after I removed `DiscardInBuffer()`.
What is the proper way to read the data from the serial port? There are so few examples online that I feel it's like some holy grail that no one has figured out.
C#, WinCE 5.0, HP thin client, Compact framework 2.0
```
private void WeighSample()
{
this._processingDone = false;
this._workerThread = new Thread(CaptureWeight);
this._workerThread.IsBackground = true;
this._workerThread.Start();
} //end of WeighSample()
private void CaptureWeight()
{
globalCounter++;
string value = "";
while (!this._processingDone)
{
try
{
value = this._sp.ReadLine();
if (value != "")
{
if (value == "ES")
{
_sp.DiscardInBuffer();
value = "";
}
else
{
this.Invoke(this.OnDataAcquiredEvent, new object[] { value });
}
}
}
catch (TimeoutException)
{
//catch it but do nothing
}
catch
{
//reset the port here?
MessageBox.Show("some other than timeout exception thrown while reading serial port");
}
}
} //end of CaptureWeight()
```
One thing to note about my application is that I start the thread (weighSample) when the cursor jumps onto the textbox. The reason to this is that the weight can also be typed in manually (part of the requirements). So I don't know in advance whether a user is going to press PRINT on the balance or type the weight. In either case after the data is acquired, I exit the worker thread. Also, note that I am not using serial port event DataReceived, since I have been told it's not reliable.
This is my first experience with serial ports. | I have *never* had luck with ReadLine working. Just do a Read into a local buffer whenever data is available and then use a separate thread to scan the data and find line breaks yourself. | Depends on what the end-of-line (EOL) character(s) is for your input data. If your data is line oriented then ReadLine is a valid function to use, but you may want to look at the NewLine property and be sure that it is set appropriately for your input data.
For example, if your scale outputs linefeed for EOL then set `port.NewLine = "\n";`
<http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.newline.aspx> | Serial Port ReadLine vs ReadExisting or how to read the data from serial port properly | [
"",
"c#",
"compact-framework",
"serial-port",
"windows-ce",
""
] |
The other week, I wrote a little thread class and a one-way message pipe to allow communication between threads (two pipes per thread, obviously, for bidirectional communication). Everything worked fine on my Athlon 64 X2, but I was wondering if I'd run into any problems if both threads were looking at the same variable and the local cached value for this variable on each core was out of sync.
I know the *volatile* keyword will force a variable to refresh from memory, but is there a way on multicore x86 processors to force the caches of all cores to synchronize? Is this something I need to worry about, or will *volatile* and proper use of lightweight locking mechanisms (I was using \_InterlockedExchange to set my volatile pipe variables) handle all cases where I want to write "lock free" code for multicore x86 CPUs?
I'm already aware of and have used Critical Sections, Mutexes, Events, and so on. I'm mostly wondering if there are x86 intrinsics that I'm not aware of which force or can be used to enforce cache coherency. | `volatile` only forces your code to re-read the value, it cannot control where the value is read from. If the value was recently read by your code then it will probably be in cache, in which case volatile will force it to be re-read from cache, NOT from memory.
There are not a lot of cache coherency instructions in x86. There are prefetch instructions like [`prefetchnta`](http://www.felixcloutier.com/x86/PREFETCHh.html), but that doesn't affect the memory-ordering semantics. It used to be implemented by bringing the value to L1 cache without polluting L2, but things are more complicated for modern Intel designs with a large shared *inclusive* L3 cache.
x86 CPUs use a variation on the [MESI protocol](https://en.wikipedia.org/wiki/MESI_protocol) (MESIF for Intel, MOESI for AMD) to keep their caches coherent with each other (including the private L1 caches of different cores). A core that wants to write a cache line has to force other cores to invalidate their copy of it before it can change its own copy from Shared to Modified state.
---
You don't need any fence instructions (like MFENCE) to produce data in one thread and consume it in another on x86, because x86 loads/stores have [acquire/release semantics](http://preshing.com/20120913/acquire-and-release-semantics/) built-in. You do need MFENCE (full barrier) to get sequential consistency. (A previous version of this answer suggested that `clflush` was needed, which is incorrect).
You do need to prevent [compile-time reordering](http://preshing.com/20120625/memory-ordering-at-compile-time/), because C++'s memory model is weakly-ordered. `volatile` is an old, bad way to do this; C++11 std::atomic is a much better way to write lock-free code. | Cache coherence is guaranteed between cores due to the MESI protocol employed by x86 processors. You only need to worry about memory coherence when dealing with external hardware which may access memory while data is still siting on cores' caches. Doesn't look like it's your case here, though, since the text suggests you're programming in userland. | Can I force cache coherency on a multicore x86 CPU? | [
"",
"c++",
"multithreading",
"x86",
"multicore",
"cpu-cache",
""
] |
I have two tables. Those tables have two relation between them.
```
Table 1
* ID_XPTO (PK)
* Detail
Table 2
* ID_XPTO (FK) (PK)
* ID_XPTO2 (FK) (PK)
```
Those two relations exists.
```
Table 1 -< Table2
Table 1 -< Table2
```
My question is that I need to delete some row in table 1. I'm currently doing,
```
declare @table Table (xptoTable2 int)
insert into @table
select ID_XPTO2
from Table2
where ID_XPTO = @ID_XPTO
delete from Table2
where ID_XPTO = @ID_XPTO
delete from Table
where ID_XPTO in (select xptoTable2from @table)
```
I know that I could use ON DELETE SET NULL on table2. On that way I could then search for all rows with null value on ID\_XPTO2 and delete them, but DBA does not wants to use it.
Is there some better solution to do this process? | You have these options:
* Delete in two statements, as you are doing now. Delete from Table2 first.
* Delete from two tables in one statement, if your brand of database supports multi-table `DELETE` syntax (e.g. MySQL). This is not standard SQL, but it is handy.
* Use cascading referential integrity constraints (I understand your DBA has nixed this option).
* Write a trigger `BEFORE DELETE` on Table1, to delete or set NULL any reference in Table2. Check with your DBA to see if this is any more acceptable than the cascading RI constraints.
Finally, I would advise talking to your DBA and asking the same question you asked here. Find out what solution he/she would prefer you to use. Folks on StackOverflow can answer technical questions, but it sounds like you are dealing with an **IT policy question**. | Use `ON DELETE CASCADE`. It'll automatically *delete* referencing rows. | Delete rows from two tables | [
"",
"sql",
"cascade",
"delete-row",
""
] |
I want to get a new string from the third character to the end of the string, e.g. `myString[2:end]`. If omitting the second part means 'to the end', and if you omit the first part, does it start from the start? | ```
>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'
```
Python calls this concept "slicing" and it works on more than just strings. Take a look [here](https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) for a comprehensive introduction. | Just for completeness as nobody else has mentioned it. The third parameter to an array slice is a step. So reversing a string is as simple as:
```
some_string[::-1]
```
Or selecting alternate characters would be:
```
"H-e-l-l-o- -W-o-r-l-d"[::2] # outputs "Hello World"
```
The ability to step forwards and backwards through the string maintains consistency with being able to array slice from the start or end. | How do I get a substring of a string in Python? | [
"",
"python",
"string",
"substring",
""
] |
I remember in vb6 there was a control that was similar to a dropbox/combobox that you can select the drive name. It raises an event which you can then set another control which enumerate files in listbox. (in drive.event you do files.path = drive.path to get this affect).
Is there anything like this in C#? a control that drops down a list of available drives and raises an event when it is changed? | There's no built-in control to do that, but it's very easy to accomplish with a standard ComboBox. Drop one on your form, change its DropDownStyle to DropDownList to prevent editing, and in the Load event for the form, add this line:
```
comboBox1.DataSource = Environment.GetLogicalDrives();
```
Now you can handle the SelectedValueChanged event to take action when someone changes the selected drive.
After answering [this question](https://stackoverflow.com/questions/623254/getdrivetype-in-c-or-find-out-if-my-drive-is-removable/623256), I've found another (better?) way to do this. You can use the DriveInfo.GetDrives() method to enumerate the drives and bind the result to the ComboBox. That way you can limit which drives apppear. So you could start with this:
```
comboBox1.DataSource = System.IO.DriveInfo.GetDrives();
comboBox1.DisplayMember = "Name";
```
Now comboBox1.SelectedValue will be of type DriveInfo, so you'll get lots more info about the selected game. And if you only want to show network drives, you can do this now:
```
comboBox1.DataSource = System.IO.DriveInfo.GetDrives()
.Where(d => d.DriveType == System.IO.DriveType.Network);
comboBox1.DisplayMember = "Name";
```
I think the DriveInfo method is a lot more flexible. | While Matt Hamiltons answer was very correct, I'm wondering if the question itself is. Because, why would you want such a control? It feels very Windows 95 to be honest. Please have a look at the Windows User Experience Interaction Guidelines: <http://msdn.microsoft.com/en-us/library/aa511258.aspx>
Especially the section about common dialogs:
<http://msdn.microsoft.com/en-us/library/aa511274.aspx> | C# dropbox of drives | [
"",
"c#",
"drive",
""
] |
I have the following table: `log(productId, status, statusDate, department...)`, where productId, status and statusDate is the primary key.
Example:
id1 01 01/01/2009
id1 02 02/01/2009
**id1 03 03/01/2009**
id1 01 06/01/2009
id1 02 07/01/2009
**id1 03 09/01/2009**
id2 01 02/01/2009
id2 02 03/01/2009
id2 01 04/01/2009
**id2 03 06/01/2009**
id3 01 03/01/2009
id3 02 04/01/2009
I want to make a query that retrieves for each productId in status03, the time that has passed between the first time it reached status01 and status03.Result expected:
id1 2
id1 3
id2 4
Any idea? Thank you | How about:
```
SELECT t.ID, t.Status, t.SDateTime,
(SELECT Top 1 SDateTime
FROM t t1 WHERE t1.Status = 1
AND t1.ID=t.ID
AND t1.SDateTime<t.SDateTime
AND t1.SDateTime>=
Nz((SELECT Top 1 SDateTime
FROM t t2
WHERE t2.Status=3
AND t2.ID=t.ID
AND t2.SDateTime<t.SDateTime),0)) AS DateStart,
[SDateTime]-[DateStart] AS Result
FROM t
WHERE t.Status=3
``` | I love stuff like this. Looks like it's more complicated than either of the other two answers so far have suggested. Here's a solution that will work. My apologies for the nasty formatting. Also, this will work in SQL Server, but I haven't used Access in forever, so you might need to adjust this a bit to work there. Or it may not work at all if Access doesn't support non-equijoins.
```
SELECT productId, MAX(tbl.TimeBetween)
FROM
(SELECT status_1.productId as productId, status_1.statusDate as status1Date, MIN(status_3.statusDate) as status3Date, DATEDIFF(m,status_1.statusDate, MIN(status_3.statusDate)) as TimeBetween
FROM
(SELECT productId, status, statusDate
FROM log
WHERE status = '01') status_1
INNER JOIN
(SELECT productId, status, statusDate
FROM log
WHERE status = '03') status_3
ON status_1.productId = status_3.productId AND status_3.statusDate > status_1.statusDate
GROUP BY status_1.productId, status_1.statusDate) tbl
GROUP BY productId, status3Date
ORDER BY productId, TimeBetween
```
1. The innermost selects get the records for each status.
2. Those are then joined to give the '03' status records that are greater than their corresponding '01' records (how often do you get to use a non-equijoin?)
3. They are then filtered to give the MIN '03' record that is still after the corresponding '01' record.
4. The outermost select enforces your 'first time it reached '01' status rule' since it may go to '01' status multiple times before reaching '03' status.
If someone else has a more elegant solution, I'd love to see it. I have had to write similar queries to this in the past, and I'd love to see a better solution to this type of problem. | SQL query to calculate correct leadtime in table (MS Access) | [
"",
"sql",
"ms-access",
""
] |
I receive the follow exception:
```
System.NotSupportedException : This stream does not support seek operations.
at System.Net.Sockets.NetworkStream.Seek(Int64 offset, SeekOrigin origin)
at System.IO.BufferedStream.FlushRead()
at System.IO.BufferedStream.WriteByte(Byte value)
```
The follow link show that this is a known problem for microsoft.
<http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=273186>
This stacktrace show 2 things:
1. The System.IO.BufferedStream do some absurd pointer move operation. A BufferedStream should buffer the underlying stream and not more. The quality of buffer will be bad if there are such seek operation.
2. It will never work stable with a stream that not support Seek.
Are there any alternatives?
Does I need a buffer together with a NetworkStream in C# or is this already buffered.
Edit: I want simply reduce the number of read/write calls to the underlying socket stream. | **The solution** is to use two independent `BufferedStream`s, one for receiving and one for sending. And don't forget to flush the sending `BufferedStream` appropriately.
---
Since even in 2018 it seems hard to get a satisfying answer to this question, for the sake of humanity, here are my two cents:
The `NetworkStream` *is* buffered on the OS side. However, that does not mean there are no reasons to buffer on the .net side. TCP behaves well on Write-Read (repeat), but stalls on Write-Write-Read due to delayed ack, etc, etc.
If you, like me, have a bunch of sub-par protocol code to take into the twentyfirst century, you want to buffer.
*Alternatively*, if you stick to the above, you could also buffer only reads/rcvs or only writes/sends, and use the `NetworkStream` directly for the other side, depending on how broken what code is. *You just have to be consistent!*
What `BufferedStream` docs fail to make abundantly clear is that you should *only switch reading and writing if your stream is seekable*. This is because it buffers reads and writes in the same buffer. **`BufferedStream` simply does not work well for `NetworkStream`.**
As Marc pointed out, the cause of this lameness is the conflation of two streams into one NetworkStream which is not one of .net's greatest design decisions. | The NetworkStream is already buffered. All data that is received is kept in a buffer waiting for you to read it. Calls to read will either be very fast, or will block waiting for data to be received from the other peer on the network, a BufferedStream will not help in either case.
If you are concerned about the blocking then you can look at switching the underlying socket to non-blocking mode. | Are there an alternative to System.IO.BufferedStream in C#? | [
"",
"c#",
".net",
"api",
"bufferedstream",
""
] |
I need to store some data that follows the simple pattern of mapping an "id" to a full table (with multiple rows) of several columns (i.e. some integer values [u, v, w]). The size of one of these tables would be a couple of KB. Basically what I need is to store a persistent cache of some intermediary results.
This could quite easily be implemented as simple sql, but there's a couple of problems, namely I need to compress the size of this structure on disk as much as possible. (because of amount of values I'm storing) Also, it's not transactional, I just need to write once and simply read the contents of the entire table, so a relational DB isn't actually a very good fit.
I was wondering if anyone had any good suggestions? For some reason I can't seem to come up with something decent atm. Especially something with an API in java would be nice. | This sounds like a job for.... `new ObjectOutputStream(new FileOutputStream(STORAGE_DIR + "/" + key + ".dat");` !!
Seriously - the simplest method is to just create a file for each data table that you want to store, serialize the data into and look it up using the key as the filename when you want to read.
On a decent file system writes can be made atomic (by writing to a temp file and then renaming the file); read/write speed is measured in 10s of MBit/second; look ups can be made very efficient by creating a simple directory tree like `STORAGE_DIR + "/" + key.substring(0,2) + "/" + key.substring(0,4) + "/" + key` which should be still efficient with millions of entries and even more efficient if your file system uses indexed directories; lastly its trivial to implement a memory-backed LRU cache on top of this for even faster retrievals.
Regarding compression - you can use Jakarta's commons-compress to affect a gzip or even bzip2 compression to the data before you store it. But this is an optimization problem and depending on your application and available disk space you may be better off investing the CPU cycles elsewhere.
Here is a sample implementation that I made: <http://geek.co.il/articles/geek-storage.zip>. It uses a simple interface (which is far from being clean - its just a demonstration of the concept) that offers methods for storing and retrieving objects from a cache with a set maximum size. A cache miss is transfered to a user implementation for handling, and the cache will periodically check that it doesn't exceed the storage requirements and will remove old data.
I also included a MySQL backed implementation for completion and a benchmark to compare the disk based and MySQL based implementations. On my home machine (an old Athlon 64) the disk benchmark scores better then twice as fast as the MySQL implementation in the enclosed benchmark (9.01 seconds vs. 18.17 seconds). Even though the DB implementation can probably tweaked for slightly better performance, I believe it demonstrates the problem well enough.
Feel free to use this as you see fit. | I'd use [EHCache](http://ehcache.sourceforge.net), it's used by Hibernate and other Java EE libraries, and is really simple and efficient:
To add a table:
```
List<List<Integer>> myTable = new(...)
cache.put(new Element("myId", myTable));
```
To read:
```
List<List<Integer>> myTable = (List<List<Integer>>) cache.get("myId").getObjectValue();
``` | Efficient persistent storage for simple id to table of values map for java | [
"",
"java",
"data-structures",
"persistence",
""
] |
I need to find names which contain three number 7 in the random order.
**My attempt**
We need to find first names which do not contain seven
```
ls | grep [^7]
```
Then, we could remove these matches from the whole space
```
ls [remove] ls | grep [^7]
```
The problem in my pseudo-code starts to repeat itself quickly.
**How can you find the names which contain three 7s in the random order by AWK/Python/Bash?**
**[edit]**
The name can contain any number of letters and it contains words of three 7s. | Something like this:
```
printf '%s\n' *|awk -F7 NF==4
``` | I don't understand the part about "random order". How do you differentiate between the "order" when it's the same token that repeats? Is "a7b7" different from "c7d7" in the order of the 7s?
Anyway, this ought to work:
```
ls *7*7*7*
```
It just let's the shell solve the problem, but maybe I didn't understand properly.
EDIT: The above is wrong, it includes cases with more than four 7s which is not wanted. Assuming this is bash, and extended globbing is enabled, this works:
```
ls *([^7])7*([^7])7*([^7])7*([^7])
```
This reads as "zero or more characters which are not sevens, followed by a seven, followed by zero or more characters that are not sevens", and so on. It's important to understand that the asterisk is a *prefix* operator here, operating on the expression `([^7])` which means "any character except 7". | Unable search names which contain three 7s in random order by AWK/Python/Bash | [
"",
"python",
"regex",
"bash",
"awk",
""
] |
I am looking for a way to convert an object tree to XML. It would be fun to write, but I am sure someone has already written it. Here is my wish list:
* It should not care about constructors
* It should ideally handle circular references (not too fussed how)
* It should not require changes to the objects - e.g., no custom attributes
* It should not care about or require known types (e.g., XmlInclude)
* The XML should be dead simple - it needs to be human readable by members of the operations team
* If a property can't be serialized, it should just suppress the error and continue
* Can handle lists and dictionaries
I don't need to reconstruct the object model, so a write-only solution is fine (probably expected).
I think that discounts:
* XmlSerializer - needs parameterless constructors, no circular reference support
* DataContractSerializer - needs attributes (opt in) | This seems like it would be straightforward to write using reflection: given an object instance, create an XML element with its class name, and then iterate through all of its properties.
For each property create an element with its name:
* if it's a value type, set its text to the XML Schema text of its value;
* if it implements `IEnumerable`, iterate through it and create an element for each item;
* if it's any other reference type, set the element's content to the property's XML representation.
Track circular/multiple references with a HashSet containing the hash codes of each object you've serialized; if you find an object's hash code in the HashSet, you've already serialized it. (I don't know what you want put into the XML if this happens.)
But no, I don't have any code that does this lying around. | Robert Rossney's post made me think it's probably less work than I thought. So here's a very rough attempt. It handles the following:
* If it is unable to read a property, it prints the exception as the value
* Cyclic references and multiple occurrences. It associates an ID with each element; if an element appears twice, it just points the ref ID. The Ref ID is unique to the object graph (I should probably use a GUID, but this suits my purposes).
* It has no problems with derived types
* It requires no attributes or specific constructors or other nonsense
* It can handle read-only properties
Here's an example of the output (in my test objects, the "Currency" product on the Order throws an exception).
```
<Customer Ref="1">
<FirstName>Paul</FirstName>
<LastName>Stovell</LastName>
<FullName>Paul Stovell</FullName>
<Orders>
<Order Ref="2">
<SKU>Apples</SKU>
<Price>27.30</Price>
<Currency>Something bad happened</Currency>
<Customer Ref="1" />
</Order>
<Order Ref="3">
<SKU>Pears</SKU>
<Price>17.85</Price>
<Currency>Something bad happened</Currency>
<Customer Ref="1" />
</Order>
<Order Ref="2" />
</Orders>
</Customer>
```
Here's the sample object model and usage:
```
static void Main(string[] args)
{
var customer = new Customer();
customer.FirstName = "Paul";
customer.LastName = "Stovell";
customer.Orders.Add(new Order(customer) { Price = 27.30M, SKU = "Apples"});
customer.Orders.Add(new Order(customer) { Price = 17.85M, SKU = "Pears"});
customer.Orders.Add(customer.Orders[0]);
var output = new StringWriter();
var writer = new XmlTextWriter(output);
writer.Formatting = Formatting.Indented;
WriteComplexObject("Customer", customer, writer);
Console.WriteLine(output.ToString());
Console.ReadKey();
}
class Customer
{
private readonly List<Order> _orders = new List<Order>();
public Customer()
{
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
// Read-only property test
get { return FirstName + " " + LastName; }
}
public List<Order> Orders
{
// Collections test
get { return _orders; }
}
}
class Order
{
private readonly Customer _customer;
public Order(Customer customer)
{
_customer = customer;
}
public string SKU { get; set; }
public decimal Price { get; set; }
public string Currency
{
// A proprty that, for some reason, can't be read
get
{
throw new Exception("Something bad happened");
}
}
public Customer Customer
{
get { return _customer; }
}
}
```
Here's the implementation:
```
public static void WriteObject(string name, object target, XmlWriter writer)
{
WriteObject(name, target, writer, new List<object>(), 0, 10, -1);
}
private static void WriteObject(string name, object target, XmlWriter writer, List<object> recurringObjects, int depth, int maxDepth, int maxListLength)
{
var formatted = TryToFormatPropertyValueAsString(target);
if (formatted != null)
{
WriteSimpleProperty(name, formatted, writer);
}
else if (target is IEnumerable)
{
WriteCollectionProperty(name, (IEnumerable)target, writer, depth, maxDepth, recurringObjects, maxListLength);
}
else
{
WriteComplexObject(name, target, writer, recurringObjects, depth, maxDepth, maxListLength);
}
}
private static void WriteComplexObject(string name, object target, XmlWriter writer, List<object> recurringObjects, int depth, int maxDepth, int maxListLength)
{
if (target == null || depth >= maxDepth) return;
if (recurringObjects.Contains(target))
{
writer.WriteStartElement(name);
writer.WriteAttributeString("Ref", (recurringObjects.IndexOf(target) + 1).ToString());
writer.WriteEndElement();
return;
}
recurringObjects.Add(target);
writer.WriteStartElement(name);
writer.WriteAttributeString("Ref", (recurringObjects.IndexOf(target) + 1).ToString());
foreach (var property in target.GetType().GetProperties())
{
var propertyValue = ReadPropertyValue(target, property);
WriteObject(property.Name, propertyValue, writer, recurringObjects, depth + 1, maxDepth, maxListLength);
}
writer.WriteEndElement();
}
private static object ReadPropertyValue(object target, PropertyInfo property)
{
try { return property.GetValue(target, null); }
catch (Exception ex) { return ReadExceptionMessage(ex); }
}
private static string ReadExceptionMessage(Exception ex)
{
if (ex is TargetInvocationException && ex.InnerException != null)
return ReadExceptionMessage(ex.InnerException);
return ex.Message;
}
private static string TryToFormatPropertyValueAsString(object propertyValue)
{
var formattedPropertyValue = null as string;
if (propertyValue == null)
{
formattedPropertyValue = string.Empty;
}
else if (propertyValue is string || propertyValue is IFormattable || propertyValue.GetType().IsPrimitive)
{
formattedPropertyValue = propertyValue.ToString();
}
return formattedPropertyValue;
}
private static void WriteSimpleProperty(string name, string formattedPropertyValue, XmlWriter writer)
{
writer.WriteStartElement(name);
writer.WriteValue(formattedPropertyValue);
writer.WriteEndElement();
}
private static void WriteCollectionProperty(string name, IEnumerable collection, XmlWriter writer, int depth, int maxDepth, List<object> recurringObjects, int maxListLength)
{
writer.WriteStartElement(name);
var enumerator = null as IEnumerator;
try
{
enumerator = collection.GetEnumerator();
for (var i = 0; enumerator.MoveNext() && (i < maxListLength || maxListLength == -1); i++)
{
if (enumerator.Current == null) continue;
WriteComplexObject(enumerator.Current.GetType().Name, enumerator.Current, writer, recurringObjects, depth + 1, maxDepth, maxListLength);
}
}
catch (Exception ex)
{
writer.WriteElementString(ex.GetType().Name, ReadExceptionMessage(ex));
}
finally
{
var disposable = enumerator as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
writer.WriteEndElement();
}
}
```
I would still be interested to know if there are more tried and tested solutions. | C#: Render object as XML | [
"",
"c#",
"xml",
"serialization",
""
] |
I have a try...except block in my code and When an exception is throw. I really just want to continue with the code because in that case, everything is still able to run just fine. The problem is if you leave the except: block empty or with a #do nothing, it gives you a syntax error. I can't use continue because its not in a loop. Is there a keyword i can use that tells the code to just keep going? | ```
except Exception:
pass
```
[Python docs for the pass statement](https://docs.python.org/3.7/tutorial/controlflow.html#pass-statements) | ### Generic answer
The standard "nop" in Python is the `pass` statement:
```
try:
do_something()
except Exception:
pass
```
Using `except Exception` instead of a bare `except` avoid catching exceptions like `SystemExit`, `KeyboardInterrupt` etc.
### Python 2
Because of the last thrown exception being remembered in Python 2, some of the objects involved in the exception-throwing statement are being kept live indefinitely (actually, until the next exception). In case this is important for you and (typically) you don't need to remember the last thrown exception, you might want to do the following instead of `pass`:
```
try:
do_something()
except Exception:
sys.exc_clear()
```
This clears the last thrown exception.
### Python 3
In Python 3, the variable that holds the exception instance gets *deleted* on exiting the `except` block. Even if the variable held a value previously, after entering and exiting the `except` block it becomes **undefined** again. | Python: How to ignore an exception and proceed? | [
"",
"python",
"exception",
""
] |
I want to use the HTML agility pack to parse tables from complex web pages, but I am somehow lost in the object model.
I looked at the link example, but did not find any table data this way.
Can I use XPath to get the tables? I am basically lost after having loaded the data as to how to get the tables. I have done this in Perl before and it was a bit clumsy, but worked. (`HTML::TableParser`).
I am also happy if one can just shed a light on the right object order for the parsing. | How about something like:
Using [HTML Agility Pack](http://html-agility-pack.net/api)
```
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table")) {
Console.WriteLine("Found: " + table.Id);
foreach (HtmlNode row in table.SelectNodes("tr")) {
Console.WriteLine("row");
foreach (HtmlNode cell in row.SelectNodes("th|td")) {
Console.WriteLine("cell: " + cell.InnerText);
}
}
}
```
Note that you can make it prettier with LINQ-to-Objects if you want:
```
var query = from table in doc.DocumentNode.SelectNodes("//table").Cast<HtmlNode>()
from row in table.SelectNodes("tr").Cast<HtmlNode>()
from cell in row.SelectNodes("th|td").Cast<HtmlNode>()
select new {Table = table.Id, CellText = cell.InnerText};
foreach(var cell in query) {
Console.WriteLine("{0}: {1}", cell.Table, cell.CellText);
}
``` | The most simple what I've found to get the XPath for a particular Element is to install FireBug extension for Firefox go to the site/webpage press F12 to bring up firebug; right select and right click the element on the page that you want to query and select "Inspect Element" Firebug will select the element in its IDE then right click the Element in Firebug and choose "Copy XPath" this function will give you the exact XPath Query you need to get the element you want using HTML Agility Library. | HTML Agility pack - parsing tables | [
"",
"c#",
"html",
"html-parsing",
"html-agility-pack",
""
] |
My problem is that, i want to count the controls on a page and then get their types, if there are textboxes, checkboxes or comboboxes, then make them enable or disable? Is there any example on the net?
Thanks | You could use a method like:
```
public int CountControls(Control top)
{
int cnt = 1;
foreach (Control c in top.Controls)
cnt += CountControls(c);
return cnt;
}
```
But as Andrew said, it would be expensive. | This would be an expensive operation as you would have to recursively walk the control collection of the page checking each control. Perhaps you are not aware that ASP.NET cascades the `Disabled` property from parent to child? In other words if you set a parent control as disabled all child input controls will be disabled as well.
**Edit:** If you *really* want to do it this way then this is the best way to do it:
```
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
int count = 0;
this.disableControls(this, ref count);
}
void disableControls(Control control, ref int count)
{
foreach (Control c in control.Controls)
{
WebControl wc = c as WebControl;
if (wc != null)
{
count++;
wc.Enabled = false;
}
this.disableControls(c, ref count);
}
}
``` | Counting controls on the page | [
"",
"c#",
"asp.net",
""
] |
I have a SQL file added to my VS.NET 2008 project as an embedded resource. Whenever I use the following code to read the file's content, the string returned always starts with three junk characters and then the text I expect. I assume this has something to do with the Encoding.Default I am using, but that is just a guess. Why does this text keep showing up? Should I just trim off the first three characters or is there a more informed approach?
```
public string GetUpdateRestoreSchemaScript()
{
var type = GetType();
var a = Assembly.GetAssembly(type);
var script = "UpdateRestoreSchema.sql";
var resourceName = String.Concat(type.Namespace, ".", script);
using(Stream stream = a.GetManifestResourceStream(resourceName))
{
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
// UPDATE: Should be Encoding.UTF8
return Encoding.Default.GetString(buffer);
}
}
```
**Update:**
I now know that my code works as expected if I simply change the last line to return a UTF-8 encoded string. It will always be true for this embedded file, but will it always be true? Is there a way to test any buffer to determine its encoding? | Probably the file is in utf-8 encoding and Encoding.Default is ASCII. Why don't you use a specific encoding?
Edit to answer a comment:
In order to guess the file encoding you could look for [BOM](http://en.wikipedia.org/wiki/Byte-order_mark) at the start of the stream. If it exists, it helps, if not then you can only guess or ask user. | if you try to load xml from assembly you actually need to inspect and skip the byte order mark bytes (drove me nuts):
```
....
byte[] data;
using (var stream = assembly.GetManifestResourceStream(filename))
{
var length = stream.Length;
data = new byte[length];
stream.Read(data, 0, (int) length);
}
if (!HasUtf8ByteOrderMark(data))
{
throw new InvalidOperationException("Expected UTF8 byte order mark EF BB BF");
}
return Encoding.UTF8.GetChars(data.Skip(3).ToArray());
```
And
```
static bool HasUtf8ByteOrderMark(byte[] data)
{
var bom = new byte[] { 0xEF, 0xBB, 0xBF };
return data[0] == bom[0] && data[1] == bom[1] && data[2] == bom[2];
}
```
[More information here](http://www.siao2.com/2005/01/20/357028.aspx) | Why does text from Assembly.GetManifestResourceStream() start with three junk characters? | [
"",
"c#",
"visual-studio-2008",
"encoding",
"resources",
""
] |
This should be trivial but I can't seem to find it (unless no such class exists!)
What's the STL class (or set of classes) for smart pointers?
**UPDATE**
Thanks for the responses,
I must say I'm surprised there's no standard implementation.
I ended up using this one: <http://archive.gamedev.net/reference/articles/article1060.asp> | With the exception of the already mentionned TR1 shared\_ptr, there is no reference-counted pointer in STL.
I suggest you use boost::shared\_ptr (downloading boost will be enough, there is nothing to compile, its implementation is header-only).
You may also want to have a look at smart pointers from Loki libraries (again, header-only implementation).
For an overview of available smart pointers, see [there](http://www.ddj.com/cpp/184403837). | If you don't want/can't use Boost **and** your compiler implements [TR1](http://en.wikipedia.org/wiki/Technical_Report_1), you can use `shared_ptr` (borrowed from Boost):
```
#include <tr1/memory>
...
std::tr1::shared_ptr<Foo> ptr(new Foo);
```
Otherwise, no, there are no smart pointers except `std::auto_ptr` in vanilla STL. | STL class for reference-counted pointers? | [
"",
"c++",
"stl",
"smart-pointers",
"reference-counting",
""
] |
I've come across a query in an application that I've inherited that looks like this:
```
Select *
From foo
where
1 <> 1
```
As I parse that, it should return nothing (`1 <> 1` should evaluate to false, right). However (at least on my Oracle box) it comes back with a full listing of everything in `foo`. When I try the same thing in MSAccess/Jet and MSSQL I get the behaviour I expect.
Why is it different for Oracle (and why would the original developer want to do this)?
Note: I've seen some superstition about the +s and -s of using "where 1 = 1", and it causing full table scans; but I don't think this is what the original developer was intending.
**Small Update:**
In this case `foo` is a view. When I try the same thing on on an actual table, I get what I would expect (no rows).
**Update 2:**
I've following the code further down the rabbit hole and determined that all he's doing is trying to grab the field/column names. I'm still at a loss as to why it's returning the full record set; but only on views.
Literally, he's building the query in a string and passing it on for another function to execute unaltered.
```
'VB6
strSQL = "SELECT * FROM " & strTableName & " WHERE 1 <> 1"
```
In this case strTableName contains the name of a view.
**Update 3:**
For reference, here is one of the views I'm having problems with
(I've changed the field/table/schema names)
```
CREATE OR REPLACE FORCE VIEW scott.foo (field1,
field2,
field4,
field5,
field12,
field8,
field6,
field7,
field16,
field11,
field13,
field14,
field15,
field17
)
AS
SELECT bar.field1,
bar.field2,
DECODE
(yadda.field9, NULL, 'N',
DECODE (yadda.field3, NULL, 'Y', 'N')
) AS field4,
bar.field5,
snafu.field6,
DECODE
(snafu.field6,
NULL,
bar.field8,
bar.field8
- snafu.field6
) AS field7,
DECODE
(yadda.field10,
NULL,
bar.field12,
yadda.field10
) AS field11,
DECODE
(SIGN ( yadda.field10 - bar.field12),
NULL, 'N', 1, 'N', 0, 'N', -1, 'Y'
) AS field13,
bar.field14,
ADD_MONTHS
(DECODE (yadda.field10, NULL, bar.field12, yadda.field10
),
bar.field14 * 12
) AS field15,
FROM clbuttic,
bar,
yadda,
snafu
WHERE clbuttic.asset_type = bar.asset_type
AND bar.field16 = yadda.field9(+)
AND bar.field1 = snafu.field1(+)
AND (bar.field17 IS NULL)
;
```
Appending `Order By 1` (or some column name in the select on foo) seems to convince Oracle to give me back the empty set. It's a long term solution, but not a short term one (changing he code and redeploying is a major PITA). I'm hoping there's a little known setting on the DB side or something wrong in the View that is the cause of this odd behaviour. | It definitely looks like a bug in the view merging code of the Oracle optimizer. I bet you only get this with views which contain outer joins. Your `ORDER BY` solves it, because it practically forces a `NO_MERGE` on the view.
I wouldn't put either an `ORDER BY` or a `NO_MERGE` hint inside the view though, because (depending on your data volume) it could degrade performance of other queries which use the view. You should put a no\_merge hint in the outer query:
```
Select /*+ NO_MERGE(foo) */ *
From foo
where
1 <> 1
```
You should also raise an SR with Oracle support, as this is definitely a bug. That query should never ever return any rows no matter what you are selecting from, or how complex it is inside. Never ever.
I couldn't reproduce it, so it's probably fixed in the version I'm using. What's the db version you are using? | Okay...why this would happen in Oracle is beyond me. However, I can tell you why it's often used in other DBs: when the person wants the columns returned, but no values. (Such as for creating a schema for a new table) | Why would "Where 1 <> 1" in a query return all rows? | [
"",
"sql",
"oracle",
"view",
""
] |
How do i pass a pointer to a member function to std::list.sort()?
Is this possible? Thanks
```
struct Node {
uint32_t ID;
char * Value;
};
class myClass {
private:
uint32_t myValueLength;
public:
list<queueNode *> MyQueue;
bool compare(Node * first, Node * second);
bool doStuff();
}
bool myClass::compare(Node * first, Node * second) {
unsigned int ii =0;
while (ii < myValueLength)
{
if (first-> Value[ii] < second-> Value[ii])
{
return true;
} else if (first-> Value[ii] > second-> Value[ii])
{
return false;
}
++ii;
}
return false;
}
bool myClass::doStuff()
{
list.sort(compare);
}
```
I want to use a length variable from within the class instead of doing strlen() within the compare function (The Value will always be the same length)
Edit: The myValueLength was not the only variable i wanted to access from within the comparison function I just simplified it to make the example shorter. | Elaborating on [grieve's](https://stackoverflow.com/questions/639100/pointer-to-member-functions-c-stdlist-sort/639112#639112) response, why not use a functor? E.g.:
```
struct Functor
{
bool operator()( char * a, char * b )
{ return strcmp(a,b) < 0; }
};
```
Then you could just use:
```
Functor f;
myList.sort(f);
```
You could even use your class as the Functor by defining operator()...
```
class myClass {
...
bool operator()( queueNode * a, queueNode * b )
{ return compare( a, b ); }
void doStuff() { MyQueue.sort(*this); }
};
```
---
Simple example code:
```
#include <iostream>
#include <list>
using namespace std;
// Assumes TYPE t; cout << t; is valid.
template<class TYPE>
inline ostream & operator<< ( ostream & theOstream,
const list<TYPE> & theList )
{
typename list<TYPE>::const_iterator listIterator = theList.begin();
for ( int i = 0; listIterator != theList.end(); listIterator ++, i ++ )
theOstream << " [" << i << "]: \"" << (*listIterator) << "\"" << endl;
return theOstream;
}
struct Functor
{
bool operator()( const char * a, const char * b )
{ return strcmp(a,b) < 0; }
};
int
main()
{
list<char*> l;
/* Load up some example test data... */
char s[3];
s[2] = '\0';
for ( s[0]='c'; s[0]>='a'; s[0]-- )
for ( s[1]='c'; s[1]>='a'; s[1]-- )
l.push_back(strdup(s));
/* Show us that test data... */
cout << l << endl;
/* Sort list. */
Functor f;
l.sort(f);
/* Show us what we have now... */
cout << l << endl;
}
``` | It is possible. Did you consider using boost::function?
```
list.sort( boost::bind( &myClass::compare, this, _1, _2 ) );
```
Is your 'compare' function will rely on **this** data? If not - you may simpy make 'compare' function to be **static**. And then it will be
```
list.sort( &myClass::compare );
```
You can add helper struct to do your comparison and then
```
list.sort( Comparer( myValueLength ) );
struct Comparer
{
Comparer( uint32_t myValueLength ):
length( myValueLength )
{}
bool operator() (Node * first, Node * second)
{
unsigned int ii =0;
while (ii < length)
{
if (first-> Value[ii] < second-> Value[ii])
{
return true;
} else if (first-> Value[ii] > second-> Value[ii])
{
return false;
}
++ii;
}
return false;
}
uint32_t length;
};
``` | Pointer to member functions - C++ std::list sort | [
"",
"c++",
"list",
"comparison",
""
] |
$clients = $CLIENT->find($options);
$client = $clients[0];
EDIT: I Realized i should be clearer. The $CLIENT->find always returns an array of objects, but I want one line of code that turns the array (that will only have 1 object) into just an object. | ```
$client = array_shift($CLIENT->find($options));
``` | ```
$client = reset($CLIENT->find($options));
```
**Edit:** Here's a less obfuscated one, you should probably use this instead:
```
list($client) = $CLIENT->find($options);
```
They aren't identical though; the first one will also work in places where a single scalar is expected (inside a function's parameter list) but the second won't (`list()` returns void). | Is there a way to do this in one step? | [
"",
"php",
"arrays",
""
] |
I'm following a simple example of how to use the update panel from here (<http://www.asp.net/Ajax/Documentation/Live/tutorials/IntroductionUpdatePanel.aspx>). Outside the update panel i've another html input control which calls a javascript function which displays an count to the user in an alert box. simple stuff. My problem is that the page behaves differently when running on IIS and on the inbuilt asp.net web server (cassini). Under IIS clicking the button within the update panel causes a full postback and so the count displayed to the user in the js function gets reset after that eachtime. under the inbuilt web server hitting the button inside the update panel behaves how i would expect it to and how i want it to in that it refreshes the label only so that the counter on the client side isn't reset.
.net 3.5 is the target framework and I'm running IIS 5.1.
I've seen posts elsewhere describing the same problem (<http://forums.asp.net/t/1169282.aspx>)
```
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
var count=0;
function incrementCounter()
{
count ++;
alert(count);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Panel Created"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<input type="button" id="Button2" value="JS Clicker" onclick="incrementCounter();" />
</form>
</body>
</html>
```
### Update:
Thanks Crossbrowser for your answer. My reply will take up to much room in the Add Comment window. Ok, so following this simple example here (<http://www.asp.net/Ajax/Documentation/Live/tutorials/IntroductionUpdatePanel.aspx>) you can see that the update mode is not set to conditional so I've reflected those changes. However my problem still persists. That is that the page when running on IIS causes a full postback. i.e. the progress bar in you browser loads, the screen flickers, client side count that i was maintaining is lost. Running the code on the inbuilt asp.net webserver does not. That is the crux of my problem. I've come across this problem by others (<http://forums.asp.net/t/1169282.aspx>).
So my question is what is different when running on IIS compared to the inbuilt asp.net one?
Updated Code:
```
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
var count=0;
function incrementCounter()
{
count ++;
alert(count);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Panel Created"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<input type="button" id="Button2" value="JS Clicker" onclick="incrementCounter();" />
</form>
</body>
</html>
``` | Since you are using the .NET Framework 3.5 I will assume you are using Visual Studio 2008, and you say you are targeting IIS 5.1 for the production platform.
The local web server that is part of Visual Studio 2008 is based off of IIS 6/7 architecture, not IIS 5. So, to answer your question of what is different with IIS compared to the local web server... unfortunately, in this case, you are mixing apples and oranges.
Are you restricted to IIS 5.1?... ie client mandate or some other reason. If you are not, and you are developing with Visual Studio 2008 (.NET Framework 3.5) you really should be using IIS7 (or at least 6) as you would most likely not have this problem.
Again, IIS7 may not be an option for you. | Have you tried using a trigger? e.g.
```
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Panel Created"></asp:Label>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Panel Refresh" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Label1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
``` | Button in update panel is doing a full postback? | [
"",
"c#",
"asp.net",
"ajax",
"iis",
""
] |
What is the order in which the destructors and the constructors are called in C++? Using the examples of some Base classes and Derived Classes | **The order is:**
1. Base constructor
2. Derived constructor
3. Derived destructor
4. Base destructor
**Example:**
```
class B
{
public:
B()
{
cout<<"Construct B"<<endl;
}
virtual ~B()
{
cout<<"Destruct B"<<endl;
}
};
class D : public B
{
public:
D()
{
cout<<"Construct D"<<endl;
}
virtual ~D()
{
cout<<"Destruct D"<<endl;
}
};
int main(int argc, char **argv)
{
D d;
return 0;
}
```
**Output of example:**
> Construct B
>
> Construct D
>
> Destruct D
>
> Destruct B
**Multiple levels of inheritance works like a stack:**
If you consider pushing an item onto the stack as construction, and taking it off as destruction, then you can look at multiple levels of inheritance like a stack.
This works for any number of levels.
Example D2 derives from D derives from B.
Push B on the stack, push D on the stack, push D2 on the stack. So the construction order is B, D, D2. Then to find out destruction order start popping. D2, D, B
**More complicated examples:**
For more complicated examples, please see the link provided by @JaredPar | A detailed description of these events, including virtual and multiple inheritance is available at the C++ FAQ Lite. Section 25.14 and 25.15
<https://isocpp.org/wiki/faq/multiple-inheritance#mi-vi-ctor-order> | What is the order in which the destructors and the constructors are called in C++ | [
"",
"c++",
"constructor",
"destructor",
""
] |
Is it confusing to design an API with multiple ways of achieving the same outcome? For example, I have my own `Date` library (which is a simple wrapper around the Java `Date`/`Calendar` classes to distinguish a *year-month-day*, `Date`, from an *instant-in-time*, `Instant` and provide mechanisms to convert between the two). I started off with one method to create an instance of a `Date`:
```
Date.valueOfYearMonthDay(int year, int month, int day);
```
But then I found that the resultant code using the API was not very readable. So I added:
```
Date.yearMonthDay(int year, int month, int day)
Date.ymd(int year, int month, int day)
Date.date(int year, int month, int day)
```
Then I started getting fluent:
```
Date.january().the(int day).in(int year);
```
*(I find that the fluent version is really useful for making readable tests).* All these methods do identical things and have accurate JavaDoc. I think I've read that a strength of `perl` is that each programmer can choose exactly which method he/she prefers to solve something. And a strength of `Java` is that there is usually only one way of doing things :-)
What are people's opinions? | I've been doing academic research for the past 10 years on different issues that have to do with API usability in Java.
I can tell you that the statement about having one way to do things in Java is fairly incorrect. There are often *many* ways to do the same thing in Java. And unfortunately, they are often not consistent or documented.
One problem with bloating the interface of a class with convenience methods is that you are making it more difficult to understand the class and how to use it. The more choices you have, things become more complex.
In an analysis of some open-source libraries, I've found instances of redundant functionality, added by different individuals using different terms. Clearly a bad idea.
A greater problem is that the information carried by a name is no longer meaningful. For example, things like putLayer vs. setLayer in swing, where one just updates the layer and the other also refreshes (guess which one?) are a problem. Similarly, getComponentAt and findComponentAt. In other ways, the more ways to do something, the more you obfuscate everything else and reduce the "entropy" of your existing functionality.
Here is a good example. Suppose you want in Java to replace a substring inside a string with another string. You can use String.replace(CharSequence, CharSequence) which works perfectly as you'd expect, literal for literal. Now suppose you wanted to do a regular expression replacement. You could use Java's Matcher and do a regular expression based replacement, and any maintainer would understand what you did. However, you could just write String.replaceAll(String, String), which calls the Matcher version. However, many of your maintainers might not be familiar with this, and not realize the consequences, including the fact that the replacement string cannot contains "$"s. So, the replacement of "USD" with "$" signs would work well with replace(), but would cause crazy things with replaceAll().
Perhaps the greatest problem, however, is that "doing the same thing" is rarely an issue of using the same method. In many places in Java APIs (and I am sure that also in other languages) you would find ways of doing "almost the same thing", but with differences in performance, synchronization, state changes, exception handling, etc. For instance, one call would work straight, while another would establish locks, and another will change the exception type, etc. This is a recipe for trouble.
So bottom line: Multiple ways to do the same thing are not a good idea, unless they are unambiguous and very simple and you take a lot of care to ensure consistency. | I'd echo what some others said in that convenience methods are great, but will take it a step further - **all "convenience" methods should eventually call the same underlying method**. The only thing that the convenience methods should do other than proxy the request is to take or return variables differently.
No calculations or processing allowed in the convenience methods. If you need to add additional functionality in one of them, go the extra mile and make it happen in the "main" / "real" one. | Do people provide multiple mechanisms for doing the same thing in an API? | [
"",
"java",
"api",
""
] |
I've created a derived column that translates a 1 to an 'M' and a 2 to 'F'. i.e. a gender indicator. The derived column feeds into a Fuzzy Lookup transformation and then to a conditional split. The problem is the derived field does not show up in any of the downstream components. In the Fuzzy Lookup transform the "Pass Through" checkbox is checked for the derived column, but in the following Conditional Split transform the column does not show up at all. Funny thing is that the \_Similarity\_Gender\_Derived does show up in the column list for the conditional split.
Hopefully someone else has seen this type of behavior.
Thanks - Mr. Do | Thanks for the response. Turns out that issue had to do with some corruption with the meta data. I ended up going back into the Derived Column Transform, renamed the column in error, then added a new derived column with the old name. I saved the transform, and then removed the original column. That fixed the problem.
Thanks for the responses. | 1. Right click on the Fuzzy Lookup task and select Show Advanced Editor.
2. Go to the "Input and Output Properties" tab.
3. Expand the "Output" item, and then the "Output Columns" item.
4. Is your derived column listed there?
If it is, it should also show up on the available input columns of the Conditional Split task. If not ...
1. Right click on the Derived Column task and select Show Advanced Editor.
2. Go to the "Input and Output Properties" tab.
3. Expand the "Derived Column Output" item, and then the "Output Columns" item, and select your derived gender column.
4. Note its LineageID attribute.
5. Repeat the earlier steps to get the Fuzzy Lookup's Output Columns.
6. Hit the "Add Column" button. Name the column the same name as your derived column, and in the "SourceInputColumnLineageID" attribute, enter the LineageID you noted earlier.
Alternate answer: is your derived column creating an all new column, or simply replacing your existing "1/2" column? In the Derived Column Editor, check your "Derived Column" .. umm .. column. If you are just replacing your existing column with the new value (instead of adding a new column) you may just be looking in the wrong place. | SSIS Derived Column Missing Downstream | [
"",
"sql",
"sql-server-2005",
"ssis",
""
] |
UPDATE: the HTML was not well formed. This was causing the script to appear in inner div. Please ignore the question.
IE ver<8 has a known bug (Internet explorer cannot display the page. Operation aborted)
If a script tries to append something to upper level block:
The bug is described [here](http://support.microsoft.com/?scid=kb;en-us;927917&x=9&y=18):
Update: I rephrased the question and simplified the example:
The bug occurs in the following code:
```
[end of html file]
<script type="text/javascript" >
if (window.document.body){
var c_div = window.document.createElement('div');
window.document.body.appendChild(c_div);
}
</script>
</body>
```
Question: This seems to me exactly similar to example1 Method1 In Microsoft workaround ([here is the link again](http://support.microsoft.com/?scid=kb;en-us;927917&x=9&y=18)). How come I still have the bug? What am I missing here? | Run your code in a domready/onload event handler. | It might be a slightly insane approach but could you pull out the innerHTML of the entire `<body>` append your string to it and then set the `<body>` innerHTML to the new value?
May affect some previously attached JS events unless it's inline onclick stuff. | how to overcome IE bug when dynamically attaching div to body from script | [
"",
"javascript",
"internet-explorer",
"dom",
"dhtml",
""
] |
I'm writing a tool that is going to be used to process a bunch of 3D data, doing things like rotating objects, translating, scaling and all that good stuff. Does anyone know of a good library that already does some of this common 3D stuff?
I'm not interested in visualizing the data at the moment, and am primarily interested in performing the operations.
Things I know I will need at this point:
* 2D/3D/4D vectors
+ (adding, subtracting, dot product, cross product, etc...)
* Rotation/Translation/Scaling using matrices
* Quaternions
I was able to locate the [Sharp3D](http://sharp3d.codeplex.com/) library, but it seems like it might do what I want but hasn't been updated in a long time. Has anyone used this before? Any other (better) suggestions? | [Microsoft.Xna.Framework](http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.aspx) (ship this XNA) could do the work.
> The XNA Framework Math library has multiple basic geometric types that can be used to manipulate objects in 2D or 3D space. The primitive objects in this library represent the data required to represent a geometric object or an operation on that object. Each geometric type has a number of mathematical operations that are supported for the type.
>
> **Vector**
>
> The XNA Framework provides the Vector2, Vector3 and Vector4 classes for representing and manipulating vectors. A vector is typically used to represent a direction and magnitude. However, in the XNA framework it might also be used to store a coordinate or some other data type with the same storage requirements.
>
> Each vector class has methods for performing standard vector operations such as:
>
> * Dot product
> * Cross product
> * Normalization
> * Transformation
> * Linear, Cubic, Catmull-Rom, or Hermite spline interpolation.
>
> **Matrices**
>
> The XNA Framework provides the Matrix class for transformation of geometry. The Matrix class uses a row major order to address matrices, which means that the row is specified before the column when describing an element of a two-dimensional matrix. The Matrix class provides methods for performing standard matrix operations such as calculating the determinate or inverse of a matrix, in addition to helper methods for creating scale, translation, and rotation matrices.
>
> **Quaternions**
>
> The XNA Framework provides the Quaternion structure to represent and calculate the efficient rotation about a vector around a specified angle. | I've never used it before but I just grabbed Sharp3D and it seems to work well (aside from some issue about strong names that took a few minutes to work around). My impression is that it's not exactly light weight but far from being on the heavy side.
As to no recent updates, it's not like math is changing or anything... | Good library for 3D math in C#? | [
"",
"c#",
"math",
"3d",
""
] |
I have a template class defined in a header file like this. Here I have defined a static variable as well:
```
#ifndef TEST1_H_
#define TEST1_H_
void f1();
static int count;
template <class T>
class MyClass
{
public:
void f()
{
++count;
}
};
#endif
```
And I have defined main() function in a different cpp file like this:
```
int main(int argc, char* argv[])
{
MyClass<int> a;
a.f();
f1();
cout<<"Main:" << count << "\n";
return 0;
}
```
I have implemented function f1() in a different cpp file like this:
```
void f1()
{
MyClass<int> a;
a.f();
cout<<"F1: " <<count <<"\n";
}
```
When I compiled this using VC6, I got the output as "F1:0 Main:2". How is this possible? Also, in general how should I handle if I want to use static variables along with templates? | You're getting two copies of the same variable because you've declared a static variable in a header file. When you declare a global variable `static` this way, you're saying it's local to the compilation unit (the `.o` file). Since you include the header in two compilation units, you get two copies of `count`.
I think what you really want here is a static template member variable associated with each *instance* of the template class. It would look like this:
```
template <class T>
class MyClass
{
// static member declaration
static int count;
...
};
// static member definition
template<class T> int MyClass<T>::count = 0;
```
This will get you a count for each instantiation of your template. That is, you'll have a count for `MyClass<int>`, `MyClass<foo>`, `MyClass<bar>`, etc. `f1()` would now look like this:
```
void f1() {
MyClass<int> a;
a.f();
cout<<"F1: " << MyClass<int>::count <<"\n";
}
```
---
If you want a count for **all** instantiations of MyClass (regardless of their template parameters), you do need to use a **global variable**.
However, you probably don't want a global variable directly because you run the risk of using it before it gets initialized. You can get around this by making a global static method that returns a reference to your count:
```
int& my_count() {
static int count = 0;
return count;
}
```
Then accessing it from within your class like this:
```
void f() {
++my_count();
}
```
This will ensure that count gets initialized before it's used, regardless of which compilation unit you access it from. See the [C++ FAQ on static initialization order](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12) for more details. | Putting the static declaration in a header file will cause each .cpp file to get its own version of the variable. So the two cout statements are printing different variables. | Using static variable along with templates | [
"",
"c++",
"templates",
"static",
"visual-c++-6",
""
] |
Why do I get the error in intellij:
Cannot determine version for JDK flex\_sdk\_3. Update JDK configuration. | This problem arises if you have a java classes in your source tree. Remove them and the error should disappear. | When loading a project in IntelliJ IDEA, part of the project file is the name of the JDK that the project uses. If you don't have that JDK installed with that name, then IDEA will complain. We found a need to standardize on JDK names in our group.
To add or edit JDKs (at least in IDEA 7.0.4, which I'm using), go into File/Settings/Project Settings. There's a "JDKs" under Platform Settings there you can add JDK versions, and the "General" under Project Settings lets you pick which JDK to use for your project. | Intellij Cannot determine verions for JDK | [
"",
"apache-flex",
"intellij-idea",
"java",
""
] |
Suppose you have a python method that gets a type as parameter; is it possible to determine if the given type is a nested class?
E.g. in this example:
```
def show_type_info(t):
print t.__name__
# print outer class name (if any) ...
class SomeClass:
pass
class OuterClass:
class InnerClass:
pass
show_type_info(SomeClass)
show_type_info(OuterClass.InnerClass)
```
I would like the call to `show_type_info(OuterClass.InnerClass)` to show also that InnerClass is defined inside OuterClass. | AFAIK, given a class and no other information, you can't tell whether or not it's a nested class. However, [see here](http://mail.python.org/pipermail/python-list/2005-July/330874.html) for how you might use a decorator to determine this.
The problem is that a nested class is simply a normal class that's an attribute of its outer class. Other solutions that you might expect to work probably won't -- `inspect.getmro`, for example, only gives you base classes, not outer classes.
Also, nested classes are rarely needed. I would strongly reconsider whether that's a good approach in each particular case where you feel tempted to use one. | An inner class offers no particular special features in Python. It's only a property of the class object, no different from an integer or string property. Your OuterClass/InnerClass example can be rewritten exactly as:
```
class OuterClass(): pass
class InnerClass(): pass
OuterClass.InnerClass= InnerClass
```
InnerClass can't know whether it was declared inside another class, because that's just a plain variable binding. The magic that makes bound methods know about their owner ‘self’ doesn't apply here.
The innerclass decorator magic in the link John posted is an interesting approach but I would not use it as-is. It doesn't cache the classes it creates for each outer object, so you get a new InnerClass every time you call outerinstance.InnerClass:
```
>>> o= OuterClass()
>>> i= o.InnerClass()
>>> isinstance(i, o.InnerClass)
False # huh?
>>> o.InnerClass is o.InnerClass
False # oh, whoops...
```
Also the way it tries to replicate the Java behaviour of making outer class variables available on the inner class with getattr/setattr is very dodgy, and unnecessary really (since the more Pythonic way would be to call i.\_\_outer\_\_.attr explicitly). | python: determine if a class is nested | [
"",
"python",
"introspection",
"inner-classes",
""
] |
I have seen different ways of writing an `if` statement.
Which one do you prefer and why?
### Example 1:
```
if (val % 2 == 1){output = “Number is odd”;}else{output = “Number is even”;}
```
### Example 2:
```
if (val % 2 == 1)
{
output = “Number is odd”;
}
else
{
output = “Number is even”;
}
```
### Example 3:
```
if (val % 2 == 1)
output = “Number is odd”;
else
output = “Number is even”;
```
### Example 4:
```
if (val % 2 == 1){
output = “Number is odd”;
} else {
output = “Number is even”;
}
```
### Similar question:
> [Why is it considered a bad practice to omit curly braces?](https://stackoverflow.com/questions/359732) | For cases like this, there's also the conditional operator:
```
output = (val % 2 == 1) ? "Number is odd" : "Number is even";
```
If you're definitely going to use an "if" I'd use version 2 or version 4, depending on the rest of your bracing style. (At work I use 4; for personal projects I use 2.) The main thing is that there are braces even around single statements.
BTW, for testing parity it's slightly quicker to use:
```
if ((val & 1) == 1)
``` | Version 2. I always include the brackets because if you ever need to put more than one line under the conditional you won't have to worry about putting the brackets in at a later date. That, and it makes sure that ALL of your if statements have the same structure which helps when you're scanning code for a certain if statement. | Different ways of writing the "if" statement | [
"",
"c#",
""
] |
How can I count the number of rows that a MySQL query returned? | ## Getting total rows in a query result...
You could just iterate the result and count them. You don't say what language or client library you are using, but the API does provide a [mysql\_num\_rows](http://dev.mysql.com/doc/refman/5.0/en/mysql-num-rows.html) function which can tell you the number of rows in a result.
This is exposed in PHP, for example, as the [mysqli\_num\_rows](http://php.net/manual/en/mysqli-result.num-rows.php) function. As you've edited the question to mention you're using PHP, here's a simple example using mysqli functions:
```
$link = mysqli_connect("localhost", "user", "password", "database");
$result = mysqli_query($link, "SELECT * FROM table1");
$num_rows = mysqli_num_rows($result);
echo "$num_rows Rows\n";
```
## Getting a count of rows matching some criteria...
Just use COUNT(\*) - see [Counting Rows](http://dev.mysql.com/doc/refman/5.0/en/counting-rows.html) in the MySQL manual. For example:
```
SELECT COUNT(*) FROM foo WHERE bar= 'value';
```
## Get total rows when LIMIT is used...
If you'd used a LIMIT clause but want to know how many rows you'd get without it, use [SQL\_CALC\_FOUND\_ROWS](http://dev.mysql.com/doc/refman/5.0/en/select.html#id959825) in your query, followed by SELECT [FOUND\_ROWS();](http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows)
```
SELECT SQL_CALC_FOUND_ROWS * FROM foo
WHERE bar="value"
LIMIT 10;
SELECT FOUND_ROWS();
```
For very large tables, this isn't going to be particularly efficient, and you're better off running a simpler query to obtain a count and caching it before running your queries to get pages of data.
> DEPRECATED as of 8.0.17 - as Etienne Bruines notes in the comments, using SQL\_CALC\_FOUND\_ROWS is [deprecated](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_found-rows) in 8.0.17 and will be removed in later versions. The recommendation is to issue a second query to calculate a count. | In the event you have to solve the problem with simple SQL you might use an inline view.
```
select count(*) from (select * from foo) as x;
``` | How can I count the numbers of rows that a MySQL query returned? | [
"",
"php",
"mysql",
""
] |
Is there a canonical solution for limiting the number of characters that someone can enter into a textarea?
I have server side validation of course, but would like to improve the user experience by adding client side code to simulate the experience you get with maxlength on an input[type="text"] so that users never see the "your input is too long" error message if they have javascript enabled. | My non-technical $0.02
Do what SO does in their comment fields, provide feedback as to what the user's character length remaining is and allow them to go past the maximum, but not submit > 300 characters. Here's why:
- Allowing users to go over the maximum number of characters allows them to complete an idea. They can then go back and edit that idea. There's nothing worse than being at the end of a sentence and being unable to complete it.- Providing feedback to character length keeps people from having to guess what their length is at. | I would do it this way:
```
$ ('#textarea-id').bind (
'change input keyup keydown keypress mouseup mousedown cut copy paste',
function () { return ($(this).val().length <= maxlength) }
)
```
So many bingings just to be *completely* sure :-) | What is the best JavaScript solution to limit the length of a textarea? | [
"",
"javascript",
"html",
""
] |
I don't think I was specific enough last time. Here we go:
I have a hex string:
> 742713478fb3c36e014d004100440041004
> e0041004e00000060f347d15798c9010060
> 6b899c5a98c9014d007900470072006f007
> 500700000002f0000001f7691944b9a3306
> 295fb5f1f57ca52090d35b50060606060606
The last 20 bytes should (theoretically) contain a SHA1 Hash of the first part (complete string - 20 bytes). But it doesn't match for me.
Trying to do this with PHP, but no luck. Can you get a match?
### Ticket:
> 742713478fb3c36e014d004100
> 440041004e0041004e00000060
> f347d15798c90100606b899c5a
> 98c9014d007900470072006f00
> 7500700000002f0000001f7691944b9a
### sha1 hash of ticket appended to original:
> 3306295fb5f1f57ca52090d35b50060606060606
### My sha1 hash of ticket:
> b6ecd613698ac3533b5f853bf22f6eb4afb94239
Here's what is in the ticket and how it's being stored. FWIW, I can pull out username, etc, and spot the various delimiters.
<http://www.codeproject.com/KB/aspnet/Forms_Auth_Internals/AuthTicket2.JPG>
Edited: I have discovered that the string is padded on the end by the decryption function it goes through before this point. I removed the last 6 bytes and adjusted by ticket and hash accordingly. Still doesn't work, but I'm closer. | Your ticket is being calculated on the hex string itself. Maybe the appended hash is calculated on another representation of the same data? | I think you are getting confused about bytes vs characters.
Internally, php stores every character in a string as a byte. The sha1 hash that PHP generates is a 40 character (40 byte) hexademical representation of the 20-byte binary data, since each binary value needs to be represented by 2 hex characters.
I'm not sure if this is the actual source of your discrepancy, but seeing this misunderstanding makes me wonder if it's related. | Why is my SHA1 hash not matching? | [
"",
"php",
"sha1",
""
] |
How can I deploy a C# Visual Studio 2005 project so that I can run the application in another system? My project has a few dependencies and files that have to be integrated while deploying the project.
What is the best way to handle this? | Have you looked into [ClickOnce](http://msdn.microsoft.com/en-us/library/t71a733d(VS.80).aspx) deployment?
It's far from perfect, but for projects without a huge amount of overhead, it's generally good enough. | You need to know what dependencies you have.
* you need to have .Net framework installed
* you have to explicitly install all dependencies that you used from the GAC on your target machine (some 3rd party components)
* and then you just need to copy files from your \bin\Release folder
* install all services, etc. if you have any
In the simplest cases only copying files should be enough. | How can I deploy my C# project? | [
"",
"c#",
"deployment",
""
] |
I'm stuck trying to figure out a solution for the problem below.
It's quite complicated. So stay with me.
I retrieve a field from the `user` table which has his friends' user ids in the form of CSV
(3,4,5,6,7)
There is another table called `transaction` which looks something like this
```
tid user1 user2 type_of_trade
1 3 4 barter
2 5 6 share
3 6 7 bargain
4 4 3 barter
5 3 7 share
```
Now I need to display the transactions of my friends.
So I split the CSV, put them in an array and for each friend I'm running the query
```
friends = explode(",","3,4,5,6,7");
for($i=0;$i<=count(friends);$i++)
{
// I execute this--SELECT * FROM transaction WHERE user1 = friends[$i] or user2 = friends[$i]
}
```
Now the same happens for 3, 4, 5, 6, and 7
When the query executes for `4`, the same result comes and hence I'm getting duplicates.
I've tried everything. But I'm unable to figure this out.
Can someone please suggest a better solution or can this itself be modified? | In this particular case, do *not* `explode` it.
```
SELECT * FROM transaction WHERE user1 IN (3, 4, 5, 6, 7) OR user2 IN (3, 4, 5, 6, 7)
``` | You should myke use of the [mysql IN() function](http://dev.mysql.com/doc/refman/5.1/en/comparison-operators.html#function_in). This will guarantee unique results.
```
SELECT * FROM transactions WHERE user1 IN (3,4,5,6,7) OR user2 IN (3,4,5,6,7);
``` | mysql and php : Data extraction | [
"",
"php",
"mysql",
""
] |
I saw the following posted by one of the fellow stackoverflower and it sort of dumbfounds me.
Would someone explain the shifting operations in the following code snippet:
```
std::vector<bool> a;
a.push_back(true);
a.push_back(false);
//...
for (auto it = a.begin(); it != a.end();) // see 0x for meaning of auto
{
unsigned b = 0;
for (int i = 0; i < 8*sizeof(b); ++i)
{
b |= (*it & 1) << (8*sizeof(b) - 1 - i);
++it;
}
// flush 'b'
}
``` | 8 \* sizeof(b) is the number of bits that can be stored in 'b' (which is an unsigned int, i.e. typically 32 or 64 bits).
What the code is doing is that it is packing the boolean values in vector 'a' to become bits in 'b'.
"\*it & 1" evalutes to 1 if the boolean value at \*it is TRUE, otherwise 0. The bit is then shifted left 32 bits minus 1 minus the index 'i', i.e. shifted left from zero to 31 bits. This means now that the first element of 'a' will control the most significant bit on 'b' (left shift 31), the second element the second most significant bit on 'b' (left shift 30) etc. Note that in C the shifts are arithmetic, i.e. regardless of the byte or bit order, x << 1 is always x \* 2.
So for example, if your vector has the first and the 30th element set, 'b' should contain by the end of the day the binary number 10000000 00000000 00000000 00000100. | antti.huima's answer looks right to me.
However there may be a bug in the procedure. The outer loop goes from a.begin to a.end, however the inner loop increments "it" regardless of whether this causes "it" to go past a.end.
if you pass a vector with an "odd" size, say 33 entries, the result could be incorrect.
This may not be a bug if the size of the vector is guarenteed (but maybe there should be test that the length is valid). | Shift operations | [
"",
"c++",
"stl",
"bit-manipulation",
""
] |
it is a little bit strange to me that boost.asio doesn`t use basic concept when client app connecting to the server - using IP address and port. May be I am a little bit noobie in Boost - and I accept that - but anyway I do not understand.
So, I have code like this to get client connected to the server on the localhost:
```
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query("localhost", "daytime");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;
tcp::socket socket(io_service);
boost::system::error_code error = boost::asio::error::host_not_found;
while(error && endpoint_iterator != end) {
socket.close();
socket.connect(*endpoint_iterator++, error);
}
```
Windows in its WinSock 2.0 uses two parameters - IP and port - to identify the server.
So, the qurestion is - how exactly Asio finds out which port is server listening to connections on? Does it scans all ports? And, if it does, what will happen if two servers listening on different ports at the same time? | You are telling it that you want to connect to localhost on the port used by the daytime service. It will look up the appropriate port number in the services file (usually C:\WINDOWS\system32\drivers\etc\services under Windows, I believe /etc/services under Unix). You could also use an explicit port number there. | Try,
```
tcp::resolver::query query("localhost", boost::lexical_cast<string>(port));//assuming port is an int
```
To answer your question, recall that you are starting the server on port 13. This happens to be the port which runs the Linux daytime service [(http://www.sorgonet.com/linux/linuxdaemons/)](http://www.sorgonet.com/linux/linuxdaemons/). Hence, they are subsequently able to use query("localhost","daytime") rather than specifying the port. | How boost.asio discover which port is my server app listening on? | [
"",
"c++",
"boost",
"boost-asio",
""
] |
I've been developing Java Web apps using Eclipse as the IDE. Planning to start developing a desktop app based on Java.
Can someone suggest the best IDE for developing Java based desktop apps? (One that would have drag drop for building the interface like Visual Studio) | I recommend [NetBeans IDE](http://www.netbeans.org) and of course it is free.
Check out [Swing GUI Builder Features](http://www.netbeans.org/features/java/swing.html) | I'd say it depends on which GUI framework you are going to use:
* For Swing, the [NetBeans Swing GUI builder](http://www.netbeans.org/features/java/swing.html) seems to be the best choice (though there are [visual editors for Swing in Eclipse](https://stackoverflow.com/questions/29426) too)
* For JavaFX, the [choice is pretty clear](http://www.netbeans.org/kb/trails/matisse.html)
* For Eclipse (i.e. [SWT](http://www.eclipse.org/swt/), [JFace](http://wiki.eclipse.org/index.php/JFace), [RCP](http://wiki.eclipse.org/index.php/Rich_Client_Platform)) the [Eclipse IDE for Java](http://www.eclipse.org/downloads/) plus the [visual editor](http://www.eclipse.org/vep/WebContent/main.php) would probably be the best way to go
Now which to choose, of course, is a [different](https://stackoverflow.com/questions/281342) [question](https://stackoverflow.com/questions/286251/alternate-java-gui-frameworks). | Best IDE for developing Java Desktop Applications | [
"",
"java",
"ide",
"desktop",
""
] |
Note that I'm not actually doing anything with a database here, so ORM tools are probably not what I'm looking for.
I want to have some containers that each hold a number of objects, with all objects in one container being of the same class. The container should show some of the behaviour of a database table, namely:
* allow one of the object's fields to be used as a unique key, i. e. other objects that have the same value in that field are not added to the container.
* upon accepting a new object, the container should issue a numeric id that is returned to the caller of the insertion method.
Instead of throwing an error when a "duplicate entry" is being requested, the container should just skip insertion and return the key of the already existing object.
Now, I would write a generic container class that accepts objects which implement an interface to get the value of the key field and use a HashMap keyed with those values as the actual storage class. Is there a better approach using existing built-in classes? I was looking through HashSet and the like, but they didn't seem to fit. | None of the Collections classes will do what you need. You'll have to write your own!
P.S. You'll also need to decide whether your class will be thread-safe or not.
P.P.S. [ConcurrentHashMap](http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html) is close, but not exactly the same. If you can subclass or wrap it or wrap the objects that enter your map such that you're relying only on that class for thread-safety, you'll have an efficient and thread-safe implementation. | You can simulate this behavior with a [HashSet](http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashSet.html). If the objects you're adding to the collection have a field that you can use as a unique ID, just have that field returned by the object's hashCode() method (or use a [calculated hash code](http://www.javapractices.com/topic/TopicAction.do?Id=28) value, either way should work).
HashSet won't throw an error when you [add](http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashSet.html#add(java.lang.Object)) a duplicate entry, it just returns false. You could wrap (or extend) HashSet so that your add method returns the unique ID that you want as a return value. | Is there a Java Collection (or similar) that behaves like an auto-id SQL table? | [
"",
"java",
"data-structures",
"collections",
""
] |
For example, would a full int[50][8] use more resources (RAM and CPU) than 8 full int[50] arrays? | In the first case you have one array object pointing to fifty array objects holding 8 int's.
So 1 + 50 array objects + fifty pointers in the first array object.
In the second case you have one array object pointing to 8 array objects holding 50 int's.
So 1 + 8 array objects + eight pointers in the first array object. Holding the int's is a wash.
There is not a good way to evaluate CPU usage for this. | There appears to be three things to compare here.
* `new int[50][8]`
* `new int[8][50]`
* `new int[400]`
Now, I get this confused, but the way to remember is to think of `new int[50][]` which is valid.
So `new int[50][8]` is an array of 50 arrays of size 8 (51 objects). `new int[8][50]` is an array of 8 arrays of size 50 (9 objects). 9 objects will have a lower overhead than 51. `new int[400]` is just one object.
However, it at this size it probably doesn't make any measurable difference to the performance of your program. You might want to encapsulate the array(s) within an object that will allow you to change the implementation and provide a more natural interface to client code. | Do 2D arrays use more resources than 1D arrays in Java? | [
"",
"java",
"arrays",
"resources",
"cpu",
""
] |
Is it possible to force the C# compiler to pull all the referenced calls out of the framework and pack them into dlls or even a single executable?
I like writing quick 'one-off' applications with C#, however I don't want to have to install the whole framework on the target machine once it's ready to go. | You ask a loaded question. C# is merely a language and does not require the .NET Framework. The process of compiling it requires a compiler, which may or may not itself take a dependency on the .NET Framework (Microsoft's C# compiler does not -- it is written in native code). Your program will need to reference some assembly where types, classes, and methods can be found for your use. You *can* remove system.dll and mscorlib.dll from your references list and reference your own assemblies. So you can avoid dependencies on the .NET Framework if you really work at it. But in the end, unless you have a C# compiler that compiles programs to native code you still have a dependency on the CLR.
That's a very technical way of saying... almost nothing. But it answers your question. :) More practically useful however is how to get your C# programs to run with a minimum of dependencies. mkbundle from mono will actually let you compile it all into an .exe with virtually no dependencies.
But if you want to stick with the Microsoft .NET Framework, you can achieve a much lighter footprint and faster install of the dependencies you commonly need by using the Client profile of .NET 3.5 SP1. You can read about it here:
<http://msdn.microsoft.com/en-us/library/cc656912.aspx> | Look at [mkbundle](http://www.mono-project.com/Guide:Running_Mono_Applications) using Mono. | Can you compile C# so it doesn't need the .NET Framework at runtime? | [
"",
"c#",
".net",
""
] |
I'm sorting strings that are comprised of text and numbers.
I want the sort to sort the number parts as numbers, not alphanumeric.
For example I want: abc1def, ..., abc9def, abc10def
instead of: abc10def, abc1def, ..., abc9def
Does anyone know an algorithm for this (in particular in c++)
Thanks | I asked [this exact question (although in Java)](https://stackoverflow.com/questions/104599/sort-on-a-string-that-may-contain-a-number) and got pointed to http://www.davekoelle.com/alphanum.html which has an algorithm and implementations of it in many languages.
Update 14 years later: Dave Koelle’s blog has gone off line and I can’t find his actual algorithm, but here’s an implementation.
<https://github.com/cblanc/koelle-sort>
Update 14 years and 5 months after the original answer: In the comments, it was pointed out that Dave Koelle’s blog is on the wayback machine at <https://web.archive.org/web/20210207124255/davekoelle.com/alphanum.html> | Several natural sort implementations for C++ are available. A brief review:
* [`natural_sort<>`](http://web.archive.org/web/20071217040157/http://www.boostcookbook.com/Recipe:/1235053) - based on Boost.Regex.
+ In my tests, it's roughly 20 times slower than other options.
* Dirk Jagdmann's [`alnum.hpp`](http://www.davekoelle.com/files/alphanum.hpp), based on Dave Koelle's [alphanum algorithm](http://www.davekoelle.com/alphanum.html)
+ Potential integer overlow issues for values over MAXINT
* Martin Pool's [`natsort`](http://sourcefrog.net/projects/natsort/) - written in C, but trivially usable from C++.
+ The only C/C++ implementation I've seen to offer a case insensitive version, which would seem to be a high priority for a "natural" sort.
+ Like the other implementations, it doesn't actually parse decimal points, but it does special case leading zeroes (anything with a leading 0 is assumed to be a fraction), which is a little weird but potentially useful.
+ PHP uses this algorithm. | How to implement a natural sort algorithm in c++? | [
"",
"c++",
"sorting",
"natural-sort",
""
] |
I am trying to teach myself Python by working through some problems I came up with, and I need some help understanding how to pass functions.
Let's say I am trying to predict tomorrow's temperature based on today's and yesterday's temperature, and I have written the following function:
```
def predict_temp(temp_today, temp_yest, k1, k2):
return k1*temp_today + k2*temp_yest
```
And I have also written an error function to compare a list of predicted temperatures with actual temperatures and return the mean absolute error:
```
def mean_abs_error(predictions, expected):
return sum([abs(x - y) for (x,y) in zip(predictions,expected)]) / float(len(predictions))
```
Now if I have a list of daily temperatures for some interval in the past, I can see how my prediction function would have done **with specific k1 and k2 parameters** like this:
```
>>> past_temps = [41, 35, 37, 42, 48, 30, 39, 42, 33]
>>> pred_temps = [predict_temp(past_temps[i-1],past_temps[i-2],0.5,0.5) for i in xrange(2,len(past_temps))]
>>> print pred_temps
[38.0, 36.0, 39.5, 45.0, 39.0, 34.5, 40.5]
>>> print mean_abs_error(pred_temps, past_temps[2:])
6.5
```
**But how do I design a function to minimize my parameters k1 and k2 of my predict\_temp function given an error function and my past\_temps data?**
Specifically I would like to write a function minimize(args\*) that takes a prediction function, an error function, some training data, and that uses some search/optimization method (gradient descent for example) to estimate and return the values of k1 and k2 that minimize my error given the data?
I am not asking how to implement the optimization method. Assume I can do that. Rather, I would just like to know **how to pass my predict and error functions** (and my data) to my minimize function, and **how to tell my minimize function that it should optimize the parameters k1 and k2**, so that my minimize function can automatically search a bunch of different settings of k1 and k2, applying my prediction function with those parameters each time to the data and computing error (like I did manually for k1=0.5 and k2=0.5 above) and then return the best results.
I would like to be able to pass these functions so I can easily swap in different prediction and error functions (differing by more than just parameter settings that is). Each prediction function might have a different number of free parameters.
My minimize function should look something like this, but I don't know how to proceed:
```
def minimize(prediction_function, which_args_to_optimize, error_function, data):
# 1: guess initial parameters
# 2: apply prediction function with current parameters to data to compute predictions
# 3: use error function to compute error between predictions and data
# 4: if stopping criterion is met, return parameters
# 5: update parameters
# 6: GOTO 2
```
Edit: It's that easy?? This is no fun. I am going back to Java.
On a more serious note, I think I was also getting hung up on how to use different prediction functions with different numbers of parameters to tune. If I just take all the free parameters in as one tuple I can keep the form of the function the same so it easy to pass and use. | Here is an example of how to pass a function into another function. `apply_func_to` will take a function `f` and a number `num` as parameters and `return f(num)`.
```
def my_func(x):
return x*x
def apply_func_to(f, num):
return f(num)
>>>apply_func_to(my_func, 2)
4
```
If you wanna be clever you can use lambda (anonymous functions too). These allow you to pass functions "on the fly" without having to define them separately
```
>>>apply_func_to(lambda x:x*x, 3)
9
```
Hope this helps. | Function passing in Python is easy, you just use the name of the function as a variable which contains the function itself.
```
def predict(...):
...
minimize(predict, ..., mean_abs_error, ...)
```
As for the rest of the question: I'd suggest looking at the way [SciPy implements this](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.leastsq.html#scipy.optimize.leastsq) as a model. Basically, they have a function `leastsq` which minimizes the sum of the squares of the residuals (I presume you know what least-squares minimization is ;-). What you pass to `leastsq` is a function to compute the residuals, initial guesses for the parameters, and an arbitrary parameter which gets passed on to your residual-computing function (the closure), which includes the data:
```
# params will be an array of your k's, i.e. [k1, k2]
def residuals(params, measurements, times):
return predict(params, times) - measurements
leastsq(residuals, initial_parameters, args = (measurements, times))
```
Note that SciPy doesn't actually concern itself with how you come up with the residuals. The `measurements` array is just passed unaltered to your `residuals` function.
I can look up an example I did recently if you want more information - or you can find examples online, of course, but in my experience they're not quite as clear. The particular bit of code I wrote would relate well to your scenario. | Need help understanding function passing in Python | [
"",
"python",
""
] |
In Python, the following statements do not work:
```
f = open("ftmp", "rw")
print >> f, "python"
```
I get the error:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 9] Bad file descriptor
```
But with the following code it works:
```
g = open("ftmp", "r+")
print >> g, "python"
```
It looks like I need to revise the file modes. What are the deep intricacies of the file opening modes?
**Update:** Python 3, doesn't allow "rw" mode. You would get the error:
`ValueError: must have exactly one of create/read/write/append mode` | As an addition to [@Jarret Hardie's answer](https://stackoverflow.com/questions/654499/python-file-modes-detail/654518#654518) here's how Python check file mode in the function [fileio\_init()](http://hg.python.org/cpython/file/3.2/Modules/_io/fileio.c#l286):
```
s = mode;
while (*s) {
switch (*s++) {
case 'r':
if (rwa) {
bad_mode:
PyErr_SetString(PyExc_ValueError,
"Must have exactly one of read/write/append mode");
goto error;
}
rwa = 1;
self->readable = 1;
break;
case 'w':
if (rwa)
goto bad_mode;
rwa = 1;
self->writable = 1;
flags |= O_CREAT | O_TRUNC;
break;
case 'a':
if (rwa)
goto bad_mode;
rwa = 1;
self->writable = 1;
flags |= O_CREAT;
append = 1;
break;
case 'b':
break;
case '+':
if (plus)
goto bad_mode;
self->readable = self->writable = 1;
plus = 1;
break;
default:
PyErr_Format(PyExc_ValueError,
"invalid mode: %.200s", mode);
goto error;
}
}
if (!rwa)
goto bad_mode;
```
That is: only `"rwab+"` characters are allowed; there must be exactly one of `"rwa"`, at most one `'+'` and `'b'` is a noop. | Better yet, let the documentation do it for you: <http://docs.python.org/library/functions.html#open>. Your issue in the question is that there is no "rw" mode... you probably want 'r+' as you wrote (or 'a+' if the file does not yet exist). | Python file modes detail | [
"",
"python",
"file-io",
""
] |
I feel like this one has been asked before, but I'm unable to find it on SO, nor can I find anything useful on Google. Maybe "covariant" isn't the word I'm looking for, but this concept is very similar to covariant return types on functions, so I think it's probably correct. Here's what I want to do and it gives me a compiler error:
```
class Base;
class Derived : public Base;
SmartPtr<Derived> d = new Derived;
SmartPtr<Base> b = d; // compiler error
```
Assume those classes are fully fleshed out... I think you get the idea. It can't convert a `SmartPtr<Derived>` into a `SmartPtr<Base>` for some unclear reason. I recall that this is normal in C++ and many other languages, though at the moment I can't remember why.
My root question is: what is the best way to perform this assignment operation? Currently, I'm pulling the pointer out of the `SmartPtr`, explicitly upcasting it to the base type, then wrapping it in a new `SmartPtr` of the appropriate type (note that this is not leaking resources because our home-grown `SmartPtr` class uses intrusive reference counting). That's long and messy, especially when I then need to wrap the `SmartPtr` in yet another object... any shortcuts? | Both the copy constructor and the assignment operator should be able to take a SmartPtr of a different type and attempt to copy the pointer from one to the other. If the types aren't compatible, the compiler will complain, and if they are compatible, you've solved your problem. Something like this:
```
template<class Type> class SmartPtr
{
....
template<class OtherType> SmartPtr(const SmartPtr<OtherType> &blah) // same logic as the SmartPtr<Type> copy constructor
template<class OtherType> SmartPtr<Type> &operator=(const SmartPtr<OtherType> &blah) // same logic as the SmartPtr<Type> assignment operator
};
``` | `SmartPtr<Base>` and `SmartPtr<Derived>` are two distinct instantiations of a the `SmartPtr` template. These new classes do not share the inheritance that `Base` and `Derived` do. Hence, your problem.
> what is the best way to perform this assignment operation?
```
SmartPtr<Base> b = d;
```
Does not invoke assignment operator. This invokes the copy-ctor (the copy is elided in most cases) and is exactly as if you wrote:
```
SmartPtr<Base> b(d);
```
Provide for a copy-ctor that takes a `SmartPtr<OtherType>` and implement it. Same goes for the assignment operator. You will have to write out the copy-ctor and op= keeping in mind the semantics of SmartPtr. | C++ covariant templates | [
"",
"c++",
"templates",
"covariance",
""
] |
Consider the following piece of code.
```
<html>
<body>
<script>
var x = 5; //globally declared
function showX()
{
alert("x="+x); //trying to display global value
var x=10; //trying to create and initialize a local x
}
</script>
<input type = "button" value="Show X" onclick="showX()">
</body>
</html>
```
The alert statement shows 'x=undefined'. And doesn't print the global value of x as expected. An equivalent java code would display 5! So, is it a bug? If not then how does one explain that behavior? | The [ECMAScript Specification](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf) says in section 12.2:
> If the variable statement occurs
> inside a FunctionDeclaration, the
> variables are defined with
> function-local scope in that function,
> as described in s10.1.3. Otherwise,
> they are defined with global scope
> (that is, they are created as members
> of the global object, as described in
> 10.1.3) using property attributes { DontDelete}. Variables are created
> when the execution scope is entered. A
> Block does not define a new execution
> scope. Only Program and
> FunctionDeclaration produce a new
> scope. Variables are initialised to
> undefined when created. A variable
> with an Initialiser is assigned the
> value of its AssignmentExpression when
> the VariableStatement is executed, not
> when the variable is created.
So it's not a bug - the local variable is created when the function is entered. | The second var-declaration is interfering with the first. You are actually referring to the as-of-yet-undeclared local x. However, to quote javascript guru Douglas Crockford:
> JavaScript's biggest problem is its
> dependence on global variables,
> particularly implied global variables.
> If a variable is not explicitly
> declared (usually with the var
> statement), then JavaScript assumes
> that the variable was global. This can
> mask misspelled names and other
> problems.
<http://www.jslint.com/lint.html>
So the recommendation is to avoid using global variables as much as possible. | Weird behavior in referring to global variable. Is this a bug in javascript? Surely it isn't! | [
"",
"javascript",
"variables",
""
] |
It had been a while since GCC caught me with this one, but it just happened today. But I've never understood why GCC requires typedef typename within templates, while VS and I guess ICC don't. Is the typedef typename thing a "bug" or an overstrict standard, or something that is left up to the compiler writers?
For those who don't know what I mean here is a sample:
```
template<typename KEY, typename VALUE>
bool find(const std::map<KEY,VALUE>& container, const KEY& key)
{
std::map<KEY,VALUE>::const_iterator iter = container.find(key);
return iter!=container.end();
}
```
The above code compiles in VS (and probably in ICC), but fails in GCC because it wants it like this:
```
template<typename KEY, typename VALUE>
bool find(const std::map<KEY,VALUE>& container, const KEY& key)
{
typedef typename std::map<KEY,VALUE>::const_iterator iterator; //typedef typename
iterator iter = container.find(key);
return iter!=container.end();
}
```
Note: This is not an actual function I'm using, but just something silly that demonstrates the problem. | The typename is required by the standard. Template compilation requires a two step verification. During the first pass the compiler must verify the template syntax without actually supplying the type substitutions. In this step, std::map::iterator is assumed to be a value. If it does denote a type, the typename keyword is required.
Why is this necessary? Before substituing the actual KEY and VALUE types, the compiler cannot guarantee that the template is not specialized and that the specialization is not redefining the *iterator* keyword as something else.
You can check it with this code:
```
class X {};
template <typename T>
struct Test
{
typedef T value;
};
template <>
struct Test<X>
{
static int value;
};
int Test<X>::value = 0;
template <typename T>
void f( T const & )
{
Test<T>::value; // during first pass, Test<T>::value is interpreted as a value
}
int main()
{
f( 5 ); // compilation error
X x; f( x ); // compiles fine f: Test<T>::value is an integer
}
```
The last call fails with an error indicating that during the first template compilation step of f() Test::value was interpreted as a value but instantiation of the Test<> template with the type X yields a type. | Well, GCC doesn't actually *require* the `typedef` -- `typename` is sufficient. This works:
```
#include <iostream>
#include <map>
template<typename KEY, typename VALUE>
bool find(const std::map<KEY,VALUE>& container, const KEY& key)
{
typename std::map<KEY,VALUE>::const_iterator iter = container.find(key);
return iter!=container.end();
}
int main() {
std::map<int, int> m;
m[5] = 10;
std::cout << find(m, 5) << std::endl;
std::cout << find(m, 6) << std::endl;
return 0;
}
```
This is an example of a context sensitive parsing problem. What the line in question means is not apparent from the syntax in this function only -- you need to know whether `std::map<KEY,VALUE>::const_iterator` is a type or not.
Now, I can't seem to think of an example of what ...`::const_iterator` might be except a type, that would also not be an error. So I guess the compiler can find out that it *has* to be a type, but it might be difficult for the poor compiler (writers).
The standard requires the use of `typename` here, according to litb by section 14.6/3 of the standard. | Why do I need to use typedef typename in g++ but not VS? | [
"",
"c++",
"g++",
"typedef",
"typename",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.