Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm trying to write an application that responds whenever the Shift key is pressed, no matter what application currently has focus.
I tried this with `SetWindowsHookEx()` and with `GetKeyboardState()`, but both of these only work when the application's window has focus. I need it to work globally.
How do I do this? | None of the provided answers helped me solve my problem, but I found the answer myself. Here it is.
Using `SetWindowsHookEx()` with `WH_KEYBOARD_LL` was the correct approach. However, the other parameters to `SetWindowsHookEx()` are unintuitive:
* The last parameter, `dwThreadId`, needs to be 0.
* The second-last parameter, `hMod`, needs to point to some DLL. I used
`User32`, which is a DLL that is always loaded anyway and is used by all
processes with a GUI. I got this idea from [a CodeProject post about this](http://www.codeproject.com/KB/cs/CSLLKeyboardHook.aspx).
Thus, the code looks a bit like this:
```
instance = LoadLibrary("User32");
hhook = SetWindowsHookEx(WH_KEYBOARD_LL, hookFunction, instance, 0);
```
The documentation is unclear about the second-last parameter. It says:
> The hMod parameter must be set to NULL [...] if the hook procedure is within the code associated with the current process.
It doesn't state that this only applies to some types of hooks, but not to `WH_KEYBOARD_LL` and `WH_MOUSE_LL`. | You'll have to use SetWindowsHookEx(). There are only two types of hooks that you can implement in a managed language, WH\_KEYBOARD\_LL and WH\_MOUSE\_LL. All other hooks require a DLL that can be injected into another process. Managed DLLs cannot be injected, the CLR cannot be initialized.
This [blog post](https://learn.microsoft.com/en-us/archive/blogs/toub/low-level-keyboard-hook-in-c) has a functional example. | Respond to keyboard when not in focus? (C#, Vista) | [
"",
"c#",
"windows",
"windows-vista",
""
] |
In MS Sql Server is easy create autoincrement fields. In my systems I stopped to use autoincrement fields for primary keys, and now I use Guid's. It was awesome, I've got a lot of advantages with that change. But in another non-primary key fields, I really was needing implement a "soft autoincrement". It's because my system is DB independent, so I create the autoinc value programatically in c#.
I would like about solutions for autoincrement fields on databases without autoincrement, what the solution that your use and why? There is some Sql Ansi statement about this? and generating directly from my c#, is a better solution?
PS: I know that *select max(id)+1 from table* it's not really concurrent friendly... | The mechanism to generate unique id values **must not** be subject to transaction isolation. This is required for the database to generate a distinct value for each client, better than the trick of `SELECT MAX(id)+1 FROM table`, which results in a race condition if two clients try to allocate new `id` values concurrently.
You can't simulate this operation using standard SQL queries (unless you use table locks or *serializable* transactions). It has to be a mechanism built into the database engine.
ANSI SQL did not describe an operation to generate unique values for surrogate keys until SQL:2003. Before that, there was no standard for auto-incrementing columns, so nearly every brand of RDBMS provided some proprietary solution. Naturally they vary a lot, and there's no way to use them in a simple, database-independent manner.
* MySQL has the `AUTO_INCREMENT` column option, or `SERIAL` pseudo-datatype which is equivalent to `BIGINT UNSIGNED AUTO_INCREMENT`;
* Microsoft SQL Server has the `IDENTITY` column option and `NEWSEQUENTIALID()` which is something between auto-increment and GUID;
* Oracle has a `SEQUENCE` object;
* PostgreSQL has a `SEQUENCE` object, or `SERIAL` pseudo-datatype which implicitly creates a sequence object according to a naming convention;
* InterBase/Firebird has a `GENERATOR` object which is pretty much like a `SEQUENCE` in Oracle; Firebird 2.1 supports `SEQUENCE` too;
* SQLite treats any integer declared as your primary key as implicitly auto-incrementing;
* DB2 UDB has just about everything: `SEQUENCE` objects, or you can declare columns with the "`GEN_ID`" option.
All these mechanisms operate outside transaction isolation, ensuring that concurrent clients get unique values. Also in all cases there is a way to query the most recently generated value *for your current session*. There has to be, so you can use it to insert rows in a child table. | I think your question is actually quite a good one. However, it is easy to get lost trying to come up with a SQL only solution. In reality you will want the optimization and transaction safety afforded by using the database implementations of the autoincrement types.
If you need to abstract out the implementation of the autoincrement operator, why not create a stored procedure to return your autoincrement value. Most SQL dialects access stored procedures in relatively the same way and it should be more portable. Then you can create database specific autoincrement logic when you create the sproc - eliminating the need to change many statements to be vendor specific.
Done this way, your inserts could be as simple as:
```
INSERT INTO foo (id, name, rank, serial_number)
VALUES (getNextFooId(), 'bar', 'fooRank', 123456);
```
Then define getNextFooId() in a database specific way when the database is being initialized. | AutoIncrement fields on databases without autoincrement field | [
"",
"sql",
"sql-server",
"auto-increment",
"ansi-sql",
""
] |
I am looking to create a system which on signup will create a subdomain on my website for the users account area.
e.g. `johndoe.website.example`
I think it would be something to do with the `.htaccess` file and possibly redirecting to another location on the website? I don't actually know. But any information to start me off would be greatly appreciated.
Creating a sign up area is not the problem - I have done this many a time. I am just unsure where to start with the subdomain. | ## The quick rundown
1. You need to create a wildcard domain on your DNS server `*.website.example`
2. Then in your vhost container you will need to specify the wildcard as well `*.website.example` - This is done in the [`ServerAlias` DOCs](http://httpd.apache.org/docs/current/mod/core.html#serveralias)
3. Then extract and verify the subdomain in PHP and display the appropriate data
## The long version
### 1. Create a wildcard DNS entry
In your DNS settings you need to create a [wildcard domain entry](http://en.wikipedia.org/wiki/Wildcard_DNS_record) such as `*.example.org`. A wildcard entry looks like this:
```
*.example.org. 3600 A 127.0.0.1
```
### 2. Include the wildcard in vhost
Next up in the Apache configuration you need to set up a vhost container that specifies the wildcard in the [`ServerAlias` DOCs](http://httpd.apache.org/docs/current/mod/core.html#serveralias) directive. An example vhost container:
```
<VirtualHost *:80>
ServerName server.example.org
ServerAlias *.example.org
UseCanonicalName Off
</VirtualHost>
```
### 3. Work out which subdomain you are on in PHP
Then in your PHP scripts you can find out the domain by looking in the `$_SERVER` super global variable. Here is an example of grabbing the subdomain in PHP:
```
preg_match('/([^.]+)\.example\.org/', $_SERVER['SERVER_NAME'], $matches);
if(isset($matches[1])) {
$subdomain = $matches[1];
}
```
I have used regex here to to allow for people hitting your site via `www.subdomain.example.org` or `subdomain.example.org`.
If you never anticipate having to deal with www. (or other subdomains) then you could simply use a substring like so:
```
$subdomain = substr(
$_SERVER['SERVER_NAME'], 0,
strpos($_SERVER['SERVER_NAME'], '.')
);
```
## Mass Virtual Hosting
Mass virtual hosting is a slightly different scheme to the above in that you would usually use it to host many distinct websites rather than attempting to use it power an application as the question proposes.
I have documented my mod\_rewrite based mass virtual hosting environment before in a [post on my blog](http://blog.simonholywell.com/post/1516566788/team-development-server), which you could look at if that is the route you wish to take. There is also, of course, the [respective Apache manual page](http://httpd.apache.org/docs/current/rewrite/vhosts.html#simple.rewrite).
Apache also has an internal way of dealing with mass virtual hosting that is slightly less flexible than the mod\_rewrite method I have used. This is all described on the Apache [Dynamically Configured Mass Virtual Hosting manual page](http://httpd.apache.org/docs/current/vhosts/mass.html#simple). | You could allow every subdomain in the first place and then check if the subdomain is valid. For example:
```
RewriteEngine on
RewriteCond %{HTTP_HOST} ^[^.]+\.example\.com$
RewriteRule !^index\.php$ index.php [L]
```
Inside the `index.php` you can than extract the subdomain using:
```
if (preg_match('/^([^.]+)\.example\.com$/', $_SERVER['HTTP_HOST'], $match)) {
var_dump($match[1]);
}
```
But all this requires that your webserver accepts every subdomain name. | Create subdomains on the fly with .htaccess (PHP) | [
"",
"php",
".htaccess",
"dns",
"virtualhost",
"subdomain",
""
] |
Is it possible to get the previous and next DST transition timestamp with the Java Calendar/Date/TimeZone API?
With `Joda-Time` I can write:
```
DateMidnight today = new DateMidnight(2009, 2, 24);
DateTimeZone zone = today.getZone();
DateTime previousTransition =
new DateTime(zone.previousTransition(today.getMillis()));
// 2008-10-26T02:59:59.999+02:00 for Europe/Berlin
System.out.println(previousTransition);
DateTime nextTransition =
new DateTime(zone.nextTransition(today.getMillis()));
// 2009-03-29T03:00:00.000+02:00 for Europe/Berlin
System.out.println(nextTransition);
```
Is there way to do this with the standard Java APIs? | There's no such functionality in java Date/Calendar/TimeZone API | The best I came up with, when I needed such functionality, is to use a Calendar and iterate through entire year, in specified time zone, and ask if each hour of each day is it the begging or ending of DST.
You have to do it like that because on Sun's JVM, the implementation of TimeZone (sun.util.calendar.ZoneInfo) holds data about time zone transitions in some kind of "compiled" form.
Code goes something like this:
```
public class Dst {
Date start;
Date end;
public static Dst calculate(TimeZone tz, int year) {
final Calendar c = Calendar.getInstance(tz);
c.setLenient(false);
c.set(year, Calendar.JANUARY, 1, 1, 0, 0);
c.set(Calendar.MILLISECOND, 0);
if (tz.getDSTSavings() == 0) {
return null;
}
Dst dst = new Dst();
boolean flag = false;
do {
Date date = c.getTime();
boolean daylight = tz.inDaylightTime(date);
if (daylight && !flag) {
flag = true;
dst.start = date;
}
else if (!daylight && flag) {
flag = false;
dst.end = date;
}
c.add(Calendar.HOUR_OF_DAY, 1);
}
while (c.get(Calendar.YEAR) == year);
return dst;
}
}
```
Of course, it would make sense to cache/memoize the result of these calculations etc.
Hope this helps. | Find DST transition timestamp with java.util.TimeZone | [
"",
"java",
"jodatime",
""
] |
I have a `DataGrid` in my Silverlight application and it works nicely, adding a row or removing a row as I manipulate the `ItemsSource` collection. However, I want there to be an additional row, or control that always appears after the last data row.
I can get the additional control to appear after the last row using a `ControlTemplate` and setting the RowsPresenter row to Auto height, but this means the rows never scroll when the render area gets too small. However, if I change the RowsPresenter row height to Star, the rows scroll but the additional control appears pinned to the bottom of the data grid rather than to the bottom of the last row.
Is there a way I can have the Star height behavior on the RowsPresenter while still having my control appear the way I want?
My current thinking is that I need to somehow use the LoadingRow event to find the position of the last row and use a Canvas or similar to place my control in the appropriate location.
Thoughts?
Thanks in advance for the help.
### Update
I also asked a question (and ultimately answered) about pinning one control below another, which could be used to fix this issue if you don't want the custom row to scroll with the rest of the rows (such as in my case, where I wanted another datagrid header row to show totals and float over the other rows).
[How do I pin one control below another in Silverlight?](https://stackoverflow.com/questions/849768/how-do-i-pin-one-control-below-another-in-silverlight) | I solved my problem last night in a flurry of inspiration. I notice that no one else has voted for this question so this answer may not be helpful to anyone, but just in case.
First of all, I combined my custom row control and RowsPresenter in a grid of two rows, each row sized to Auto. I then placed the grid inside a ScrollViewer and then sized the scroll viewer row to Star sizing. I did not add the VerticalScrollbar template part into my template as this only scrolls the RowsPresenter.
This gave me the exact behaviour I was looking for where a row is added and the custom row remains pinned to the bottom of the last data row. When the rows and custom row overflow off the end of the visible area, the scrollbar appears to allow scrolling while keeping the headers fixed in place.
Job done. I hope someone finds this helpful. Below is my ControlTemplate XAML.
```
<ControlTemplate TargetType="swcd:DataGrid" x:Key="DataGridTemplate">
<Border
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid Name="Root" Background="{TemplateBinding Background}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<swcdp:DataGridColumnHeader Name="TopLeftCornerHeader" Grid.Column="0"/>
<swcdp:DataGridColumnHeadersPresenter Name="ColumnHeadersPresenter" Grid.Column="1"/>
<swcdp:DataGridColumnHeader Name="TopRightCornerHeader" Grid.Column="2"/>
<ScrollViewer
Grid.Row="1"
Grid.Column="1"
Grid.ColumnSpan="1"
Padding="0,0,0,0"
BorderThickness="0,0,0,0"
VerticalScrollBarVisibility="Auto">
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<swcdp:DataGridRowsPresenter Name="RowsPresenter" Grid.Row="0" />
<Border
Margin="1,1,1,1"
Padding="2,2,2,2"
BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Grid.Row="1">
<Grid Background="{TemplateBinding Background}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock
Grid.Row="0"
TextAlignment="Left"
TextWrapping="NoWrap"
Text="Add a new item using the lists below:" />
<mystuff:MySelectionControl
HorizontalContentAlignment="Stretch"
Grid.Row="1"
SelectionChanged="OnSelectionChanged"/>
</Grid>
</Border>
</Grid>
</ScrollViewer>
<Rectangle Name="BottomLeftCorner" Grid.Row="3" Grid.ColumnSpan="2" />
<Grid Grid.Column="1" Grid.Row="3">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Rectangle Name="FrozenColumnScrollBarSpacer" />
<ScrollBar Name="HorizontalScrollbar" Grid.Column="1" Orientation="Horizontal" Height="18" />
</Grid>
<Rectangle Name="BottomRightCorner" Grid.Column="2" Grid.Row="3" />
</Grid>
</Border>
</ControlTemplate>
``` | Not sure if this helps for Silverlight, but I added a totals row to a WPF DataGrid by adding and invisible column, called IsTotal. I was able to get this row to always appear at the buttom of the grid using custom grouping / sorting. The grouping / sort order was configured to use this column as the primary sort, with a fix direction. Seems to work well. | How do I include a custom row at the end of a DataGrid in Silverlight? | [
"",
"c#",
"xaml",
"datagrid",
"silverlight-2.0",
"controltemplates",
""
] |
Is there any way to use different types of iterators in different vectors? Or, is there a function that returns the position of element in vector as an integer?
```
std::vector<DWORD>::iterator it; // Iterator
// monsterQueue is a <DWORD> vector
it = std::find(bot.monsterQueue.begin(), bot.monsterQueue.end(), object);
// Check do we have the object in the queue
if(it != bot.monsterQueue.end()) // If we do have it
{
bot.monsterDists.at(it) = mobDist; // monsterDists is <int> vector
bot.monsterCoordX.at(it) = PosX; // monsterCoordX is <int> vector
bot.monsterCoordY.at(it) = PosY; // monsterCoordY is <int> vector too
}
```
That's some sample code, does anyone have any pointers? | Try
```
std::vector<DWORD>::iterator it; // Iterator
// monsterQueue is a <DWORD> vector
it = std::find(bot.monsterQueue.begin(), bot.monsterQueue.end(), object);
// Check do we have the object in the queue
if(it != bot.monsterQueue.end()) // If we do have it
{
```
**size\_t idx = it - bot.monsterQueue.begin()**
```
bot.monsterDists.at(idx) = mobDist; // monsterDists is <int> vector
bot.monsterCoordX.at(idx) = PosX; // monsterCoordX is <int> vector
bot.monsterCoordY.at(idx) = PosY; // monsterCoordY is <int> vector too
}
```
Also probably it will be a better idea to create a struct with 4 members 'monster',monsterDist and coordinateX and coordinateY and store the struct objects in vector. | ```
index = std::distance( monsterQueue.begin(), it );
``` | Vectors, iterators and std::find | [
"",
"c++",
"vector",
"iterator",
""
] |
I'm looking for a light-weight database library that I can compile into a C++ application.
Does any such exist? | For pure XML embedded database you might want to peek at [Oracle Berkeley DB XML](http://www.oracle.com/database/berkeley-db/xml/index.html). | [SQLite](http://www.sqlite.org/). Not flat-file, but it is file based, can be easily embedded in apps. | Looking for an open-source flatfile/xml database C++ library | [
"",
"c++",
"database",
"open-source",
"flat-file",
""
] |
I am writing a (my first) C++ class on top of some code written in C, but I can only get the C++ to compile by declaring the C functions in a extern block. My project uses autotools; is there any way to automate this process so I don't have to maintain two header files? | Yes create wrapper header files which include your C header files like so...
```
//Wrapper.h
#ifdef __cplusplus
extern "C"
{
#include "Actual.h"
}
#else
#include "Actual.h"
#endif
//Use.cpp
#include "Wrapper.h"
int main()
{
return 0;
}
//Use.c
#include "Wrapper.h"
/*or #include "Actual.h" */
int main()
{
return 0;
}
``` | Use a extern block inside a #ifdef in C codes header files
Start of header files
```
#ifdef __cplusplus
extern "C" {
#endif
```
...and at end of the header files
```
#ifdef __cplusplus
}
#endif
```
This way it will work for being included in both C and C++ sources | Using C code from C++ using autotools | [
"",
"c++",
"c",
"linker",
""
] |
The problem I'm trying to solve is that I have a table like this:
a and b refer to point on a different table. distance is the distance between the points.
```
| id | a_id | b_id | distance | delete |
| 1 | 1 | 1 | 1 | 0 |
| 2 | 1 | 2 | 0.2345 | 0 |
| 3 | 1 | 3 | 100 | 0 |
| 4 | 2 | 1 | 1343.2 | 0 |
| 5 | 2 | 2 | 0.45 | 0 |
| 6 | 2 | 3 | 110 | 0 |
....
```
The important column I'm looking is a\_id. If I wanted to keep the closet b for each a, I could do something like this:
```
update mytable set delete = 1 from (select a_id, min(distance) as dist from table group by a_id) as x where a_gid = a_gid and distance > dist;
delete from mytable where delete = 1;
```
Which would give me a result table like this:
```
| id | a_id | b_id | distance | delete |
| 1 | 1 | 1 | 1 | 0 |
| 5 | 2 | 2 | 0.45 | 0 |
....
```
i.e. I need one row for each value of a\_id, and that row should have the lowest value of distance for each a\_id.
However I want to keep the 10 closest points for each a\_gid. I could do this with a plpgsql function but I'm curious if there is a more SQL-y way.
min() and max() return the smallest and largest, if there was an aggregate function like nth(), which'd return the nth largest/smallest value then I could do this in similar manner to the above.
I'm using PostgeSQL. | Try this:
```
SELECT *
FROM (
SELECT a_id, (
SELECT b_id
FROM mytable mib
WHERE mib.a_id = ma.a_id
ORDER BY
dist DESC
LIMIT 1 OFFSET s
) AS b_id
FROM (
SELECT DISTINCT a_id
FROM mytable mia
) ma, generate_series (1, 10) s
) ab
WHERE b_id IS NOT NULL
```
Checked on PostgreSQL 8.3 | I love postgres, so it took it as a challenge the second I saw this question.
So, for the table:
```
Table "pg_temp_29.foo"
Column | Type | Modifiers
--------+---------+-----------
value | integer |
```
With the values:
```
SELECT value FROM foo ORDER BY value;
value
-------
0
1
2
3
4
5
6
7
8
9
14
20
32
(13 rows)
```
You can do a:
```
SELECT value FROM foo ORDER BY value DESC LIMIT 1 OFFSET X
```
Where X = 0 for the highest value, 1 for the second highest, 2... And so forth.
This can be further embedded in a subquery to retrieve the value needed. So, to use the dataset provided in the original question we can get the a\_ids with the top ten lowest distances by doing:
```
SELECT a_id, distance FROM mytable
WHERE id IN
(SELECT id FROM mytable WHERE t1.a_id = t2.a_id
ORDER BY distance LIMIT 10);
ORDER BY a_id, distance;
a_id | distance
------+----------
1 | 0.2345
1 | 1
1 | 100
2 | 0.45
2 | 110
2 | 1342.2
``` | SQL - min() gets the lowest value, max() the highest, what if I want the 2nd (or 5th or nth) lowest value? | [
"",
"sql",
"postgresql",
""
] |
I'm doing some string replacement on text I'm getting back from a JSON web service, the string may look like this:
```
"Hello I am a string.\r\nThis is a second line.\r\n\r\nThis is a bigger space"
```
I want to replace all the `\r\n` with `<br />` tags so that the HTML is formatted, but when I do:
```
var string = result.replace('\r\n','<br />');
```
I only get the first instance replaced, not any other.
What am I doing wrong? | Try a regexp with the global flag set:
```
var string = result.replace(/\r\n/g,'<br />');
``` | Nothing. That's just how the JavaScript replace function works :)
You can use regular expressions to replace all occurences.
```
var string = result.replace(/\r\n/g, '<br />');
```
Take a look at [this](http://www.tizag.com/javascriptT/javascript-string-replace.php "JavaScript replace tutorial") link | JavaScript string replacement problem | [
"",
"javascript",
""
] |
Which is better, MySQL or MySQLi? And why? Which should I use?
I mean better not just in terms of performance, but any other relevant feature. | If you have a look at [MySQL Improved Extension Overview](http://php.net/manual/en/mysqli.overview.php), it should tell you everything you need to know about the differences between the two.
The main useful features are:
* an Object-oriented interface
* support for prepared statements
* support for multiple statements
* support for transactions
* enhanced debugging capabilities
* embedded server support. | There is a manual page dedicated to help choosing between mysql, mysqli and PDO at
* <http://php.net/manual/en/mysqlinfo.api.choosing.php> and
* <http://www.php.net/manual/en/mysqlinfo.library.choosing.php>
The PHP team recommends mysqli or PDO\_MySQL for new development:
> It is recommended to use either the mysqli or PDO\_MySQL extensions. It is not recommended to use the old mysql extension for new development. A detailed feature comparison matrix is provided below. The overall performance of all three extensions is considered to be about the same. Although the performance of the extension contributes only a fraction of the total run time of a PHP web request. Often, the impact is as low as 0.1%.
The page also has a feature matrix comparing the extension APIs. The main differences between mysqli and mysql API are as follows:
```
mysqli mysql
Development Status Active Maintenance only
Lifecycle Active Long Term Deprecation Announced*
Recommended Yes No
OOP API Yes No
Asynchronous Queries Yes No
Server-Side Prep. Statements Yes No
Stored Procedures Yes No
Multiple Statements Yes No
Transactions Yes No
MySQL 5.1+ functionality Yes No
```
\* <http://news.php.net/php.internals/53799>
There is an additional feature matrix comparing the libraries (new mysqlnd versus libmysql) at
* <http://www.php.net/manual/en/mysqlinfo.library.choosing.php>
and a very thorough blog article at
* <http://blog.ulf-wendel.de/2012/php-mysql-why-to-upgrade-extmysql/> | MySQL vs MySQLi when using PHP | [
"",
"php",
"mysql",
"mysqli",
""
] |
I have an annoying problem in one of my projects where the production environment uses Microsoft Office 2000 and we only have Microsoft Office 2003 in the developement environment.
I use automation to do some manipulation of Word documents so to make this work in both the production and the developement environments i have to put a conditional compiler statement into the using-section of my code in all the files that uses automation.
```
#if DEVELOPEMENT
using Word = Microsoft.Office.Interop.Word;
#else
using Office;
#endif
```
Edit: I know the obvious solution is to get Microsoft Office 2000 onto the developement environment, but that is not easy if you want to do it the legal way.
I use Visual Studio 2005, so is there a more elegant way to avoid this conditional compiler statement?
Edit: The solution with using the TlbImp.exe tool from the SDK works beautifully, you just have to remember to give the generated file a strong name by generating a keyfile using the sn.exe tool else the Visual Studio wont compile the solution:
```
"c:\...\SDK\v2.0\Bin\TlbImp.exe" "c:\...\Microsoft Office\Office10\MSWORD9.OLB" /keyfile:Office.snk /out:Office.dll
``` | Locate a machine that has Office 2000 and .NET installed. Run this command on it:
Tlbimp "c:...\msword.olb" /out:Word.dll
where ... is the Office installation directory. Copy Word.dll to your dev machines. Add a reference to it in your project, make sure Copy Local is set to Yes (it is by default). You can now use "using Word" for any version of Office. The Word.dll file must be deployed to the target machine in the same directory as your .exe | Have someone find the OFfice 2000 installer and put Office 2000 in development. If you don't have like environments you can't be sure that your code will work in production. | Different using-statements on production and developement environments | [
"",
"c#",
"deployment",
"automation",
""
] |
given this html code:
```
<td><img class='del' id='4' src='images/delete.gif'></td>
```
I am in trouble understanding how to complete the following code:
```
$(document).ready(
function(){
setup();
}
);
function setup(){
$("#deleteForm").hide();
$("img.del").bind('click', formDisplay);
}
function formDisplay(){
$("#deleteForm").show();
}
```
Here I need to pass to the callback the value of the `id` attribute of the image element but I have some problem to understand how `this` or `$('this')` work in jQuery
Still better, I would like to have html code this way:
```
<tr id='4'>
<td>...</td><td>...</td><td><img class='del' src='images/delete.gif'></td>
</tr>
```
being able to get the value of each of the child of the `<tr>` element identified by its id from *within* the callback.
Has someone some advices?
Many thanks | Just re-formatting bendewey's answer:
```
jQuery(function($) {
$("#deleteForm").hide();
$("img.del").click(function() {
$("#deleteForm").show();
$(this).attr('id'); // this is the image Id
})
});
``` | ```
$(document).ready( function(){
setup();
});
function setup() {
$("#deleteForm").hide();
$("img.del").bind('click', formDisplay);
}
function formDisplay() {
$("#deleteForm").show();
$(this).attr('id'); // this is the image Id
$(this).closest('tr').attr('id'); // this is the tr Id
}
``` | jQuery: selecting a parent attribute from a callback | [
"",
"javascript",
"jquery",
"dom",
""
] |
A client of mine wants a news website designed in Java, and I told him that Java is overkill for that kind of website. I suggested to him that there are dozens of CMS that we can customize for him, as well as other programming languages that are better suited for websites but he insisted.
Is Java overkill for news websites? | I think the real issue here is that whoever your client is has this notion that problems can be solved by name-dropping programming languages. I understand that you recognize this problem too, but in any business "the customer is always right" and you'll have to give in.
So is Java overkill for news websites? That depends. If what he's asking for is available in Drupal or even Wordpress out of the box, then the answer is yes. The real questions further on will be:
* How much expertise does his organization have on Java (you have to consider the possibility that he wants to maintain the system by himself -- if his employees know Java, you now know why he insists on it)
* What are the features that he actually wants? How will the site evolve in the future? (There will be features that will be more difficult to implement in PHP than in Java)
* What are the cost implications? (If he wants it cheaper, you can offer to simply customize Drupal or Wordpress, but if budget is not a major consideration, going with Java would be fine). | I think the language argument is a little irrelevant, you can realistically code anything in anything given enough time and skill. Java is no better/worse than many other tools. However the real answer is already here - using a CMS must make sense. Why write from scratch, sure sounds like a wheel being re-invented.
Why not do a basic list of requirements, cross-match to CMS (Java, Python, Ruby et al), and then price up the same features if you had to code from scratch. That's a pretty good argument. | Is Java overkill for news websites? | [
"",
"java",
"web",
""
] |
I'm working on a .net 3.5 site, standard website project.
I've written a custom page class in the sites App\_Code folder (MyPage).
I also have a master page with a property.
```
public partial class MyMaster : System.Web.UI.MasterPage
{
...
private string pageID = "";
public string PageID
{
get { return pageID; }
set { pageID = value; }
}
}
```
I'm trying to reference this property from a property in MyPage.
```
public class MyPage : System.Web.UI.Page
{
...
public string PageID
{
set
{
((MyMaster)Master).PageID = value;
}
get
{
return ((MyMaster)Master).PageID;
}
}
}
```
I end up with "The type or namespace name 'MyMaster' could not be found. I've got it working by using FindControl() instead of a property on the MyMaster page, but IDs in the master page could change. | I've tended to do the following with Web Site projects:
In App\_Code create the the following:
**BaseMaster.cs**
```
using System.Web.UI;
public class BaseMaster : MasterPage
{
public string MyString { get; set; }
}
```
**BasePage.cs:**
```
using System;
using System.Web.UI;
public class BasePage : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (null != Master && Master is BaseMaster)
{
((BaseMaster)Master).MyString = "Some value";
}
}
}
```
My Master pages then inherit from BaseMaster:
```
using System;
public partial class Masters_MyMasterPage : BaseMaster
{
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(MyString))
{
// Do something.
}
}
}
```
And my pages inherit from BasePage:
```
public partial class _Default : BasePage
``` | I found some background to this, it happens because of the way things are built and referenced.
Everything in App\_Code compiles into an assembly.
The rest, aspx files, code behind, masterpages etc, compile into another assemlby that references the App\_Code one.
Hence the one way street.
And also why Ben's solution works. Thanks Ben.
Tis all clear to me now. | How do I reference an ASP.net MasterPage from App_Code | [
"",
"c#",
"asp.net",
"master-pages",
""
] |
Java Newbie question :
I need to capture the text being written to a printStream by a 3rd party component.
The PrintStream is defaulted to System.err, but can be changed to another PrintStream.
Looking through the docs, I couldn't find an easy way to direct the contents of a PrintStream to a string writer / buffer.
Can someone please assist? | ```
PipedOutputStream pipeOut = new PipedOutputStream();
PipedInputStream pipeIn = new PipedInputStream(pipeOut);
System.setOut(new PrintStream(pipeOut));
// now read from pipeIn
``` | ```
import java.io.*;
public class Test {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("errors.txt");
} catch(IOException ioe) {
System.err.println("redirection not possible: "+ioe);
System.exit(-1);
}
PrintStream ps = new PrintStream(fos);
System.setErr(ps);
System.err.println("goes into file");
}
}
``` | Java - Capturing System.err.println or Capturing a PrintStream | [
"",
"java",
"io",
"stream",
""
] |
I am currently developing a sports website where one of the pages with be forthcoming fixtures in which the user will be able to what team and where the team are playing their next match.
I have a database with the following fields...
* ID
* TEAM NUMBER
* OPPOSITION
* VENUE
* DATE
* MEET TIME
* MATCH TYPE
So a row of data pulled from the DB and print\_r'd may look like this
ID=>[1] TEAM NUMBER=>[1] OPPOSITION=>[YORKSHIRE] VENUE=>[HOME] DATE=>[2009/4/25] MEET TIME=>[13.00] MATCH TYPE=>[CUP]
My problem is i cannot work out how to show the next match dependent on what the current date is, so for example for now I want the site to show all the games that will happen over the weeken of the 25th April 2009 and then once that has gone the fixtures for the next weekend.
Hope this makes sense and some one give me an idea of how to tackle this. | Instead of relying entirely on MySQL, you can also use PHP's strtotime() function:
```
$query = "select * from my_events where date between now() and ".
date("Y-m-d", strtotime("+1 week"));
``` | ```
select * from my_events where date between now() and date_add(now(), interval 7 day);
```
Should do it I think. | Getting an event from a database a week in advancee | [
"",
"php",
"mysql",
"database",
"datetime",
""
] |
I have a webpage that has a comment box that can be toggled by clicking a link (the opening and closing of the box is controlled using JavaScript, specifically JQuery). This box is hidden by default, so naturally, it's impossible to display without the use of JavaScript. I'm not concerned by this fact: the comment box is not a "necessary" feature and this is a small personal site, so I don't mind that a tiny percentage of visitors may not experience full functionality. However, I would like to display a warning if the user does not have JavaScript enabled.
I've considered the idea of doing this by presenting a small message (with the use of a simple HTML `<p>` tag) near the link that toggles the comment box, using the following bit of code:
```
<p class="alert" id="nojs-warning">You must have JavaScript enabled to leave a comment.</p>
```
Of course, I don't want to display this if JavaScript *is* enabled, so I have the following JQuery trigger set up to immediately hide the box when the page is loaded:
```
$(function() {
$('#nojs-warning').hide();
});
```
Thus, if the user has JavaScript enabled, the event will fire and the warning will be hidden; if the user doesn't have JavaScript enabled, the event *won't* fire, and thus the warning will still be displayed.
For such a small, personal site, this seems like an elegant solution. Are there any pitfalls to this approach? | Why not use the [`<noscript>`](http://www.w3schools.com/TAGS/tag_noscript.asp) tag? That's what it's intended for. | The only obvious concern is that the function doesn't run even if javascript is enabled. Is there a particular reason you aren't using the tag built into HTML. It's likely doing the same thing but without the need for javascript.
[link text](http://www.w3schools.com/TAGS/tag_noscript.asp) | Are there any pitfalls in displaying a "No JavaScript" warning in the following fashion? | [
"",
"javascript",
""
] |
Why are my Swing applications not closing when using Netbeans 6.5 on Ubuntu 8.10 with Sun JDK 6. Even the Netbeans tutorials downloaded from the Netbeans website do the same. When I close the application I'm left with a dead window. I then have to manually kill the process. It comes and goes, but I can't figure out what triggers this behavior.
I have also run my applications from the command line terminal using openjdk (6b12-0ubuntu6.1) and sun-java (6-10-0ubuntu2), still no luck. I have noticed when running it through netbeans after trying to close it netbeans still shows the app as running and after manually killing the process my netbeans log prints "Java Result: 137"
Update - 4Mar: I have also tried upgrading to Sun JDK 6u12 and Netbeans 6.7m2. But still no luck.
Update - 4Mar: Ok, after further testing I found that this behavior starts as soon as I add JPA to my application. That makes explains why the JPA tutorial examples on the netbeans website also do the same. I have tried writing an ExitListener to first close the EntityManager but no luck yet. If I delete the EntityManager, Query and List from my Form Panel the applications closes properly again. | This is caused by using the "System Default" or "GTKLookAndFeel" look and feel. I switched over to "NimbusLookAndFeel" and the issue disappeared.
I have tried all suggestions including Netbeans 6.7 and Java 6.12.
Still unclear as to why this is happening on Ubuntu 8.10. | make sure you call setDefaultCLoseOperation(JFrame.EXIT\_ON\_CLOSE); | Why do my Swing application windows intermittently not close when the application exits? | [
"",
"java",
"swing",
"netbeans",
"ubuntu-8.10",
""
] |
I'm porting an application written in C++ from Windows to Linux. I have a problem with the header files path. Windows uses `\` and Linux uses `/`. I am finding it cumbersome to change this in each and every source and header file. Is there some work around? | Always use forward slashes in #include paths. It is the compiler's job to map the path to whatever slash/directory scheme the underlying OS supports. | You people! *Yes*, you can, and should, always use forward slashes. I think the issue is how to get *there* from *here*!
If you have Perl installed, the following one liner will convert a C++ source file to use forward slashes, saving the original version in a file with extension `.bak`:
```
perl -i.bak -pe "tr!\\!/! if /^\s*#\s*include\b/" myfile.cpp
```
(The above command line is for Windows; if you're using Linux or other Unix-like shell, use single quotes around the 3rd parameter instead of double quotes.)
If you have a bunch of files you need to convert, say all files ending in `.cpp`:
```
for %f in (*.cpp) do perl -i.bak -pe "tr!\\!/! if /^\s*#\s*include\b/" %f
```
The corresponding command for a Bourne shell environment (typical Linux shell):
```
for f in *.cpp; do perl -i.bak -pe 'tr!\\!/! if /^\s*#\s*include\b/' $f; done
```
If you don't have Perl installed, you should be able to find a text editor that allows search and replace across files. | Include header path change from Windows to Linux | [
"",
"c++",
"header",
"include",
"backslash",
""
] |
Warning: Here be beginner SQL! Be gentle...
I have two queries that independently give me what I want from the relevant tables in a reasonably timely fashion, but when I try to combine the two in a (fugly) union, things quickly fall to bits and the query either gives me duplicate records, takes an inordinately long time to run, or refuses to run at all quoting various syntax errors at me.
Note: I had to create a 'dummy' table (tblAllDates) with a single field containing dates from 1 Jan 2008 as I need the query to return a single record from each day, and there are days in both tables that have no data. This is the only way I could figure to do this, no doubt there is a smarter way...
Here are the queries:
```
SELECT tblAllDates.date, SUM(tblvolumedata.STT)
FROM tblvolumedata RIGHT JOIN tblAllDates ON tblvolumedata.date=tblAllDates.date
GROUP BY tblAllDates.date;
SELECT tblAllDates.date, SUM(NZ(tblTimesheetData.batching)+NZ(tblTimesheetData.categorisation)+NZ(tblTimesheetData.CDT)+NZ(tblTimesheetData.CSI)+NZ(tblTimesheetData.destruction)+NZ(tblTimesheetData.extraction)+NZ(tblTimesheetData.indexing)+NZ(tblTimesheetData.mail)+NZ(tblTimesheetData.newlodgement)+NZ(tblTimesheetData.recordedDeliveries)+NZ(tblTimesheetData.retrieval)+NZ(tblTimesheetData.scanning)) AS VA
FROM tblTimesheetData RIGHT JOIN tblAllDates ON tblTimesheetData.date=tblAllDates.date
GROUP BY tblAllDates.date;
```
The best result I have managed is the following:
```
SELECT tblAllDates.date, 0 AS STT, SUM(NZ(tblTimesheetData.batching)+NZ(tblTimesheetData.categorisation)+NZ(tblTimesheetData.CDT)+NZ(tblTimesheetData.CSI)+NZ(tblTimesheetData.destruction)+NZ(tblTimesheetData.extraction)+NZ(tblTimesheetData.indexing)+NZ(tblTimesheetData.mail)+NZ(tblTimesheetData.newlodgement)+NZ(tblTimesheetData.recordedDeliveries)+NZ(tblTimesheetData.retrieval)+NZ(tblTimesheetData.scanning)) AS VA
FROM tblTimesheetData RIGHT JOIN tblAllDates ON tblTimesheetData.date=tblAllDates.date
GROUP BY tblAllDates.date
UNION SELECT tblAllDates.date, SUM(tblvolumedata.STT) AS STT, 0 AS VA
FROM tblvolumedata RIGHT JOIN tblAllDates ON tblvolumedata.date=tblAllDates.date
GROUP BY tblAllDates.date;
```
This gives me the VA and STT data I want, but in two records where I have data from both in a single day, like this:
```
date STT VA
28/07/2008 0 54020
28/07/2008 33812 0
29/07/2008 0 53890
29/07/2008 33289 0
30/07/2008 0 51780
30/07/2008 30456 0
31/07/2008 0 52790
31/07/2008 31305 0
```
What I'm after is the STT and VA data in single row per day. How might this be achieved, and how far am I away from a query that could be considered optimal? (don't laugh, I only seek to learn!) | You could put all of that into one query like so
```
SELECT
dates.date,
SUM(volume.STT) AS STT,
SUM(NZ(timesheet.batching)+NZ(timesheet.categorisation)+NZ(timesheet.CDT)+NZ(timesheet.CSI)+NZ(timesheet.destruction)+NZ(timesheet.extraction)+NZ(timesheet.indexing)+NZ(timesheet.mail)+NZ(timesheet.newlodgement)+NZ(timesheet.recordedDeliveries)+NZ(timesheet.retrieval)+NZ(timesheet.scanning)) AS VA
FROM
tblAllDates dates
LEFT JOIN tblvolumedata volume
ON dates.date = volume.date
LEFT JOIN tblTimesheetData timesheet
ON
dates.date timesheet.date
GROUP BY dates.date;
```
I've put the dates table first in the `FROM` clause and then `LEFT JOIN`ed the two other tables.
The jet database can be funny with more than one join in a query, so you may need to wrap one of the joins in parentheses (I believe this is referred to as Bill's SQL!) - I would recommend `LEFT JOIN`ing the tables in the query builder and then taking the SQL code view and modifying that to add in the `SUM`s, `GROUP BY`, etc.
**EDIT:**
Ensure that the date field in each table is indexed as you're joining each table on this field.
**EDIT 2:**
How about this -
```
SELECT date,
Sum(STT),
Sum(VA)
FROM
(SELECT dates.date, 0 AS STT, SUM(NZ(tblTimesheetData.batching)+NZ(tblTimesheetData.categorisation)+NZ(tblTimesheetData.CDT)+NZ(tblTimesheetData.CSI)+NZ(tblTimesheetData.destruction)+NZ(tblTimesheetData.extraction)+NZ(tblTimesheetData.indexing)+NZ(tblTimesheetData.mail)+NZ(tblTimesheetData.newlodgement)+NZ(tblTimesheetData.recordedDeliveries)+NZ(tblTimesheetData.retrieval)+NZ(tblTimesheetData.scanning)) AS VA
FROM tblTimesheetData RIGHT JOIN dates ON tblTimesheetData.date=dates.date
GROUP BY dates.date
UNION SELECT dates.date, SUM(tblvolumedata.STT) AS STT, 0 AS VA
FROM tblvolumedata RIGHT JOIN dates ON tblvolumedata.date=dates.date
GROUP BY dates.date
)
GROUP BY date;
```
Interestingly, When I ran my first statement against some test data, the figures for STT and VA had all been multiplied by 4, compared to the second statement. Very strange behaviour and certainly not what I expected. | The table of dates is the best way.
Combine the joins in there FROM clause. Something like this....
```
SELECT d.date,
a.value,
b.value
FROM tableOfDates d
RIGHT JOIN firstTable a
ON d.date = a.date
RIGHT JOIN secondTable b
ON d.date = b.date
``` | Having difficulty combining JET SQL queries | [
"",
"sql",
"ms-access",
"jet",
""
] |
I am starting a project with asp.net visual studio 2008 / SQL 2000 (2005 in future) using c#.
The tricky part for me is that the existing DB schema changes often and the import files columns will all have to be matched up with the existing db schema since they may not be one to one match on column names. (There is a lookup table that provides the tables schema with column names I will use)
I am exploring different ways to approach this, and need some expert advice. Is there any existing controls or frameworks that I can leverage to do any of this?
So far I explored FileUpload .NET control, as well as some 3rd party upload controls to accomplish the upload such as [SlickUpload](http://krystalware.com/Products/SlickUpload/) but the files uploaded should be < 500mb
Next part is reading of my csv /excel and parsing it for display to the user so they can match it with our db schema. I saw [CSVReader](http://www.codeproject.com/KB/database/CsvReader.aspx) and others but for excel its more difficult since I will need to support different versions.
Essentially The user performing this import will insert and/or update several tables from this import file. There are other more advance requirements like record matching but and preview of the import records, but I wish to get through understanding how to do this first.
Update: I ended up using csvReader with LumenWorks.Framework for uploading the csv files. | I am using csvReader from LumenWorks.Framework for uploading and importing the csv files into a sql table and a DataTable in memory which I create based on the columns imported.
I also have the user map the fields in the ui and proceed to validate and prepare the data for import by labeling each record as insert/update/error. I then create/populate strongly typed DataSet for each table that will be affected and build the insert/update queries for Enterprise Library UpdateDataset() method.
Then I submit the transaction to insert/update the database. –
The mapping is a grid with 4 columns. ( import field name, destination table, destination field name, ignore, match status), with destination table and field names being selects which refresh based on table selected. I dynamically populate the selects. Initially select combo is populated with 1 value if the match is found, or please select if it isn't. ignore allows user to ignore the field. match status is if a field was auto-mapped | Check out the excellent FileHelpers library - there an [article on CodeProject](http://www.codeproject.com/KB/database/filehelpers.aspx) about it, and it's hosted [here](http://www.filehelpers.com/).
It's pure C#, and it can import just about any flat-file, CSV, and it deals with Excel, too. The import is totally configurable - you can define things like delimiters, rows and/or columns to skip, and so on - lots of options.
I've successfully used it in various projects and it just works flawlessly - highly recommended. | import csv file/excel into sql database asp.net | [
"",
"c#",
"asp.net",
"architecture",
".net-3.5",
"import",
""
] |
Has anyone not noticed that JQuery uses ActiveX controls?
When a user has limited their activex security they will get script prompt popups and a yellow bar accross the top of their browser window.
-This setting is by default on Windows Servers.
-Internet Cafe's dont support Active X.
-Company internal workstations dont support this.
Considering this I don't see how people can use JQuery in a commercial application.
Do you use JQuery in a commercial application? Does this concern you?
Do you think I should be concerned with this? | Only spot where `ActiveX` is mentioned in the jQuery code is for the `ActiveXObject` which is used for XMLHttpRequests:
```
// Create the request object; Microsoft failed to properly
// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
```
There's an open [issue here](http://dev.jquery.com/ticket/3623) ... seems like jQuery doesn't fallback to use the native XMLHttpRequest on IE7 (this is probably what you're experiencing).
Also this might help: [link](http://www.mail-archive.com/discuss@jquery.com/msg06791.html) | jQuery, like most libraries that provide support for AJAX, will use ActiveX to create the XMLHttpRequest object when running in IE. Because that's how you get an `XMLHttpRequest` object in IE. If you disable it, then you don't get AJAX.
So no, don't worry about it. If you don't use AJAX, then you won't have problems on systems where ActiveX is disabled; if you do, then you will have issues *regardless* of library, unless you use a work-around such as using iframes to submit background requests. | A serious issue with jQuery and ActiveX security? | [
"",
"javascript",
"jquery",
"internet-explorer",
"activex",
""
] |
I have a batch file that starts a Java process in a Windows 2003 server. As per the security policy, the users of that machine are logged off forcefully, if the user is inactive for a certain period of time. The problem is that when the user is logged out, the process also dies.
I scheduled a new task (Control Panel -> Scheduled Tasks) and selected the option of 'When my computer starts' and gave the user account details there. But it doesn't seem to have any effect, the user is still logged out and the process dies. Is a reboot necessary to make this change effective? And after the reboot, will I achieve what I'm expecting (keeping the process alive)?
Alternatively, will running this process as a Windows Service solve the problem? If so, can you please let me know how I can make a Java program or a batch file to run as a Windows Service? I would prefer not to use any other third party tools or libraries.
Thanks | Wrapping the process with srvany.exe and launching as a service would work as well.
<http://support.microsoft.com/kb/137890> | If you want it to run under Scheduled tasks you have to make sure you don't have "only run when user logged in" checked, which usually means you need to supply a password.
A windows service would be the normal way to do this: the [Java service wrapper](http://wrapper.tanukisoftware.org/doc/english/introduction.html) is 3rd party but loads of people use it.
If you really wanted to not use a 3rd party method you could use [svrany.exe (http://support.microsoft.com/kb/137890)](http://support.microsoft.com/kb/137890) on WIndows NT or later, but it is not designed specifically for Java. | Running a Java process in Windows even after the user is logged out | [
"",
"java",
"windows",
"windows-services",
""
] |
In Java I have a SortedSet that may have 100,000 elements. I would like to efficiently and elegantly get the last 25 elements. I'm a bit puzzled.
To get the *first* 25 I'd iterate and stop after 25 elements. But I don't know how to iterate in reverse order. Any ideas?
```
SortedSet<Integer> summaries = getSortedSet();
// what goes here :-(
``` | You need a `NavigableSet`. Else you’ll have to do it inefficiently, iterating through the whole `SortedSet` and collecting elements into a `Queue` that you keep trimmed at 25 elements. | SortedSet`<T>` was designed assuming a very simple iteration model, forward only, thus finding the top n entries is easy but finding the last would require an expensive read through the iterator maintaining a window of the last n entries.
[NavigableSet`<T>`](http://java.sun.com/javase/6/docs/api/java/util/NavigableSet.html) adding in 1.6 solves this (and the only SortedSet implementation from 1.4 TreeSet implements it so it is likely to be a drop in replacement for you).
```
NavigableSet<T> set = new TreeSet<T>();
// add elements
set.descendingIterator() // iterate over the last n entires as needed
``` | How to get the last 25 elements of a SortedSet? | [
"",
"java",
"sortedset",
""
] |
In Javascript we don't have to declare a variable with `var` keyword before using it. We can straight away do things like `myCount = 12;` or `myStr = "Hello";` (where myCount, myStr are not declared before). Any such usage, declares and initializes the variables in the 'global' scope.
What could be the reasons for providing this feature? And is it a good standard at all?
**UPDATE:** My question is not what the differences are between 'using a variable without declaring' and 'declaring and then using' and how it affects scope.
My question is 'why it is allowed in javascript to use a variable directly without declaring it' as most of the programming languages have a strict check on this.
**UPDATE** : I see the following quoted text as a bad effect of this feature. So, why have this feature at all?
"Suppose there is a globally declared variable `x` (`var x="comparison string"`) already which i am unaware of and i with intention of creating my own global 'x' inside one of my functions initialize one(`x=-1`) and there i end up breaking other functionality.
So, is there any good reason at all? for having this feature? | Javascript was intended for very simple scripts in the browser. Requiring variable declarations seemed unnecessary.
Of course, it's an error in the language. And the makers of javascript know that. They wanted to change it. But they couldn't. Why?
Because Microsoft had already reverse engineered JavaScript and created their duplicate JScript, with bugs and all. Microsoft vetoed any changes, even bugfixes, since they were adamant about not breaking anyones scripts. So even if they changed JavaScript, JScript in IE would stay the same.
It's not a good reason. But it's the one we have.
Source: I got my javascript history class from Douglas Crockford: "The JavaScript Programming Language", <http://video.yahoo.com/watch/111593/1710507> This part of the story is between 9 and 11 minutes into the video. | Good reasons? Honestly can't think of one, it's one of the few things I really dislike about JS.
It's possible because everything happens within the global scope if not otherwise controlled and JS allows implicit variable creation like this. The cost of this is enormous potential for scoping bugs and pollution, and only benefit given that "this" exists to explicitly define self scope and "window" and "document" exist for global referencing, is saving a few characters - which is no reason at all. | Why isn't it a must to declare a variable in Javascript before using it? | [
"",
"javascript",
"variables",
""
] |
Could someone take the time to explain me the language underpinnings here :
```
int foo = myObject.SomeList.Count;
for (int i = 0 ; i < foo ; i++)
{
myObject.SomeList.Add(bar);
}
```
goes into an infinite loop because `foo` references a value that keeps being incremented. Modifying the first line to:
```
int foo = (int)myObject.SomeList.Count;
```
makes it go away, somehow changing `foo` from reference to value once and for all. This is probably textbook but, why is this happening ?
Many thanks
**EDIT :** Ok, as Patrick mentions, the infinite loop only happens when there is no prior storage to foo, the cast being pointless, which makes sense. That's indeed what I thought initially while debugging this. Hence my surprise when the cast fixed it. What actually happened is that I was misled by Visual Studio into thinking I had fixed it when there was actually a problem of synchronization between edited code and executed code, which led to wrong conclusions. | I tried this on my system and can't replicate your problem. I could however replicate it with the following code, maybe this is what you meant:
```
// SomeList is not empty before the loop
for (int i = 0; i < myObject.SomeList.Count; i++)
{
myObject.SomeList.Add(bar);
}
```
In this case we are not storing the Count in an int, so every time we add to the list, we are comparing i+1 with Count+1, hence the endless loop. | Are you sure?!!
`int` is a value type. This is not supposed to happen.
Jon Skeet, come and help! | Effect of casting to int in C# | [
"",
"c#",
"reference",
"casting",
""
] |
If you have an object like this:
```
public class Foo
{
private int _id;
public int id
{
get { return _id; }
set { _id = value; }
}
private string _name;
public string name
{
get { return _name; }
set { _name = value; }
}
}
```
And you want to initialize id to -1 and name to String.Empty what is the best practice? (and why)
Doing:
```
private int _id = -1
```
Or
Setting \_id = -1 and name = String.Empty in the constructor? | This is more of a style question than anything else. There are only a few cases where it is a functional issue
1. When you have many constructors which all initialize the fields to the same value. At that point you have redundant code and should either refactor your constructors or use field initializers.
2. Don't use a field initializer if it depends on the value of another field in the same class hierarchy. In the abscence of partial classes the outcome is predictable but still can throw people for a loop.. | depends on when you want it to be set...
```
private int _id = -1
```
will initialize \_id before the constructor is called. | Default value of a property | [
"",
"c#",
"initialization",
""
] |
So, this is problem a stupid mistake, but I've been hacking away at it for about an hour and can't seem to solve it.
I have a class main.cpp which is full of random GUI crap (not really relevant to my problem I believe) but in one of my methods I make a reference to another one of my classes "TiffSpec"
TiffSpec is a class I wrote and so far have no compile errors in it. The compile error I get is:
"undefined reference to `TiffSpec::TiffSpec(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)`"
Note: I don't believe this is a problem with the string class as I tried to write a default constructor and reference it and still got the same error without the "std::basic\_..." stuff.
TiffSpec.h, TiffSpec.cpp and main.cpp are all in the same directory.
Here is the code in main.cpp up until the error:
```
#include <GL/glut.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <string.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <ctype.h>
#include <vector>
#include <list>
#include <typeinfo>
#include <math.h>
#include "TiffSpec.h"
/* Create checkerboard image */
#define checkImageWidth 1024
#define checkImageHeight 1024
GLubyte checkImage[checkImageHeight][checkImageWidth][3];
static GLint height;
//list of all non-main methods
void init(void);
void display(void);
void reshape(int w, int h);
void motion(int x, int y);
void read_next_command(unsigned char key, int x, int y);
void makeCheckImage(void);
void main_loop(char line[]);
void evaluateLine(char line[], std::vector<char> delimiters);
void evaluateCommand(std::list<std::string> command);
void read(std::list<std::string> command);
void draw(std::list<std::string> command);
void color(std::list<std::string> command);
void move(std::list<std::string> command);
void TiffStat(std::string fileName);
std::string convertInputToFloating(std::string input);
std::string trimExtraZeros(std::string input);
std::vector<char> getDelimiters();
//end of list
void
TiffStat(std::string fileName)
{
TiffSpec * testing = new TiffSpec(fileName);
}
```
Here is the beginning of the code in TiffSpec.h:
```
#include <GL/glut.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <string.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <ctype.h>
#include <vector>
#include <list>
#include <typeinfo>
#include <math.h>
#include <exception>
#ifndef TIFFSPEC_H_
#define TIFFSPEC_H_
using namespace std;
class TiffSpec {
public:
TiffSpec();
TiffSpec(std::string filename);
```
And for good measure, here is some code from TiffSpec.cpp
```
#include "TiffSpec.h"
#include <algorithm>
bool isLittleEndian();
void ByteSwap_(unsigned char * b, int n);
bool tagRecognized(unsigned short tag);
bool fieldTypeRecognized(unsigned short fieldType);
void gatherValues(IFDEntry & entry, ifstream &fileStream);
valueTypes retrieveCorrectType(unsigned short fieldType, unsigned long numberOfValues);
int getFieldByteSize(short fieldType);
TiffSpec::TiffSpec()
{}
TiffSpec::TiffSpec(std::string fileName)
{
std::ifstream fileStream;
```
Any idea what my problem might be? Also, is there any more effiecient way to signify a coding block rather than writing 4 spaces before every line? Looked in the reference guide and didn't see anything...
Okay I think I have an idea of what is going wrong. I'm using eclipse for the first time (in c++ at least) and have been pampered by MSVS in some ways. One of those ways being the make file. I think the problem is my makefile.
The makefile was supplied to me. I think I need to make a reference to these new classes, but where? And do I need to do it for both the .h and .cpp files?
makefile:
```
SHELL = /bin/sh
prefix = /usr
CC = gcc
C++ = g++
GLUT_LIBS = $(prefix)/lib/libglut.so.3
X_LIBADD = -lXmu -lXext -lXi -lX11
INCLUDES = -Iinclude -I$(prefix)/include
LDADD = $(GLUT_LIBS) $(prefix)/lib/libGLU.so.1 $(prefix)/lib/libGL.so.1 -lm
CFLAGS = -g -O2 -Wall -fomit-frame-pointer -ffast-math -fexpensive-optimizations-D_REENTRANT
COMPILE = $(CC) $(DEFS) $(INCLUDES) $(CPPFLAGS) $(CFLAGS)
LINK = $(CC) $(CFLAGS) $(LDFLAGS) -o $@
.SUFFIXES:
.SUFFIXES: .cpp .c .o
.c.o:
$(COMPILE) -c $<
.cpp.o:
$(C++) $(DEFS) $(INCLUDES) $(CPPFLAGS) $(CFLAGS) -c $<
all: main
CLI_OBJECTS=main.o
main: $(CLI_OBJECTS)
$(LINK) $(CLI_OBJECTS) $(LDADD) $(LIBS)
clean:
-rm -f *.o $(PROGRAMS)
```
I believe it has something to do with only main.o being there. But what I exactly need to write to correct it is unknown to me. | It's the `CLI_OBJECTS` line that seems to list the object files. Add TiffSpec.o:
```
CLI_OBJECTS=main.o TiffSpec.o
```
---
The linking command comes from this rule in the makefile:
```
main: $(CLI_OBJECTS)
$(LINK) $(CLI_OBJECTS) $(LDADD) $(LIBS)
```
This says that `main` should be built from the files listed in `CLI_OBJECTS` by running the command on the line below. | Make sure you are linking `TiffSpec.cpp` into your project. How to do this depends on your development environment.
For GCC, make sure you add `TiffSpec.o` to your linker (and compile `TiffSpec.cpp` into `TiffSpec.o`, of course).
For MSVC, make sure you add `TiffSpec.cpp` to be compiled and linked into your executable. (FIXME) | Frustrating C++ compiler error regarding undefined references | [
"",
"c++",
"linker",
""
] |
I'm building a site were users can upload images and then "use" them. What I would like is some thoughts and ideas about how to manage temporary uploads.
For example, a user uploads an image but decides not to do anything with it and just leaves the site. I have then either uploaded the file to the server, or loaded it to the server memory, but how do I know when the image can be removed? First, I thought of just having a temporary upload folder which is emptied periodically, but it feels like there must be something better?
BTW I'm using cakePHP and MySQL. Although images are stored on the server, only the location is stored in the dbb. | Save the information about file to MySQL, and save the last time the image was viewed - can be done via some script that would be altered everytime the image is being used.. and check the database for images not used for 30 days, delete them.. | You could try to define a "session" in some way and give the user some information about it. For example, in SO, there is a popup when you started an answer but try to leave the site (and your answer would be lost). You could do the same and delete the uploaded image if the user proceeds. Of course, you can still use a timeout or some other rules (maximum image folder size etc.). | How do I handle image management (upload, removal, etc.) in CakePHP? | [
"",
"php",
"mysql",
"cakephp",
"image",
"storage",
""
] |
Is there no way I could avoid name mangling of C++ classes and its member functions when exposed from a c++ dll.
Can't I use a def file mechanism in this regard ? | I think the best way to do this is to provide C wrappers around the C++ library. This was quite popular 10 or more years back when I was programming in C++ but I don't know if it is done any more.
Basically, for every `class C`, for every constructor `ctor` to be exposed to create an `extern "C" CPtr cCtor(....)` method that returns an opaque pointer `CPtr` and for every function `func` to be exposed you create `extern "C" cFunc(CPtr,....)`
Another approach is to create a `CStruct` that has member variables of function pointer types, implement them to call the class methods and let the client do all the hard work. | I don't believe so. Name mangling is used so that each overloaded function has a different name as viewed by the linker.
You could rewrite them in C and use the `extern "C" {}` construct but then you lose all your beautiful inheritance, polymorphism and so forth. You could also wrap the C++ inside C functions and expose only the C functions. | Name mangling of c++ classes and its member functions? | [
"",
"c++",
""
] |
So I have an application that I inherited and I want to build up an automated test suite around it. The application wasn't designed with testability in mind, and the code is a "big ball of mud". My plan was to use a UI Automation testing framework and create a suite of tests at the UI level until I had enough coverage to allow me to start refactoring with confidence and introducing some seams into the code to improve testability and design.
It's a .Net WinForms application, and the two frameworks I'm aware of are:
[NUnitForms](http://nunitforms.sourceforge.net/)
and
[Project White](http://www.codeplex.com/white)
From what I've read both frameworks pose issues when trying to run as part of an automated build (Continuous Integration) due to the fact that most CI products run as a Windows Service and if the UI uses modal dialogs the application will die a horrible death. I'm using CruiseControl.Net as my CI tool.
Does anybody have any suggestions to work around this issue? An alternative framework to use that may make the situation better?
Thanks,
Dylan | NUnitForms has a "hidden desktop" feature that will let you run unit tests from cc.net.
<http://automaticchainsaw.blogspot.com/2007/09/winforms-testing-using-nunitforms.html>
<http://automaticchainsaw.blogspot.com/2007/09/hidden-desktops-and-nunitforms.html> | You can actually run cruise control via the console app so it can have interactive desktop access. It won't recover automatically if the server is rebooted or it crashes, but at least you can do it.
That said, the approach most people take with automated UI testing (winforms, wpf or web) is to run all the non-interactive tests via the build server. Once those tests pass, then they deploy the application to a test environment and manually trigger a test run against the newly built version of the code.
This gives people the chance to reset the test environment (important for UI testing) as well as check that he new version of the application was built correctly and that all unit tests passed. After all, there's no point running the UI tests if you know the unit tests fell over. :-) | UI Testing Framework + Continuous Integration? | [
"",
"c#",
"winforms",
"unit-testing",
"continuous-integration",
"cruisecontrol.net",
""
] |
So, every time I have written a lambda expression or anonymous method inside a method that I did not get *quite* right, I am forced to recompile and restart the entire application or unit test framework in order to fix it. This is seriously annoying, and I end up wasting more time than I saved by using these constructs in the first place. It is so bad that I try to stay away from them if I can, even though Linq and lambdas are among my favourite C# features.
I suppose there is a good technical reason for why it is this way, and perhaps someone knows? Furthermore, does anyone know if it will be fixed in VS2010?
Thanks. | Yes there is a very good reason for why you cannot do this. The simple reason is cost. The cost of enabling this feature in C# (or VB) is **extremely** high.
Editing a lambda function is a specific case of a class of ENC issues that are very difficult to solve with the current ENC (Edit'n'Continue) architecture. Namely, it's very difficult to ENC any method which where the ENC does one of the following:-
1. Generates Metadata in the form of a class
2. Edits or generates a generic method
The first issue is more of a logic constraint but it also bumps into a couple of limitations in the ENC architecture. Namely the problem is generating the first class isn't terribly difficult. What's bothersome is generating the class after the second edit. The ENC engine must start tracking the symbol table for not only the live code, but the generated classes as well. Normally this is not so bad, but this becomes increasingly difficult when the shape of a generated class is based on the context in which it is used (as is the case with lambdas because of closures). More importantly, how do you resolve the differences against instances of the classes that are already alive in the process?
The second issue is a strict limitation in the CLR ENC architecture. There is nothing that C# (or VB) can do to work around this.
Lambdas unfortunately hit both of these issues dead on. The short version is that ENC'ing a lambda involves lots of mutations on existing classes (which may or may not have been generated from other ENC's). The big problem comes in resolving the differences between the new code and the existing closure instances alive in the current process space. Also, lambdas tend to use generics a lot more than other code and hit issue #2.
The details are pretty hairy and a bit too involved for a normal SO answer. I have considered writing a lengthy blog post on the subject. If I get around to it I'll link it back into this particular answer. | According to a list of [Supported Code Changes](http://msdn.microsoft.com/en-us/library/ms164927.aspx), you cannot add fields to existing types. Anonymous methods are compiled into oddly-named classes (kinda `<>_c__DisplayClass1`), which are precisely that: types. Even though your modifications to the anonymous method may not include changing the set of enclosed variables (adding those would alter fields of an existing class), I guess that's the reason it's impossible to modify anonymous methods. | Why can I not edit a method that contains an anonymous method in the debugger? | [
"",
"c#",
"debugging",
"visual-studio-2010",
"lambda",
"anonymous-methods",
""
] |
I need to transfer data from one table to another. The second table got a primary key constraint (and the first one have no constraint). They have the same structure. What I want is to select all rows from table A and insert it in table B without the duplicate row (if a row is0 duplicate, I only want to take the first one I found)
Example :
```
MyField1 (PK) | MyField2 (PK) | MyField3(PK) | MyField4 | MyField5
----------
1 | 'Test' | 'A1' | 'Data1' | 'Data1'
2 | 'Test1' | 'A2' | 'Data2' | 'Data2'
2 | 'Test1' | 'A2' | 'Data3' | 'Data3'
4 | 'Test2' | 'A3' | 'Data4' | 'Data4'
```
Like you can see, the second and third line got the same pk key, but different data in MyField4 and MyField5. So, in this example, I would like to have the first, second, and fourth row. Not the third one because it's a duplication of the second (even if MyField4 and MyField5 contain different data).
How can I do that with one single select ?
thx | First, you need to define what makes a row "first". I'll make up an arbitrary definition and you can change the SQL as you need to for what you want. For this example, I assume "first" to be the lowest value for MyField4 and if they are equal then the lowest value for MyField5. It also accounts for the possibility of all 5 columns being identical.
```
SELECT DISTINCT
T1.MyField1,
T1.MyField2,
T1.MyField3,
T1.MyField4,
T1.MyField5
FROM
MyTable T1
LEFT OUTER JOIN MyTable T2 ON
T2.MyField1 = T1.MyField1 AND
T2.MyField2 = T1.MyField2 AND
T2.MyField3 = T1.MyField3 AND
(
T2.MyField4 > T1.MyField4 OR
(
T2.MyField4 = T1.MyField4 AND
T2.MyField5 > T1.MyField5
)
)
WHERE
T2.MyField1 IS NULL
```
If you also want to account for PKs that are not duplicated in the source table, but already exist in your destination table then you'll need to account for that too. | Not sure how you know which of row 2 and row 3 you want in the new table, but in mysql you can simply:
```
insert ignore into new_table (select * from old_table);
```
And the PK won't allow duplicate entries to be inserted. | SQL - Only select row that is not duplicated | [
"",
"sql",
"duplicates",
""
] |
Whenever I click a JSlider it gets positioned one majorTick in the direction of the click instead of jumping to the spot I actually click. (If slider is at point 47 and I click 5 it'll jump to 37 instead of 5). Is there any way to change this while using JSliders, or do I have to use another datastructure? | As bizarre as this might seem, it's actually the Look and Feel which controls this behaviour. Take a look at `BasicSliderUI`, the method that you need to override is [`scrollDueToClickInTrack(int)`](http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/plaf/basic/BasicSliderUI.html#scrollDueToClickInTrack(int)).
In order to set the value of the `JSlider` to the nearest value to where the user clicked on the track, you'd need to do some fancy pants translation between the mouse coordinates from `getMousePosition()` to a valid track value, taking into account the position of the `Component`, it's orientation, size and distance between ticks *etc*. Luckily, `BasicSliderUI` gives us two handy functions to do this: [`valueForXPosition(int xPos)`](http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/plaf/basic/BasicSliderUI.html#valueForXPosition(int)) and [`valueForYPosition(int yPos)`](http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/plaf/basic/BasicSliderUI.html#valueForYPosition(int)):
```
JSlider slider = new JSlider(JSlider.HORIZONTAL);
slider.setUI(new MetalSliderUI() {
protected void scrollDueToClickInTrack(int direction) {
// this is the default behaviour, let's comment that out
//scrollByBlock(direction);
int value = slider.getValue();
if (slider.getOrientation() == JSlider.HORIZONTAL) {
value = this.valueForXPosition(slider.getMousePosition().x);
} else if (slider.getOrientation() == JSlider.VERTICAL) {
value = this.valueForYPosition(slider.getMousePosition().y);
}
slider.setValue(value);
}
});
``` | This question is kind of old, but I just ran across this problem myself. This is my solution:
```
JSlider slider = new JSlider(/* your options here if desired */) {
{
MouseListener[] listeners = getMouseListeners();
for (MouseListener l : listeners)
removeMouseListener(l); // remove UI-installed TrackListener
final BasicSliderUI ui = (BasicSliderUI) getUI();
BasicSliderUI.TrackListener tl = ui.new TrackListener() {
// this is where we jump to absolute value of click
@Override public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
int value = ui.valueForXPosition(p.x);
setValue(value);
}
// disable check that will invoke scrollDueToClickInTrack
@Override public boolean shouldScroll(int dir) {
return false;
}
};
addMouseListener(tl);
}
};
``` | JSlider question: Position after leftclick | [
"",
"java",
"swing",
"user-interface",
"jslider",
""
] |
Suppose I have a Java application that opens a database connection. Normally I would add a connection.close() in a finally block, but this block wouldn't be executed in the case of a kill operation, or any other abnormal termination, would it? Are there any other precautions that I, as a programmer, can make in order to close the connection properly before the application exits? | You should look at the Runtime.addShutdownHook() method for Java (<http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)>). It allows you to add a hook that will be called when the virtual machine terminates. You can use it to call a cleanup routine.
That would be for a TERM signal though. A KILL signal will kill the process and not allow it to do any cleanup (because the KILL signal cannot be caught or ignored by the receiving process). | If something external kills your program, there's nothing you can do about it. Obviously they wanted to stop it, so how can you prevent them?
I was going to suggest a [shutdown hook](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)), but the Javadocs state:
> In rare circumstances the virtual machine may *abort*, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the `SIGKILL` signal on Unix or the `TerminateProcess call` on Microsoft Windows. The virtual machine may also abort if a native method goes awry by, for example, corrupting internal data structures or attempting to access nonexistent memory. **If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run.**
(emphasis mine) | Handling abnormal Java program exits | [
"",
"java",
"database",
"termination",
""
] |
I have this very simple script that allows the user to specify the url of any site. The the script replaces the url of the "data" attribute on an object tag to display the site of the users choice inside the object on the HTML page.
How could I validate the input so the user can't load any page from my site inside the object because I have noticed that it will display my code.
The code:
```
<?php
$url = 'http://www.google.com';
if (array_key_exists('_check', $_POST)) {
$url = $_POST['url'];
}
//gets the title from the selected page
$file = @ fopen(($url),"r") or die ("Can't read input stream");
$text = fread($file,16384);
if (preg_match('/<title>(.*?)<\/title>/is',$text,$found)) {
$title = $found[1];
} else {
$title = "Untitled Document";
}
?>
```
Edit: (more details)
This is NOT meant to be a proxy. I am letting the users decide which website is loaded into an object tag (similar to iframe). The only thing php is going to read is the title tag from the input url so it can be loaded into the title of my site. (Don't worry its not to trick the user) Although it may display the title of any site, it will not bypass any filters in any other way.
I am also aware of vulnerabilities involved with what I am doing that's why im looking into validation. | As gahooa said, I think you need to be very careful with what you're doing here, because you're playing with fire. It's possible to do safely, but be very cautious with what you do with the data from the URL the user gives you.
For the specific problem you're having though, I assume it happens if you get an input of a filename, so for example if someone types "index.php" into the box. All you need to do is make sure that their URL starts with "http://" so that fopen uses the network method, instead of opening a local file. Something like this before the fopen line should do the trick:
```
if (!preg_match('/^http:\/\//', $url))
$url = 'http://'.$url;
``` | parse\_url: <https://www.php.net/parse_url>
You can check for scheme and host.
If scheme is http, then make sure host is not your website. I would suggest using preg\_match, to grab the part between dots. As in [www.google.com](http://www.google.com) or google.com, use preg\_match to get the word google.
If the host is an ip, I am not sure what you want to do in that situation. By default, the preg match would only get the middle 2 numbers and the dot(assuming u try to use preg\_match to get the sitename before the .com) | PHP Input validation for a single input for a url | [
"",
"php",
"html",
"validation",
"object-tag",
""
] |
What I don't understand about C/C++ is:
Yes, everyone uses it to get blazingly fast executables, so they compile with optimization turned on.
But for compilation with debug information turned on, we don't care about speed. So why not include more information in that compile mode, for example detect some segfaults before they happen? Effectively, insert an `assert(ptr != NULL)` before every access to a pointer `ptr`. Why can't the compiler do that? Again, that should be off by default, but there should be such a possibility, I think.
**EDIT:** Some people said that the detection I suggested doesn't make sense or doesn't do anything that the report of `segmentation fault` wouldn't already do. But what I have in mind is just a more graceful and informative abort, which prints the file name and line number of the offending code, just like an `assert()` would do. | There are a few major problems with your suggestion:
What conditions do you want the compiler to detect? On Linux/x86, unaligned access can cause `SIGBUS` and stack overflow can cause `SIGSEGV`, but in both cases it technically is possible to write the application to detect those conditions and fail "gracefully". `NULL` pointer checks can be detected, but the most insidious bugs are due to invalid pointer access, rather than `NULL` pointers.
The C and C++ programming languages provide enough flexibility so it is impossible for a runtime to determine with 100% success if a given random address is a valid pointer of an arbitrary type.
What would you like the runtime environment to do when it detects this situation? It can't correct the behavior (unless you believe in magic). It can only continue executing or exit. But wait a minute... that's what already happens when a signal is delivered! The program exits, a core dump is generated, and that core dump can be used by application developers to determine the state of the program when it crashed.
What you're advocating actually sounds like you want to run your application in a debugger (`gdb`) or through some form of virtualization (`valgrind`). This is already possible, but it makes no sense to do it by default, because it provides no benefit to non-developers.
Update to respond to comments:
There's no reason to modify the compilation process for debug versions. If you need a "gentle" debug version of the application, you should run it inside of a debugger. It's very easy to wrap your executable in a script that does this for you transparently. | What should the program do in that case? If it informs the user of a bug, then that's what the segfault does.
If it's supposed to keep going and avoid the bug, how does it know what to do?
Not to mention that if it did somehow magically know how to continue properly, then you have a bug in your release build (debug builds are intended to help you identify and fix bugs - not hide them).
---
In response to the additional information added to the question (I guess I misunderstood your intent):
> what I have in mind is just a more graceful and informative abort, which prints the file name and line number of the offending code, just like an assert() would do.
This is something the compiler could do - as you say, the compiler would essentially be automatically inserting an `assert()` anywhere a pointer was dereferenced. This might add pretty significantly to the size of a debug build, but it would probably still be acceptable for many (or most) purposes. I think this would be a reasonable option for a compiler to provide.
I'm not sure what compiler vendors would say... Maybe post a request on [Microsoft's Connect site for the VC++ product](http://connect.microsoft.com/VisualStudio) and see what they say. | Debug-compiled executable: Why not abort gracefully on invalid write to NULL? | [
"",
"c++",
"error-handling",
"debugging",
"segmentation-fault",
""
] |
I just inherited a C# project that runs way to slow and will have to start optimizing it. What I wanted to do first is learn a little more about profiling/optimizing since I didnt have to do it before. So the question is where do I start, what books/blogs/articels can I read?
I do know OF the .net profilers like ANTS profiler and so on, but I have no idea how to use them efficiently. I have not really used it, just let it run on a few sample apps to play around with the output. | There are two steps to optimizing code.
First, you need to find out what's slow. That's profiling, and, as you might guess, a profiler is commonly used for this. Most profilers are generally straightforward to use. You run your application through a profiler, and when it terminates, the profiler will show you how much time was spent in each function, exclusive (this function without counting time spent in function called from that) as well as inclusive (time spent in this function, including child function calls).
In other words, you get a big call tree, and you just have to hunt down the big numbers. Usually, you have very few functions consuming more than 10% of the execution time. So locate these and you know *what* to optimize.
Note that a profiler is neither necessary nor, necessarily, the *best* approach. A remarkably simple, but effective, approach is to just run the program in a debugger, and, at a few quasi-random times, pause execution and look at the call stack. Do this just a couple of times, and you have a very good idea of where your execution time is being spent. @Mike Dunlavey who commented under this answer has described this approach in depth elsewhere.
But now that you know where the execution time is being spent, then comes the tricky part, *how* to optimize the code.
Of course, the most effective approach is often the high-level one. Does the problem have to be solved in this way? Does it have to be solved at all? Could it have been solved in advance and the result cached so it could be delivered instantly when the rest of the app needed it?
Are there more efficient algorithms for solving the problem?
If you can apply such high-level optimizations, do that, see if that improved performance sufficiently, and if not, profile again.
Sooner or later, you may have to dive into more low-level optimizations. This is tricky territory though. Today's computers are pretty complex, and the performance you get from them is not straightforward. The cost of a branch or a function call can vary widely depending on the context. Adding two numbers together may take anywhere from 0 to 100 clock cycles depending on whether both values were already in the CPU's registers, what *else* is being executed at the time, and a number of other factors. So optimization at this level requires (1) a good understanding of how the CPU works, and (2) lots of experimentation and measurements. You can easily make a change that you *think* will be faster, but you need to be sure, so measure the performance before and after the change.
There are a few general rules of thumb that can often help guide optimizations:
I/O is expensive. CPU instructions are measured in fractions of a nanosecond. RAM access is in the order of tens to hundreds of nanoseconds. A harddrive access may take tens of *milli*seconds. So often, I/O will be what's slowing down your application.
Does your application perform few large I/O reads (read a 20MB file in one big chunk), or countless small ones (read bytes 2,052 to 2073 from one file, then read a couple of bytes from another file)? Fewer large reads can speed your I/O up by a factor of several thousand.
Pagefaults involve harddrive accesses too. In-memory pages have to be pushed to the pagefile, and paged-out ones have to be read back into memory. If this happens a lot, it's going to be slow. can you improve the locality of your data so fewer pages will be needed at the same time? Can you simply buy more RAM for the host computer to avoid having to page data out? (As a general rule, hardware is cheap. Upgrading the computer is a perfectly valid optimization - but make sure the upgrade will make a difference. Disk reads won't be a lot faster by buying a faster computer. And if everything fits into RAM on your old system, there's no point in buying one with 8 times as much RAM)
Your database relies on harddrive accesses too. So can you get away with caching more data in RAM, and only occasionally writing it out to the database? (Of course there's a risk there. What happens if the application crashes?
And then there's everyone favorite, threading. A modern CPU has anywhere from 2 to 16 CPU cores available. Are you using them all? Would you benefit from using them? Are there long-running operations that can be executed asynchronously? The application starts the operation in a separate thread, and is then able to resume normal operation instantly, rather than blocking until the operation is complete.
So basically, use the profiler to understand your application. How does it spend its execution time, where is it being spent? Is memory consumption a problem? What are the I/O patterns (both harddrive and network accesses, as well as any other kind of I/O)?
Is the CPU just churning away all the time, or is it idle waiting for some external events, such as I/O or timers?
And then understand as much as possible about the computer it's running on. Understand what resources it has available (CPU cache, multiple cores), and what each of them means for performance.
This is all pretty vague, because the tricks to optimizing a big database server are going to be *very* different from what you'd do to optimize some big number-crunching algorithm. | I'm taking an undergraduate course (one topic is Performance Analysis) and the recommended text is [The Art of Computer Systems Performance Analysis: Techniques for Experimental Design, Measurement, Simulation, and Modeling](https://rads.stackoverflow.com/amzn/click/com/0471503363). It's something of a bible on the subject and might be a bit overkill. | What are some resources I can use to learn profiling/optimizing? | [
"",
"c#",
".net",
"optimization",
"profiling",
""
] |
I'd like to find a replacement for provided System.Windows.Form.Treeview. I need the following improvements :
* Multiple selection of items
* Better performance (performance of standard widget is simply awful, in particular when adding a long list of items)
* Scrolling while drag and dropping an item inside the treeview widget
I may be forgetting some, but these are quite important. Since i already have a software that makes use of the standard Treeview, I will take in consideration API differences. | As an open source alternative, [TreeViewAdv](http://sourceforge.net/projects/treeviewadv/) is very good. | How about [this](http://www.codeproject.com/KB/tree/treeviewadv.aspx)? | C# replacement for standard Treeview? | [
"",
"c#",
"treeview",
""
] |
Is there any way to connect to an MS SQL Server database with python on linux using Windows Domain Credentials?
I can connect perfectly fine from my windows machine using Windows Credentials, but attempting to do the same from a linux python with pyodbs + freetds + unixodbc
```
>>import pyodbc
>>conn = pyodbc.connect("DRIVER={FreeTDS};SERVER=servername;UID=username;PWD=password;DATABASE=dbname")
```
results in this error:
```
class 'pyodbc.Error'>: ('28000', '[28000] [unixODBC][FreeTDS][SQL Server]Login incorrect. (20014) (SQLDriverConnectW)')
```
I'm sure the password is written correctly, but I've tried many different combinations of username:
```
DOMAIN\username
DOMAIN\\username
```
or even
```
UID=username;DOMAIN=domain
```
to no avail. Any ideas? | **As pointed out in one of the comments, this answer is quite stale by now. I regularly and routinely use GSSAPI to authenticate from Linux to SQL Server 2008 R2 but mostly with the EasySoft ODBC manager and the (commercial) EasySoft ODBC SQL Server driver.**
In early 2009, a colleague and I managed to connect to a SQL Server 2005 instance from Solaris 10 using GSSAPI (Kerberos credentials) using DBB::Perl over a FreeTDS build linked against a particular version of the MIT kerberos libraries. The trick was -- and this is a little bit difficult to believe but I have verified it by looking through the FreeTDS source code -- to specify a *zero-length* user\_name. If the length of the user\_name string is 0 then the FreeTDS code will attempt to use GSSAPI (if that support has been compiled in). I have not been able to do this via Python and pyodbc as I could not figure out a way of getting ODBC to pass down a zero-length user\_name.
Here in the perl code .. there are multiple opportunities for breakage wrt configuration files such as .freetds.conf etc. I seem to recall that the principal had to be in uppercase but my notes seem to be in disagreement with that.
```
$serverprincipal = 'MSSQLSvc/foo.bar.yourdomain.com:1433@YOURDOMAIN.COM';
$dbh = DBI->connect("dbi:Sybase:server=THESERVERNAME;kerberos=$serverprincipal", '', '');
```
You will have to know how to use the setspn utility in order to get the SQL Server server to use the appropriate security principal name.
I do not have any knowledge of the kerberos side of things because our environment was set up by an out and out Kerberos guru and has fancy stuff like mutual trust set up between the AD domain that the SQL Server is running in and the Kerberos domain that my client was running in.
There is some code <http://code.google.com/p/libsqljdbc-auth/> which does GSSAPI authentication from Linux to SQL Server but it is Java only. The author (who seems to know his stuff) also has contributed a similar patch to the jTDS project which works with more recent versions of Java that have GSSAPI built in.
So the pieces are all there, it is just a big tangled mess trying to get them all to work together. I found the pyodbc to unixODBC to FreeTDS odbc to TDS integration pretty hard to trace/debug. The perl stuff because it was a pretty thin wrapper on top to CT-Lib was much easier to get going. | As of at least March 2013, this seems to work out of the box with FreeTDS. I specified the [TDS protocol version](http://www.freetds.org/userguide/choosingtdsprotocol.htm) for good measure--not sure if that makes the difference:
```
connStr = "DRIVER={{FreeTDS}};SERVER={0};PORT=1433;TDS_Version=7.2;UID={1}\\{2};PWD={3}".format(hostname, active_directory_domain, username, password)
```
Integrated authentication also appears to be supported in Microsoft's official driver for linux: <http://msdn.microsoft.com/en-us/library/hh568450.aspx> . I'm not sure how many Linux distributions it actually works on or how much of the source is available. They explicitly mention RHEL 5 and 6 and some dependencies on the [download page](https://www.microsoft.com/en-us/download/details.aspx?id=28160). | Connecting to MS SQL Server using python on linux with 'Windows Credentials' | [
"",
"python",
"sql-server",
"pyodbc",
"freetds",
"unixodbc",
""
] |
I need to shut down my application and then delete the executable. I am doing it by kicking off a low priority batch job and then immediately shutting down the exe. Is there a better way? | As long as any code from an executable is in memory, it cannot be deleted, but there are some other things you can try:
* Telling [`MoveFileEx`](http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx) to defer the delete until next reboot is one approach typically used by install/uninstall code.
* Use the [Task Scheduler](http://msdn.microsoft.com/en-us/library/aa383614(VS.85).aspx) to schedule `cmd.exe /c del c:\path\myprog.exe` to run 60 seconds from now, then quit promptly so it has a chance of succeeding.
* A batch file works well and can actually delete itself because a batch file is closed between lines.
If you're using the batch file method, consider something like the following:
```
:loop
ping -n 6 127.0.0.1
del /y %1
if exist %1 goto :loop
del byebye.bat
```
The `ping` command here is being abused to insert a delay, since `sleep` is not a standard command on Windows. The loop enables the batch process to bide its time until it can actually remove the executable. | There are the PendMoves and [MoveFile](http://technet.microsoft.com/en-us/sysinternals/bb897556.aspx) utilities from [sysinternals](http://www.sysinternals.com/). According to the documentation, you can use the movefile to delete a file on the next bootup by specifying an empty destination:
```
movefile your.exe ""
```
This utility is commonly used to remove stubborn malware, but I'm not sure if it will immediately delete your application after it closes or only on the next reboot.
The utility uses the [MoveFileEx API](http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx), so if you want you can use that API to achieve the same effect. | What's the best way to shut down a .Net winforms application and delete the executable | [
"",
"c#",
".net",
"winforms",
"shutdown",
""
] |
Below is the code for my player which will automatically generate a `playlist.xml` file according to the songs selected by the user. I kept this file as `player.php` in my root folder, and in the form I give:
```
<form method="post" action="/player.php" target="_blank">
```
so this player is opening and playing songs according to what is selected.
But the problem is when the user again selects different songs while previously selected songs are playing in the player in new window, the new songs selected are opening in one more window, i.e. now two player windows are opened.
Actually, I want the second selected songs will play in the same window which is already opened. You can check what's happening in my site by playing songs: <http://www.musicking.in/hindi-songs/69.html>
```
<html>
<body>
<?php
if(isset($_POST["song"])&& $_POST['song'] != "") {
$song = $_POST["song"];
}
else { $song=array(); }
for ($i="0"; $i<count($song); $i++) {
//echo $song[$i];
}
//start of new php codep
// create doctype
//$array = array(
// 'song.mp3','song.mp3','song.mp3',
//);
$dom = new DOMDocument("1.0");
// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");
// create root element
$root = $dom->createElement("xml");
$dom->appendChild($root);
$i = "1";
foreach ($song as $counter) {
// create child element
$song = $dom->createElement("track");
$root->appendChild($song);
$song1 = $dom->createElement("path");
$song->appendChild($song1);
// create text node
$text = $dom->createTextNode($counter);
$song1->appendChild($text);
$song1 = $dom->createElement("title");
$song->appendChild($song1);
$text = $dom->createTextNode("song ".$i);
$song1->appendChild($text);
$i++;
}
// save and display tree
//echo $dom->saveXML();
$dom->save("playlist.xml");
?>
<script type="text/javascript" src="swfobject.js"></script>
<div id="flashPlayer">
This text will be replaced by the flash music player.
</div>
<script type="text/javascript">
var so = new SWFObject("playerMultipleList.swf", "mymovie", "295", "200", "7", "#FFFFFF");
so.addVariable("autoPlay","yes")
so.addVariable("playlistPath","playlist.xml")
so.write("flashPlayer");
</script>
</body>
</html>
``` | you can only do this with javascript as far as i know ... and theres a small hack to detect if a pop-up was opened and if it did to send javascript requests to it. | I know this probably isn't the "FIX" you are looking for, but try specifying the target in your flash vars.
I think it may help to specify \_self
just a thought | How do I get my PHP application to re-use the same window for playing music? | [
"",
"php",
"html",
"xml",
""
] |
I'm trying to create a class which I can serialize to produce the following XML:
```
<chart palette='1'>
<categories>
<category label='2001' />
<category label='2002' />
```
..etc
I have a class which look something like this:
```
[XmlRoot("chart")]
public class Chart
{
[XmlAttributeAttribute("palette")]
public string Palette;
[XmlElement("categories")]
public List<Category> Categories = new List<Category>();
}
[XmlRoot("category")]
public class Category
{
[XmlAttributeAttribute("label")]
public string Label;
}
```
However, this does not produce the desired chart->categories->category@label structure. The XmlRoot on the Category class doesn't seem to be used.
Here is the output I have from that code:
```
<chart palette="2">
<categories label="2002" />
</chart>
```
How can I get the XML structure I want? | Use [XmlArrayAttribute](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayattribute.aspx) and [XmlArrayItemAttribute](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayitemattribute.aspx)
```
[XmlRoot("chart")]
public class Chart
{
[XmlAttributeAttribute("palette")]
public string Palette;
[XmlArray("categories")]
[XmlArrayItem("category")]
public List<Category> Categories = new List<Category>();
}
public class Category
{
[XmlAttributeAttribute("label")]
public string Label;
}
```
Sometimes is can be useful to just create the xml structure you want, and then use xsd.exe to generate classes from it. This has to be done in a 2-step process, first generating an xsd file, and then classes from that.
```
xsd.exe something.xml
xsd.exe something.xsd /classes
```
This will probably not give the exact result you want (unless you have a really good xsd, and don't just generate it from the xml), but does give some ideas | Should be:
```
[XmlRoot("chart")]
public class Chart
{
[XmlAttributeAttribute("palette")]
public string Palette;
[XmlArray("categories")]
[XmlArrayItem("category")]
public List<Category> Categories = new List<Category>();
}
[XmlRoot("category")]
public class Category
{
[XmlAttribute("label")]
public string Label;
}
``` | Serialize custom object to XML | [
"",
"c#",
"xml",
"serialization",
""
] |
I'd like to ask about the most elegant approach when it comes to designing models with virtual fields such as below in Django...
Let's say we're building an online store and all the products in the system are defined by the model "*Product*".
```
class Product(models.Model):
# common fields that all products share
name = ...
brand = ...
price = ...
```
But the store will have lots of product types completely unrelated with eachother, so I need some way to store those virtual fields of different product types (ie. capacity of a MP3 player, pagecount of a book,..).
The solutions I could come up with my raw Django skills are far from perfect so far:
* Having a "custom\_fields" property
and intermediate tables that I
manage manually. (screaming ugly in
my face :))
* Or inheriting classes from
"*Product*" on the fly with Python's
dangerous exec-eval statements (that is too
much voodoo magic for maintenance
and also implementation would
require knowledge of Django internals).
What's your take on this?
TIA. | Products have Features.
```
class Feature( models.Model ):
feature_name = models.CharField( max_length=128 )
feature_value = models.TextField()
part_of = models.ForeignKey( Product )
```
Like that.
Just a list of features.
```
p= Product( "iPhone", "Apple", 350 )
p.save()
f= Feature( "mp3 capacity", "16Gb", p )
f.save()
```
If you want, you can have a master list of feature names in a separate table. Don't over-analyze features. You can't do any processing on them. All you do is present them. | Ruby on Rails has a "serialized" field which allows you to pack a dictionary into a text field. Perhaps DJango offers something similar?
[This article](http://www.davidcramer.net/code/181/custom-fields-in-django.html) has an implementation of a SerializedDataField. | Django - designing models with virtual fields? | [
"",
"python",
"django",
"django-models",
""
] |
How can I get back the autogenerated ID for a new record I just inserted?
(Using ASP classic and MSSQL 2005) | Thanks all who suggested SELECT SCOPE\_IDENTITY(). I was able to create a stored procedure:
```
USE [dbname]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spInsert]
(
@Nn varchar(30)
)
AS
BEGIN TRANSACTION InsertRecord
INSERT INTO A (Nn)
VALUES (@Nn)
SELECT NewID = SCOPE_IDENTITY() -- returns the new record ID of this transaction
COMMIT TRANSACTION InsertRecord
```
and call the sproc using VB:
```
Dim strNn '<- var to be passed'
Set cn = Server.CreateObject("ADODB.Connection")
connectString = "DSN"
cn.Open connectString, "user", "PW0rd"
Set rs = Server.CreateObject("ADODB.Recordset")
set rs = cn.Execute("EXEC [dbname].[dbo].[A] @Nn=" & strNn)
'return the value'
resultID = rs(0)
```
I can now use resultID anytime I refer to the newly created ID. | ```
SELECT SCOPE_IDENTITY()
```
using @@IDENTITY can have unexpected results, so be careful how you use that one. Triggers that insert records to other tables will cause the @@IDENTITY value to change - where SCOPE\_IDENTITY() will give you the last identity from only your current scope.
Here's a sample that'll show the difference between @@IDENTITY and SCOPE\_INSERT() and how they can return different values..
```
use tempdb
go
create table table1
(ID int identity)
go
create table table2
(ID int identity(100, 1))
go
create trigger temptrig
on table1
for insert
as
begin
insert table2
default values;
end
go
insert table1
default values;
select SCOPE_IDENTITY(),
@@IDENTITY
```
Another option that nobody has discussed here is to use the OUTPUT clause that is in SQL 2005. In this case, you'd just have to add the output clause to your insert, and then catch that recordset from your code. This works well when inserting multiple records instead of just 1...
```
use tempdb
go
create table table1
(ID int identity)
go
insert table1
output inserted.ID
default values;
--OR...
insert table1
output inserted.$identity
default values;
``` | get new SQL record ID | [
"",
"sql",
"sql-server",
"sql-server-2005",
"asp-classic",
""
] |
We have a large database with enquiries, each enquirys is referenced using a Guid. The Guid isn't very customer friendly so we want to the additional 5 digit "human id" (ok as we'll very likely won't have more than 99999 enquirys active at any time, and it's ok if a humanuid reference multiple enquirys as they aren't used for anything important).
1) Is there any way to have a IDENTITY column reset to 1 after 99999?
My current workaround to this is to use a `INT IDENTITY(1,1) NOT NULL` column and when presenting a HumanId take `HumanId % 100000`.
2) Is there any way to automatically "randomly distribute" the ids over [0..99999] so that two enquirys created after each other don't get the adjacent ids? I guess I'm looking for a two-way one-to-one hash function??
... Ideally I'd like to create this using T-SQL automatically creating these id's when a enquiry is created. | If you absolutely need to do this in the database, then why not derive your human-friendly value directly from the GUID column?
```
-- human_id doesn't have to be calculated when you retrieve the data
-- you could create a computed column on the table itself if you prefer
SELECT (CAST(your_guid_column AS BINARY(3)) % 100000) AS human_id
FROM your_table
```
This will give you a random-ish value between 0 and 99999, derived from the first 3 bytes of the GUID. If you want a larger, or smaller, range then adjust the divisor accordingly. | If performance and concurrency isn't too much of an issue, you can use triggers and the MAX() function to calculate a 'next human ID' value. You probably would want to keep your IDENTITY column as is, and have the 'human ID' in a separate column.
EDIT: On a side note, this sounds like a 'presentation layer' issue, which shouldn't be in your database. Your presentation layer of your application should have the code to worry about presenting a record in a human readable manner. Just a thought... | TSQL: Generate human readable ids | [
"",
"c#",
"t-sql",
""
] |
I am looking for a JavaScript array insert method, in the style of:
```
arr.insert(index, item)
```
Preferably in jQuery, but any JavaScript implementation will do at this point. | You want the **[`splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)** function on the native array object.
`arr.splice(index, 0, item);` will insert `item` into `arr` at the specified `index` (deleting `0` items first, that is, it's just an insert).
In this example we will create an array and add an element to it into index 2:
```
var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";
console.log(arr.join()); // Jani,Hege,Stale,Kai Jim,Borge
arr.splice(2, 0, "Lene");
console.log(arr.join()); // Jani,Hege,Lene,Stale,Kai Jim,Borge
``` | You can implement the `Array.insert` method by doing this:
```
Array.prototype.insert = function ( index, ...items ) {
this.splice( index, 0, ...items );
};
```
Then you can use it like:
```
var arr = [ 'A', 'B', 'E' ];
arr.insert(2, 'C', 'D');
// => arr == [ 'A', 'B', 'C', 'D', 'E' ]
``` | How to insert an item into an array at a specific index? | [
"",
"javascript",
"arrays",
""
] |
Where can I find a list of all HQL keywords? | In the full Hibernate source download there's a `grammar\hql.g` file, which is the [ANTLR](http://www.antlr.org/) language definition. You can view the latest version of this file from the official GitHub source repository [here](https://raw.githubusercontent.com/hibernate/hibernate-orm/master/hibernate-core/src/main/antlr/hql.g).
In the `tokens` section you'll find all the tokens, including the keywords (they're the ones defined as strings, e.g. `ALL="all"`). | Try [this](http://www.hibernate.org/hib_docs/v3/api/org/hibernate/hql/antlr/HqlTokenTypes.html)...not sure if it's complete or exact, but it may be, as it's a list of HQL tokens. | Where can I find a list of all HQL keywords? | [
"",
"java",
"hibernate",
"jpa",
"hql",
"keyword",
""
] |
A `JTextComponent` allows you to add a `DocumentListener` to its `Document`, which will tell you when text was added or removed, and the offset and length of the change. It will not, however, tell you what the text of the change was.
This is not much of a problem for text addition, as you can use the offset and the length to find the added text. However, you can't use it to find the deleted text, as the text is already gone.
Has anyone run into this problem before? How can you get the string that was deleted from a document? | Install a `DocumentFilter` into the `AbstractDocument`.
(BTW: In Swing it's usually best to go straight to the model (in this case document).) | Every time text is added, store the document in memory. Every time text is removed, compare the document to what was last stored to determine what was removed. | Getting the removed text from a Java text component | [
"",
"java",
"swing",
"text",
"jtextcomponent",
""
] |
Now that we have tremendous functionality thanks to LINQ, I'm wondering which syntax is preferable. For example, I found the following method (just thought it was a good example):
```
foreach (FixtureImageServicesData image in _fixture.Images)
{
if (image.Filename != _selectedFixtureImage.Filename && image.IsPrimary)
{
image.IsPrimary = false;
image.IsChanged = true;
}
}
```
If we were to convert it to a LINQ approach, it would look like this (not tested):
```
_fixture.Images.Where(x => x.Filename != _selectedFixtureImage.Filename && x.IsPrimary).ForEach(x => { x.IsPrimary = false; x.IsChanged = true; });
```
Which would you would rather see and maintain? Is this crazy or genius? | Using a `ForEach` extension method is okay, but there's an intermediate approach:
```
// Rename 'query' to something meaningful :)
var query = _fixture.Images
.Where(image => _selectedFixtureImage.Filename
&& image.IsPrimary);
foreach (FixtureImageServicesData image in query)
{
image.IsPrimary = false;
image.IsChanged = true;
}
```
If you *do* use a `ForEach` method, I'd definitely format it in multiple lines:
```
_fixture.Images
.Where(image => _selectedFixtureImage.Filename && image.IsPrimary)
.ForEach(image => { image.IsPrimary = false; image.IsChanged = true;});
```
(Reduced indentation to avoid wrapping...)
or:
```
_fixture.Images
.Where(image => _selectedFixtureImage.Filename && image.IsPrimary)
.ForEach(image => { image.IsPrimary = false;
image.IsChanged = true; });
```
You might even want to extract the "making non-primary" bit into a separate method, at which point you'd have:
```
_fixture.Images
.Where(image => _selectedFixtureImage.Filename && image.IsPrimary)
.ForEach(MakeNonPrimary);
``` | This reminds me a bit of "should I use Regex or standard string functions" or "should I use XSLT/XPATH to transform XML or use SelectSingleNode()".
The first option (ie. Regex/ XSLT/ Linq) is often considered more elegant and powerful by anyone who has spent some time learning it.
While for everyone else it appears to be less readable and more complex when compared to the second option (ie. string functions, SelectSingleNode(), simple foreach loop).
In the past I've been accused of over-complicating things by using Regex and XSLT/XPATH in my design.
Just recently I was accused of being "scared of change" by preferring simple foreach (and even for) loops in many situations over Linq Where, Foreach etc.
I soon realised that the people in both cases who said this were the sort who feel that there is "the one way" to do everything.
Whereas I've always found it's much smarter to consider each situation on its merits and choose the right tool for the job. I just ignore them and continue with my approach ;)
For that situation you describe, the first option is more preferable to me. However I probably would use the Linq approach if my team were all competent in Linq, and we had coding guidelines to avoid big one-liners (by splitting it them up) | Is it wise to use LINQ to replace loops? | [
"",
"c#",
".net",
"linq",
"extension-methods",
""
] |
Was wondering what the best WYSIWYG editor that I can embed in a web-site based on the ASP.NET MVC Framework? Ideally it should be Xhtml compliant and allow users to embed images etc.
The only one I've used before is the [FCKEditor](http://www.fckeditor.net/), how well does this work with the MVC - has anyone tried...?
My main requirements are:
* Xhtml compliance
* Deprecate (as best it can) when Javascript is disabled
* Modify the toolbar options
* Skinable (at least easily change the look and feel)
* Easy to use client side api
* Plays nicely with the ASP.NET MVC framework
**Edit:**
As [Nick](https://stackoverflow.com/questions/590960/whats-the-best-wysiwyg-editor-when-using-the-asp-net-mvc-framework/591025#591025) said, the [XStandard](http://www.xstandard.com/) editor is good, but requires a plug-in...what are your thoughts on requiring a plug-in for web-site functionality?
Thanks,
Kieron
**Additional info:**
As [Hippo](https://stackoverflow.com/questions/590960/whats-the-best-wysiwyg-editor-when-using-the-asp-net-mvc-framework/591037#591037) answered, the TinyMCE edit is ideal - for completness here's there download page:
<http://tinymce.moxiecode.com/download.php>
There's a download for .NET, JSP, ColdFusion, PHP and a jQuery plug-in too.
Also, there are language packs available.
Been using it for a while now, best editor I've used. Thanks all! | I really like [TinyMCE](http://tinymce.moxiecode.com/) which also should fit your requirements. It is well documented and offers a lot of possibilities to configure. | [CKEditor](http://ckeditor.com/) (the next version of FCKEditor) is in beta, but looks like it might eventually be pretty nice. | What's the best WYSIWYG editor when using the ASP.NET MVC Framework? | [
"",
"javascript",
"asp.net-mvc",
"xhtml",
"wysiwyg",
""
] |
Over the time i developed my own framework and it's working great - it's light, it's fast and is proven that can handle decent load.
Now I'm working on project that can be described as a online shop where every user will have his sub domain where his items will be available for sale.
My framework works by splitting request url by / and determening what is the
controller, actions params.. etc..
and that works just fine, but what to do with subdomains?
i've modified my reqest object, so when i type lets say:
<http://kodi.shop.local/>
(i added SeverAlias \*.shop.local )
this is how my request object look like:
```
DPLS_Request Object
(
[_request] => Array
(
[0] =>
[1] =>
[action] => defaultAction
[controller] => home
)
[_params] => Array
(
)
[_rurl:private] => kodi.shop.local
[_segment] => kodi
[get_params] => Array
(
)
)
```
so \_segment is the subdomain, and later i can use it in code to validate it vs username and other stuff but i'm having conceptual problems even before that.
my problem is that my framework expect some controller and actions to be passed, and because all he gets at the end of URL is / he assumes that it shoud display index page :(
so what to do next ... how to incorporate subdomains in whole mvc controllers/actions story?
one quick and dirty sollution is to modify part of my request class:
```
if($this->_request['controller']==''){
$this->_request['controller'] = DEFAULT_CONTROLLER;
}
if($this->_request['action']==''){
$this->_request['action'] = DEFAULT_ACTION;
}
```
and to wrap that in yet another **if** to test if \_segment is present, and if it is then assign to controller DEFAULT \_SHOP \_CONTROLLER, which i will define in config file as lets say 'store'
so the request above will be analog to typing <http://shop.local/store/>
(it will run 'store' controller and default action)
what would you do in this case?
is there any "best practice" when dealing with subdomains and controllers and actions? | It sounds like, to me, the approach you are describing is the logical next step to implement the features you are adding. The new features will bring some added complexity but your Request object/Router should do a good job of encapsulating the logic of "What controller do I invoke when a segment is provided? When a segment AND a controller are provided?" etc. I say go for it. | I personally wouldn't start adding all kinds of 'specific' conditions into your framework related to subdomains, because what subdomains means in one situation doesn't necessarily mean the same thing in another situation. (Besides, the more the framework assumes, the crappier it gets)
For example, some people uses subdomains to define locale (en.site.com for english version, fr.site.com for french...), yet with this set up, it would use the 'same' controllers no matter what language the site is translated to.
Just do a simple rewrite rule like:
rewrite \*.store.site.com into \*.site.com/store/ | how to incorporate subdomains into MVC framework | [
"",
"php",
"model-view-controller",
""
] |
Can any one tell what is numeric promotion? | Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required. | **Numeric Promotion Rules**
1. If two values have different data types, Java will automatically promote one of the values to the larger of the two data types.
2. If one of the values is integral and the other is floating-point, Java will automatically promote the integral value to the floating-point value’s data type.
3. Smaller data types, namely byte, short, and char, are first promoted to int any time they’re used with a Java binary arithmetic operator, even if neither of the operands is int.
4. After all promotion has occurred and the operands have the same data type, the resulting value will have the same data type as its promoted operands | What is numeric promotion? | [
"",
"java",
""
] |
I was going to use jQuery to clone the input field when I click a button to make another field, but I was thinking of doing:
`Page One, Page Two, Page Three` <- then send that as one `$_POST` to the server and have it take each page and break on the "," comma then for each insert in to my POSTS table.
Any idea on how I would do that? Would I use explode()? Then inside a `foreach()` run a query for each item in the field.
So if there were 5 pages typed in separated by commas, it would run five times using the `foreach()`.
```
for each(){
EXECUTE SQL HERE
}
```
Does that sound like it would be the best way of going about it? | If you set the `name` attribute of the `input` element to the name of an array, e.g. `foo[]`, you'll be able to access it as such when processing the `$_POST` vars, e.g.
```
<input name="foo[]" type="text"/>
<input name="foo[]" type="text"/>
```
becomes two iterations of:
```
foreach ($_POST['foo'] as $foo) {
// process $foo
}
``` | explode and foreach sound good.
But as Click Upvote indicated: is it for pagination? 'cause then there could be a betetr way to achieve this. | How to send multiple related values from my html form to server via $_POST? | [
"",
"php",
"html",
"arrays",
"forms",
""
] |
I have a standard WinForms TextBox and I want to insert text at the cursor's position in the text. How can I get the cursor's position?
Thanks | Regardless of whether any text is selected, the [SelectionStart](http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.selectionstart.aspx) property represents the index into the text where you caret sits. So you can use [String.Insert](http://msdn.microsoft.com/en-us/library/system.string.insert.aspx) to inject some text, like this:
```
myTextBox.Text = myTextBox.Text.Insert(myTextBox.SelectionStart, "Hello world");
``` | You want to check the `SelectionStart` property of the `TextBox`. | How do I find the position of a cursor in a text box? C# | [
"",
"c#",
"cursor-position",
""
] |
Is it possible include images (jpegs) as resources in a win32 c++ executable? If so how? | Here's the MSDN documentation about resource files.
<http://msdn.microsoft.com/en-us/library/aa380599(VS.85).aspx> | If it's Windows only then use a custom resource. If you want something cross-platform then do what I did for a recent project - create an app that will encode the JPEG as a `char*` buffer in a header file and then include these headers in your main project. You will also need to store the size of the buffer as it will be sure to contain NULs.
For example, I have an app that you can pass a load of files to be encoded and for each file you get a header file that looks something like this:
```
#ifndef RESOURCE_SOMEFILE_JPG_HPP
#define RESOURCE_SOMEFILE_JPG_HPP
namespace resource {
const char* SOMEFILE_JPG[] =
{
...raw jpeg data...
};
const int SOMEFILE_JPG_LEN = 1234;
} // resource
#endif // RESOURCE_SOMEFILE_JPG_HPP
```
The app has to escape special non-printable chars in `\x` format, but it's pretty simple. The app uses the `boost::program_options` library so a list of files to encode can be stored in a config file. Each file gets its own header like similar to the above.
However, be warned - this only works for small files as some compilers have a limit on the maximum size a static char buffer can be. I'm sure there are other ways to do this but this scheme works for me (a C++ web app that stores the HTML, CSS, JavaScript and image files in this way). | How do you include images as resources in a C++ executable? | [
"",
"c++",
"windows",
"resources",
""
] |
In several C++ examples I see a use of the type `size_t` where I would have used a simple `int`. What's the difference, and why `size_t` should be better? | From [the friendly Wikipedia](http://en.wikipedia.org/wiki/Size_t#Member_data_types):
> The stdlib.h and stddef.h header files define a datatype called **size\_t** which is used to represent the size of an object. Library functions that take sizes expect them to be of type size\_t, and the sizeof operator evaluates to size\_t.
>
> The actual type of size\_t is platform-dependent; a common mistake is to assume size\_t is the same as unsigned int, which can lead to programming errors, particularly as 64-bit architectures become more prevalent.
Also, check [Why size\_t matters](http://www.embedded.com/electronics-blogs/programming-pointers/4026076/Why-size-t-matters) | `size_t` **1)** is the data type used to represent sizes (as its name implies) and **2)** is platform (and even potentially implementation) dependent, so it should be used ***only*** for representing sizes.
Representing a size, `size_t` is naturally unsigned (can you have a box that is negative 3 meters wide?). Many `stdlib` functions, including `malloc`, `sizeof`, and various string operation functions use `size_t` as a datatype.
An `int` is signed by default, and even though its size is also platform dependent, it will be a fixed 32bits on most modern machine (and though `size_t` is 64 bits on any 64-bit architecture, `int` *remains* 32 bits long on those same 64-bit architectures).
**Summary**: Use `size_t` to represent the size of an object and `int` (or `long`) in other cases. Be aware that `size_t` is unsigned while both `int` and `long` are signed by default (unless prepended with `unsigned` , or modified to `uint` or `ulong`). | What's the difference between size_t and int in C++? | [
"",
"c++",
"c",
"types",
"integer",
"size-t",
""
] |
I have two `IEnumerable<T>`s.
One gets filled with the fallback ellements. This one will always contain the most elements.
The other one will get filled depending on some parameters and will possibly contain less elements.
If an element doesn't exist in the second one, I need to fill it with the equivalent one of the first one.
This code does the job, but feels inefficient to me and requires me to cast the IEnumerables to ILists or to use a temporary list
Person implements IEquatable
```
IEnumerable<Person> fallBack = Repository.GetPersons();
IList<Person> translated = Repository.GetPersons(language).ToList();
foreach (Person person in fallBack)
{
if (!translated.Any(p=>p.equals(person)))
translated.add(person);
}
```
Any suggestions? | Try this.
```
public static IEnumerable<Person> SmartCombine(IEnumerable<Person> fallback, IEnumerable<Person> translated) {
return translated.Concat(fallback.Where(p => !translated.Any(x => x.id.equals(p.id)));
}
``` | ```
translated.Union(fallback)
```
or (if Person doesn't implement `IEquatable<Person>` by ID)
```
translated.Union(fallback, PersonComparer.Instance)
```
where PersonComparer is:
```
public class PersonComparer : IEqualityComparer<Person>
{
public static readonly PersonComparer Instance = new PersonComparer();
// We don't need any more instances
private PersonComparer() {}
public int GetHashCode(Person p)
{
return p.id;
}
public bool Equals(Person p1, Person p2)
{
if (Object.ReferenceEquals(p1, p2))
{
return true;
}
if (Object.ReferenceEquals(p1, null) ||
Object.ReferenceEquals(p2, null))
{
return false;
}
return p1.id == p2.id;
}
}
``` | Merging two IEnumerable<T>s | [
"",
"c#",
"merge",
""
] |
i have to review a code made by some other person that has some memory leaks. Right now i'm searching the disposable objects to enclause them with the using statement and i would like to know if there is a quick way that tells you all the disposable objects declared in. I mean something like resharper or another visual studio plugin.
thanks. | I know what you mean. I don't know, but look at FxCop. It might have a rule in there somewhere that checks whether objects implementing IDisposable are not disposed. Just a hunch, mind.
**UPDATE**: [Mitch Wheat](https://stackoverflow.com/users/16076/mitch-wheat) writes:
> FxCop includes the rule, thats says all types that derive from types that implement IDisposable should implement the Dispose() pattern
Thanks, Mitch. | You could do this with [ReSharper](http://www.jetbrains.com/resharper/). With ReSharper you can navigate implementations of any interface with ease by using Alt-End, but for a popular interface such as `IDisposable` this is not practical.
Here's what you could do:
1. Go to Object Browser (Ctrl-Alt-J or View->Object Browser)
2. Find `System.IDisposable`
3. Right click and select "Find Usages Advanced" (ReSharper's menu item)
4. User Find, check "Implementations", under Scope choose Solution
5. You will get a list of *all* types (of your solution) implementing `IDisposable`. Those in **bold** are the ones you want - they implement `IDisposable` directly.
Hope that helps. | Identify IDisposable objects | [
"",
"c#",
"memory-leaks",
"dispose",
"idisposable",
"using-statement",
""
] |
Does anyone know how to reset the border color of an input control once you have modified it using javascript? Useful for validation by highlighting fields that have incorrect or invalid data in them etc.
E.g. changing the border:
```
document.getElementById('myinput').style.border = '1px solid red';
```
how to reset? the next line just removes the border completely...
```
document.getElementById('myinput').style.border = '';
```
if I reset the border color back to a particular color (e.g. black or grey etc), it may look strange in some browsers/operating systems that sort of 'theme' the controls...
thanks heaps! | Don't do it with setting style attributes. Do it by using CSS classes. I would also recommend using a Javascript library to handle this. It just makes the code cleaner.
Removing CSS attributes is problematic because you don't always know what they should be set back to. Adding and removing classes just... works.
You can have multiple classes per element so there's really no argument against doing it this way (imho).
I'm used to jQuery so my example is with that.
Wrong way:
```
$("#myinput").css("border", "1px solid red");
```
Right way:
```
<style type="text/css">
.redborder { border: 1px solid red; }
</style>
<script type="text/javascript">
$("#myinput").addClass("redborder");
$("#myinput").removeClass("redborder");
$("#myinput").toggleClass("redborder");
</script>
``` | This works for me:
```
document.getElementById('myinput').style.removeProperty('border');
``` | Reset an input control's border color (HTML/Javascript) | [
"",
"javascript",
"html",
"dom",
"border",
"validation",
""
] |
Basically, I want this:
```
<select size="2">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
```
But instead of having two lines, I want it on a single line. Can this be done without Javascript?
If not, I would imagine it's common enough (though I can't find any relevant links on Google) that there exists a standard cross-browser solution for this which would be helpful.
EDIT: The control is also called a [stepper](http://developer.apple.com/documentation/UserExperience/Conceptual/AppleHIGuidelines/XHIGControls/chapter_19_section_4.html#//apple_ref/doc/uid/TP30000359-TPXREF204) or a [spinner](http://msdn.microsoft.com/en-us/library/aa511491.aspx) (this link also has UI guidelines for when to use a spin control)
# Solution A:
```
<select size="2" style="height:40px; font-size:28px;">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
```
This solution relies on the fact that the select box is big enough to enable controls but the text is big enough to so that there's only one line of text showing. The problem is that it needs to be quite big for this to work. It works on IE/FF but still precarious because of the browser default text size discrepancies. | If you *can* use JavaScript, it looks like there are [some options for spinner controls](http://www.google.com/search?hl=en&q=javascript+spinner). [One such control](http://extjs.com/learn/Extension:Ext.ux.form.Spinner) has pretty good UI and functionality. Example:
[](https://i.stack.imgur.com/jYTjD.jpg)
(source: [extjs.com](http://extjs.com/learn/w/images/a/ae/Ux-form-spinner.jpg)) | You may want to rethink the user interaction side of this before struggling to find a workable JavaScript-free solution.
When a user is presented with a single-line `<select>` the default behavior is for a dropdown list to appear. Changing this goes against the user's expectations and may make your form harder to use, ultimately reducing completion or at least increasing the time involvement to use it.
If you eventually want to allow multiple selections, then a single-line input would be almost impossible to use.
Unless you have legitimate feedback that users would like dropdown lists to behave differently, you may be heading in the wrong direction, at least from a UX perspective. | Single line select box with up/down arrows like in a multi line select box | [
"",
"javascript",
"html",
"css",
"forms",
""
] |
Are there any differences between...
```
if ($value) {
}
```
...and...
```
if ($value):
endif;
```
? | They are the same but the second one is great if you have MVC in your code and don't want to have a lot of echos in your code. For example, in my `.phtml` files (Zend Framework) I will write something like this:
```
<?php if($this->value): ?>
Hello
<?php elseif($this->asd): ?>
Your name is: <?= $this->name ?>
<?php else: ?>
You don't have a name.
<?php endif; ?>
``` | At our company, the preferred way for handling HTML is:
```
<? if($condition) { ?>
HTML content here
<? } else { ?>
Other HTML content here
<? } ?>
```
In the end, it really is a matter of choosing one and sticking with it. | Difference between if () { } and if () : endif; | [
"",
"php",
"syntax",
""
] |
Anyone know what is the project home site of the RSS4J. I found several reference on Maven repositories, but can't find the original project site. Also is this project alive? | It was on www.churchillobjects.com, but that domain has now been tranferred to a domain parking site. The Wayback Machine has [this page](http://web.archive.org/web/20070202202600/www.churchillobjects.com/c/13005.html) for RSS4J from February 2007. | It looks like [RSS4J](http://rss4j.sourceforge.net/) is hosted on SourceForge. | Whereabout of the RSS4J project | [
"",
"java",
"rss",
"class-library",
""
] |
I am creating a little dashboard for a user that will allow him to run specific jobs. I am using Django so I want him to be able to click a link to start the job and then return the page back to him with a message that the job is running. The results of the job will be emailed to him later.
I believe I am supposed to use `subprocess.Popen` but I'm not sure of that. So in pseudocode, here is what I want to do:
```
if job == 1:
run script in background: /path/to/script.py
return 'Job is running'
``` | ```
p = subprocess.Popen([sys.executable, '/path/to/script.py'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
```
That will start the subprocess in background. Your script will keep running normally.
Read the documentation [here](http://docs.python.org/library/subprocess.html). | Running this through a message queue is definitely the way to go if you're thinking about long-term scaling. Send a message to the queue who's running constantly in the background, and write job handlers to deal with the different sorts of messages.
Since you're using Django, I think [Beanstalkd](http://xph.us/software/beanstalkd/ "Beanstalkd") is a pretty good fit. [Here's](http://parand.com/say/index.php/2008/10/12/beanstalkd-python-basic-tutorial/) a pretty nice tutorial on the subject. The first comment in that article also has some good tips.
Personally I've rolled with a custom in-memory queue server written in Erlang, with Python-bindings written in C. But [redis](http://code.google.com/p/redis/) looks like it might work out as a great contender for future queuing/messaging-needs. Hope this helps! | How do I run another script in Python without waiting for it to finish? | [
"",
"python",
"django",
"process",
"background",
"subprocess",
""
] |
I have a requirement to map all of the field values and child collections between ObjectV1 and ObjectV2 by field name. ObjectV2 is in a different namspace to ObjectV1.
Inheritence between the template ClassV1 and ClassV2 has been discounted as these 2 classes need to evolve independently. I have considered using both reflection (which is slow) and binary serialisation (which is also slow) to perform the mapping of the common properties.
Is there a preferred approach? Are there any other alternatives? | As an alternative to using reflection every time, you could create a helper class which dynamically creates copy methods using Reflection.Emit - this would mean you only get the performance hit on startup. This may give you the combination of flexibility and performance that you need.
As Reflection.Emit is quite clunky, I would suggest checking out [this](http://www.codeplex.com/reflectoraddins/Wiki/View.aspx?title=ReflectionEmitLanguage&referringTitle=Home) Reflector addin, which is brilliant for building this sort of code. | What version of .NET is it?
**For shallow copy:**
In 3.5, you can pre-compile an `Expression` to do this. In 2.0, you can use `HyperDescriptor` very easily to do the same. Both will vastly out-perform reflection.
There is a pre-canned implementation of the `Expression` approach in [`MiscUtil`](http://www.yoda.arachsys.com/csharp/miscutil/) - `PropertyCopy`:
```
DestType clone = PropertyCopy<DestType>.CopyFrom(original);
```
**(end shallow)**
BinaryFormatter (in the question) is not an option here - it simply won't work since the original and destination types are different. If the data is contract based, XmlSerializer or DataContractSerializer would work **if** all the contract-names match, but the two (shallow) options above would be much quicker if they are possible.
Also - if your types are marked with common serialization attributes (`XmlType` or `DataContract`), then [protobuf-net](http://code.google.com/p/protobuf-net/) **can** (in some cases) do a deep-copy / change-type for you:
```
DestType clone = Serializer.ChangeType<OriginalType, DestType>(original);
```
But this depends on the types having very similar schemas (in fact, it doesn't use the names, it uses the explicit "Order" etc on the attributes) | How to deep copy between objects of different types in C#.NET | [
"",
"c#",
".net",
"reflection",
"serialization",
""
] |
In C#, when I have an interface and several concrete implementations, can I cast the interface to a concrete type or is concrete type cast to interface?
What are the rules in this case? | Both directions are allowed in Java and C#. Downcasting needs an explicit cast and may throw an Exception if the object is not of the correct type. Upcasting, however, needs no explicit cast and is always safe to do.
That is, assuming you have `public interface Animal` and two implementations of this `interface`, `Cat` and `Dog`....
```
Animal meowAnimal = new Cat(); // No cast required
Animal barkAnimal = new Dog(); // No cast required
Cat myCat = (Cat) meowAnimal; // Explicit cast needed
Dog myDog = (Dog) barkAnimal; // Explicit cast needed
Dog myPet = (Dog) meowAnimal; // Will compile but throws an Exception
```
and you'll want a `try` / `catch` around the explicit casts. In C# you have the useful `as` keyword:
```
Dog myDog = barkAnimal as Dog;
Dog myPet = meowAnimal as Dog;
```
No exception will be thrown, and myDog will be nonNull and myPet will be null. Java does not have an equivalent keyword although you can always use `if (meowAnimal instanceof Dog)` tests to keep type safety. (I would guess that the "`as`" keyword generates bytecode that does the if, assigning null of the `is` fails. But perhaps .NET has a bytecode instruction that does the equivalent of "`as`".) | In most languages you can cast both directions. If you have a concrete class, you can cast it to the interface. If you have an interface, it is possible to cast to the concrete class.
Generally, you only want to go in the first direction. The reason being that you shouldn't know what the concrete class is when you have only a pointer to the interface. If you are passing something around as an interface, you should be able to do whatever you need to from that interface. If you find yourself needing to use parts of the concrete object not on the interface, you have a design problem that should be fixed instead of casting. | Cast interface to its concrete implementation object or vice versa? | [
"",
"c#",
"oop",
""
] |
I want to get the PropertyInfo for a specific property. I could use:
```
foreach(PropertyInfo p in typeof(MyObject).GetProperties())
{
if ( p.Name == "MyProperty") { return p }
}
```
But there must be a way to do something similar to
```
typeof(MyProperty) as PropertyInfo
```
Is there? Or am I stuck doing a type-unsafe string comparison?
Cheers. | You can use the new `nameof()` operator that is part of C# 6 and available in Visual Studio 2015. More info [here](https://msdn.microsoft.com/en-us/library/dn986596.aspx).
For your example you would use:
```
PropertyInfo result = typeof(MyObject).GetProperty(nameof(MyObject.MyProperty)) ?? throw new Exception();
```
The compiler will convert `nameof(MyObject.MyProperty)` to the string "MyProperty" but you gain the benefit of being able to refactor the property name without having to remember to change the string because Visual Studio, ReSharper, and the like know how to refactor `nameof()` values. | There is a .NET 3.5 way with lambdas/`Expression` that doesn't use strings...
```
using System;
using System.Linq.Expressions;
using System.Reflection;
class Foo
{
public string Bar { get; set; }
}
static class Program
{
static void Main()
{
PropertyInfo prop = PropertyHelper<Foo>.GetProperty(x => x.Bar);
}
}
public static class PropertyHelper<T>
{
public static PropertyInfo GetProperty<TValue>(
Expression<Func<T, TValue>> selector)
{
Expression body = selector;
if (body is LambdaExpression)
{
body = ((LambdaExpression)body).Body;
}
switch (body.NodeType)
{
case ExpressionType.MemberAccess:
return (PropertyInfo)((MemberExpression)body).Member;
default:
throw new InvalidOperationException();
}
}
}
``` | How to get the PropertyInfo of a specific property? | [
"",
"c#",
"reflection",
""
] |
I'm building an XML Deserializer for a project and I run across this type of code situation fairly often:
```
var myVariable = ParseNDecimal(xml.Element("myElement")) == null ?
0 : ParseNDecimal(xml.Element("myElement")).Value;
```
Is there a better way to write this statement?
EDIT : Perhaps I should have clarified my example as I do have a helper method to parse the string into a decimal. | You can use extension method:
```
public static T TryGetValue<T>( this XmlElement element ) {
if ( null == element ) return default(T);
return (T)element.Value;
}
...
...
var myVariable = xml.Element("myElement").TryGetValue<decimal>();
```
**EDIT:**
The "universal" solution:
```
static class Program {
static void Main() {
var xmlDecimal = new XElement( "decimal" );
xmlDecimal.Value = ( 123.456m ).ToString();
decimal valueOfDecimal_1 = xmlDecimal.ValueAs<decimal>( decimal.TryParse );
bool valueOfBool_1 = xmlDecimal.ValueAs<bool>( bool.TryParse );
var xmlBool = new XElement( "bool" );
xmlBool.Value = true.ToString();
decimal valueOfDecimal_2 = xmlBool.ValueAs<decimal>( decimal.TryParse );
bool valueOfBool_2 = xmlBool.ValueAs<bool>( bool.TryParse );
}
}
public static class StaticClass {
public delegate bool TryParseDelegate<T>( string text, out T value );
public static T ValueAs<T>( this XElement element, TryParseDelegate<T> parseDelegate ) {
return ValueAs<T>( element, parseDelegate, default( T ) );
}
public static T ValueAs<T>( this XElement element, TryParseDelegate<T> parseDelegate, T defaultValue ) {
if ( null == element ) { return defaultValue; }
T result;
bool ok = parseDelegate( element.Value, out result );
if ( ok ) { return result; }
return defaultValue;
}
}
``` | **Edit:** Given the edited question, this is much simpler.
Again it uses an extension method, but now there's no need to do a conversion in the method.
```
var myVariable = ParseNDecimal(xml.Element("myElement").ValueOrDefault("0"));
...
public static string ValueOrDefault(this XElement element,
string defaultValue)
{
return element != null ? element.Value : defaultValue;
}
```
If you don't like the method taking a string parameter, you could make it take `object` and call `ToString`, then call it like this:
```
var myVariable = ParseNDecimal(xml.Element("myElement").ValueOrDefault(0m));
```
However, that feels a little bit wrong to me. It assumes that the parsing will be the reverse of `ToString` formatting.
**Original answer**
There's nothing particularly in the language to help you. (I'm not sure that you've got the exact code right - don't you mean something with an `XAttribute`?) I'd suggest writing a utility method:
```
var myVariable = xml.Element("myElement").ValueOrDefault(0m);
...
public static decimal ValueOrDefault(this XElement element,
decimal defaultValue)
{
return element != null ?(decimal) element.Value : defaultValue;
}
```
If you adjust the code in the question, I'll do likewise for the code here. I suspect you *did* mean to use `XAttribute`, which leads to a problem with generics - I haven't written the above in a generic way, because I believe you will want to call the `XAttribute` "conversion to decimal" operator. A generic cast won't do that, as it doesn't know what kind of conversion you want at compile time. You can, however, overload the above method for all the result types you're interested in. | C# ?? combined with ?: question | [
"",
"c#",
"ternary-operator",
"conditional-operator",
""
] |
It's probably beginner question but I'm going through documentation for longer time already and I can't find any solution. I thought I could use implode for each dimension and then put those strings back together with `str_split` to make new simple array. However I never know if the join pattern isn't also in values and so after doing `str_split` my original values could break.
Is there something like `combine($array1, $array2)` for arrays inside of multi-dimensional array? | [Use `array_walk_recursive`](http://php.net/manual/en/function.array-walk-recursive.php)
```
<?php
$aNonFlat = array(
1,
2,
array(
3,
4,
5,
array(
6,
7
),
8,
9,
),
10,
11
);
$objTmp = (object) array('aFlat' => array());
array_walk_recursive($aNonFlat, create_function('&$v, $k, &$t', '$t->aFlat[] = $v;'), $objTmp);
var_dump($objTmp->aFlat);
/*
array(11) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
[5]=>
int(6)
[6]=>
int(7)
[7]=>
int(8)
[8]=>
int(9)
[9]=>
int(10)
[10]=>
int(11)
}
*/
?>
```
Tested with PHP 5.5.9-1ubuntu4.24 (cli) (built: Mar 16 2018 12:32:06) | ```
$array = your array
$result = call_user_func_array('array_merge', $array);
echo "<pre>";
print_r($result);
```
REF: <http://php.net/manual/en/function.call-user-func-array.php>
**Here is another solution (works with multi-dimensional array) :**
```
function array_flatten($array) {
$return = array();
foreach ($array as $key => $value) {
if (is_array($value)){ $return = array_merge($return, array_flatten($value));}
else {$return[$key] = $value;}
}
return $return;
}
$array = Your array
$result = array_flatten($array);
echo "<pre>";
print_r($result);
``` | How to "flatten" a multi-dimensional array to simple one in PHP? | [
"",
"php",
"arrays",
"multidimensional-array",
""
] |
I'm imagining that this will come down to personal preference but which way would you go?
```
StringBuilder markup = new StringBuilder();
foreach (SearchResult image in Search.GetImages(componentId))
{
markup.Append(String.Format("<div class=\"captionedImage\"><img src=\"{0}\" width=\"150\" alt=\"{1}\"/><p>{1}</p></div>", image.Resolutions[0].Uri, image.Caption));
}
LiteralMarkup.Text = markup.ToString();
```
Vs.
```
StringBuilder markup = new StringBuilder();
foreach (SearchResult image in Search.GetImages(componentId))
{
markup.Append(String.Format(@"<div class=""captionedImage""><img src=""{0}"" width=""150"" alt=""{1}""/><p>{1}</p></div>", image.Resolutions[0].Uri, image.Caption));
}
LiteralMarkup.Text = markup.ToString();
```
Or should I not be doing this at all and using the HtmlTextWriter class instead?
**EDIT: Some really good suggestions here. We are on 2.0 framework so LINQ is not available** | Another vote for "AppendFormat". Also, for the sake of the server code I might put up with single quotes here to avoid the need to escape anything:
```
StringBuilder markup = new StringBuilder();
foreach (SearchResult image in Search.GetImages(componentId))
{
markup.AppendFormat(
"<div class='captionedImage'><img src='{0}' width='150' alt='{1}'/><p>{1}</p></div>",
image.Resolutions[0].Uri, image.Caption
);
}
LiteralMarkup.Text = markup.ToString();
```
Finally, you may also want an additional check in there somewhere to prevent html/xss injection.
Another option is to encapsulate your image in a class:
```
public class CaptionedHtmlImage
{
public Uri src {get; set;};
public string Caption {get; set;}
CaptionedHtmlImage(Uri src, string Caption)
{
this.src = src;
this.Caption = Caption;
}
public override string ToString()
{
return String.Format(
"<div class='captionedImage'><img src='{0}' width='150' alt='{1}'/><p>{1}</p></div>"
src.ToString(), Caption
);
}
}
```
This has the advantage of making it easy to re-use and add features to the concept over time. To get real fancy you can turn that class into a usercontrol. | Me personally I would opt for the first option. Just to point out also, a quick code saving tip here. you can use **AppendFormat** for the StringBuilder.
**EDIT: The HtmlTextWriter approach would give you a much more structured result, and if the amount of HTML to generate grew, then this would be an obvious choice. OR the use of an HTML file and using it as a template and maybe string replacements**
ASP.NET User Control are another good choice for templating. | Which Method Do You Find More Readable To Output Dynamic HTML? | [
"",
"c#",
"readability",
"html-generation",
""
] |
I have a tool that generates most (but not all) files that need to be compiled in Visual Studio. The tool reads a configuration file and generates c++ files afterwards. This list can differ from one call to another when the configuration is altered.
I am wondering whether it would be possible to adapt the compiling process to my needs, which would be :
1. Launch the tool (not needed if configuration file has been modified)
2. Retrieve new list of C++ files to be compiled (ideally isolated in a folder inside the project)
3. Compile C++ files
EDIT: Having to close Visual Studio for this process to work is a no-go for me. The idea would be to have cpp files dynamically added as the first step of the compilation process. | * Use a pre-build step to run your tool.
+ Also, create a file containing the list of includes and sources
+ This file name should be fixed (so that you don't have to change project properties or the vcproj file) -- add it to the project. E.g:
Project Properties > Command Line > Additional Options > @headerListingFile
You are not trying to integrate lex/yacc output with VS, are you? | I think what you should do is create a custom makefile and use that for builds.
Please [see this page for more information](http://msdn.microsoft.com/en-us/library/txcwa2xx(VS.71).aspx). | Can the list of C++ files in a Visual Studio project be dynamically filled? | [
"",
"c++",
"visual-studio-2005",
"compilation",
""
] |
I've got a Wordpress site on our home intranet that has run into trouble now that the IP address has changed - The index page loads, but not the CSS and I can't log in to the site administration panel.
Unfortunately I am a bit behind on backups. Is there a way to get Wordpress to refer to the new IP address? | You have two places to update this (well three, but we'll stick with the two).
***If*** you can still log into your admin section, type the following for your URI /wp-admin/options.php - so for example, if your site is <http://localhost> then your full URL will be <http://localhost/wp-admin/options.php>. Once you've logged into your site you should see two fields (well you'll see a lot of fields), but you'll want to look for the two with URL's in them - the Site URL and the Blog URL (in WP 2.7 the fields are labeled "home" and "siteurl", not sure on the other versions).
Or, you can log into MySQL database and run the following.
```
Select * from wp_options where option_name IN('siteurl','home');
```
I just ran this today on one of my installs. If you're option\_value is set to your localhost - you can then run the following:
```
update wp_options set option_value='http://www.yourblogname.com' where option_name = 'siteurl';
update wp_options set option_value='http://www.yourblogname.com' where option_name = 'home';
```
This should update your table structure. | You have to change the 'home' and 'siteurl' in the settings. Since you cannot open the admin side of wordpress, open the database in phpMyAdmin(or something similar).
The options can be found in the 'wp\_options' table(wp\_ prefix might be different). Find the necessary setting using this query...
```
SELECT * FROM `wp_options` WHERE `option_name` IN ('siteurl', 'home')
```
Change the values of both the options to the new IP. | Wordpress host IP changed | [
"",
"php",
"wordpress",
""
] |
I need to export the pages of an arbitrary PDF document into a series of individual images in jpeg/png/etc format. I need to do this in in Java.
Although I do know about iText, PDFBox and various other java pdf libraries, I am hoping for a pointer to some working example, or some how-to.
Thanks. | Here is one way to do it, combining some code fragments from around the web.
**How do I draw a PDF into an Image?**
[https://pdf-renderer.dev.java.net/examples.html](http://java.net/projects/pdf-renderer)
**Creating a Buffered Image from an Image**
ORIGINAL: <http://www.exampledepot.com/egs/java.awt.image/Image2Buf.html>
UPDATED: [How to convert buffered image to image and vice-versa?](https://stackoverflow.com/questions/9132149/how-to-convert-buffered-image-to-image-and-vice-versa)
**Saving a Generated Graphic to a PNG or JPEG File**
ORIGINAL: <http://www.exampledepot.com/egs/javax.imageio/Graphic2File.html>
UPDATED: <http://docs.oracle.com/javase/tutorial/2d/images/saveimage.html>
Combined together into something that works like this to turn all the pages into images:
```
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Transparency;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import javax.swing.*;
import javax.imageio.*;
import java.awt.image.*;
public class ImageMain {
public static void setup() throws IOException {
// load a pdf from a byte buffer
File file = new File("test.pdf");
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
int numPgs = pdffile.getNumPages();
for (int i = 0; i < numPgs; i++) {
// draw the first page to an image
PDFPage page = pdffile.getPage(i);
// get the width and height for the doc at the default zoom
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight());
// generate the image
Image img = page.getImage(rect.width, rect.height, // width & height
rect, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
// save it as a file
BufferedImage bImg = toBufferedImage(img);
File yourImageFile = new File("page_" + i + ".png");
ImageIO.write(bImg, "png", yourImageFile);
}
}
// This method returns a buffered image with the contents of an image
public static BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
}
// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).getImage();
// Determine if the image has transparent pixels; for this method's
// implementation, see e661 Determining If an Image Has Transparent
// Pixels
boolean hasAlpha = hasAlpha(image);
// Create a buffered image with a format that's compatible with the
// screen
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
// Determine the type of transparency of the new buffered image
int transparency = Transparency.OPAQUE;
if (hasAlpha) {
transparency = Transparency.BITMASK;
}
// Create the buffered image
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) {
// The system does not have a screen
}
if (bimage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
if (hasAlpha) {
type = BufferedImage.TYPE_INT_ARGB;
}
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
}
// Copy image to buffered image
Graphics g = bimage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}
public static boolean hasAlpha(Image image) {
// If buffered image, the color model is readily available
if (image instanceof BufferedImage) {
BufferedImage bimage = (BufferedImage) image;
return bimage.getColorModel().hasAlpha();
}
// Use a pixel grabber to retrieve the image's color model;
// grabbing a single pixel is usually sufficient
PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
try {
pg.grabPixels();
} catch (InterruptedException e) {
}
// Get the image's color model
ColorModel cm = pg.getColorModel();
return cm.hasAlpha();
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
ImageMain.setup();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
}
``` | If you consider the JPedal PDF library, its built in and documented with eample source at <https://support.idrsolutions.com/hc/en-us/articles/115001978091-Convert-PDF-Files-to-Image> | Export PDF pages to a series of images in Java | [
"",
"java",
"image",
"pdf",
"export",
""
] |
When debugging C/C++ (unmanaged?) code in VS, after stepping out of a function, you can see the returned value in the 'autos' window:
[alt text http://img156.imageshack.us/img156/6082/cpp.jpg](http://img156.imageshack.us/img156/6082/cpp.jpg)
However, this does not work for C# code:
[alt text http://img120.imageshack.us/img120/9350/38617355.jpg](http://img120.imageshack.us/img120/9350/38617355.jpg)
Any suggestion on how to get the return value other than cluttering the code with temporary variables? | It is actually visible. Debug + Other Windows + Registers. Look at the value of EAX (RAX in x64). The value of simple integral types are returned in the EAX register. Long in EDX:EAX. Floating point in STx (XMM00 in x64).
---
This has been hard to implement, the jitter determines how methods return a value and different jitters will make different choices. Particularly so when the return value type isn't simple, like a struct. If it is large then the jitter will reserve stack space on the calling method and pass a pointer to that space so the called method can copy the return value there. Nevertheless, VS2013 [finally made it available](https://web.archive.org/web/20160111075417/http://blogs.msdn.com:80/b/visualstudioalm/archive/2013/06/27/seeing-function-return-values-in-the-debugger-in-visual-studio-2013.aspx), currently available in preview. Visible in the Autos window and by using the `$ReturnValue` intrinsic variable in the Immediate window and watch expressions. | Unfortunately cluttering your code with temporary variables in the only way in managed code (C# or VB). The CLR has no support for "managed return values" in the debugger and hence VS does not either.
In C++ this feature is a bit simpler. C++ can just grab the register or stack location of the last return value. It doesn't have to deal with issues like a JITer and garbage collection. Both of which greatly complicate a feature such as this.
If you'd like this feature I **strongly** encourage you to file a feature request or vote for an existing one on connect
<https://connect.microsoft.com/VisualStudio> | VS get returned value in C# code? | [
"",
"c#",
"visual-studio",
"debugging",
""
] |
I have the following array, which I would like to reindex so the keys are reversed (ideally starting at 1):
Current array (**edit:** the array actually looks like this):
```
Array (
[2] => Object
(
[title] => Section
[linked] => 1
)
[1] => Object
(
[title] => Sub-Section
[linked] => 1
)
[0] => Object
(
[title] => Sub-Sub-Section
[linked] =>
)
)
```
How it should be:
```
Array (
[1] => Object
(
[title] => Section
[linked] => 1
)
[2] => Object
(
[title] => Sub-Section
[linked] => 1
)
[3] => Object
(
[title] => Sub-Sub-Section
[linked] =>
)
)
``` | If you want to re-index starting to zero, simply do the following:
```
$iZero = array_values($arr);
```
If you need it to start at one, then use the following:
```
$iOne = array_combine(range(1, count($arr)), array_values($arr));
```
Here are the manual pages for the functions used:
* [`array_values()`](https://www.php.net/manual/en/function.array-values.php)
* [`array_combine()`](https://www.php.net/manual/en/function.array-combine.php)
* [`range()`](https://www.php.net/manual/en/function.range.php) | Why reindexing? Just add 1 to the index:
```
foreach ($array as $key => $val) {
echo $key + 1, '<br>';
}
```
---
**Edit** After the question has been clarified: You could use the `array_values` to reset the index starting at 0. Then you could use the algorithm above if you just want printed elements to start at 1. | How do you reindex an array in PHP but with indexes starting from 1? | [
"",
"php",
"arrays",
"indexing",
""
] |
I want to extract
```
FROM codes WHERE FieldName='ContactMethod' and IsNull(Deactived,'') != 'T'
```
from
```
SELECT FieldDescription,FieldValue FROM codes WHERE FieldName='ContactMethod'
and IsNull(Deactived,'') != 'T' order by fielddescription
```
using a regular expression. I have a regex like this:
```
\FROM.*\order
```
which extracts
```
FROM codes WHERE FieldName='ContactMethod' and IsNull(Deactived,'') != 'T' order
```
Also, how can I get rid of the capitalization? | The trick here would probably be to capture the part you actually want with parens:
```
(FROM.*) order
```
This would greedily match until the last `order`, if you want only until the first occurrence, match lazily:
```
(FROM.*?) order
``` | Expanding on Fabian Steeg's answer
```
Dim regex As Regex = New Regex( _
"(FROM.*?) ORDER", _
RegexOptions.IgnoreCase _
Or RegexOptions.CultureInvariant _
Or RegexOptions.IgnorePatternWhitespace _
Or RegexOptions.Compiled _
)
Dim ms As MatchCollection = regex.Matches(InputText)
```
where InputText is of course your SQL query string.
ms(1) should hold the parentheses match | How to create a regular expression to parse my SQL statement | [
"",
"sql",
"vb.net",
"regex",
"text-parsing",
""
] |
The API for the Java [Set](http://java.sun.com/javase/6/docs/api/java/util/Set.html) interface states:
> For example, some implementations prohibit `null` elements and some have restrictions on the types of their elements
I am looking for a basic Set implementation that does not require ordering (as [ArrayList](http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html) provides for the [List](http://java.sun.com/javase/6/docs/api/java/util/List.html) interface) and that does not permit `null`. [TreeSet](http://java.sun.com/javase/6/docs/api/java/util/TreeSet.html), [HashSet](http://java.sun.com/javase/6/docs/api/java/util/HashSet.html), and [LinkedHashSet](http://java.sun.com/javase/6/docs/api/java/util/LinkedHashSet.html) all allow null elements. Additionally, TreeSet has the requirement that elements implement [Comparable](http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html).
It seems that no such basic `Set` exists currently. Does anyone know why? Or if one does exist where I can find it?
[Edit]: I do not want to allow `null`s, because later in the code my class will iterate over all elements in the collection and call a specific method. (I'm actually using `HashSet<MyRandomObject`>). I would rather fail fast than fail later or accidentally incur some bizarre behavior due to a `null` being in the set. | Better than extending a particular implementation, you can easily write a proxy implementation of `Set` that checks for `null`s. This analogous to `Collections.checkedSet`. Other than being applicable to any implementation, you can also be sure that you have overridden all applicable methods. Many flaws have been found by extending concrete collections which then have additional methods added in later versions. | I would say use composition instead of inheritance... it might be more work but it'll be more stable in the face of any changes that Sun might make to the Collections Framework.
```
public class NoNullSet<E> implements Set<E>
{
/** The set that is wrapped. */
final private Set<E> wrappedSet = new HashSet<E>();
public boolean add(E e)
{
if (e == null)
throw new IllegalArgumentException("You cannot add null to a NoNullSet");
return wrappedSet.add(e);
}
public boolean addAll(Collection<? extends E> c)
{
for (E e : c) add(e);
}
public void clear()
{ wrappedSet.clear(); }
public boolean contains(Object o)
{ return wrappedSet.contains(o); }
... wrap the rest of them ...
}
```
Note that this implementation does not depend on `addAll` calling `add` (which is an implementation detail and should not be used because it cannot be guaranteed to remain true in all Java releases). | Is there a basic Java Set implementation that does not permit nulls? | [
"",
"java",
"api",
"null",
"set",
""
] |
I have a field on a form that takes the following values: -1, 2-10, 99
I have a business rule that's concerned with answers 2-10.
I'm trying to write a regular expression that will match 2-10 but *not* 99, and I'm having trouble.
The original expression:
```
^2|3|4|5|6|7|8|9|10$
```
Fails because 99 is matched (technically, twice). Also, the Line boundries are something I've never been comfortable with. I oberve different behavior from them in expresso than I do in other places (e.g. .net). In this particular instance, the regex is being run in **javascript**. Anyway, expresso seems to ignore them (and if I put the values in brackets:
```
^[2|3|4|5|6|7|8|9|10]$
^[2-9]$
```
either "all spelled out" or as a range, expresso never returns any matches if I specify the opening line/string closing line/string characters (and yes, I was trying to match the 10 separately in the second case there).
I know, I know. If you use a regex to solve a problem, then you have two problems (and presumably they'll start inviting friends over, thing 1 and thing 2 style). I don't **have** to use one here; I may switch to a case statement. But it seems like I should be able to use a regex here, and it seems a reasonable thing to do. I'm still pretty green when it comes to the regex; | You need parantheses for that. I would further use ranges to keep things readable:
```
^([2-9]|10)$
``` | This is clearly a case where you shouldn't use RegExp but numerical evaluation:
```
var num = parseInt(aNumber, 10);
if (num >= 2 && num <= 10) {
alert("Match found!");
}
``` | Regex to match 2-10, but not 99 | [
"",
"javascript",
"regex",
"numeric-ranges",
""
] |
I have the following statement:
```
btnApply.Attributes.Add("onclick", "alert('Must be a member to Use this Tool')");
```
Is there a way to add a new line. I tried, but it showed the in the text. In addition, can I add a link that would close the alert and take the user to another page?
How can I do this with my example?
When I added the \n, the alert doesn't show up. | You can't use HTML, but you can add line breaks:
```
alert('line1\nline2');
```
If a rich modal popup is really what you want though, you can use [jQuery's dialog](http://docs.jquery.com/UI/Dialog) feature and put whatever you want in there. | Use \\n (needs two slashes).
You'll notice that before doing this the alert will not post even a javascript error. \n will not work because the slash needs to be escaped. | Can I add a <br/> and links to a javascript alert? | [
"",
"javascript",
""
] |
I'm wondering what the common project/application structure is when the user model extended/sub-classed and this Resulting User model is shared and used across multiple apps.
I'd like to reference the same user model in multiple apps.
I haven't built the login interface yet, so I'm not sure how it should fit together.
The following comes to mind:
```
project.loginapp.app1
project.loginapp.app2
```
Is there a common pattern for this situation?
Would login best be handled by a 'login app'?
Similar to this question but more specific.
[django application configuration](https://stackoverflow.com/questions/464010/django-application-configuration)
**UPDATE**
Clarified my use-case above.
I'd like to add fields (extend or subclass?) to the existing auth user model. And then reference that model in multiple apps. | Why are you extending User? Please clarify.
If you're adding more information about the users, you don't need to roll your own user and auth system. Django's version of that is quite solid. The user management is located in django.contrib.auth.
If you need to customize the information stored with users, first define a model such as
```
class Profile(models.Model):
...
user = models.ForeignKey("django.contrib.auth.models.User", unique=True)
```
and then set
```
AUTH_PROFILE_MODULE = "appname.profile"
```
in your settings.py
The advantage of setting this allows you to use code like this in your views:
```
def my_view(request):
profile = request.user.get_profile()
etc...
```
If you're trying to provide more ways for users to authenticate, you can add an auth backend. Extend or re-implement django.contrib.auth.backends.ModelBackend and set it as
your AUTHENTICATION\_BACKENDS in settings.py.
If you want to make use of a different permissions or groups concept than is provided by django, there's nothing that will stop you. Django makes use of those two concepts only in django.contrib.admin (That I know of), and you are free to use some other concept for those topics as you see fit. | You should check first if the contrib.auth module satisfies your needs, so you don't have to reinvent the wheel:
<http://docs.djangoproject.com/en/dev/topics/auth/#topics-auth>
edit:
Check this snippet that creates a UserProfile after the creation of a new User.
```
def create_user_profile_handler(sender, instance, created, **kwargs):
if not created: return
user_profile = UserProfile.objects.create(user=instance)
user_profile.save()
post_save.connect(create_user_profile_handler, sender=User)
``` | Django Project structure, recommended structure to share an extended auth "User" model across apps? | [
"",
"python",
"django",
"django-models",
"django-project-architect",
""
] |
I have two classes:
```
class Foo
{
public Bar SomeBar { get; set; }
}
class Bar
{
public string Name { get; set; }
}
```
I have a list of Foos that I group together:
```
var someGroup = from f in fooList
orderby f.SomeBar.Name ascending
group f by f.SomeBar.Name into Group
select Group;
```
How can I get the list of the distinct Bars from someGroup? | Will there potentially be more than one Bar with the same name? If so, it's tricky. If not, you could just change it to:
```
var grouped = from f in fooList
orderby f.SomeBar.Name ascending
group f by f.SomeBar into Group
select Group;
var bars = grouped.Select(group => group.Key);
```
Alternatively, if you only want one Bar per *name*, you could stick with your original query, but change the last bit:
```
var someGroup = from f in fooList
orderby f.SomeBar.Name ascending
group f by f.SomeBar.Name into Group
select Group;
var bars = someGroup.Select(group => group.First().SomeBar);
```
This will take the first Foo in each group, and find its Bar. | If you define "being distinct" by a special `Equals` implementation for `Bar`, you could use:
```
var result = someGroup.SelectMany(x => x.Select(t => t.SomeBar)).Distinct();
``` | C# Select Distinct Values from IGrouping | [
"",
"c#",
"lambda",
""
] |
In a Visual Studio, you would use `Ctrl`+`L`, whereas in Eclipse I am forced to select a line or, if it is empty, go the beginning of the line before clicking delete/backspace.
Is there a quick shortcut? Thanks! | `Ctrl` + `D`
From **Help**->**Key Assist**... there are all kinds of useful keyboard shortcuts for Eclipse.
For Mac users: `⌘` + `D` | In the future, if you need to quickly find a keyboard shortcut for something simple, just hit `Ctrl`+`Shift`+`L`. | Delete a line in Eclipse | [
"",
"java",
"eclipse",
""
] |
```
Interface IView
{
List<string> Names {get; set;}
}
public class Presenter
{
public List<string> GetNames(IView view)
{
return view.Names;
}
}
var mockView = MockRepository.GenerateMock<IView>();
var presenter = new Presenter();
var names = new List<string> {"Test", "Test1"};
mockView.Expect(v => v.Names).Return(names);
Assert.AreEqual(names, presenter.GetNames(mockView)) // Here presenter returns null which is incorrect behaviour in my case;
```
When I use the above code to return the mock list of names ,it doesn't match the expecatation then returns null and fails
thanks for your help
Edit:
I am passing the view as the paramter to presenter's GetNames method.Here the problem is when i return list object from the mocked property it returns null. However when i change the property data type to string/int i.e.premitive type then value is returned correctly | Thanks for your help, after investigating I found that I was creating a new list object inside the presenter with the same content of view list object, and because of this it was failing.
Now I used the property constraints to match the parameters in expectation and it worked!!
Thanks all | I don't see anywhere where your mockView is getting attached to your presenter. So from the presenter's point of view, the view is null. You might have to do something like:
```
presenter.View = view;
```
---
I just coded this with NUnit and RhinoMocks 3.5 to make sure it works. Here's my two class files. The test passed.
```
using System.Collections.Generic;
namespace Tests
{
public interface IView
{
List<string> Names { get; set; }
}
public class Presenter
{
public List<string> GetNames(IView view)
{
return view.Names;
}
}
}
using System.Collections.Generic;
using NUnit.Framework;
using Rhino.Mocks;
namespace Tests
{
[TestFixture]
public class TestFixture
{
[Test]
public void TestForStackOverflow()
{
var mockView = MockRepository.GenerateMock<IView>();
var presenter = new Presenter();
var names = new List<string> {"Test", "Test1"};
mockView.Expect(v => v.Names).Return(names);
Assert.AreEqual(names, presenter.GetNames(mockView));
}
}
}
```
I can only guess you are doing something wrong with the way you've mixed up your code. | How to mock the property which returns the list object - In rhino mock | [
"",
"c#",
"mocking",
"rhino-mocks",
""
] |
Is there a simple way to convert a date stored in a varchar in the format mon-yy (e.g. "Feb-09") to a datetime which will convert any invalid values to null.
I'm currently using string manipulation combined with a case statement but it's rather cumbersome. | For valid values you can just put a day on it and it's a complete date:
```
convert(datetime,'01-' + 'Feb-09',120)
``` | This will do it.
```
SELECT convert(datetime,'01-' + 'Feb-09',120)
``` | Convert varchar in format mon-yy to datetime in SQL server | [
"",
"sql",
"sql-server",
"sql-server-2005",
"datetime",
""
] |
Does XNA provide a means of audio input from the line-in? I looked at the [MSDNA website](http://msdn.microsoft.com/en-us/library/bb195038.aspx) but can't find anything on audio *input*. If it is indeed possible, a snippet of code or a tutorial website would be great.
Edit:
I need to do buffered reads from the audio-line in. I'm not so much interested in the implementation but rather if it has low latency.
Also development will be implemented into a PC only game. | If you're looking at doing a Windows only project, you could certainly capture the audio coming in with code from outside the XNA framework and play it back with the same. Because of how the XNA content manager works, you wouldn't be able to use the regular playback methods because the content manager translates everything into .xnb files at compile time and reads them from there. Nothing keeping you from playing using standard windows API calls though. You wouldn't really have an XNA project at that point, but I don't suppose the distinction is all that important since you're not looking to be compatible with the other platforms anyway. | I think all sound files need to be compiled by XACT before they can be used in XNA.
So either you get hold of DirectSound and look at the sample in:
\Samples\Managed\DirectSound\CaptureSound
...or you could interop with winmm.dll. This guy has made a small example of how to do it:
<http://www.codeproject.com/KB/audio-video/cswavrec.aspx>
And this guy writes some more about enumerating all sound recording devices:
<http://www.codeproject.com/KB/cs/Enum_Recording_Devices.aspx>
Hope it helps!
Edit:
I'm not sure what you want to do with your audio stream so this tutorial might be of interest as well:
<http://nyxtom.vox.com/library/post/recording-audio-in-c.html>
Edit 2:
What he said (in the comment)
```
|
|
V
``` | Does XNA provide audio input (line in)? | [
"",
"c#",
"xna",
""
] |
Is there any way of writing a decorator such that the following would work?
```
assert 'z' not in globals()
@my_decorator
def func(x, y):
print z
```
---
EDIT: moved from anwser
In answer to hop's "why?": syntax sugar / DRY.
It's not about caching, it's about calculating z (and z1, z2, z3, ...) based upon the values of x & y.
I have lots of functions which do related things, and I don't want to do have to write
```
z1, z2, z3=calculate_from(x, y)
```
at the beginning of every single function - I'll get it wrong somewhere. If this were c I'd do this with cpp (if this were lisp, I'd do this with macros ...), but I wanted to see if decorators could do the same thing.
If it helps, I'd almost certainly call the decorator "precalculate\_z", and it certainly wouldn't be part of any public API.
I could probably get a similar effect from using the class infrastructure as well, but I wanted to see if it was doable with raw functions. | Echoing Hop's answer
1. Don't do it.
2. Seriously, don't do this. Lisp and Ruby are more appropriate languages for writing your own custom syntax. Use one of those. Or find a cleaner way to do this
3. If you must, you want dynamic scoped variables, not lexically scoped.
Python doesn't have dynamically scoped variables, but you can simulate it. Here's an example that simulates it by creating a global binding, but restores the previous value on exit:
[http://codepad.org/6vAY8Leh](http://codepad.org/6vAY8Leh "dynamic scope in python")
```
def adds_dynamic_z_decorator(f):
def replacement(*arg,**karg):
# create a new 'z' binding in globals, saving previous
if 'z' in globals():
oldZ = (globals()['z'],)
else:
oldZ = None
try:
globals()['z'] = None
#invoke the original function
res = f(*arg, **karg)
finally:
#restore any old bindings
if oldZ:
globals()['z'] = oldZ[0]
else:
del(globals()['z'])
return res
return replacement
@adds_dynamic_z_decorator
def func(x,y):
print z
def other_recurse(x):
global z
print 'x=%s, z=%s' %(x,z)
recurse(x+1)
print 'x=%s, z=%s' %(x,z)
@adds_dynamic_z_decorator
def recurse(x=0):
global z
z = x
if x < 3:
other_recurse(x)
print 'calling func(1,2)'
func(1,2)
print 'calling recurse()'
recurse()
```
I make no warranties on the utility or sanity of the above code. Actually, I warrant that it *is* insane, and you should avoid using it unless you want a flogging from your Python peers.
This code is similar to both eduffy's and John Montgomery's code, but ensures that 'z' is created and properly restored "like" a local variable would be -- for instance, note how 'other\_recurse' is able to see the binding for 'z' specified in the body of 'recurse'. | I don't know about the local scope, but you could provide an alternative global name space temporarily. Something like:
```
import types
def my_decorator(fn):
def decorated(*args,**kw):
my_globals={}
my_globals.update(globals())
my_globals['z']='value of z'
call_fn=types.FunctionType(fn.func_code,my_globals)
return call_fn(*args,**kw)
return decorated
@my_decorator
def func(x, y):
print z
func(0,1)
```
Which should print "value of z" | Can I use a decorator to mutate the local scope of a function in Python? | [
"",
"python",
"decorator",
""
] |
```
string webPath = folderPath.Replace("\", "/");
```
Hi, I'm trying to replace the above but struggling.
Will I need an apply an escape sequence to /.
If so anyone know what it is in c#.
Any help/hints much appreciated. | ```
string webPath = folderPath.Replace(@"\", "/");
``` | ```
string webPath = folderPath.Replace("\\", "/");
```
... would also work. | string webPath = folderPath.Replace("\\", "/"); | [
"",
"c#",
".net",
""
] |
In C++ you can often drastically improve the readability of your code by careful usage of the "using" keyword, for example:
```
void foo()
{
std::vector< std::map <int, std::string> > crazyVector;
std::cout << crazyVector[0].begin()->first;
}
```
becomes
```
void foo()
{
using namespace std; // limited in scope to foo
vector< map <int, string> > crazyVector;
cout << crazyVector[0].begin()->first;
}
```
Does something similar exist for python, or do I have to fully qualify everything?
I'll add the disclaimer that I know that using has its pitfalls and it should be appropriately limited in scope. | As Bill said, Python does have the construction
```
from X import *
```
but you can also explicitly specify which names you want imported from the module (namespace):
```
from X import foo, bar, blah
```
This tends to make the code even more readable/easier to understand, since someone seeing an identifier in the source doesn't need to hunt through all imported modules to see where it comes from. Here's a related question: [Namespace Specification In Absence of Ambuguity](https://stackoverflow.com/questions/539578/namespace-specification-in-absence-of-ambuguity)
*EDIT*: in response to Pax's comment, I'll mention that you can also write things like
```
import X.foo
```
but then you'll need to write
```
X.foo.moo()
```
instead of just
```
foo.moo()
```
This is not necessarily a bad thing, of course. I usually use a mixture of the `from X import y` and `import X.y` forms, whatever I feel makes my code clearest. It's certainly a subjective thing to some extent. | Sure, python's dynamism makes this trivial. If you had a class buried deep in a namespace: foo.bar.baz.blah, you can do:
```
def foo:
f = foo.bar.baz.blah
f1 = f()
``` | Does python have something like C++'s using keyword? | [
"",
"python",
"namespaces",
"using",
""
] |
long time ago I wrote webservice that is still in use. Now I plan to refactor it. The webservice is full of most likely unused functions and I have no idea how it is used by the clients. In order to strip away the unused functions I need to analyze the function calls and data of currently installed webservice.
Is there a (free/opensource) tool that will enable me to log all activities of the webservice.
The ideal output of the tool I'm looking for could be a database containing all the called functions and a list of the data that was send to it for each call.
### Solution
With the help of Martins answer I created this HttpModule which does exactly what I wanted:
```
public class LoggingModule : IHttpModule
{
void IHttpModule.Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(BeginRequest);
}
private void BeginRequest(object sender, EventArgs e)
{
TryAppendLog("Content-Type");
TryAppendLog("SOAPAction");
}
void TryAppendLog(string key)
{
string value = HttpContext.Current.Request.Headers[key];
if (string.IsNullOrEmpty(value)) { return; }
HttpContext.Current.Response
.AppendToLog(string.Format("{0}: {1} ", key, value));
}
#region IHttpModule Member
public void Dispose() { }
#endregion
}
``` | As Kobi wrote, you can find the required information in the IIS log files (i.e. in c:\WINDOWS\system32\LogFiles\W3SVC1).
If you want to log the usage into a database, you could write a simple HttpModule, which checks every request, and logs it into the DB if it is a call to your web service.
E.g. here's the relevant parts of a very simple HttpModule, which logs calls to mywebservice.asmx:
```
public class MyWebServiceDiagnosticsModule : IHttpModule
{
public MyWebServiceDiagnosticsModule ()
{
}
void IHttpModule.Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(BeginRequest);
}
private void BeginRequest(object sender, EventArgs e)
{
HttpContext ctx = HttpContext.Current;
string url = ctx.Request.Url.ToString().ToLower();
if (url.Contains("mywebservice.asmx"))
{
LogMethodCall(url); // parse URL and write to DB
}
}
}
``` | You can potentially write your own IHttpHandler that would log all the information and then delegate the call to appropriate .NET HTTP Handler, but that wouldn't be a simple task.
And a word on terminology. "Refactoring" is not about changing external behavior, so if refactoring is really what you're heading for, I'd recommend to keep the public contract (interface) of the web service intact. Instead, roll out a new version of the same service with only core functionality. | Analyze the use of a ASP.NET webservice | [
"",
"c#",
".net",
"web-services",
""
] |
Is there an easy way to be inside a python function and get a list of the parameter names?
For example:
```
def func(a,b,c):
print magic_that_does_what_I_want()
>>> func()
['a','b','c']
```
Thanks | Well we don't actually need `inspect` here.
```
>>> func = lambda x, y: (x, y)
>>>
>>> func.__code__.co_argcount
2
>>> func.__code__.co_varnames
('x', 'y')
>>>
>>> def func2(x,y=3):
... print(func2.__code__.co_varnames)
... pass # Other things
...
>>> func2(3,3)
('x', 'y')
>>>
>>> func2.__defaults__
(3,)
``` | [`locals()`](https://docs.python.org/library/functions.html#locals) returns a dictionary with local names:
```
def func(a, b, c):
print(locals().keys())
```
prints the list of parameters. If you use other local variables those will be included in this list. But you could make a copy at the beginning of your function. | Getting list of parameter names inside python function | [
"",
"python",
"parameters",
""
] |
Is there any way I can use a visual editor to make swing applications in Eclipse? I'm using Ganymede. | I use [Jigloo](http://www.cloudgarden.com/jigloo/index.html) a fair bit and it is quite good. Can generate GUIs for both Swing and SWT. Free for non-commercial use, and pretty affordable at $US85 per developer for commercial use. Works fine with 3.4 (Ganymede). | Your options are:
1. [WindowBuilder Pro](http://www.eclipse.org/windowbuilder/) (eclipse.org): "WindowBuilder is a powerful and easy to use bi-directional Java GUI designer", see also [WindowBuilder Pro on code.google.com](http://code.google.com/javadevtools/wbpro/index.html).
2. [Visual Swing for Eclipse](http://code.google.com/p/visualswing4eclipse/) - an editor that works directly with the .java source files. Notes:
1. The update url on the front page is wrong ([issue 115](http://code.google.com/p/visualswing4eclipse/issues/detail?id=115)), should instead be: `http://visualswing4eclipse.googlecode.com/svn/trunk/vs4e/`
2. You have to untick "Group items by category" to be able to see the install.
3. The [original announcement of visual swing for eclipse](http://eclipse.dzone.com/announcements/visual-swing-designer-eclipse).
4. Crashed for me when opening a netbeans-generated swing file.
3. [Visual Editor from ehecht.com](http://www.ehecht.com/eclipse_ve/ve.html) - someone's own version, last updated 2010-08-29: "prelininary [sic] eclipse 3.6 (helios) version" (direct download: [ve\_eclipse\_36\_win32\_201008292115.zip](http://www.ehecht.com/eclipse_ve/ve_eclipse_36_win32_201008292115.zip)) *"These files are non official builds. So you use it on [sic] your own risk."*
4. Use [NetBeans](http://netbeans.org/) instead
1. Built-in GUI editor
2. Uses an xml file as the source for gui design, performing a one-way conversion
3. Adds its own libraries to your project to support GUI creation.
5. [Jigloo SWT/Swing GUI Builder for Eclipse and WebSphere](http://www.cloudgarden.com/jigloo/index.html) - *Note: Jigloo is free for non-commercial use, but purchase of a Professional License is required for commercial use (after successfully evaluating Jigloo).*
---
Options no longer viable / available:
* Official "Visual Editor", [archived by eclipse](http://www.eclipse.org/archived/): (Archived: June 2011), the matching install instructions at <http://wiki.eclipse.org/VE/Update>, and the outdated article / tutorial at <http://www.eclipse.org/articles/Article-VE-Custom-Widget/customwidget.html>, see also [Is eclipse visual editor dead?](https://stackoverflow.com/questions/319242/is-eclipse-visual-editor-dead)
---
This is a summary of all the other answers to this question as it took me a while to make sense of them. | Visual swing in Eclipse | [
"",
"java",
"eclipse",
"swing",
""
] |
Do you know a tool that automatically refactors a method with a single loop into a recursive method, preferably in Java?
This is for teaching purposes. | I don't think such a tool exists, since usually refactoring aims at increasing performance, not decreasing it (which is the case when using recursive methods instead of loops). If it is for teaching purposes, why not make the students create the tool that would do that? This way, they could learn at the same time recursion and parsing.
I don't know if the recursification can be automated, but here's what the transformation should look like. Let's take a generic for loop, in pseudo-code, for the sake of demonstration:
```
loopFunc() // method (could return a value or not)
{
for (initialization ; // Sets the context
test ; // Test continuation wrt the context
counting_exp // Update the context after each iteration
)
{
loop_body
}
}
```
The loop is composed of four parts: `initialization`, which initialize the context (usually variables); `test`, which is a boolean expression that checks wheter or not the loop is finished; `counting_exp`, which is a statement that is performed after each iteration; and finally, `loop_body`, that represents the operations that are executed at each iteration.
A recursive version of this method should be decomposed in two parts: one for initialization, and the other one to actually perform the loop:
```
recFunc()
{
initialization // Sets the context
innerRecFunc(context) // We need to pass the context to the inner function
}
innerRecFunc(context)
{
if not test then return // could return a value
else
{
loop_body // Can update context
counting_exp // Can update context
innerRecFunc(context) // Recursive call (note tail-recursion)
}
}
```
I didn't think about the problem enough to be 100% sure that this would work in all cases, but for simple loops this should be correct. Of course, this transformation can easily be adapted to other types of loops (while, do while). | I'm not entirely sure that this is even possible in the generic sense, as it seems to me like a variation of [the halting problem](http://en.wikipedia.org/wiki/Halting_problem). | Automatically refactor a loop into a recursive method? | [
"",
"java",
"refactoring",
"recursion",
"loops",
""
] |
I want to compute a checksum of all of the values of a column in aggregate.
In other words, I want to do some equivalent of
```
md5(group_concat(some_column))
```
The problem with this approach is:
1. It's inefficient. It has to concat all of the values of the column as a string in some temporary storage before passing it to the md5 function
2. group\_concat has a max length of 1024, after which everything else will be truncated.
(In case you're wondering, you can ensure that the concat of the values is in a consistent order, however, as believe it or not group\_concat() accepts an order by clause within it, e.g. `group_concat(some_column order by some_column)`)
MySQL offers the nonstandard bitwise aggregate functions BIT\_AND(), BIT\_OR() and BIT\_XOR() which I presume would be useful for this problem. The column is numeric in this case but I would be interested to know if there was a way to do it with string columns.
For this particular application, the checksum does not have to be cryptologically safe. | It seems like you might as well use `crc32` instead of `md5` if you don't care about cryptographic strength. I think this:
```
select sum(crc32(some_column)) from some_table;
```
would work on strings. It might be inefficient as perhaps MySQL would create a temporary table (especially if you added an `order by`). | The following query is used in Percona's Mysql Table Checksumming tool. Its a little tough to understand, but essentially it `CRC32`s the column (or a bunch of columns concatted) for every row, then `XOR`s them all together using the `BIT_XOR` group function. If one crc hash is different, the result of `XOR`ing everything will also be different. This happens in fixed memory, so you can checksum arbitrarily large tables.
`SELECT CONV(BIT_XOR(CAST(CRC32(column) AS UNSIGNED)), 10, 16)`
One thing to keep in mind though that this does not prevent possible collisions, and `CRC32` is a pretty weak function by today's standards. A nicer hashing function would be something like the `FNV_64`. It would be very unlikely to have two hashes which complement each other when `XOR`ed together. | Create an aggregate checksum of a column | [
"",
"sql",
"mysql",
"checksum",
""
] |
I know this question sounds rather vague so I will make it more clear with an example:
```
$var = 'bar';
$bar = new {$var}Class('var for __construct()'); //$bar = new barClass('var for __construct()');
```
This is what I want to do. How would you do it? I could off course use eval() like this:
```
$var = 'bar';
eval('$bar = new '.$var.'Class(\'var for __construct()\');');
```
But I'd rather stay away from eval(). Is there any way to do this without eval()? | Put the classname into a variable first:
```
$classname=$var.'Class';
$bar=new $classname("xyz");
```
This is often the sort of thing you'll see wrapped up in a Factory pattern.
See [Namespaces and dynamic language features](http://php.net/manual/en/language.namespaces.dynamic.php) for further details. | # If You Use Namespaces
In my own findings, I think it's good to mention that you (as far as I can tell) must declare the full namespace path of a class.
MyClass.php
```
namespace com\company\lib;
class MyClass {
}
```
index.php
```
namespace com\company\lib;
//Works fine
$i = new MyClass();
$cname = 'MyClass';
//Errors
//$i = new $cname;
//Works fine
$cname = "com\\company\\lib\\".$cname;
$i = new $cname;
``` | instantiate a class from a variable in PHP? | [
"",
"php",
"class",
"variables",
"eval",
""
] |
Hey all, I am trying to test if the argument passed into my function is a class name so that I may compare it to other classes using instanceof.
For example:
```
function foo(class1, class2) {
// Test to see if the parameter is a class.
if(class1 is a class)
{
//do some kind of class comparison.
if(class2 is a class)
{
if(class1 instanceof class2)
{
//...
}
}
else
{
//...
}
}
else
//...
}
```
Is this possible? I am having trouble googleing an answer. | There is really no such thing as a "class" in javascript -- everything but primitives are an object. Even functions are objects.
instanceof DOES work with functions though. Check out this [link](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/instanceof_Operator).
```
function Car(make, model, year)
{
this.make = make;
this.model = model;
this.year = year;
}
var mycar = new Car("Honda", "Accord", 1998);
var a = mycar instanceof Car; // returns true
var b = mycar instanceof Object; // returns true
``` | **Now that we have native implementations of ES6**, there are "real classes". These are largely syntactic sugar for prototypal inheritance as with constructor functions, but there are subtle differences and the two are not completely interchangeable.
So far, the only way I've found is to get the `.toString()` of the object's prototype's constructor function and check if it starts with `class` OR if the object has a constructor and the `.toString()` of *that* starts with `class`.
Note that if your code is compiled (ie: most Babel or TypeScript setups), then this will return `function...` instead of `class...` at runtime (since classes are transpiled to constructor functions).
```
function isClass(obj) {
const isCtorClass = obj.constructor
&& obj.constructor.toString().substring(0, 5) === 'class'
if(obj.prototype === undefined) {
return isCtorClass
}
const isPrototypeCtorClass = obj.prototype.constructor
&& obj.prototype.constructor.toString
&& obj.prototype.constructor.toString().substring(0, 5) === 'class'
return isCtorClass || isPrototypeCtorClass
}
```
This will only work in native environments (Chrome, Firefox, Edge, node.js, etc.) that have implemented `class` for code that has not been transpiled to `function`.
Usage:
```
class A {}
class B extends A {}
isClass(A) // true
isClass(new A()) // true
isClass(B) // true
isClass(new B()) // true
function C() {}
isClass(C) // false
isClass(new C()) // false
isClass({}) // false
isClass(Date) // false
isClass(new Date()) // false
//These cases return 'true' but I'm not sure it's desired
isClass(Object.create(A)) // true
const x = {}
Object.setPrototypeOf(x, A)
isClass(x) // true
```
If there is a better way, I'd love to know what it is. | Testing if something is a class in javascript | [
"",
"javascript",
""
] |
I'm working on a regression-testing tool that will validate a very large number of Excel spreadsheets. At the moment I control them via COM from a Python script using the latest version of the pywin32 product. Unfortunately COM seems to have a number of annoying drawbacks:
For example, the slightest upset seems to be able to break the connection to the COM-Server, once severed there seems to be no safe way to re-connect to the Excel application. There's absolutely no safety built into the COM Application object.
The Excel COM interface will not allow me to safely remote-control two seperate instances of the Excel application operating on the same workbook file, even if they are read-only.
Also when something does go wrong I seldom get any useful error-messages... at best I can except a numerical error-code or a barely useful message such as "An Exception has occurred". It's almost impossible to know why something went wrong.
Finally, COM lacks the ability to control some of the most fundamental aspects of Excel? For example there's no way to do a guaranteed close of just the Excel process that a COM client is connected to. You cannot even use COM to find Excel's PID.
**So what if I were to completely abandon COM?** Is there an alternative way to control Excel?
All I want to do is run macros, open and close workbooks and read and write cell-ranges? Perhaps some .NET experts know a trick or two which have not yet bubbled into the Python community? What about you office-hackers? Could there be a better way to get at Excel's innards than COM? | There is no way that completely bypasses COM. You can use VSTO (Visual Studio Tools for Office), which has nice .NET wrappers on the COM objects, but it is still COM underneath. | > The Excel COM interface will not allow me to safely remote-control two seperate instances of the Excel application operating on the same workbook file, even if they are read-only.
This is not a limitation of COM, this is a [limitation of Excel](http://blogs.msdn.com/excel/archive/2009/01/07/why-can-t-i-open-two-files-with-the-same-name.aspx). Excel will not even let you open two files with the same name at the same time if they exist in different directories. It is a fundamental limitation of the Excel program.
To answer your other questions
If you check your python documentation, there should be a way to connect to an existing server if the connection is lost.
The lack of useful error messages again may be to do with Python.
> You cannot even use COM to find Excel's PID.
COM is an internal object model and exposed what it wishes. PID are available to outside processes as much as they are to internal, there is no real reason to expose as a COM interface. | Is there a better way (besides COM) to remote-control Excel? | [
"",
"python",
".net",
"excel",
"com",
""
] |
I have a string in C++ of type `const char*` passed as argument to strlen, but it returns void.
it goes like
```
strlen(astruct.string);
```
Thanks..
EDIT: Did some checking,
```
strlen("test");
```
still gives void.. why?
EDIT: Here's the image
<http://img14.imageshack.us/img14/1808/strlen.png>
Sorry for being unclear previously. Formatting was not working quite well. Anyway, the confusion was solved by both Evan Teran and Vlad Romascanu. Also take a look at Brian R. Bondy's answer.
Thanks. Feel free to close. | Referring to your screen shot: your debugger is displaying `<void>` for `strlen(...)` when in fact it should display an error.
You cannot call methods and display their results in the debugger watch. The debugger will only display existing variables and data. It cannot invoke arbitrary methods on demand since the methods can alter the state of the program being debugged in ways that were not anticipated by either the author of the code nor by the debugger.
What you can do is, in your code, temporarily add:
```
size_t tmp_len = strlen(struc.string);
```
then compile, and add tmp\_len to the watch. | You are confused by the crappy debugger of visual studio 6.0. Don't rely on this. It likely couldn't get the return value due to inlining or something similar.
Print the value out to get the real value.
EDIT: Also, from your example, it seems that you may not be storing the result of strlen anyway. This also may be a reason why the debugger isn't seeing the return value. It's entirely possible that the compiler decided that it doesn't need to actually execute the strlen if you aren't using the value.
NOTE: at this point there is no real excuse for **still** using VC++ 6.0. It is an ancient compiler and IDE which is an embarrassingly poor c++ compiler. The newer versions of the visual c++ compiler are free (without the IDE), use them. | Why does strlen() appear to return <void> in the VC++ debugger? | [
"",
"c++",
"string",
"visual-c++",
"visual-c++-6",
""
] |
> **Possible Duplicate:**
> [Cast int to enum in C#](https://stackoverflow.com/questions/29482/cast-int-to-enum-in-c-sharp)
If I have the following code:
```
enum foo : int
{
option1 = 1,
option2,
...
}
private foo convertIntToFoo(int value)
{
// Convert int to respective Foo value or throw exception
}
```
What would the conversion code look like? | It's fine just to cast your int to Foo:
```
int i = 1;
Foo f = (Foo)i;
```
If you try to cast a value that's not defined it will still work. The only harm that may come from this is in how you use the value later on.
If you really want to make sure your value is defined in the enum, you can use Enum.IsDefined:
```
int i = 1;
if (Enum.IsDefined(typeof(Foo), i))
{
Foo f = (Foo)i;
}
else
{
// Throw exception, etc.
}
```
However, using IsDefined costs more than just casting. Which you use depends on your implemenation. You might consider restricting user input, or handling a default case when you use the enum.
Also note that you don't have to specify that your enum inherits from int; this is the default behavior. | I'm pretty sure you can do explicit casting here.
```
foo f = (foo)value;
```
So long as you say the enum inherits(?) from int, which you have.
```
enum foo : int
```
**EDIT** Yes it turns out that by default, an enums underlying type is int. You can however use any integral type except char.
You can also cast from a value that's not in the enum, producing an invalid enum. I suspect this works by just changing the type of the reference and not actually changing the value in memory.
[enum (C# Reference)](http://msdn.microsoft.com/en-us/library/sbbt4032.aspx)
[Enumeration Types (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/cc138362.aspx) | C# int to enum conversion | [
"",
"c#",
"enums",
""
] |
I'm working on a site where a user could select certain dates that apply to them, e.g Date 1,Date 2, Date 3, etc.
Each date will have certain questions belonging to it, so if the customer checked off 'Date 1' to indicate that this date applies to him, he'll then see a bunch of textboxes asking him about Date 1 and how it applies to them. Same goes for all other dates.
Date 1 and 2 and several questions, but the remaining dates have just 1 question.
These dates and their answers will later be used to create personalized reminders for the customer and sent out to him.
I'd also like a design which makes it simple (or as simple as possible) to add additional dates and fields.
My question is, what's the best way to store all the dates and their answers related to the user in the database? I was thinking that in the `user` table, I have `boolean` columns from Date 1 - Last date (obviously they're not actually named date 1, date 2 etc). If the column for Date 1 is set to 0, it means the customer didn't check it off, and if its 1 then it means he did and he answered the questions for it.
Regarding the actual storage of the dates, I'm considering these two options:
**1)** 1 table for each date, with columns for every question asked for that date and a `user_id` column. So in `Date_1` table I'll have columns like `Q1_name`, `Q2_name` and the answers of the questions that the user gave.
But I want something more elegant because 1), it will make it a pain to fetch all the user's answers when calculating what info. applies to them when sending the personalized emails. 2) Some dates have only 1 question, so it'll be ugly to create a full-blown table for them.
**2)** A `user_answer` table, with the columns:
```
user_id,date_name,question_name,answer_val
```
2 seems the most elegant so far, but there should be a better solution. Any thoughts? | It sounds like you want something like the following (basic) table structure:
* **User** - `userId, userInfo`
* **Date** - `dateId, dateInfo`
* **Question** - `questionId, questionInfo`
* **UserDate** - `userId, dateId` - this stores all dates that apply for a given user and represents the many to many relationship between Users and Dates - a user can have many dates and a date can have many users
* **DateQuestion** - `dateId, questionId` - this stores all questions that apply for a given date and represents the many to many relationship between Dates and Questions - a date can have many questions and, I assume, a question can be used against more than one date
* **UserResponse** - `userId, questionId, questionResponse` - this stores all user responses to any questions asked. If you need to know which date the question applies to, assuming they can answer the same question more than once for multiple dates, add a `dateId` column. | Option 2 seems close to the good solution, but I'd replace `date_name` and `question_name` with `date_id` and `question_id`.
An optimal, and simplest solution that enables adding new questions and dates seems to be:
1. Dates table with the fields `date_id, title, date`.
2. Questions table with the fields `question_id, date_id, title` (and possibly type off the answer and description).
3. Answers table with `question_id` and `answer`.
You'll also need to decide whether or not you have questions that are common to several dates, and what to do in that case. (you may want two different answers, or a common answer). I'd recommend against the first solution, it'd make the question not dynamic - you'd have to change the sql and table structure for each change in the questions or dates. | Most elegant solution for humungous problem | [
"",
"php",
"mysql",
"database-design",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.