Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I need to determine the current year in Java as an integer. I could just use `java.util.Date()`, but it is deprecated.
|
For Java 8 onwards:
```
int year = Year.now().getValue();
```
For older version of Java:
```
int year = Calendar.getInstance().get(Calendar.YEAR);
```
|
Using Java 8's time API (assuming you are happy to get the year in your system's default time zone), you could use [the `Year::now` method](https://docs.oracle.com/javase/8/docs/api/java/time/Year.html#now--):
```
int year = Year.now().getValue();
```
|
Get integer value of the current year in Java
|
[
"",
"java",
"datetime",
"date",
""
] |
Not sure how to ask a followup on SO, but this is in reference to an earlier question:
[Fetch one row per account id from list](https://stackoverflow.com/questions/94930/fetch-one-row-per-account-id-from-list)
The query I'm working with is:
```
SELECT *
FROM scores s1
WHERE accountid NOT IN (SELECT accountid FROM scores s2 WHERE s1.score < s2.score)
ORDER BY score DESC
```
This selects the top scores, and limits results to one row per accountid; their top score.
The last hurdle is that this query is returning multiple rows for accountids that have multiple occurrences of their top score. So if accountid 17 has scores of 40, 75, 30, 75 the query returns both rows with scores of 75.
Can anyone modify this query (or provide a better one) to fix this case, and truly limit it to one row per account id?
Thanks again!
|
If you're only interested in the accountid and the score, then you can use the simple GROUP BY query given by Paul above.
```
SELECT accountid, MAX(score)
FROM scores
GROUP BY accountid;
```
If you need other attributes from the scores table, then you can get other attributes from the row with a query like the following:
```
SELECT s1.*
FROM scores AS s1
LEFT OUTER JOIN scores AS s2 ON (s1.accountid = s2.accountid
AND s1.score < s2.score)
WHERE s2.accountid IS NULL;
```
But this still gives multiple rows, in your example where a given accountid has two scores matching its maximum value. To further reduce the result set to a single row, for example the row with the latest gamedate, try this:
```
SELECT s1.*
FROM scores AS s1
LEFT OUTER JOIN scores AS s2 ON (s1.accountid = s2.accountid
AND s1.score < s2.score)
LEFT OUTER JOIN scores AS s3 ON (s1.accountid = s3.accountid
AND s1.score = s3.score AND s1.gamedate < s3.gamedate)
WHERE s2.accountid IS NULL
AND s3.accountid IS NULL;
```
|
```
select accountid, max(score) from scores group by accountid;
```
|
Fetch one row per account id from list, part 2
|
[
"",
"sql",
"mysql",
"database",
""
] |
I'd like to be able to do some drawing to the right of the menu bar, in the nonclient area of a window.
Is this possible, using C++ / MFC?
|
Charlie hit on the answer with `WM_NCPAINT`. If you're using MFC, the code would look something like this:
```
// in the message map
ON_WM_NCPAINT()
// ...
void CMainFrame::OnNcPaint()
{
// still want the menu to be drawn, so trigger default handler first
Default();
// get menu bar bounds
MENUBARINFO menuInfo = {sizeof(MENUBARINFO)};
if ( GetMenuBarInfo(OBJID_MENU, 0, &menuInfo) )
{
CRect windowBounds;
GetWindowRect(&windowBounds);
CRect menuBounds(menuInfo.rcBar);
menuBounds.OffsetRect(-windowBounds.TopLeft());
// horrible, horrible icon-drawing code. Don't use this. Seriously.
CWindowDC dc(this);
HICON appIcon = (HICON)::LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
::DrawIconEx(dc, menuBounds.right-18, menuBounds.top+2, appIcon, 0,0, 0, NULL, DI_NORMAL);
::DestroyIcon(appIcon);
}
}
```
|
In order to draw in the non-client area, you need to get the "window" DC (rather than "client" DC), and draw in the "window" DC.
|
How to draw in the nonclient area?
|
[
"",
"c++",
"mfc",
"drawing",
"nonclient",
""
] |
Obviously the [Java API](http://java.sun.com/j2se/1.5.0/docs/api/) reference, but what else is there that you all use?
I've been doing web development my entire career. Lately I've been messing around a lot with [Groovy](http://groovy.codehaus.org) and I've decided to do a small application in [Griffon](http://groovy.codehaus.org/griffon) just to experiment more with Groovy and also break some ground in desktop development. The only thing is I'm totally green when it comes to desktop apps.
So, world, where's a good place to start?
|
[The Swing Tutorial](http://java.sun.com/docs/books/tutorial/uiswing/) is very good. Apart from that, the Swing API is obviously *the* reference, however it's also a treasure trove of fairly good source code! Add the API source to your IDE and you can jump directly to the implementation to all the Swing classes. This is a great way to explore the functionality, see how various Swing components work and learn a good Swing "style". Furthermore, it's great to be able to step through the API classes if things don't seem to work and you have no idea why! Adding the API source to the IDE has the additional benefit that you get all the JavaDocs along with it, although all modern IDEs can also pull them [from the net](http://java.sun.com/j2se/1.4.2/docs/) -- you do **not** want to program desktop Java without the documentation available from within the IDE!
NetBeans and other IDEs do make the creation of IDEs very easy, but be aware that there is a lot more to Swing than just containers and layout managers. In fact, containers and layout managers are among the easier things, and I'd recommend learning to use them by hand, too. There is nothing at all wrong with using a GUI builder, but in some cases it's overkill, and then it's nicer to just quickly whip up a GUI from source. In other cases you need to be able to create a GUI dynamically and then GUI builders are no use at all! For creating very complex layouts from source, I recommend [FormLayout](http://www.jgoodies.com/freeware/forms/), which has its own set of quirks, but which does scale (in terms of programming effort) to very big frames and layouts.
If you've only done Groovy so far, you'll be surprised how well documented Swing and the rest of the Java API is and how well everything is integrated. It might also take some getting used to a different style of programming, using the debugger more often and println-debugging less, etc. There might also be some "boiler-plate" code that will be very annoying. ;) Enjoy.
|
The Sun Java tutorials are pretty good. I cannot vouch specifically for the Swing one as it has been ages since I've done any Swing development and I have not read it myself.
[Creating a GUI with JFC/Swing](http://java.sun.com/docs/books/tutorial/uiswing/)
|
What's the definitive Java Swing starter guide and reference?
|
[
"",
"java",
"swing",
"groovy",
"griffon",
""
] |
I am coming from Java and am currently working on a C# project. What is the recommended way to go about a) unit testing existing C# code and b) accomplishing TDD for C# development?
Also is there an equivalent to EMMA / EclEmma (free yet powerful code coverage tool) for Visual Studio and C# code?
|
1 [Nunit](http://www.nunit.org/)
2 [NCover](http://ncover.org/) or
3 [PartCover](http://sourceforge.net/projects/partcover/) (I never used it)
|
[NUnit](http://www.nunit.org/index.php) is patterned after JUnit, but if you're using Visual Studio 2008 then consider the built-in unit testing framework.
|
What is the equivalent to JUnit in C#?
|
[
"",
"c#",
"unit-testing",
"junit",
""
] |
I'm trying to use a link to open an overlay instead of in a separate popup window. This overlay should consist of a semi-transparent div layer that blocks the whole screen from being clicked on. I also aim to disable scrolling at this point. Not matter where you are on the main page, when the link is clicked, the overlay should be in the center of the screen's X and Y origins. Inside of this overlay div, should be an iframe configured such that 3 sizes of content can be loaded.
|
You might want to check out an old JS lib I wrote, called [SubModal](http://code.google.com/p/submodal/).
Easy to understand and modify. Go to town ;)
Once you've modded it, use [Minify](http://code.google.com/p/minify/) in combination with gzip on your server. The lib size will be teeny tiny.
|
[Shadowbox](http://mjijackson.com/shadowbox/) is a nice script for inline "popups". It can work with any of the usual JS libraries if you use any (jQuery, Prototype, etc) or on its own, has a pretty comprehensive skinning system so you can adapt the looks without having to go into the source code itself.
It is also the only such script (there are dozens) I've tried that would work reliably across all usual browsers.
It won't disable scrolling for you (you can still see the normal page background scroll by through the dark overlay), but the "popup" will in any case stay fixed on the screen.
|
How can I create a Netflix-style iframe overlay without a huge javascript library?
|
[
"",
"javascript",
"css",
"overlay",
""
] |
I was curious if anyone had any problems creating unit tests around using the ResourceManager. I am using Visual Studio test edition and it appears that the satellite assemblies don't get loaded during the test. When I try to get a resource for another culture, the test always fails and the resource manager always falls back to the default culture. The exact same code runs fine within the normal application.
|
I've had similar problems in the past with satellite assemblies. Try
adding the satellite assemblies to the unit projects dependecies. In Visual Studio
Test -- Edit Test Run configuration. Select Deployment and add the files
here.
On executing all applications, dlls, etc are copied to a special directory.
Strong named dll's may be ignored as these are expected to be in the GAC.
|
That got me going in the right direction. Adding the files to the deployment config didn't help, but disabling deployment did work.
For future reference, Visit [this blog post](http://stephenwalther.com/blog/archive/2008/03/20/tdd-test-driven-development-with-visual-studio-2008-unit-tests.aspx) and scroll down to the section "Managing Test Runs" for details of creating a test configuration and how to disable the deployment
|
ResourceManager and Unit Testing
|
[
"",
"c#",
"asp.net",
"asp.net-mvc",
"resources",
""
] |
Seeing as Java doesn't have nullable types, nor does it have a TryParse(),
how do you handle input validation without throwing an exceptions?
The usual way:
```
String userdata = /*value from gui*/
int val;
try
{
val = Integer.parseInt(userdata);
}
catch (NumberFormatException nfe)
{
// bad data - set to sentinel
val = Integer.MIN_VALUE;
}
```
I could use a regex to check if it's parseable, but that seems like a lot of overhead as well.
What's the best practice for handling this situation?
EDIT: Rationale:
There's been a lot of talk on SO about exception handling, and the general attitude is that exceptions should be used for unexpected scenarios only. However, I think bad user input is EXPECTED, not rare. Yes, it really is an academic point.
Further Edits:
Some of the answers demonstrate exactly what is wrong with SO. You ignore the question being asked, and answer another question that has nothing to do with it. The question isn't asking about transition between layers. The question isn't asking what to return if the number is un-parseable. For all you know, val = Integer.MIN\_VALUE; is exactly the right option for the application that this completely context free code snippet was take from.
|
That's pretty much it, although returning MIN\_VALUE is kind of questionable, unless you're sure it's the right thing to use for what you're essentially using as an error code. At the very least I'd document the error code behavior, though.
Might also be useful (depending on the application) to log the bad input so you can trace.
|
I asked [if there were open source utility libraries that had methods to do this parsing for you](https://stackoverflow.com/questions/16698647/java-library-that-has-parseint-parselong-parsedouble-etc-that-accept-default) and the answer is yes!
From [Apache Commons Lang](http://commons.apache.org/proper/commons-lang/) you can use [NumberUtils.toInt](https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/NumberUtils.html#toInt%28java.lang.String,%20int%29):
```
// returns defaultValue if the string cannot be parsed.
int i = org.apache.commons.lang.math.NumberUtils.toInt(s, defaultValue);
```
From [Google Guava](http://code.google.com/p/guava-libraries/) you can use [Ints.tryParse](https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Ints.html#tryParse(java.lang.String)):
```
// returns null if the string cannot be parsed
// Will throw a NullPointerException if the string is null
Integer i = com.google.common.primitives.Ints.tryParse(s);
```
There is no need to write your own methods to parse numbers without throwing exceptions.
|
String to Int in java - Likely bad data, need to avoid exceptions
|
[
"",
"java",
"parsing",
"numbers",
""
] |
I'm writing a GUI in C#, Visual Studio 2008, using the Designer and WinForms. I've got a ComboBox control, and I'd like it to only allow to select from the provided options and not to accept a user-entered string. It doesn't appear to have a ReadOnly property, and disabling it hinders the readability of the control (as well as disallowing user-selection).
|
Set DropDownStyle to "DropDownList"
|
Set the ComboBox.DropDownStyle property to ComboBoxStyle.DropDownList.
|
Readonly ComboBox in WinForms
|
[
"",
"c#",
"winforms",
"combobox",
"readonly",
""
] |
Several frameworks for writing web-based desktop-like applications have recently appeared. E.g. [SproutCore](http://www.sproutcore.com/) and [Cappuccino](http://cappuccino.org/). Do you have any experience using them? What's your impression? Did I miss some other framework?
I've seen [related](https://stackoverflow.com/questions/68114/what-is-the-single-most-useful-general-purpose-javascript-library-for-rich-inte) [questions](https://stackoverflow.com/questions/913/what-javascript-library-would-you-choose-for-a-new-project-and-why) on StackOverflow, but they generate mostly standard answers like "use jQuery or MochiKit or MooTools or Dojo or YUI". While some people give [non-standard](https://stackoverflow.com/questions/68114/what-is-the-single-most-useful-general-purpose-javascript-library-for-rich-inte#68564) [answers](https://stackoverflow.com/questions/913/what-javascript-library-would-you-choose-for-a-new-project-and-why#74111), they seem to have little experience *using* this frameworks.
Can anyone share real experience developing destop-like apps for the browser?
|
Due to the speed issues these high-level frameworks cause for many larger (as in: non-trivial) applications, we only use plain jQuery. In our tests, all high-level frameworks broke down in situations where there are many draggable objects or many drop targets, and in situation where long lists (with >1000 entries) were shown on screen.
Part of this is due to issues with IE6 and IE7 (where performance suddenly starts to deteriorate dramatically after DOM trees reach a certain complexity), but part is due to the overhead these frameworks generate.
So I would not recommend any of the high-level frameworks. My recommendation would be to use jQuery and work with the DOM directly.
**Some tips to improve performance:**
* Where possibly, render HTML on the
server.
* Keep the HTML as simple as
possible.
* Avoid having many elements
in the DOM tree.
* Avoid recursive
table structure (IE suddenly stops
showing them after relatively few
levels of nesting).
* Remove invisible
elements from the DOM tree.
* Remove
things from the DOM tree before
changing them and then re-insert
them, rather than changing them
while they're in the tree.
|
To my point of view, Cappuccino is an example of what NOT to do. They implemented another language on top of JavaScript, which already bring slowliness while browser developer are already fighting hard against, and, what is worst, they don't rely at all on the browser widget, breaking all the user navigation experience. For example, they implemented their own scrollbar, with the main drawback that using mouse wheel won't work anymore!
I really prefer ExtJS's approach which give you rich widgets while keeping the UI as close as possible from the browser.
|
What framework would you recommend for making desktop-like apps for the web?
|
[
"",
"javascript",
"web-applications",
"frameworks",
""
] |
I need to copy several tables from one DB to another in SQL Server 2000, using C# (VS 2005). The call needs to be parameterized - I need to be able to pass in the name of the database to which I am going to be copying these tables.
I could use DTS with parameters, but I can't find any sample code that does this from C#.
Alternatively, I could just use
```
drop table TableName
select * into TableName from SourceDB..TableName
```
and then reconstruct the indexes etc - but that is **really** kludgy.
Any other ideas?
Thanks!
|
For SQL Server 7.0 and 2000, we have SQLDMO for this. For SQL Server 2005 there is SMO. This allows you do to pretty much everything related to administering the database, scripting objects, enumerating databases, and much more. This is better, IMO, than trying a "roll your own" approach.
SQL 2000:
[Developing SQL-DMO Applications](http://msdn.microsoft.com/en-us/library/aa274758(SQL.80).aspx)
[Transfer Object](http://msdn.microsoft.com/en-us/library/aa276080(SQL.80).aspx)
SQL 2005:
Here is the SMO main page:
[Microsoft SQL Server Management Objects (SMO)](http://msdn.microsoft.com/en-us/library/ms162169(SQL.90).aspx)
Here is the Transfer functionality:
[Transferring Data](http://msdn.microsoft.com/en-us/library/ms162563(SQL.90).aspx)
[How to: Transfer Schema and Data from One Database to Another in Visual Basic .NET](http://msdn.microsoft.com/en-us/library/ms162138(SQL.90).aspx)
|
If the destination table is being dropped every time then why not do SELECT INTO? Doesn't seem like a kludge at all.
If it works just fine and ticks all the requirements boxes why create a days worth of work growing code to do exactly the same thing?
Let SQL do all the heavy lifting for you.
|
How do you copy a MS SQL 2000 database programmatically using C#?
|
[
"",
"c#",
".net",
"sql-server",
"dts",
""
] |
Should be pretty simple: I have an InputStream where I want to peek at (not read) the first two bytes, i.e. I want the "current position" of the InputStream to stil be at 0 after my peeking. What is the best and safest way to do this?
**Answer** - As I had suspected, the solution was to wrap it in a BufferedInputStream which offers markability. Thanks Rasmus.
|
For a general InputStream, I would wrap it in a BufferedInputStream and do something like this:
```
BufferedInputStream bis = new BufferedInputStream(inputStream);
bis.mark(2);
int byte1 = bis.read();
int byte2 = bis.read();
bis.reset();
// note: you must continue using the BufferedInputStream instead of the inputStream
```
|
You might find PushbackInputStream to be useful:
<http://docs.oracle.com/javase/6/docs/api/java/io/PushbackInputStream.html>
|
How do I peek at the first two bytes in an InputStream?
|
[
"",
"java",
"inputstream",
"bufferedinputstream",
""
] |
I recently inherited a database on which one of the tables has the primary key composed of encoded values (Part1\*1000 + Part2).
I normalized that column, but I cannot change the old values.
So now I have
```
select ID from table order by ID
ID
100001
100002
101001
...
```
I want to find the "holes" in the table (more precisely, the first "hole" after 100000) for new rows.
I'm using the following select, but is there a better way to do that?
```
select /* top 1 */ ID+1 as newID from table
where ID > 100000 and
ID + 1 not in (select ID from table)
order by ID
newID
100003
101029
...
```
The database is Microsoft SQL Server 2000. I'm ok with using SQL extensions.
|
```
select ID +1 From Table t1
where not exists (select * from Table t2 where t1.id +1 = t2.id);
```
not sure if this version would be faster than the one you mentioned originally.
|
```
SELECT (ID+1) FROM table AS t1
LEFT JOIN table as t2
ON t1.ID+1 = t2.ID
WHERE t2.ID IS NULL
```
|
How to find "holes" in a table
|
[
"",
"sql",
""
] |
If I wish to simply rename a column (not change its type or constraints, just its name) in an SQL database using SQL, how do I do that? Or is it not possible?
This is for any database claiming to support SQL, I'm simply looking for an SQL-specific query that will work regardless of actual database implementation.
|
On PostgreSQL (and many other RDBMS), you can do it with regular `ALTER TABLE` statement:
```
=> SELECT * FROM Test1;
id | foo | bar
----+-----+-----
2 | 1 | 2
=> ALTER TABLE Test1 RENAME COLUMN foo TO baz;
ALTER TABLE
=> SELECT * FROM Test1;
id | baz | bar
----+-----+-----
2 | 1 | 2
```
|
Specifically for SQL Server, use [`sp_rename`](http://msdn.microsoft.com/en-us/library/ms188351.aspx)
```
USE AdventureWorks;
GO
EXEC sp_rename 'Sales.SalesTerritory.TerritoryID', 'TerrID', 'COLUMN';
GO
```
|
How do I rename a column in a database table using SQL?
|
[
"",
"sql",
"database",
"rename",
""
] |
What is the difference between `ROWNUM` and `ROW_NUMBER` ?
|
ROWNUM is a "pseudocolumn" that assigns a number to each row returned by a query:
```
SQL> select rownum, ename, deptno
2 from emp;
ROWNUM ENAME DEPTNO
---------- ---------- ----------
1 SMITH 99
2 ALLEN 30
3 WARD 30
4 JONES 20
5 MARTIN 30
6 BLAKE 30
7 CLARK 10
8 SCOTT 20
9 KING 10
10 TURNER 30
11 FORD 20
12 MILLER 10
```
ROW\_NUMBER is an analytic function that assigns a number to each row according to its ordering within a group of rows:
```
SQL> select ename, deptno, row_number() over (partition by deptno order by ename) rn
2 from emp;
ENAME DEPTNO RN
---------- ---------- ----------
CLARK 10 1
KING 10 2
MILLER 10 3
FORD 20 1
JONES 20 2
SCOTT 20 3
ALLEN 30 1
BLAKE 30 2
MARTIN 30 3
TURNER 30 4
WARD 30 5
SMITH 99 1
```
|
From a little reading, ROWNUM is a value automatically assigned by Oracle to a rowset (prior to ORDER BY being evaluated, so don't **ever** `ORDER BY ROWNUM` or use a `WHERE ROWNUM < 10` with an `ORDER BY`).
[ROW\_NUMBER()](http://download.oracle.com/docs/cd/B10500_01/server.920/a96540/functions105a.htm) appears to be a function for assigning row numbers to a result set returned by a subquery or partition.
|
In an Oracle database, what is the difference between ROWNUM and ROW_NUMBER?
|
[
"",
"sql",
"oracle",
"row-number",
"rownum",
""
] |
I have a PHP script that is called from a cron job every minute. This script takes some info from the database and then calls another PHP script using the System function (passing it some parameters).
That means that I can start up to 10 scripts from this "main" one. And what I would like to do is that I would call the script and continue the execution of the main script, that is, not wait for the System call to complete and then call the next one.
How can this be done?
|
You may be able to use [`proc_open()`](http://www.php.net/manual/en/function.proc-open.php), [`stream_select()`](http://www.php.net/manual/en/function.stream-select.php) and [`stream_set_blocking()`](http://www.php.net/manual/en/function.stream-set-blocking.php) in concert to achieve this kind of thing.
If that sounds vague, I was going to paste a big chunk of code in here that I used in a recent project that did something similar, but then felt it may hinder rather than help! In summary though, the code worked like this:
1. cronjob calls cronjob\_wrapper.php
2. cronjob\_wrapper.php creates a new Manager class and then calls *start* on it.
3. Manager class start method check to see how many instances are running (looking for pid files in a particular location). If it's less than a given max number of instances it writes out it's own process id to a pid file and then carries on
4. Manage class creates an instance of an appropriate Encoder class and calls *exec* on it.
5. The *exec* method uses proc\_open, stream\_select and stream\_set\_blocking to run a system command in a non-blocking fashion (running ffmpeg in this case - and could take quite a while!)
6. When it has finally run it cleans up its PID file and bails out.
Now the reason I'm being vague and handwavy is that our multiple instances here are being handled by the cronjob not by PHP. I was trying to do very much the kind of thing you are talking about, and got something working pretty well with [`pcntl_fork()`](http://www.php.net/manual/en/function.pcntl-fork.php) and friends, but in the end I encountered a couple of problems (if I recall at least one was a bug in PHP) and decided that this approach was a much more rock-solid way to achieve the same thing. YMMV.
Well worth a look at those functions though, you can achieve a lot with them. Though somehow I don't think PHP will ever become the sockets programming language of choice... :)
|
If your OS supports it, you can use the [pcntl\_fork()](http://www.php.net/manual/en/function.pcntl-fork.php) function to spin off child processes that the parent doesn't wait for. Be careful though, it is easy to accidentally create too many child processes, especially if they take longer than expected to run!
|
Don't wait for the process to exit
|
[
"",
"php",
""
] |
How do I write a decorator that restores the current working directory to what it was before the decorated function was called? In other words, if I use the decorator on a function that does an `os.chdir()`, the cwd will not be changed after the function is called.
|
The [path.py](https://github.com/jaraco/path.py) module (which you really should use if dealing with paths in python scripts) has a context manager:
```
subdir = d / 'subdir' #subdir is a path object, in the path.py module
with subdir:
# here current dir is subdir
#not anymore
```
(credits goes to [this blog post](http://ralsina.me/weblog/posts/BB963.html) from Roberto Alsina)
|
The answer for a decorator has been given; it works at the function definition stage as requested.
With Python 2.5+, you also have an option to do that at the function *call* stage using a context manager:
```
from __future__ import with_statement # needed for 2.5 ≤ Python < 2.6
import contextlib, os
@contextlib.contextmanager
def remember_cwd():
curdir= os.getcwd()
try: yield
finally: os.chdir(curdir)
```
which can be used if needed at the function call time as:
```
print "getcwd before:", os.getcwd()
with remember_cwd():
walk_around_the_filesystem()
print "getcwd after:", os.getcwd()
```
It's a nice option to have.
EDIT: I added error handling as suggested by codeape. Since my answer has been voted up, it's fair to offer a complete answer, all other issues aside.
|
How do I write a decorator that restores the cwd?
|
[
"",
"python",
"decorator",
"cwd",
""
] |
I'd like to use the Wiimote (accelerometers, gyroscopes, infrared camera, etc, etc, etc) on various applications.
It's a bluetooth device, and I know others have connected it to their computer.
* What's the easiest way to start using it in my software - are there libraries for C#, for instance?
* I want my software to be usable and easily installable - what's the current easiest way to connect a wiimote to the computer? Can I make that process part of my software installation?
-Adam
|
Have you seen [Johnny Chung Lee's 'Procrastineering' Blog](http://procrastineering.blogspot.com/)? He's written a lot on the subject of using wii remotes and has some fantastic demonstration videos. **[Edit]** I just found out Mr Lee did [a TED talk](http://www.ted.com/index.php/talks/johnny_lee_demos_wii_remote_hacks.html) which gives a good introduction to the stuff he's done too...
There's a wealth of information over on [Wiibrew.org](http://wiibrew.org) - check out their [Wiimote Library](http://wiibrew.org/wiki/Wiimote_Library) page for some other APIs if you want to look beyond c#. As an avid Python fan, I'm quite curious to have a play with [the pyWiimote library](http://code.google.com/p/pywiimote/) :-)
|
Coding4Fun had a managed C# library up that would allow you to interface with it but it seems their site is down right now. Though I think they used the Robotics Studio so that may be a place to start.
Found it... <http://www.codeplex.com/WiimoteLib>
Oh and I forgot to post a link to these videos I saw quite some time ago. <http://www.cs.cmu.edu/~johnny/projects/wii/>
|
Wiimote example programs
|
[
"",
"c#",
"user-interface",
"wiimote",
"wii",
""
] |
Is there a manual for cross-compiling a C++ application from Linux to Windows?
Just that. I would like some information (links, reference, examples...) to guide me to do that.
I don't even know if it's possible.
My objective is to compile a program in Linux and get a .exe file that I can run under Windows.
|
The basics are not too difficult:
```
sudo apt-get install mingw32
cat > main.c <<EOF
int main()
{
printf("Hello, World!");
}
EOF
i586-mingw32msvc-cc main.c -o hello.exe
```
Replace `apt-get` with `yum`, or whatever your Linux distro uses. That will generate a `hello.exe` for Windows.
Once you get your head around that, you could use [autotools](http://sources.redhat.com/autobook/autobook/autobook_268.html#SEC268), and set `CC=i586-mingw32msvc-cc`
```
CC=i586-mingw32msvc-cc ./configure && make
```
Or use [CMake and a toolchain file](http://www.cmake.org/Wiki/CMake_Cross_Compiling) to manage the build. More difficult still is adding native cross libraries. Usually they are stored in `/usr/cross/i586-mingw32msvc/{include,lib}` and you would need to add those paths in separately in the configure step of the build process.
|
It depends on what you mean (I couldn't really say).
1. If you mean that you want to use an existing Linux application on Windows, then you could try compiling it using [Cygwin](http://en.wikipedia.org/wiki/Cygwin) on Windows. This however does not give you a Windows executable free from all dependencies towards Cygwin (your executable still depends on the `cygwin.dll` file) - and it still may need some porting before it will work. See <http://www.cygwin.com>.
2. If you mean that you want to be able to perform the actual compilation of a Windows application on Linux and produce a .exe file that is executable on Windows - thus using your Linux box for development and/or compilation then you should look into [MinGW](http://en.wikipedia.org/wiki/MinGW) for Linux which is a tool for crosscompiling for Windows on Linux. See <http://www.mingw.org/wiki/LinuxCrossMinGW>.
Best regards!
|
Manual for cross-compiling a C++ application from Linux to Windows?
|
[
"",
"c++",
"windows",
"linux",
"cross-compiling",
""
] |
I'm witting a WCF service for a customer to send part information to our application. We have multiple customers that will have one or many locations, and part information is scoped to each location for the customer. When the customer calls our service they will need to specify the location.
Options that we have considered are:
1) Placing a location id(s) in a custom header. All part information would apply to all locations listed.
2) Adding a "context" node to the message body. All part information would apply to all locations listed.
3) Adding a location node in the message body over that would contain the part information. Each location would have it's own list of parts.
I'm looking for best practice/standards help in determining how this should be handled. We will have to create other services that will have the customer/location scope as well, and would like to handle this in a consistent manor.
|
I would say if it's only one or two operations that need it, make it part of the data contract - sort of like making it a parameter to a method call. If every operation requires it, put it in the header, since it's just as much context as username, roles, tenant, or other authentication information - sort of like something you'd put in a request context (e.g., HttpContext).
|
Do you need to use a message contract? I use Data contracts unless I need to stream something back, so everything just ends up in the body. But, even for a message contract I would put that information in the body, I tend to reserve the header for authentication information.
|
WCF customheader or messagebody for context?
|
[
"",
"c#",
"wcf",
""
] |
I am trying to write a simple networked chat program in Java. I have almost no networking experience. I was wondering what resources I should begin looking at (beside here of course).
Sticking with the core Java API would be best for now.
|
I found a great tutorial into networking and java from sun's own website: <http://download.oracle.com/javase/tutorial/networking/TOC.html>
The socket section even has you write a mini client / server chat demo.
|
I recommend you to first learn networking. If you have time read the [Tanenbaum book](https://rads.stackoverflow.com/amzn/click/com/0133499456), the greatest reference in networking. If you want a quick leard, here is a road map:
* OSI layers
* UDP and TCP/IP
* Sockets
* Broadcast and Multicast
* Network security
Then go with Java: Socket, ServerSocket, DatagramSocket, RMI, etc.
|
Java: Best Place to Begin Learning Basic Networking
|
[
"",
"java",
"networking",
""
] |
I am looking for a (preferably pure) python library to do AES 256 encryption and decryption.
This library should support the CBC cipher mode and use PKCS7 padding [according to the answer to an earlier question of mine](https://stackoverflow.com/questions/172392/what-symmetric-cypher-to-use-for-encrypting-messages).
The library should at least work on Mac OS X (10.4) and Windows XP. Ideally just by dropping it into the source directory of my project. I have seen [this by Josh Davis](http://www.josh-davis.org/pythonAES), but am not sure about how good it is and if it does the required CBC cipher mode... Scanning the source suggests it doesn't
|
~~[PyCrypto](http://www.dlitz.net/software/pycrypto/) should be the one for you.~~
Edit 02/10/2020: unfortunately I cannot delete this post, since it's the accepted answer. As people pointed out in the comments, this library is not mantained anymore and probably also vulnerable from a security point of view. So please, take a look to the below answers instead.
|
<https://github.com/caller9/pythonaes>
That is pure python with PKCS7 padding. Supports CBC, CFB, and OFB modes.
The problem is that python is not super fast for this type of thing. The code from serprex's fork is a little bit inscrutable, but much faster than mine due to using all kinds of tricks to squeeze every last bit of speed out of Python.
Really though, the best libraries for this are compiled and hook into SSE/MMX stuff.
Also Intel is baking in AES instructions since the Core(tm) line of chips.
I wrote my version to get a true pure Python version out there to be able to run on any architecture, cross-platform, and with 3.x as well as 2.7.
|
What (pure) Python library to use for AES 256 encryption?
|
[
"",
"python",
"encryption",
"aes",
""
] |
The use of weak references is something that I've never seen an implementation of so I'm trying to figure out what the use case for them is and how the implementation would work. When have you needed to use a `WeakHashMap` or `WeakReference` and how was it used?
|
> One problem with strong references is
> caching, particular with very large
> structures like images. Suppose you
> have an application which has to work
> with user-supplied images, like the
> web site design tool I work on.
> Naturally you want to cache these
> images, because loading them from disk
> is very expensive and you want to
> avoid the possibility of having two
> copies of the (potentially gigantic)
> image in memory at once.
>
> Because an image cache is supposed to
> prevent us from reloading images when
> we don't absolutely need to, you will
> quickly realize that the cache should
> always contain a reference to any
> image which is already in memory. With
> ordinary strong references, though,
> that reference itself will force the
> image to remain in memory, which
> requires you to somehow determine when
> the image is no longer needed in
> memory and remove it from the cache,
> so that it becomes eligible for
> garbage collection. You are forced to
> duplicate the behavior of the garbage
> collector and manually determine
> whether or not an object should be in
> memory.
[Understanding Weak References](https://community.oracle.com/blogs/enicholas/2006/05/04/understanding-weak-references), Ethan Nicholas
|
# `WeakReference` versus `SoftReference`
One distinction to be clear on is the difference between a [`WeakReference`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ref/WeakReference.html) and a [`SoftReference`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ref/SoftReference.html).
Basically a `WeakReference` will be [GC-d](https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)) by the [JVM](https://en.wikipedia.org/wiki/Java_virtual_machine) eagerly, once the referenced object has no *hard* references to it. A `SoftReference`d object on the other hand, will tend to be left about by the garbage collector until it really needs to reclaim the memory.
A cache where the **values** are held inside `WeakReference`s would be pretty useless (in a `WeakHashMap`, it is the keys which are weakly referenced). `SoftReferences` are useful to wrap the values around when you want to implement a cache which can grow and shrink with the available memory.
|
When would you use a WeakHashMap or a WeakReference?
|
[
"",
"java",
"weak-references",
""
] |
*<flavor> I want to create a spelling test program for my grade schoolers that would let them enter and record their spelling words then test them on them through out the week.</flavor>*
What's a good Delphi API with which I could select a recording device, capture and save sound files, then play them back?
I'm also toying with doing the same project in C#, so C# Sound capture/playback API recommendations would also be appreciated.
|
An alternative to recording would be to use the MS Speech API with C#, enter the words via keyboard, and have it state what was keyed in.
Just a thought... Good luck on your app -- it sounds like a really cool program!
|
I've found [New Audio Components](http://symmetrica.net/newac/) to be quite good for Delphi.
|
What's a good API for recording/capturing and playing back sound in Delphi and/or C#?
|
[
"",
"c#",
"delphi",
"desktop-application",
""
] |
What resources have to be manually cleaned up in *C#* and what are the consequences of not doing so?
For example, say I have the following code:
```
myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
// Use Brush
```
If I don't clean up the brush using the dispose method, I'm assuming the garbage collector frees the memory used at program termination? Is this correct?
What other resources do I need to manually clean up?
|
Technically anything that inherits from IDisposable should be proactively disposed. You can use the 'using' statement to make things easier.
<http://msdn.microsoft.com/en-us/library/yh598w02.aspx>
Sometimes you will see inconsistent use of IDisposable derived objects in documentation sample code as well as code that is generated by tools (i.e. visual studio).
What's nice about IDisposable is that it gives you the ability to *proactively* release the underlying unmanaged resource. Sometimes you really want to do this - think network connections and file resources for example.
|
* Handles to internal windows data structures.
* Database connections.
* File handles.
* Network connections.
* COM/OLE references.
The list goes on.
It's important to call `Dispose` or even better yet, use the `using` pattern.
```
using (SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black))
{
// use myBrush
}
```
---
If you don't dispose something, it'll be cleaned up when the garbage collector notices that there are no more references to it, which may be after some time.
In the case of `System.Drawing.Brush`, Windows will keep internal windows structures for the brush loaded in memory until all programs release their handle.
|
Resources that have to be manually cleaned up in C#?
|
[
"",
"c#",
"memory-management",
"resources",
"garbage-collection",
""
] |
I use [XFire](http://xfire.codehaus.org/) to create a webservice wrapper around my application. XFire provides the webservice interface and WSDL at runtime (or creates them at compile time, don't know exactly).
Many of our customers don't know webservices very well and additionally they simply don't read any external documentation like Javadoc. I know that it's possible to add documentation (for parameters and methods) directly to the WSDL file.
I thought about Annotations or Aegis XML files but I don't know how... Do you know a way?
Edit: I just found this [JIRA issue](http://jira.codehaus.org/browse/XFIRE-507) but the last activity was 2006. Any ideas?
|
XFire is slowly headed for /dev/null. Use [CXF](http://cxf.apache.org/) instead. In other words, XFire is being deprecated in favor of CXF - it's pretty much the same developers.
Since you use the Java-first approach, I suggest you generate you WSDL once and for all with CXF's `java2wsdl` tool, then you put your documentation in that and tell CXF to use *that* documented WSDL instead of letting CXF generate its own (undocumented) WSDL at runtime/deploy-time.
[This page](http://cwiki.apache.org/CXF20DOC/developing-a-service.html) has pretty much everything you need to know about creating a web service in CXF.
|
> And my last hint regarding CXF - use Aegis for data binding instead of JAXB. It doesn't work for complex POJO.
In my experience we have no problem with complex POJO and JAXB, the only problem is that the code starts to be cluttered with JAXBElements. On the other hand, Aegis documentation is pretty sparse and not well-maintained with relation to CXF.
|
How to create documented WSDL using XFire
|
[
"",
"java",
"web-services",
"documentation",
"wsdl",
"xfire",
""
] |
How do I get a list of all files (and directories) in a given directory in Python?
|
This is a way to traverse every file and directory in a directory tree:
```
import os
for dirname, dirnames, filenames in os.walk('.'):
# print path to all subdirectories first.
for subdirname in dirnames:
print(os.path.join(dirname, subdirname))
# print path to all filenames.
for filename in filenames:
print(os.path.join(dirname, filename))
# Advanced usage:
# editing the 'dirnames' list will stop os.walk() from recursing into there.
if '.git' in dirnames:
# don't go into any .git directories.
dirnames.remove('.git')
```
|
You can use
```
os.listdir(path)
```
For reference and more os functions look here:
* Python 2 docs: <https://docs.python.org/2/library/os.html#os.listdir>
* Python 3 docs: <https://docs.python.org/3/library/os.html#os.listdir>
|
Directory-tree listing in Python
|
[
"",
"python",
"file",
"directory",
"subdirectory",
"directory-tree",
""
] |
I'm currently having a major issue with a python script. The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting.
The issue I'm having is getting the script to work correctly on windows with a command that contains ampersands in it's path. I've attempted quoting the command, escaping the ampersand with ^ and neither works. I'm now out of ideas. Any suggestions?
To clarify from current responses:
1. I am using the subprocess module
2. I am passing the command line + arguments in as a list
3. The issue is with the path to the command itself, not any of the arguments
4. I've tried quoting the command. It causes a `[Error 123] The filename, directory name, or volume label syntax is incorrect` error
5. I'm using no shell argument (so `shell=false`)
6. In case it matters, I'm grabbing a pipe to stderr for processing it, but ignoring stdout and stdin
7. It is only for use on Windows currently, and works as expected in all other cases that I've tested so far.
8. The command that is failing is:
> p = subprocess.Popen(prog, stderr = subprocess.PIPE, bufsize=-1)
when the first element of the list 'prog' contains any ampersands. Quoting this first string does not work.
|
Make sure you are using lists and no shell expansion:
```
subprocess.Popen(['command', 'argument1', 'argument2'], shell=False)
```
|
Try quoting the argument that contains the &
```
wget "http://foo.com/?bar=baz&baz=bar"
```
Is usually what has to be done in a Linux shell
|
Python subprocess issue with ampersands
|
[
"",
"python",
"windows",
"subprocess",
"command-line-arguments",
""
] |
I'm trying to run SQuirreL SQL.
I've downloaded it and installed it, but when I try to run it I get this error message:
> Java Virtual Machine Launcher.
> Could not find the main class.
> Program will exit.
I get the gist of this, but I have not idea how to fix it. Any help?
### more info:
* I'm on Windows XP pro.
* I have java 1.6 installed, and other apps are running OK.
* The install ran OK.
* I believe I've followed the installation instructions correctly.
* To run it, I'm invoking the **squirrel-sql.bat** file.
### Update
This question: ["Could not find the main class: XX. Program will exit."](https://stackoverflow.com/questions/1417328/could-not-find-the-main-class) gives some background on this error from the point of view of a java developer.
|
Is Java installed on your computer? Is the path to its bin directory set properly (in other words if you type 'java' from the command line do you get back a list of instructions or do you get something like "java is not recognized as a .....")?
You could try try running `squirrel-sql.jar` from the command line (from the squirrel sql directory), using:
```
java -jar squirrel-sql.jar
```
|
The classpath is the path that the system will follow when trying to find the classes that you're trying to run. In the batch file you're trying to execute it probably has a variable like CLASSPATH=blah;blah;etc or a java command that looks similar to
```
java -classpath "c:\directory\lib\squirrel-sql.jar" com.some.squirrel.package.file
```
If you can find or add that classpath setting, make sure that it includes a path to the squirrel-sql.jar and any other jar files that it may depend on separated by semicolons (or the root /lib directory that may be included with the installation).
Basically you just need to tell java where to find the class files that you're trying to execute. Wikipedia has a more indepth discussion about classpath and can offer you more insight. <http://en.wikipedia.org/wiki/Classpath_(Java)>
|
"Could not find the main class. Program will exit"
|
[
"",
"java",
"squirrel-sql",
""
] |
I am developing an auto-builder that will run a series of steps in our build process and build our target application. We used to use a batch file which set up a bunch of environment variables or called tools that setup environment variables and ultimately runs a 'make'.
I've been using the 'Process' class which works great for running those commands but unfortunately every time one runs which makes changes to the environment (like adding something to the PATH) those variables are lost when the 'Process' completes. The next 'Process' is instantiated and inherits the env from the 'calling' app (my exe) again - which means all env setup by the last command are lost. How do you handle this situation? Is there a better way to run a series of batch-file like commands within C# and maintain the environment they set up?
Please note that unfortunately the old-schoolers have declared that nant/ant are not an option so "Hey, why not use Nant - it does that!" is not the answer I am looking for.
Thanks.
|
i would suggest some code that would save your environment variables to an external file, and then you can retrieve these variables via the external file at the start of following processes.
|
Environment variables are never set and cannot be set for the parent process (\*). Only for the current process and the ones it creates - that is part of the concept.
(\*) apart from, maybe, messing around with OS-internals.
|
How do I run a series of processes in C# and keep their environment settings?
|
[
"",
"c#",
"build-process",
"makefile",
"environment",
"auto-build",
""
] |
Last time [I asked about the reverse process](https://stackoverflow.com/questions/169506/get-form-input-fields-with-jquery), and got some very efficient answers. I'm aiming for least lines of code here. I have a form of fields and an associative array in the {fieldname:data} format, I want to populate a corresponding form with it.
|
When I did this for a project, I found that setting the value of select fields, radio buttons and checkboxes necessitated more complex code, something along the lines of:
```
jQuery.each(data, function (name,value) {
jQuery("input[name='"+name+"'],select[name='"+name+"']").each(function() {
switch (this.nodeName.toLowerCase()) {
case "input":
switch (this.type) {
case "radio":
case "checkbox":
if (this.value==value) { jQuery(this).click(); }
break;
default:
jQuery(this).val(value);
break;
}
break;
case "select":
jQuery("option",this).each(function(){
if (this.value==value) { this.selected=true; }
});
break;
}
});
});
```
I haven't tested this code so I hope there are no silly syntax errors that I should have caught. Hope this helps.
I am not allowed to comment on the comments here (yet), so ....
As noted in the comment, the jQuery .val(val) method handles setting radio buttons,checkboxes and selects.
You will still need to put select[name=...] into your jQuery selector pattern or the select elements won't be updated.
|
If your form elements have their ID set to the fieldname:
```
$.each(myAssocArry, function(i,val) { $('#'+i).val(val); });
```
|
Populate a form with data from an associative array with jQuery
|
[
"",
"javascript",
"jquery",
""
] |
I'll go first.
I'm 100% in the set-operations camp. But what happens when the set logic
on the entire desired input domain leads to a such a large retrieval that the query slows down significantly, comes to a crawl, or basically takes infinite time?
That's one case where I'll use a itty-bitty cursor (or a while loop) of perhaps most dozens of rows (as opposed to the millions I'm targeting). Thus, I'm still working in (partitioned sub) sets, but my retrieval runs faster.
Of course, an even faster solution would be to call the partioned input domains in parallel from outside, but that introduces an interaction will an external system, and when "good enough" speed can be achieved by looping in serial, just may not be worth it (epecially during development).
|
Sure, there are a number of places where cursors might be better than set-based operations.
One is if you're updating a lot of data in a table (for example a SQL Agent job to pre-compute data on a schedule) then you might use cursors to do it in multiple small sets rather than one large one to reduce the amount of concurrent locking and thus reduce the chance of lock contention and/or deadlocks with other processes accessing the data.
Another is if you want to take application-level locks using the `sp_getapplock` stored procedure, which is useful when you want to ensure rows that are being polled for by multiple processes are retrieved exactly once ([example here](http://gregbeech.com/blogs/tech/archive/2008/06/11/retrieving-a-row-exactly-once-with-multiple-polling-processes-in-sql-server.aspx)).
In general though, I'd agree that it's best to start using set based operations if possible, and only move to cursors if required either for functionality or performance reasons (with evidence to back the latter up).
|
I've got plenty of cases where rows from a configuration table have to be read and code generated and executed, or in many meta-programming scenarios.
There are also cases when cursors simply outperform because the optimizer is not smart enough. In those cases, either there is meta-information in your head which is simply not revealed to the optimizer through the indexes or statistics on the tables, or the code is just so complicated that the joins (and usually, re-joins) simply can't be optimized in the way you can visualize them in a cursor-based fashion. In SQL Server 2005, I believe CTEs tend to make this look a lot simpler in the code, but whether the optimizer also sees them as simpler is hard to know - it comes down to comparing the execution plan to how you think it could be done most efficiently and making the call.
General rule - don't use a cursor unless necessary. But when necessary, don't give yourself a hard time about it.
|
SQL Cursors...Any use cases you would defend?
|
[
"",
"sql",
"sql-server",
"t-sql",
"set",
""
] |
In my base page I need to remove an item from the query string and redirect. I can't use
```
Request.QueryString.Remove("foo")
```
because the collection is read-only. Is there any way to get the query string (except for that one item) without iterating through the collection and re-building it?
|
You'd have to reconstruct the url and then redirect. Something like this:
```
string url = Request.RawUrl;
NameValueCollection params = Request.QueryString;
for (int i=0; i<params.Count; i++)
{
if (params[i].GetKey(i).ToLower() == "foo")
{
url += string.Concat((i==0 ? "?" : "&"), params[i].GetKey(i), "=", params.Get(i));
}
}
Response.Redirect(url);
```
Anyway, I didn't test that or anything, but it should work (or at least get you in thye right direction)
|
You can avoid touching the original query string by working on a copy of it instead. You can then redirect the page to the a url containing your modified query string like so:
```
var nvc = new NameValueCollection();
nvc.Add(HttpUtility.ParseQueryString(Request.Url.Query));
nvc.Remove("foo");
string url = Request.Url.AbsolutePath;
for (int i = 0; i < nvc.Count; i++)
url += string.Format("{0}{1}={2}", (i == 0 ? "?" : "&"), nvc.Keys[i], nvc[i]);
Response.Redirect(url);
```
**Update:**
Turns out we can simplify the code like so:
```
var nvc = HttpUtility.ParseQueryString(Request.Url.Query);
nvc.Remove("foo");
string url = Request.Url.AbsolutePath + "?" + nvc.ToString();
Response.Redirect(url);
```
|
How do I remove items from the query string for redirection?
|
[
"",
"c#",
"asp.net",
"webforms",
""
] |
Ok I give up, I've been trying to write a regexp in ant to replace the version number from something that I have in a properties file. I have the following:
```
<?xml version="1.0" encoding="UTF-8"?>
<feature
id="some.feature.id"
label="Some test feature"
version="1.0.0"
provider-name="Provider">
<plugin
id="test.plugin"
download-size="0"
install-size="0"
version="0.0.0"
unpack="false"/>
..... many plugins later....
</feature>
```
What I want to achieve is substitute the version number of the feature tag only, without changing the version of the xml or the version of the miriad of plugins in the file.
The problem I have is that I either match too much or too little. Definitively matching "version" is not enough, because everything would be changed
Is there any easy way to match then only the version inside the tag, taking into consideration that the '0.0.0' could be any number?
|
Assuming you're using the `replaceregexp` task:
```
<replaceregexp file="whatever"
match="(<feature\b[^<>]+?version=\")[^\"]+"
replace="\1${feature.version}" />
```
I'm also assuming there's only the one `<feature>` element.
|
The following regex may do what you want...
```
(?<=<feature[^>]{*,1000}version=")[^"]*(?=")
```
Which, in human speak, roughly means
> I want to match text that immediately
> follows the string "<feature", followed by up to a thousand
> characters not the greater-than bracket, and
> "version=""; the text to match is immediately followed
> by a double quote, and contains no
> double quotes.
`**`*Thanks to Alan M for the heads up about java lookbehinds* ಠ\_ಠ
If you use this regex with a Replace operation, it will switch out whatever is inside the version="" attribute with whatever you set as the replacement value. Its up to you to provide the correctly formatted version number.
Now, since you're doing this with XML, the obvious question is, "Why aren't you using XPath?"
|
Regexp: Substituting a version number in an XML file
|
[
"",
"java",
"regex",
"ant",
""
] |
What does it take to get C++ **tr1** members (shared\_ptr especially, but we'd like function and bind and ALL the others) working with **GCC 3.4.4** (for the Nokia **N810** tablet computer).
Has anyone done this? Attempted this?
It may **not** be feasible for us to upgrade to GCC 4.x to cross-compile for this device (but if you've done that, we'd love to know).
There may be many approaches, and I'd like to avoid dead ends others have hit.
We're trying to avoid bringing in boost, since it can be pretty interdependent (you bring in one boost header and you end up with 20 more), and keeping code size down is important to us.
Thank you!
|
For shared\_ptr from boost, at least, the number of dependencies is pretty small. You can use [bcp](http://www.boost.org/doc/libs/1_36_0/tools/bcp/bcp.html) to extract subsets from boost as well, so you don't need the whole of boost to compile your application.
|
Are you able to use [Boost](http://www.boost.org/) ([Smart Pointers](http://www.boost.org/libs/smart_ptr/), [Bind](http://www.boost.org/libs/bind/), [Function](http://www.boost.org/libs/function/)) directly? From the [GCC changelogs](http://gcc.gnu.org/gcc-4.0/changes.html), the actual `std::tr1` stuff is only available from 4.0 onwards. :-(
I know there are differences between the Boost and `std::tr1`, but hopefully these can be worked around satisfactorily. Let me know how it works for you. :-)
|
C++ tr1 on GCC 3.4.4 (for the Nokia N810 tablet computer)
|
[
"",
"c++",
"gcc",
"tr1",
""
] |
I have this code:
```
chars = #some list
try:
indx = chars.index(chars)
except ValueError:
#doSomething
else:
#doSomethingElse
```
I want to be able to do this because I don't like knowfully causing Exceptions:
```
chars = #some list
indx = chars.index(chars)
if indx == -1:
#doSomething
else:
#doSomethingElse
```
Is there a way I can do this?
|
Note that the latter approach is going against the generally accepted "pythonic" philosophy of [EAFP, or "It is Easier to Ask for Forgiveness than Permission."](http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Exceptions), while the former follows it.
|
```
if element in mylist:
index = mylist.index(element)
# ... do something
else:
# ... do something else
```
|
Do I have to cause an ValueError in Python
|
[
"",
"python",
"exception",
"list",
""
] |
I have have some code which adds new cells to a table and fills them with text boxes.
The way I've coded it so far works fine:
```
TableCell tCell1 = new TableCell();
TableCell tCell2 = new TableCell();
TableCell tCell3 = new TableCell();
TableCell tCell4 = new TableCell();
TableCell tCell5 = new TableCell();
TableCell tCell6 = new TableCell();
TableCell tCell7 = new TableCell();
TextBox txt1 = new TextBox();
TextBox txt2 = new TextBox();
TextBox txt3 = new TextBox();
TextBox txt4 = new TextBox();
TextBox txt5 = new TextBox();
TextBox txt6 = new TextBox();
TextBox txt7 = new TextBox();
tCell1.Controls.Add(txt1);
tCell2.Controls.Add(txt2);
tCell3.Controls.Add(txt3);
tCell4.Controls.Add(txt4);
tCell5.Controls.Add(txt5);
tCell6.Controls.Add(txt6);
tCell7.Controls.Add(txt7);
tRow.Cells.Add(tCell1);
tRow.Cells.Add(tCell2);
tRow.Cells.Add(tCell3);
tRow.Cells.Add(tCell4);
tRow.Cells.Add(tCell5);
tRow.Cells.Add(tCell6);
tRow.Cells.Add(tCell7);
```
As you can see there's basically 4 instructions getting repeated 7 times. I'm sure there has to be a way to accomplish this with just 4 lines of code within a FOR loop and having all the names dynamically assigned but I just can't seem to find anything that would point me in the direction of how to do it.
Something like the following is what I'm after:
```
for (int i = 0; i < 6; i++)
{
TableCell tCell[i] = new TableCell();
TextBox txt[i] = new TextBox();
tCell[i].Controls.Add(txt[i]);
tRow.Cells.Add(tCell[i]);
}
```
Any help would be much appreciated.
|
I think this should do it:
```
for (int i = 0; i < 7; i++)
{
TableCell tCell = new TableCell();
TextBox txt = new TextBox();
tCell.Controls.Add(txt);
tRow.Cells.Add(tCell);
}
```
Make sure that 6 is changed to a 7.
|
This should work fine?
```
for (int i = 0; i < 6; i++)
{
TableCell tCell = new TableCell();
TextBox txt = new TextBox();
tCell.Controls.Add(txt);
tRow.Cells.Add(tCell);
}
```
I don't really get what you need the names for though.
Do you plan on using the "txt5" name as a reference to that specific textbox?
Why not just use `tRow.Cells[4].Controls[0] As TextBox` ?
|
Creating controls within a Loop
|
[
"",
"c#",
"asp.net",
".net-2.0",
""
] |
Why is it bad to name a variable `id` in Python?
|
`id()` is a fundamental built-in:
> Help on built-in function `id` in module
> `__builtin__`:
>
> ```
> id(...)
>
> id(object) -> integer
>
> Return the identity of an object. This is guaranteed to be unique among
> simultaneously existing objects. (Hint: it's the object's memory
> address.)
> ```
In general, using variable names that eclipse a keyword or built-in function in any language is a bad idea, even if it is allowed.
|
In **PEP 8 - Style Guide for Python Code**, the following guidance appears in the section [Descriptive: Naming Styles](https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles) :
> * `single_trailing_underscore_` : used by convention to avoid conflicts
> with Python keyword, e.g.
>
> `Tkinter.Toplevel(master, class_='ClassName')`
So, to answer the question, an example that applies this guideline is:
```
id_ = 42
```
Including the trailing underscore in the variable name makes the intent clear (to those familiar with the guidance in PEP 8).
|
'id' is a bad variable name in Python
|
[
"",
"python",
""
] |
I want to write a raw byte/byte stream to a position in a file.
This is what I have currently:
```
$fpr = fopen($out, 'r+');
fseek($fpr, 1); //seek to second byte
fwrite($fpr, 0x63);
fclose($fpr);
```
This currently writes the actually string value of "99" starting at byte offset 1. IE, it writes bytes "9" and "9". I just want to write the actual one byte value 0x63 which happens to represent number 99.
Thanks for your time.
|
`fwrite()` takes strings. Try `chr(0x63)` if you want to write a `0x63` byte to the file.
|
That's because fwrite() expects a string as its second argument. Try doing this instead:
```
fwrite($fpr, chr(0x63));
```
chr(0x63) returns a string with one character with ASCII value 0x63. (So it'll write the number 0x63 to the file.)
|
How can I use the PHP File api to write raw bytes?
|
[
"",
"php",
"file-io",
""
] |
I am creating an HTTP handler that listens for calls to a specific file type, and handles it accordingly. My HTTP Handler listens for .bcn files, then writes a cookie to the user's computer and sends back an image... this will be used in advertising banners so that the user is tagged as seeing the banner, and we can then offer special deals when they visit our site later.
The problem i'm having is getting access to the Page object... of course an HTTPHandler is not actually a page, and since the Response object lives within the Page object, I can't get access to it to write the cookie.
Is there a way around this, or do i need to revert back to just using a standard aspx page to do this?
Thanks heaps..
Greg
|
You can access the Response object from the HttpContext object passed to the ProcessRequest method from IHttpHandler. This is the same object exposed by Page.Response.
|
the ProcessRequest() method defined in IHttpHandler is passed a HttpContext reference. This HttpContext object will have a property named Response and Request, which you can use.
|
Writing a cookie from an ASP.Net HTTPHandler - Page.Response object?
|
[
"",
"c#",
"asp.net",
"cookies",
"asp.net-1.1",
""
] |
I am trying to display a list of all files found in the selected directory (and optionally any subdirectories). The problem I am having is that when the GetFiles() method comes across a folder that it cannot access, it throws an exception and the process stops.
How do I ignore this exception (and ignore the protected folder/file) and continue adding accessible files to the list?
```
try
{
if (cbSubFolders.Checked == false)
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach (string fileName in files)
ProcessFile(fileName);
}
else
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
foreach (string fileName in files)
ProcessFile(fileName);
}
lblNumberOfFilesDisplay.Enabled = true;
}
catch (UnauthorizedAccessException) { }
finally {}
```
|
You will have to do the recursion manually; don't use AllDirectories - look one folder at a time, then try getting the files from sub-dirs. Untested, but something like below (note uses a delegate rather than building an array):
```
using System;
using System.IO;
static class Program
{
static void Main()
{
string path = ""; // TODO
ApplyAllFiles(path, ProcessFile);
}
static void ProcessFile(string path) {/* ... */}
static void ApplyAllFiles(string folder, Action<string> fileAction)
{
foreach (string file in Directory.GetFiles(folder))
{
fileAction(file);
}
foreach (string subDir in Directory.GetDirectories(folder))
{
try
{
ApplyAllFiles(subDir, fileAction);
}
catch
{
// swallow, log, whatever
}
}
}
}
```
|
Since .NET Standard 2.1 (.NET Core 3+, .NET 5+), you can now just do:
```
var filePaths = Directory.EnumerateFiles(@"C:\my\files", "*.xml", new EnumerationOptions
{
IgnoreInaccessible = true,
RecurseSubdirectories = true
});
```
According to the [MSDN docs](https://learn.microsoft.com/en-us/dotnet/api/system.io.enumerationoptions?view=netstandard-2.1) about **IgnoreInaccessible**:
> Gets or sets a value that indicates whether to skip files or directories when access is denied (for example, UnauthorizedAccessException or SecurityException). The default is true.
Default value is actually true, but I've kept it here just to show the property.
The same overload is available for `DirectoryInfo` as well.
|
Ignore folders/files when Directory.GetFiles() is denied access
|
[
"",
"c#",
"getfiles",
""
] |
This code produces a FileNotFoundException, but ultimately runs without issue:
```
void ReadXml()
{
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
//...
}
```
Here is the exception:
---
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
Additional information: Could not load file or assembly 'MyAssembly.XmlSerializers, Version=1.4.3190.15950, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
---
**It appears that the framework automatically generates the serialization assembly if it isn't found.** I can generate it manually using sgen.exe, which alleviates the exception.
**How do I get visual studio to generate the XML Serialization assembly automatically?**
---
**Update: The Generate Serialization Assembly: On setting doesn't appear to do anything.**
|
This is how I managed to do it by modifying the MSBUILD script in my .CSPROJ file:
First, open your .CSPROJ file as a file rather than as a project. Scroll to the bottom of the file until you find this commented out code, just before the close of the Project tag:
```
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
```
Now we just insert our own AfterBuild target to delete any existing XmlSerializer and SGen our own, like so:
```
<Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)" Outputs="$(OutputPath)$(_SGenDllName)">
<!-- Delete the file because I can't figure out how to force the SGen task. -->
<Delete
Files="$(TargetDir)$(TargetName).XmlSerializers.dll"
ContinueOnError="true" />
<SGen
BuildAssemblyName="$(TargetFileName)"
BuildAssemblyPath="$(OutputPath)"
References="@(ReferencePath)"
ShouldGenerateSerializer="true"
UseProxyTypes="false"
KeyContainer="$(KeyContainerName)"
KeyFile="$(KeyOriginatorFile)"
DelaySign="$(DelaySign)"
ToolPath="$(TargetFrameworkSDKToolsDirectory)"
Platform="$(Platform)">
<Output
TaskParameter="SerializationAssembly"
ItemName="SerializationAssembly" />
</SGen>
</Target>
```
That works for me.
|
As Martin has explained in [his answer](https://stackoverflow.com/a/264464/94928), turning on generation of the serialization assembly through the project properties is not enough because the SGen task is adding the `/proxytypes` switch to the sgen.exe command line.
Microsoft has a [documented MSBuild property](http://msdn.microsoft.com/en-us/library/bb629394.aspx) which allows you to disable the `/proxytypes` switch and causes the SGen Task to generate the serialization assemblies even if there are no proxy types in the assembly.
> SGenUseProxyTypes
>
> A boolean value that indicates whether proxy types
> should be generated by SGen.exe. The SGen target uses this property to
> set the UseProxyTypes flag. This property defaults to true, and there
> is no UI to change this. To generate the serialization assembly for
> non-webservice types, add this property to the project file and set it
> to false before importing the Microsoft.Common.Targets or the
> C#/VB.targets
As the documentation suggests you must modify your project file by hand, but you can add the `SGenUseProxyTypes` property to your configuration to enable generation. Your project files configuration would end up looking something like this:
```
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<!-- Snip... -->
<GenerateSerializationAssemblies>On</GenerateSerializationAssemblies>
<SGenUseProxyTypes>false</SGenUseProxyTypes>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<!-- Snip... -->
<GenerateSerializationAssemblies>On</GenerateSerializationAssemblies>
<SGenUseProxyTypes>false</SGenUseProxyTypes>
</PropertyGroup>
```
|
Generating an Xml Serialization assembly as part of my build
|
[
"",
"c#",
"xml",
"xml-serialization",
""
] |
```
function returnsAnArray ()
{
return array ('test');
}
echo returnsAnArray ()[0];
```
generates a syntax error in PHP. What's the most efficient way to directly obtain an element from a returned array without assigning the result to a temp variable?
|
Here's one way, using the [list](http://www.php.net/list) language construct
```
function returnsAnArray ()
{
return array ('test');
}
list($foo)=returnsAnArray();
```
You could grab a sequence of elements from an offset by combining this with [array\_slice](http://www.php.net/array_slice)
```
list($third,$fourth,$fifth)=array_slice(returnsAnArray(), 2, 3);
```
|
Define a new function for returning a specific index from an array.
```
function arr_index($arr, $i) { return $arr[$i]; }
```
You might want to add some error and type checking there.
And then use it like this:
```
echo arr_index(returnsAnArray(), 0);
```
Happy Coding :)
|
Most efficient way to index a returned array?
|
[
"",
"php",
""
] |
I want to build a site where the user can enter text and format it in Markdown. The reason I'd like a Javascript solution is because I want to display a live preview, just like on StackOverflow.
My site is not targeted at developers, however, so an editor control would be ideal.
I gather that on StackOverflow, the WMD editor is being used.
A quick search on Google also turns up Showdown library, which I think is actually being used by WMD.
Are there any other options? Are WMD/Showdown great tools already? What have been your experiences with the different options?
|
If you're not averse to using Ajax to generate the live preview, then another option is [markItUp!](http://markitup.jaysalvat.com/home/). markItUp! is a universal markup-editor, and very flexible. It does provide
an easy way of creating a markup editor, but unlike WMD, it doesn't provide its own live preview.
I used markItUp!, along with a simple JSP (using [MarkdownJ](http://sourceforge.net/projects/markdownj/)) for one of my open-source projects (a [Markdown plugin](http://github.com/myabc/roller-markdown/tree/master) for [Roller](http://roller.apache.org/)). If you're using another server-side technology, replace that simple JSP as appropriate.
I actually starting using this before I came across WMD. I'd agree, WMD is great, but has only just been open-sourced and is, at this stage, more difficult to customize the behavior of.
|
We've been pretty happy with WMD. There are a few niggling bugs in it, however. Nothing major, but I would *love* if John Fraser (the author) made the code open source so we can fix some of them. He's promised to do so but other real life projects are getting in the way.
~~I do follow up with John every week. I'll post on the blog once the WMD source is finally available.~~ Haven't been able to contact John Fraser in over a year now.
We have open sourced both the JavaScript Markdown library
<http://code.google.com/p/pagedown/>
and the server-side C# Markdown library
<http://code.google.com/p/markdownsharp/>
|
Is there any good Markdown Javascript library or control?
|
[
"",
"javascript",
"controls",
"markdown",
""
] |
I'm trying to use the `this` keyword in a static method, but the compiler won't allow me to use it.
Why not?
|
That's an easy one. The keyword 'this' returns a reference to the current instance of the class containing it. Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class. There is a much more [in depth explanation](http://msdn.microsoft.com/en-us/library/98f28cdx(printer).aspx) of what static members are and why/when to use them in the MSDN docs.
|
As an additional note, from a Static method, you can access or static members of that class. Making the example below valid and at times quite useful.
```
public static void StaticMethod(Object o)
{
MyClass.StaticProperty = o;
}
```
|
Why can't you use the keyword 'this' in a static method in .Net?
|
[
"",
"c#",
".net",
""
] |
Assume the following:
*models.py*
```
class Entry(models.Model):
title = models.CharField(max_length=50)
slug = models.CharField(max_length=50, unique=True)
body = models.CharField(max_length=200)
```
*admin.py*
```
class EntryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug':('title',)}
```
I want the slug to be pre-populated by the title, but I dont want the user to be able to edit it from the admin. I assumed that adding the fields=[] to the admin object and not including the slug would have worked, but it didnt. I also tried setting editable=False in the model, but that also didnt work (infact, stops the page from rendering).
Thoughts?
|
For this particular case you can override your save method to slugify (it's built-in method, look at django source) the title and store it in slug field. Also from there you can easily check if this slug is indeed unique and change it somehow if it's not.
Consider this example:
```
def save(self):
from django.template.defaultfilters import slugify
if not self.slug:
self.slug = slugify(self.title)
super(Your_Model_Name,self).save()
```
|
I'm not sure what you're asking for IS possible. Your best bet is probably to hide the slug from the admin interface completely by specifying your fieldsets, and than overriding the save method to copy the slug from the tile, and potentially slugifying it...
|
Is there a way to define which fields in the model are editable in the admin app?
|
[
"",
"python",
"django",
""
] |
SQL to find duplicate entries (within a group)
I have a small problem and I'm not sure what would be the best way to fix it, as I only have limited access to the database (Oracle) itself.
In our Table "EVENT" we have about 160k entries, each EVENT has a GROUPID and a normal entry has exactly 5 rows with the same GROUPID. Due to a bug we currently get a couple of duplicate entries (duplicate, so 10 rows instead of 5, just a different EVENTID. This may change, so it's just <> 5). We need to filter all the entries of these groups.
Due to limited access to the database we can not use a temporary table, nor can we add an index to the GROUPID column to make it faster.
We can get the GROUPIDs with this query, but we would need a second query to get the needed data
```
select A."GROUPID"
from "EVENT" A
group by A."GROUPID"
having count(A."GROUPID") <> 5
```
One solution would be a subselect:
```
select *
from "EVENT" A
where A."GROUPID" IN (
select B."GROUPID"
from "EVENT" B
group by B."GROUPID"
having count(B."GROUPID") <> 5
)
```
Without an index on GROUPID and 160k entries, this takes much too long.
Tried thinking about a join that can handle this, but can't find a good solution so far.
Anybody can find a good solution for this maybe?
Small edit:
We don't have 100% duplicates here, as each entry still has a unique ID and the GROUPID is not unique either (that's why we need to use "group by") - or maybe I just miss an easy solution for it :)
Small example about the data (I don't want to delete it, just find it)
`EVENTID | GROUPID | TYPEID
123456 123 12
123457 123 145
123458 123 2612
123459 123 41
123460 123 238
234567 123 12
234568 123 145
234569 123 2612
234570 123 41
234571 123 238`
It has some more columns, like timestamp etc, but as you can see already, everything is identical, besides the EVENTID.
We will run it more often for testing, to find the bug and check if it happens again.
|
You can get the answer with a join instead of a subquery
```
select
a.*
from
event as a
inner join
(select groupid
from event
group by groupid
having count(*) <> 5) as b
on a.groupid = b.groupid
```
This is a fairly common way of obtaining the all the information out of the rows in a group.
Like your suggested answer and the other responses, this will run a lot faster with an index on groupid. It's up to the DBA to balance the benefit of making your query run a lot faster against the cost of maintaining yet another index.
If the DBA decides against the index, make sure the appropriate people understand that its the index strategy and not the way you wrote the query that is slowing things down.
|
A classic problem for analytic queries to solve:
```
select eventid,
groupid,
typeid
from (
Select eventid,
groupid,
typeid,
count(*) over (partition by group_id) count_by_group_id
from EVENT
)
where count_by_group_id <> 5
```
|
SQL to find duplicate entries (within a group)
|
[
"",
"sql",
"oracle",
"join",
""
] |
I have a basic C# console application that reads a text file (CSV format) line by line and puts the data into a HashTable. The first CSV item in the line is the key (id num) and the rest of the line is the value. However I've discovered that my import file has a few duplicate keys that it shouldn't have. When I try to import the file the application errors out because you can't have duplicate keys in a HashTable. I want my program to be able to handle this error though. When I run into a duplicate key I would like to put that key into a arraylist and continue importing the rest of the data into the hashtable. How can I do this in C#
Here is my code:
---
private static Hashtable importFile(Hashtable myHashtable, String myFileName)
{
```
StreamReader sr = new StreamReader(myFileName);
CSVReader csvReader = new CSVReader();
ArrayList tempArray = new ArrayList();
int count = 0;
while (!sr.EndOfStream)
{
String temp = sr.ReadLine();
if (temp.StartsWith(" "))
{
ServMissing.Add(temp);
}
else
{
tempArray = csvReader.CSVParser(temp);
Boolean first = true;
String key = "";
String value = "";
foreach (String x in tempArray)
{
if (first)
{
key = x;
first = false;
}
else
{
value += x + ",";
}
}
myHashtable.Add(key, value);
}
count++;
}
Console.WriteLine("Import Count: " + count);
return myHashtable;
}
```
|
```
if (myHashtable.ContainsKey(key))
duplicates.Add(key);
else
myHashtable.Add(key, value);
```
|
A better solution is to call ContainsKey to check if the key exist before adding it to the hash table instead. Throwing exception on this kind of error is a performance hit and doesn't improve the program flow.
|
C# Exception Handling continue on error
|
[
"",
"c#",
"exception",
"csv",
""
] |
Sybase db tables do not have a concept of self updating row numbers. However , for one of the modules , I require the presence of rownumber corresponding to each row in the database such that max(Column) would always tell me the number of rows in the table.
I thought I'll introduce an int column and keep updating this column to keep track of the row number. However I'm having problems in updating this column in case of deletes. What sql should I use in delete trigger to update this column?
|
## Delete trigger
```
CREATE TRIGGER tigger ON myTable FOR DELETE
AS
update myTable
set id = id - (select count(*) from deleted d where d.id < t.id)
from myTable t
```
## To avoid locking problems
You could add an extra table (which joins to your primary table) like this:
```
CREATE TABLE rowCounter
(id int, -- foreign key to main table
rownum int)
```
... and use the rownum field from this table.
If you put the delete trigger on this table then you would hugely reduce the potential for locking problems.
## Approximate solution?
Does the table need to keep its rownumbers up to date all the time?
If not, you could have a job which runs every minute or so, which checks for gaps in the rownum, and does an update.
Question: do the rownumbers have to reflect the order in which rows were inserted?
If not, you could do far fewer updates, but only updating the most recent rows, "moving" them into gaps.
Leave a comment if you would like me to post any SQL for these ideas.
|
You can easily assign a unique number to each row by using an identity column. The identity can be a numeric or an integer (in ASE12+).
This will *almost* do what you require. There are certain circumstances in which you will get a gap in the identity sequence. (These are called "identity gaps", the best discussion on them is [here](http://www.sypron.nl/idgaps.html)). Also deletes will cause gaps in the sequence as you've identified.
Why do you need to use max(col) to get the number of rows in the table, when you could just use count(\*)? If you're trying to get the last row from the table, then you can do
```
select * from table where column = (select max(column) from table).
```
Regarding the delete trigger to update a manually managed column, I think this would be a potential source of deadlocks, and many performance issues. Imagine you have 1 million rows in your table, and you delete row 1, that's 999999 rows you now have to update to subtract 1 from the id.
|
Row number in Sybase tables
|
[
"",
"sql",
"sybase",
""
] |
I am looking for a pseudo random number generator which would be specialized to work fast when it is given a seed before generating each number. Most generators I have seen so far assume you set seed once and then generate a long sequence of numbers. The only thing which looks somewhat similar to I have seen so far is Perlin Noise, but it generates too "smooth" data - for similar inputs it tends to produce similar results.
The declaration of the generator should look something like:
```
int RandomNumber1(int seed);
```
Or:
```
int RandomNumber3(int seedX, int seedY, int seedZ);
```
I think having good RandomNumber1 should be enough, as it is possible to implement RandomNumber3 by hashing its inputs and passing the result into the RandomNumber1, but I wrote the 2nd prototype in case some implementation could use the independent inputs.
The intended use for this generator is to use it for procedural content generator, like generating a forest by placing trees in a grid and determining a random tree species and random spatial offsets for each location.
The generator needs to be very efficient (below 500 CPU cycles), because the procedural content is created in huge quantities in real time during rendering.
|
Seems like you're asking for a hash-function rather than a PRNG. Googling 'fast hash function' yields several promising-looking results.
[For example](http://burtleburtle.net/bob/hash/integer.html):
```
uint32_t hash( uint32_t a)
a = (a ^ 61) ^ (a >> 16);
a = a + (a << 3);
a = a ^ (a >> 4);
a = a * 0x27d4eb2d;
a = a ^ (a >> 15);
return a;
}
```
**Edit:** Yep, some hash functions definitely look more suitable than others.
For your purposes, it should be sufficient to eyeball thefunction and check that a single-bit change in the input will propagate to lots of output bits.
|
Yep, you are looking for a fast integer hash algorithm rather than a PRNG.
This [page](http://www.concentric.net/~Ttwang/tech/inthash.htm) has a few algorithms, I'm sure you'll find plenty more now you know the correct search terms.
**Edit**: The original page has been removed, a live version can be [found on GitHub](https://gist.github.com/badboy/6267743).
|
Fast pseudo random number generator for procedural content
|
[
"",
"c++",
"x86",
"random",
""
] |
I recently began profiling an osgi java application that I am writing using VisualVM. One thing I have noticed is that when the application starts sending data to a client (over JMS), the number of loaded classes starts increasing at a steady rate. The Heap size and the PermGen size remains constant, however. The number of classes never falls, even after it stops sending data. Is this a memory leak? I think it is, because the loaded classes have to be stored somewhere, however the heap and permgen never increase even after I run the application for several hours.
For the screenshot of my profiling application go [here](http://sites.google.com/site/javaperformacescreenshot/Home/profile.png)
|
> Are you dynamically creating new classes on the fly somehow?
Thanks for your help. I figured out what the problem is. In one of my classes, I was using Jaxb to create an XML string. In doing this, JAXB ueses reflection to create a new class.
```
JAXBContext context = JAXBContext.newInstance(this.getClass());
```
So although the JAXBContext wasn't saying around in the heap, the classes had been loaded.
I have run my program again, and I see a normal plateau as I would expect.
|
You might find some hotspot flags to be of use in understanding this behavior like:
* -XX:+TraceClassLoading
* -XX:+TraceClassUnloading
This is a good reference:
<http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp>
|
Possible Memory leak in Number of Loaded classes in Java Application
|
[
"",
"java",
"profiling",
""
] |
What's a simple way to implement a c++ Win32 program to...
- display an 800x600x24 uncompressed bitmap image
- in a window without borders (the only thing visible is the image)
- that closes after ten seconds
- and doesn't use MFC
|
You can:
* Create a dialog in your resource file
* Have it contain a Picture control
* Set the picture control type to Bitmap
* Create/import your bitmap in the resource file and set that bitmap ID to the picture control in your dialog
* Create the window by using CreateDialogParam
* Handle the WM\_INITDIALOG in order to set a timer for 10 seconds (use SetTimer)
* Handle WM\_TIMER to catch your timer event and to destroy the window (use DestroyWindow)
|
If you're targeting modern versions of Windows (Windows 2000) and above, you can use the [UpdateLayeredWindow](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-updatelayeredwindow) function to display any bitmap (including one with an alpha channel, if so desired).
I [blogged a four-part series](https://faithlife.codes/blog/2008/09/displaying_a_splash_screen_with_c_introduction/) on how to write a C++ Win32 app that does this. If you need to wait for exactly ten seconds to close the splash screen (instead of until the main window is ready), you would need to use Dan Cristoloveanu's suggested technique of a timer that calls DestroyWindow.
|
Quickest way to implement a C++ Win32 Splash Screen
|
[
"",
"c++",
"winapi",
""
] |
When viewing someone else's webpage containing an applet, how can I force Internet Explorer 6.0 to use a a particular JRE when I have several installed?
|
If you mean when you are not the person writing the web page, then you could disable the add ons you do not wish to use with the [Manage Add-Ons](http://windowsxp.mvps.org/addons.htm) IE Options screen added in Win XP SP2
|
First, disable the currently installed version of Java. To do this, go to **Control Panel > Java > Advanced > Default Java for Browsers** and uncheck **Microsoft Internet Explorer**.
Next, enable the version of Java you want to use instead. To do this, go to (for example) **C:\Program Files\Java\*jre1.5.0\_15*\bin** (where **jre1.5.0\_15** is the version of Java you want to use), and run **javacpl.exe**. Go to **Advanced > Default Java for Browsers** and check **Microsoft Internet Explorer**.
To get your old version of Java back you need to reverse these steps.
Note that in older versions of Java, **Default Java for Browsers** is called **<APPLET> Tag Support** (but the effect is the same).
The good thing about this method is that it doesn't affect other browsers, and doesn't affect the default system JRE.
|
Force Internet Explorer to use a specific Java Runtime Environment install?
|
[
"",
"internet-explorer",
"internet-explorer-6",
"java",
"plugins",
""
] |
How do I suspend a whole process (like the Process Explorer does when I click Suspend) in C#.
I'm starting the Process with Process.Start, and on a certain event, I want to suspend the process to be able to do some investigation on a "snapshot" of it.
|
Here's my suggestion:
```
[Flags]
public enum ThreadAccess : int
{
TERMINATE = (0x0001),
SUSPEND_RESUME = (0x0002),
GET_CONTEXT = (0x0008),
SET_CONTEXT = (0x0010),
SET_INFORMATION = (0x0020),
QUERY_INFORMATION = (0x0040),
SET_THREAD_TOKEN = (0x0080),
IMPERSONATE = (0x0100),
DIRECT_IMPERSONATION = (0x0200)
}
[DllImport("kernel32.dll")]
static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
[DllImport("kernel32.dll")]
static extern uint SuspendThread(IntPtr hThread);
[DllImport("kernel32.dll")]
static extern int ResumeThread(IntPtr hThread);
[DllImport("kernel32", CharSet = CharSet.Auto,SetLastError = true)]
static extern bool CloseHandle(IntPtr handle);
private static void SuspendProcess(int pid)
{
var process = Process.GetProcessById(pid); // throws exception if process does not exist
foreach (ProcessThread pT in process.Threads)
{
IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);
if (pOpenThread == IntPtr.Zero)
{
continue;
}
SuspendThread(pOpenThread);
CloseHandle(pOpenThread);
}
}
public static void ResumeProcess(int pid)
{
var process = Process.GetProcessById(pid);
if (process.ProcessName == string.Empty)
return;
foreach (ProcessThread pT in process.Threads)
{
IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);
if (pOpenThread == IntPtr.Zero)
{
continue;
}
var suspendCount = 0;
do
{
suspendCount = ResumeThread(pOpenThread);
} while (suspendCount > 0);
CloseHandle(pOpenThread);
}
}
```
|
Thanks to Magnus
After including the Flags, I modified the code a bit to be an extension method in my project. I could now use
```
var process = Process.GetProcessById(param.PId);
process.Suspend();
```
Here is the code for those who might be interested.
```
public static class ProcessExtension
{
[DllImport("kernel32.dll")]
static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
[DllImport("kernel32.dll")]
static extern uint SuspendThread(IntPtr hThread);
[DllImport("kernel32.dll")]
static extern int ResumeThread(IntPtr hThread);
public static void Suspend(this Process process)
{
foreach (ProcessThread thread in process.Threads)
{
var pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)thread.Id);
if (pOpenThread == IntPtr.Zero)
{
break;
}
SuspendThread(pOpenThread);
}
}
public static void Resume(this Process process)
{
foreach (ProcessThread thread in process.Threads)
{
var pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)thread.Id);
if (pOpenThread == IntPtr.Zero)
{
break;
}
ResumeThread(pOpenThread);
}
}
}
```
I have a utility done which I use to generally suspend/kill/list a process. Full source is [on Git](https://github.com/SarathR/ProcessUtil.git)
|
Suspend Process in C#
|
[
"",
"c#",
".net",
""
] |
I have a class that looks like this
```
public class SomeClass
{
public SomeChildClass[] childArray;
}
```
which will output XML from the XMLSerializer like this:
```
<SomeClass>
<SomeChildClass>
...
</SomeChildClass>
<SomeChildClass>
...
</SomeChildClass>
</SomeClass>
```
But I want the XML to look like this:
```
<SomeClass>
<SomeChildClass index=1>
...
</SomeChildClass>
<SomeChildClass index=2>
...
</SomeChildClass>
</SomeClass>
```
Where the index attribute is equal to the items position in the array.
I could add an index property to SomeChildClass with the "XMLAttribute" attribute but then I would have to remember to loop through the array and set that value before I serialize my object.
Is there some attribute i can add or some other way to automatically generate the index attribute for me?
|
The best approach would be to do what you said and add a property to the "SomeChildClass" like this
```
[XmlAttribute("Index")]
public int Order
{ { get; set; } }
```
Then however you are adding these items to your array, make sure that this property get's set. Then when you serialize....Presto!
|
You may need to look into implementing System.Xml.Serialization.IXmlSerializable to accomplish this.
|
Including arrary index in XML Serialization
|
[
"",
"c#",
".net",
"xml-serialization",
""
] |
I have returned to php development from [Moose](http://www.iinteractive.com/moose/) and I really miss CLOS like object model for php. Is there some kind of syntaxtic sugar which would allow me to write **less code** in php when dealing with objects?
Just to stress this requirement a bit more. I don't want to write one thing in several places. I can live with part of code being generated automatically, but in the code that I have to see to develop I don't want to see redundant information which is just clutter (think: LISP macro if you really need more analogy). So this part can be also called DSL if that makes more sense.
I would love to have at least **roles** (mixins), and some kind of **introspection** without re-inventing the weel. Code generators and auto-loaders might be one way to solve at least part of this problem.
p.s. For JavaScript there is [Joose](http://code.google.com/p/joose-js/), so similar API would be very useful.
|
There is also new project <http://github.com/huberry/phuby> which implements roles in php!
|
There are no mixins in php yet but there is an RFC for traits which will work roughly the same. <http://wiki.php.net/rfc/traits>
Using overloading for \_\_call can allow you to dispatch methods to other classes and have it look like a mixin.
|
CLOS like object model for PHP
|
[
"",
"php",
"oop",
"moose",
"clos",
""
] |
What is the difference between g++ and gcc? Which one of them should be used for general c++ development?
|
`gcc` and `g++` are compiler-drivers of the GNU Compiler *Collection* (which was once upon a time just the GNU *C Compiler*).
Even though they automatically determine which backends (`cc1` `cc1plus` ...) to call depending on the file-type, unless overridden with `-x language`, they have some differences.
The probably most important difference in their defaults is which libraries they link against automatically.
According to GCC's online documentation [link options](https://gcc.gnu.org/onlinedocs/gcc/Link-Options.html) and [how g++ is invoked](https://gcc.gnu.org/onlinedocs/gcc/Invoking-G_002b_002b.html), `g++` is *roughly* equivalent to `gcc -xc++ -lstdc++ -shared-libgcc` (the 1st is a compiler option, the 2nd two are linker options). This can be checked by running both with the `-v` option (it displays the backend toolchain commands being run).
By default (and unlike `gcc`), [g++ also adds linker option `-lm`](https://stackoverflow.com/questions/1033898/why-do-you-have-to-link-the-math-library-in-c/1033940#1033940) -- to link against `libm` which contains implementations for `math.h`.
|
GCC: GNU Compiler Collection
* Referrers to all the different languages that are supported by the GNU compiler.
`gcc`: GNU C Compiler
`g++`: GNU C++ Compiler
The main differences:
1. `gcc` will compile: `*.c\*.cpp` files as C and C++ respectively.
2. `g++` will compile: `*.c\*.cpp` files but they will all be treated as C++ files.
3. Also if you use `g++` to link the object files it automatically links in the std C++ libraries (`gcc` does not do this).
4. `gcc` compiling C files has fewer predefined macros.
5. `gcc` compiling `*.cpp` and `g++` compiling `*.c\*.cpp` files has a few extra macros.
Extra Macros when compiling `*.cpp` files:
```
#define __GXX_WEAK__ 1
#define __cplusplus 1
#define __DEPRECATED 1
#define __GNUG__ 4
#define __EXCEPTIONS 1
#define __private_extern__ extern
```
|
What is the difference between g++ and gcc?
|
[
"",
"c++",
"gcc",
"g++",
""
] |
From [Wikipedia](http://en.wikipedia.org/wiki/Generic_programming):
> Generic programming is a style of
> computer programming in which
> algorithms are written in terms of
> to-be-specified-later types that are
> then instantiated when needed for
> specific types provided as parameters
> and was pioneered by Ada which
> appeared in 1983. This approach
> permits writing common functions or
> types that differ only in the set of
> types on which they operate when used,
> thus reducing duplication.
Generics provide the ability to define types that are specified later. You don't have to cast items to a type to use them because they are already typed.
Why does C# and VB have Generics? What benefit do they provide? What benefits do you find using them?
What other languages also have generics?
|
C# and VB have generics to take advantage of generics support in the underlying CLR (or is the other way around?). They allow you to write code ina statically-typed language that can apply to more than one kind of type without rewriting the code for each type you use them for (the runtime will do that for you) or otherwise using **System.Object** and casting everywhere (like we had to do with ArrayList).
Did you read the [article](http://en.wikipedia.org/wiki/Generic_programming)?
These languages also have generics:
* C++ (via *templates*)
* Ada (via *templates*)
* Eiffel
* D (via *templates*)
* Haskell
* Java
|
Personally, I think they allows to save a lot of time. I'm still using .NET Framework 1.1 and every time you want a specific collection, you need to create a strongly typed collection by implementing CollectionBase. With Generics, you just need to declare your collection like that `List<MyObject>` and it's done.
|
Why do C# and VB have Generics? What benefit do they provide? Generics, FTW
|
[
"",
"c#",
".net",
"vb.net",
"generics",
""
] |
I just want a simple tool that will help me quickly write scripts/packages that I can schedule to run. My transform requirements are pretty simple (changing column names, merging/splitting tables, and date conversions). I'll sacrifice flexibility for speed of development on this one.
Any come to mind?
|
SQL Server 2005? SSIS (but I wouldn't call it simple, but then again out of the list of things you gave, only the naming is really simple)
You can actually script package creation using C# (.NET/whatever, presumably even PowerShell).
Resources [here](http://blogs.conchango.com/jamiethomson/archive/2007/03/28/SSIS_3A00_-Building-Packages-Programatically.aspx) and [here](http://msdn.microsoft.com/en-us/library/ms345167.aspx)
EDIT: (hope you don't mind me butting in here Cade) Check that your ODBC driver plays nicely with SSIS. Some drivers (DB2/400 and some versions of Sybase for example) don't work all that well.
|
I like the Pentaho Data Integration tool (also known as kettle) - although that might be a bit "too big for you .. but worth checking out!
|
Tool: ETL from an ODBC to SQL 05?
|
[
"",
"sql",
"database",
"odbc",
"etl",
""
] |
When I try this with a generic class where this.value is T:
```
if (this.value.GetType() == typeof(int))
{
((int)this.value)++;
}
else
{
throw new InvalidOperationException
("T must be an int to perform this operation");
}
```
I get a compile-time error: "Cannot convert type 'T' to 'int'"
What should I do to perform an integral operation on this.value when it's an int?
Note that this is just an example. The code does type conversions with generics, and "int" is just an example of one type for T.
|
Unfortunately, it is very hard to convince the compiler about specific T implementations. One (nasty) approach is to cast to object in the middle (note this will box and unbox value-types):
```
int i = (int)(object)this.value;
i++;
this.value = (T)(object)i;
```
Ugly but it works. In .NET 3.5 I have some better wrappers for generic arithmetic, [here](http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html). The Operator class is part of [MiscUtil](http://www.yoda.arachsys.com/csharp/miscutil/); at the simplest level, I suspect AddAlternative would work very well:
```
this.value = Operator.AddAlternative(this.value, 1);
```
This should infer the implicit <T,int> automatically, or you can add them yourself:
```
this.value = Operator.AddAlternative<T,int>(this.value, 1);
```
**Benefit**: This is preferable to the original code as it doesn't actually care about the original T - it will work for any type (even your own) that supports "T +(T,int)".
I think there is also a ChangeType hiding around somewhere in there...
[edit] Collin K and others make a valid remark about the architectural implications - but being pragmatic there are times when the T really does matter that much... but I'd agree with avoiding this type of specialization unless *really* necessary. That said (as per my comment on Collin's post), the ability to perform things like basic arithmetic (increment, Int32 division, etc) on (for example) a Matrix<T> [for T in decimal/float/int/double/etc] is often highly valuable.
|
In my opinion, type-specific code in a generic class is a code smell. I would refactor it to get something like this:
```
public class MyClass<T>
{
...
}
public class IntClass : MyClass<int>
{
public void IncrementMe()
{
this.value++;
}
}
```
|
Typing generic values (C#)
|
[
"",
"c#",
"generics",
""
] |
It seems like a standard requirement: next time the user launches the application, open the window in the same position and state as it was before. Here's my wish list:
* Window position same as it was
+ Unless the screen has resized and the old position is now off screen.
* Splitters should retain their position
* Tab containers should retain their selection
* Some dropdowns should retain their selection
* Window state (maximize, minimize, normal) is the same as it was.
+ Maybe you should never start minimized, I haven't decided.
I'll add my current solutions as an answer along with the limitations.
|
My other option is to write more custom code around the application settings and execute it on formLoad and formClosed. This doesn't use data binding.
Drawbacks:
* More code to write.
* Very fiddly. The order you set the properties on formLoad is confusing. For example, you have to make sure you've set the window size before you set the splitter distance.
Right now, this is my preferred solution, but it seems like too much work. To reduce the work, I created a WindowSettings class that serializes the window location, size, state, and any splitter positions to a single application setting. Then I can just create a setting of that type for each form in my application, save on close, and restore on load.
I posted [the source code](https://github.com/donkirkby/donkirkby/blob/master/WindowSettings/WindowSettings.cs), including the WindowSettings class and some forms that use it. Instructions on adding it to a project are included in the WindowSettings.cs file. The trickiest part was figuring out how to add an application setting with a custom type. You choose Browse... from the type dropdown, and then manually enter the namespace and class name. Types from your project don't show up in the list.
**Update:** I added some static methods to simplify the boilerplate code that you add to each form. Once you've followed the instructions for adding the WindowSettings class to your project and creating an application setting, here's an example of the code that has to be added to each form whose position you want to record and restore.
```
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
Settings.Default.CustomWindowSettings = WindowSettings.Record(
Settings.Default.CustomWindowSettings,
this,
splitContainer1);
}
private void MyForm_Load(object sender, EventArgs e)
{
WindowSettings.Restore(
Settings.Default.CustomWindowSettings,
this,
splitContainer1);
}
```
|
The sample below shows how I do it
* SavePreferences is called when closing the form and saves the form's size, and a flag indicating if it's maximized (in this version I don't save if it's minimized - it will come back up restored or maximized next time).
* LoadPreferences is called from OnLoad.
* First save the design-time WindowState and set it to Normal. You can only successfully set the form size if it's WindowState is Normal.
* Next restore the Size from your persisted settings.
* Now make sure the form fits on your screen (call to FitToScreen). The screen resolution may have changed since you last ran the application.
* Finally set the WindowState back to Maximized (if persisted as such), or to the design-time value saved earlier.
This could obviously be adapted to persist the start position and whether the form was minimized when closed - I didn't need to do that. Other settings for controls on your form such as splitter position and tab container are straightforward.
```
private void FitToScreen()
{
if (this.Width > Screen.PrimaryScreen.WorkingArea.Width)
{
this.Width = Screen.PrimaryScreen.WorkingArea.Width;
}
if (this.Height > Screen.PrimaryScreen.WorkingArea.Height)
{
this.Height = Screen.PrimaryScreen.WorkingArea.Height;
}
}
private void LoadPreferences()
{
// Called from Form.OnLoad
// Remember the initial window state and set it to Normal before sizing the form
FormWindowState initialWindowState = this.WindowState;
this.WindowState = FormWindowState.Normal;
this.Size = UserPreferencesManager.LoadSetting("_Size", this.Size);
_currentFormSize = Size;
// Fit to the current screen size in case the screen resolution
// has changed since the size was last persisted.
FitToScreen();
bool isMaximized = UserPreferencesManager.LoadSetting("_Max", initialWindowState == FormWindowState.Maximized);
WindowState = isMaximized ? FormWindowState.Maximized : FormWindowState.Normal;
}
private void SavePreferences()
{
// Called from Form.OnClosed
UserPreferencesManager.SaveSetting("_Size", _currentFormSize);
UserPreferencesManager.SaveSetting("_Max", this.WindowState == FormWindowState.Maximized);
... save other settings
}
```
x
|
How to record window position in Windows Forms application settings
|
[
"",
"c#",
".net",
"winforms",
"settings",
""
] |
I am looking for a toolkit that will allow me to design widgets containing 2D graphics for an elevator simulation in Java. Once created, those widgets will be integrated with SWT, Swing, or QtJambi framework.
Background information:
I am developing an Elevator Simulator for fun. My main goal is to increase my knowledge of Java, Eclipse IDE, and more importantly concurrency. It is certainly fun and I enjoyed implementing this [State Machine Pattern](http://dotnet.zcu.cz/NET_2006/Papers_2006/short/B31-full.pdf).
Anyway, I am at a point where I would like to see the Elevator on the screen and not limit myself to log its operations on the console.
I will probably choose SWT, Swing, or QtJambi for the UI controls but I am wondering what to do with the graphical part of the simulation.
|
You can use an SWT canvas (or Swing canvas, or OpenGL canvas via JOGL, ...), and set it up as an Observer of your simulation, and whenever the simulation state changes, you can redraw the new state.
|
You could get some abstract graphics out of a Graph visualisation tool such as [JGraph](http://jgraph.com/). You could use this to visualise which state your elevator is in. However, i'm not sure how flexible these sort of graph visualisation tools are and whether you can add your own graphics and animations.
|
Selecting proper toolkit for a 2D simulation project in Java
|
[
"",
"java",
"graphics",
"simulation",
""
] |
Is it possible to retrieve items from a Python dictionary in the order that they were inserted?
|
The standard Python `dict` does this by default if you're using CPython 3.6+ (or Python 3.7+ for any other implementation of Python).
On older versions of Python you can use [`collections.OrderedDict`](https://docs.python.org/library/collections.html#ordereddict-objects).
|
As of Python 3.7, the standard dict preserves insertion order. From the [docs](https://docs.python.org/3.7/library/stdtypes.html#mapping-types-dict):
> Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was implementation detail of CPython from 3.6.
So, you should be able to iterate over the dictionary normally or use `popitem()`.
|
How do you retrieve items from a dictionary in the order that they're inserted?
|
[
"",
"python",
"dictionary",
""
] |
How would I have a [JavaScript](http://en.wikipedia.org/wiki/JavaScript) action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark, then the new URL is used?
It would also be nice if the back button would reload the original URL.
I am trying to record JavaScript state in the URL.
|
With HTML 5, use the [`history.pushState` function](http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html). As an example:
```
<script type="text/javascript">
var stateObj = { foo: "bar" };
function change_my_url()
{
history.pushState(stateObj, "page 2", "bar.html");
}
var link = document.getElementById('click');
link.addEventListener('click', change_my_url, false);
</script>
```
and a href:
```
<a href="#" id='click'>Click to change url to bar.html</a>
```
---
If you want to change the URL without adding an entry to the back button list, use `history.replaceState` instead.
|
If you want it to work in browsers that don't support `history.pushState` and `history.popState` yet, the "old" way is to set the fragment identifier, which won't cause a page reload.
The basic idea is to set the `window.location.hash` property to a value that contains whatever state information you need, then either use the [window.onhashchange event](https://developer.mozilla.org/en/DOM/window.onhashchange), or for older browsers that don't support `onhashchange` (IE < 8, Firefox < 3.6), periodically check to see if the hash has changed (using `setInterval` for example) and update the page. You will also need to check the hash value on page load to set up the initial content.
If you're using jQuery there's a [hashchange plugin](http://benalman.com/projects/jquery-hashchange-plugin/) that will use whichever method the browser supports. I'm sure there are plugins for other libraries as well.
One thing to be careful of is colliding with ids on the page, because the browser will scroll to any element with a matching id.
|
Change the URL in the browser without loading the new page using JavaScript
|
[
"",
"javascript",
"url",
"html5-history",
"fragment-identifier",
"hashchange",
""
] |
Is there a best practice when it comes to setting client side "onclick" events when using ASP.Net controls? Simply adding the onclick attribute results in a Visual Studio warning that onclick is not a valid attribute of that control. Adding it during the Page\_Load event through codebehind works, but is less clear than I'd like.
Are these the only two choices? Is there a right way to do this that I'm missing?
Thanks!
Eric Sipple
|
`**`*just a pre-note on the answer: HTML validation in VS is often BS. It complains about stuff that works IRL, even if that stuff is bad practice. But sometimes you gotta bend the rules to get stuff done.*
Every ASP.NET page (2.0 and greater) comes with a [ClientScriptManager](http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.aspx). You use this to register javascript from server side code. You can pass in javascript that registers events on controls after the page has loaded, when the HTML controls on the page are all present in the DOM.
It presents a single, unified place on pages to dynamically add javascript, which isn't a bad thing. It is, however, awfully ugly.
In this time of the death of the ASP.NET server control model, you might want to set events the way they will be in the future of ASP.NET MVC. Grab a copy of [jQuery](http://jquery.com) and add it to your website. You can then easily register your events thusly:
```
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("controlId").bind("click", function(e) { /* do your best here! */ });
});
</script>
</head>
<!-- etc -->
</html>
```
|
You can add the events through Javascript to the HTML elements that you want. This is the cleanest way, since it doesn't mix the server&client technologies. Furthermore, this way many handlers can be registered to the same event (in contrast to the onclick attribute).
Basically, the code would be
```
document.getElementById('myLovelyButtonId').attachEvent('onclick',doSomething)
```
for Internet Explorer and
```
document.getElementById('myLovelyButtonId').addEventListener('click',doSomething,false)
```
for other browsers. (doSomething is an event handler - JavaScript function). These calls should be made in the *window load* event handler
Consider reading the [advanced event registration article on Quirksmode](http://quirksmode.org/js/events_advanced.html) for further info.
Also, consider using a library like [jQuery](http://jquery.com/). This way, the statement will become
```
$('#myLovelyButtonId').click(
function doSomething () {
alert('my lovely code here');
});
```
|
Using Javascript With ASP.Net controls
|
[
"",
"asp.net",
"javascript",
"events",
""
] |
I am creating a decoupled WMI provider in a class library. Everything I have read points towards including something along these lines:
```
[System.ComponentModel.RunInstaller(true)]
public class MyApplicationManagementInstaller : DefaultManagementInstaller { }
```
I gather the purpose of this installation is because the Windows WMI infrastructure needs to be aware of the structure of my WMI provider before it is used.
My question is - when is this "installer" ran? MSDN says that the installer will be invoked "during installation of an assembly", but I am not sure what that means or when it would happen in the context of a class library containing a WMI provider.
I was under the impression that this was an automated replacement for manually running **InstallUtil.exe** against the assembly containing the WMI provider, but changes I make to the provider are not recognised by the Windows WMI infrastructure unless I manually run InstallUtil from the command prompt. I can do this on my own machine during development, but if an application using the provider is deployed to other machines - what then?
It seems that this RunInstaller / DefaultManagementInstaller combination is not working properly - correct?
|
As I understand, DefaultManagementInstaller is ran by installutil.exe - if you don't include it, the class is not installed in WMI. Maybe it is possible to create a 'setup project' or 'installer project' that runs it, but I'm not sure because I don't use Visual Studio.
[edit]
for remote instalation, an option could be to use Installutil with /MOF option to generate MOF for the assembly and use mofcomp to move it to WMI.
|
I use something like this to call InstallUtil programmatically:
```
public static void Run( Type type )
{
// Register WMI stuff
var installArgs = new[]
{
string.Format( "//logfile={0}", @"c:\Temp\sample.InstallLog" ), "//LogToConsole=false", "//ShowCallStack",
type.Assembly.Location,
};
ManagedInstallerClass.InstallHelper( installArgs );
}
```
Call this from your Main() method.
-dave
|
The RunInstaller attribute in a WMI provider assembly
|
[
"",
"c#",
"windows",
"wmi",
""
] |
Say I have two tables I want to join.
Categories:
```
id name
----------
1 Cars
2 Games
3 Pencils
```
And items:
```
id categoryid itemname
---------------------------
1 1 Ford
2 1 BMW
3 1 VW
4 2 Tetris
5 2 Pong
6 3 Foobar Pencil Factory
```
I want a query that returns the category and the first (and only the first) itemname:
```
category.id category.name item.id item.itemname
-------------------------------------------------
1 Cars 1 Ford
2 Games 4 Tetris
3 Pencils 6 Foobar Pencil Factory
```
And is there a way I could get random results like:
```
category.id category.name item.id item.itemname
-------------------------------------------------
1 Cars 3 VW
2 Games 5 Pong
3 Pencils 6 Foobar Pencil Factory
```
Thanks!
|
Just done a quick test. This seems to work:
```
mysql> select * from categories c, items i
-> where i.categoryid = c.id
-> group by c.id;
+------+---------+------+------------+----------------+
| id | name | id | categoryid | name |
+------+---------+------+------------+----------------+
| 1 | Cars | 1 | 1 | Ford |
| 2 | Games | 4 | 2 | Tetris |
| 3 | Pencils | 6 | 3 | Pencil Factory |
+------+---------+------+------------+----------------+
3 rows in set (0.00 sec)
```
I think this would fulfil your first question. Not sure about the second one - I think that needs an inner query with order by random() or something like that!
|
Mysql lets you to have columns not included in grouping or aggregate, in which case they've got random values:
```
select category.id, category.name, itemid, itemname
inner join
(select item.categoryid, item.id as itemid, item.name as itemname
from item group by categoryid)
on category.id = categoryid
```
Or, for minimums,
```
select category.id, category.name, itemid, itemname
inner join
(select item.categoryid, min(item.id) as itemid, item.name as itemname
from items
group by item.categoryid)
on category.id = categoryid
```
|
MySQL Query: LIMITing a JOIN
|
[
"",
"mysql",
"sql",
"join",
"greatest-n-per-group",
""
] |
I am trying to write a Windows Form and ASP.NET C# front-end and MSAccess backend for a pretty small database concept I have.
I have written this application once before in just MSAccess but I now need the app and database to be in different places. I have now figured out (thanks to a StackOverflow user) that ADO will be a bad choice because it has to have a connection open all of the time.
I bought Microsoft ADO.Net 2.0 Step-by-Step and I have read through some of it and understand (I think) the basic concepts at play in ADO.NET. (Datasets and the like)
Where I get confused is the actual implementation. What I want to know is do any of you know of a C# project that has a database backend which is open source that I can go look at the code and see how they did it. I find I learn better that way. The book has a CD with code examples that I may turn to, but I would rather see real code in a real app.
|
I haven't used this but it looks like it might be a good fit:
<http://www.codeproject.com/KB/database/DBaseFactGenerics.aspx>
|
Take a look at the MySQL .net connector. It is the nuts and bolts of how the ADO.net classes talk to the DB engine. ADO.net as a whole does not keep connections open. Certain higher level classes do. Technically the lower level objects such as the connection and command objects are part of ADO.net, but you have a high degree of control over them.
|
Where can I find an open source C# project that uses ADO.NET?
|
[
"",
"c#",
"database",
"open-source",
"ado.net",
""
] |
I would like to add a typing speed indicator just below the textarea we use on our contact form. It is just for fun and to give the user some interactivity with the page while they are completing the form.
It should display the average speed while typing and keep the last average when the keystrokes are idle. When they leave the textarea the last average should stick.
Ideally I would like to have a jQuery plugin if it is available.
[Edit] this was originally for just a few of my websites. But after I posted the question it struck me how this would be a neat feature for SO. If you agree [vote here](http://stackoverflow.uservoice.com/pages/general/suggestions/32755)
|
Here's a tested implementation,which seems ok, but I don't guarantee the math.
A Demo: <http://jsfiddle.net/iaezzy/pLpx5oLf/>
And the code:
```
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Type Speed</title>
<script type="text/javascript" src="js/jquery-1.2.6.js"></script>
<style type="text/css">
form {
margin: 20px auto;
width: 500px;
}
#textariffic {
width: 400px;
height: 400px;
font-size: 12px;
font-family: monospace;
line-height: 15px;
}
</style>
<script type="text/javascript">
$(function() {
$('textarea')
.keyup(checkSpeed);
});
var iLastTime = 0;
var iTime = 0;
var iTotal = 0;
var iKeys = 0;
function checkSpeed() {
iTime = new Date().getTime();
if (iLastTime != 0) {
iKeys++;
iTotal += iTime - iLastTime;
iWords = $('textarea').val().split(/\s/).length;
$('#CPM').html(Math.round(iKeys / iTotal * 6000, 2));
$('#WPM').html(Math.round(iWords / iTotal * 6000, 2));
}
iLastTime = iTime;
}
</script>
</head>
<body>
<form id="tipper">
<textarea id="textariffic"></textarea>
<p>
<span class="label">CPM</span>
<span id="CPM">0</span>
</p>
<p>
<span class="label">WPM</span>
<span id="WPM">0</span>
</p>
</form>
</body>
</html>
```
|
It's my own ego involvement:
```
<textarea id="b" onblur="clc();"></textarea>
<script>
t=0;
document.getElementById('b').onkeypress=function()
{
t==0 ? s=new Date() : e=new Date();
t=1;
}
function clc()
{
d = e.getTime() - s.getTime();
c = b.value.length;
b.value += "\n"+c+"s in "+d+"ms: "+c/d+" cpms";
}
</script>
```
I spent over a week on this learning JavaScript from zero (cutting and cutting). This will be a good starting point. It's now so simple that needs bare explanation. You could add anything to it. Its the best known minimalist and purest form.
It just gives you all into a textarea:

|
How can you display Typing Speed using Javascript or the jQuery library?
|
[
"",
"javascript",
""
] |
If I open a file using urllib2, like so:
```
remotefile = urllib2.urlopen('http://example.com/somefile.zip')
```
Is there an easy way to get the file name other then parsing the original URL?
EDIT: changed openfile to urlopen... not sure how that happened.
EDIT2: I ended up using:
```
filename = url.split('/')[-1].split('#')[0].split('?')[0]
```
Unless I'm mistaken, this should strip out all potential queries as well.
|
Did you mean [urllib2.urlopen](http://www.python.org/doc/2.5.2/lib/module-urllib2.html#l2h-3928)?
You could potentially lift the *intended* filename *if* the server was sending a Content-Disposition header by checking `remotefile.info()['Content-Disposition']`, but as it is I think you'll just have to parse the url.
You could use `urlparse.urlsplit`, but if you have any URLs like at the second example, you'll end up having to pull the file name out yourself anyway:
```
>>> urlparse.urlsplit('http://example.com/somefile.zip')
('http', 'example.com', '/somefile.zip', '', '')
>>> urlparse.urlsplit('http://example.com/somedir/somefile.zip')
('http', 'example.com', '/somedir/somefile.zip', '', '')
```
Might as well just do this:
```
>>> 'http://example.com/somefile.zip'.split('/')[-1]
'somefile.zip'
>>> 'http://example.com/somedir/somefile.zip'.split('/')[-1]
'somefile.zip'
```
|
If you only want the file name itself, assuming that there's no query variables at the end like <http://example.com/somedir/somefile.zip?foo=bar> then you can use os.path.basename for this:
```
[user@host]$ python
Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04)
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.basename("http://example.com/somefile.zip")
'somefile.zip'
>>> os.path.basename("http://example.com/somedir/somefile.zip")
'somefile.zip'
>>> os.path.basename("http://example.com/somedir/somefile.zip?foo=bar")
'somefile.zip?foo=bar'
```
Some other posters mentioned using urlparse, which will work, but you'd still need to strip the leading directory from the file name. If you use os.path.basename() then you don't have to worry about that, since it returns only the final part of the URL or file path.
|
urllib2 file name
|
[
"",
"python",
"url",
"urllib2",
""
] |
I have an application that seems to throw exceptions only after the program has been closed. And it is very inconsistent. (We all know how fun inconsistent bugs are...)
My guess is there is an error during the clean up process. But these memory read/write errors seem to indicate something wrong in my "unsafe" code usage (pointers?).
What I am interested in is what is the best method to debug these situations?
How do you debug a program that has already closed?
I am looking for a starting point to break down a larger problem.
These errors seem to present themselves in several ways (some run time, some debug):
```
1: .NET-BroadcastEventWindow.2.0.0.0.378734a.0: Application.exe - Application Error
The instruction at "0x03b4eddb" referenced memory at "0x00000004". The memory could not be "written".
2: Application.vshost.exe - Application Error
The instruction at "0x0450eddb" referenced memory at "0x00000004". The memory could not be "written".
3: Application.vshost.exe - Application Error
The instruction at "0x7c911669" referenced memory at "0x00000000". The memory could not be "read".
4: Application.vshost.exe - Application Error
The instruction at "0x7c910ed4" referenced memory at "0xfffffff8". The memory could not be "read".
```
|
If your app is multi-threaded you could be getting errors from worker threads which aren't properly terminating and trying to access disposed objects.
|
I had this problem using AcrobarReader COM component. Every now and then after application exit I had "Application.vshost.exe - Application Error" "memory could not be read". GC.Collect() and WaitForPendingFinalizers() didn't help.
My google-fu lead me to this page: <http://support.microsoft.com/kb/826220>. I modified method 3 for my case.
Using process explorer I found that AcroPDF.dll is not released before the last line in the Main function. So, here come the API calls.
DLLImports (DLLImport is in System.Runtime.InteropServices namespace):
```
<DllImport("kernel32.dll", EntryPoint:="GetModuleHandle", _
SetLastError:=True, CharSet:=CharSet.Auto, _
CallingConvention:=CallingConvention.StdCall)> _
Public Overloads Shared Function GetModuleHandle(ByVal sLibName As String) As IntPtr
End Function
<DllImport("kernel32.dll", EntryPoint:="FreeLibrary", _
SetLastError:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Overloads Shared Function FreeLibrary(ByVal hMod As IntPtr) As Integer
End Function
```
And then before application exit:
```
Dim hOwcHandle As IntPtr = GetModuleHandle("AcroPDF.dll")
If Not hOwcHandle.Equals(IntPtr.Zero) Then
FreeLibrary(hOwcHandle)
Debug.WriteLine("AcroPDF.dll freed")
End If
```
This procedure can be modified for any other ill-behaved dll. I just hope it doesn't introduce any new bugs.
|
Exceptions Thrown (Errors Encountered) After Program Termination
|
[
"",
"c#",
"vb.net",
"unsafe",
""
] |
I have a class holding complex scientific computations. It is set up to only allow a user to create a properly instantiated case. To properly test the code, however, requires setting internal state variables directly, since the reference documents supply this data in their test cases. Done improperly, however, it can invalidate the state.
So I must have the ability, a member function, to set internal variables from the unit test programs. But I want to **strongly discourage** normal users from calling this function. (Yes, a determined user can muck with anything... but I don't want to *advertise* that there is a way to do something *wrong*.)
It would be nice to be able to tell Intellisense to not show the function, for instance.
The best solution I have at the moment is to just name the function something like: DangerousSet().
What other options do I have?
**Follow-Up**
I found Amy B's answer most useful to my situation. Thanks!
Mufasa's suggestion to use reflection was great, but harder to implement (for me).
Chris' suggestion of using a decorator was good, but didn't pan out.
BFree's suggestion on XML is also good, and was already in use, but doesn't really solve the problem.
Finally, BillTheLizard's suggestion that the problem is in the source documents is not something I can control. International experts publish highly technical books and journal articles for use by their community. The fact that they don't address my particular needs is a fact of life. There simply are no alternative documents.
|
Suppose you want to test this object by manipulating its fields.
```
public class ComplexCalculation
{
protected int favoriteNumber;
public int FavoriteNumber
{
get { return favoriteNumber; }
}
}
```
Place this object in your test assembly/namespace:
```
public class ComplexCalculationTest : ComplexCalculation
{
public void SetFavoriteNumber(int newFavoriteNumber)
{
this.favoriteNumber = newFavoriteNumber;
}
}
```
And write your test:
```
public void Test()
{
ComplexCalculationTest myTestObject = new ComplexCalculationTest();
myTestObject.SetFavoriteNumber(3);
ComplexCalculation myObject = myTestObject;
if (myObject.FavoriteNumber == 3)
Console.WriteLine("Win!");
}
```
PS: I know you said *internal*, but I don't think you meant [internal](http://msdn.microsoft.com/en-us/library/7c5ka91b(VS.80).aspx).
|
You can use [InternalsVisibleToAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx) to mark internal members as visible to your test assembly. It seems to shine when used in this context, though its not quite "friend".
1. Mark your `DangerousSet` function `internal` instead of `public`.
2. In Properties\AssemblyInfo.cs of the project containing `DangerousSet`:
`[assembly:InternalsVisibleTo("YourTestAssembly")]`
If you have two test assemblies for whatever reason, the syntax is:
```
[assembly:InternalsVisibleTo("TestAssembly1"),
InternalsVisibleTo("TestAssembly2")]
```
|
Hiding a function
|
[
"",
"c#",
"visual-studio",
"intellisense",
""
] |
I encountered the following ddl in a pl/sql script this morning:
create index genuser.idx$$\_0bdd0011
...
My initial thought was that the index name was generated by a tool...but I'm also not a pl/sql superstar so I could very well be incorrect. Does the double dollar sign have any special significance in this statement?
|
Your initial thought seems to be correct. That would look to be an index name generated by a tool (but not assigned by Oracle because an index name wasn't specified). Dollar signs don't have any particular meaning other than being valid symbols that are rarely used by human developers and so are handy to reduce the risk that a system-generated name conflicts with a human-generated name.
|
No special meaning or significance.
```
SQL> create table t (col number)
2 /
Table created.
SQL> create index idx$$_0bdd0011 on t(col)
2 /
Index created.
```
Note: CREATE INDEX is a DDL statement which is usually executed in a SQL script, not in PL/SQL.
|
pl/sql dollar operator?
|
[
"",
"sql",
"database",
"oracle",
""
] |
I have a bunch of tasks in a MySQL database, and one of the fields is "deadline date". Not every task has to have to a deadline date.
I'd like to use SQL to sort the tasks by deadline date, but put the ones without a deadline date in the back of the result set. As it is now, the null dates show up first, then the rest are sorted by deadline date earliest to latest.
Any ideas on how to do this with SQL alone? (I can do it with PHP if needed, but an SQL-only solution would be great.)
Thanks!
|
Here's a solution using only standard SQL, not ISNULL(). That function is not standard SQL, and may not work on other brands of RDBMS.
```
SELECT * FROM myTable
WHERE ...
ORDER BY CASE WHEN myDate IS NULL THEN 1 ELSE 0 END, myDate;
```
|
```
SELECT * FROM myTable
WHERE ...
ORDER BY ISNULL(myDate), myDate
```
|
Possible to use SQL to sort by date but put null dates at the back of the results set?
|
[
"",
"sql",
"mysql",
""
] |
I have a set of objects in a Vector from which I'd like to select a random subset (e.g. 100 items coming back; pick 5 randomly). In my first (very hasty) pass I did an extremely simple and perhaps overly clever solution:
```
Vector itemsVector = getItems();
Collections.shuffle(itemsVector);
itemsVector.setSize(5);
```
While this has the advantage of being nice and simple, I suspect it's not going to scale very well, i.e. Collections.shuffle() must be O(n) at least. My less clever alternative is
```
Vector itemsVector = getItems();
Random rand = new Random(System.currentTimeMillis()); // would make this static to the class
List subsetList = new ArrayList(5);
for (int i = 0; i < 5; i++) {
// be sure to use Vector.remove() or you may get the same item twice
subsetList.add(itemsVector.remove(rand.nextInt(itemsVector.size())));
}
```
Any suggestions on better ways to draw out a random subset from a Collection?
|
Jon Bentley discusses this in either 'Programming Pearls' or 'More Programming Pearls'. You need to be careful with your N of M selection process, but I think the code shown works correctly. Rather than randomly shuffle all the items, you can do the random shuffle only shuffling the first N positions - which is a useful saving when N << M.
Knuth also discusses these algorithms - I believe that would be Vol 3 "Sorting and Searching", but my set is packed pending a move of house so I can't formally check that.
|
@Jonathan,
I believe this is the solution you're talking about:
```
void genknuth(int m, int n)
{ for (int i = 0; i < n; i++)
/* select m of remaining n-i */
if ((bigrand() % (n-i)) < m) {
cout << i << "\n";
m--;
}
}
```
It's on page 127 of Programming Pearls by Jon Bentley and is based off of Knuth's implementation.
EDIT: I just saw a further modification on page 129:
```
void genshuf(int m, int n)
{ int i,j;
int *x = new int[n];
for (i = 0; i < n; i++)
x[i] = i;
for (i = 0; i < m; i++) {
j = randint(i, n-1);
int t = x[i]; x[i] = x[j]; x[j] = t;
}
sort(x, x+m);
for (i = 0; i< m; i++)
cout << x[i] << "\n";
}
```
This is based on the idea that "...we need shuffle only the first *m* elements of the array..."
|
best way to pick a random subset from a collection?
|
[
"",
"java",
"algorithm",
"collections",
"random",
"subset",
""
] |
I'm creating a generic class and in one of the methods I need to know the Class of the generic type currently in use. The reason is that one of the method's I call expects this as an argument.
Example:
```
public class MyGenericClass<T> {
public void doSomething() {
// Snip...
// Call to a 3rd party lib
T bean = (T)someObject.create(T.class);
// Snip...
}
}
```
Clearly the example above doesn't work and results in the following error: Illegal class literal for the type parameter T.
My question is: does someone know a good alternative or workaround for this?
|
Still the same problems : Generic informations are erased at runtime, it cannot be recovered. A workaround is to pass the class T in parameter of a static method :
```
public class MyGenericClass<T> {
private final Class<T> clazz;
public static <U> MyGenericClass<U> createMyGeneric(Class<U> clazz) {
return new MyGenericClass<U>(clazz);
}
protected MyGenericClass(Class<T> clazz) {
this.clazz = clazz;
}
public void doSomething() {
T instance = clazz.newInstance();
}
}
```
It's ugly, but it works.
|
I was just pointed to this solution:
```
import java.lang.reflect.ParameterizedType;
public abstract class A<B> {
public Class<B> g() throws Exception {
ParameterizedType superclass =
(ParameterizedType) getClass().getGenericSuperclass();
return (Class<B>) superclass.getActualTypeArguments()[0];
}
}
```
This works if `A` is given a concrete type by a subclass:
```
new A<String>() {}.g() // this will work
class B extends A<String> {}
new B().g() // this will work
class C<T> extends A<T> {}
new C<String>().g() // this will NOT work
```
|
How to determine the class of a generic type?
|
[
"",
"java",
"generics",
""
] |
I have a photo website and i want to support tags as my original category bucketing is starting to fail (some pictures are family and vacations, or school and friends). Is there an agreed tagging db schema?
I still want to support having photos as part of an album.
Right now i have a few tables:
**Photos**
* PhotoID
* PhotoAlbumID
* Caption
* Date
**Photo Album**
* AlbumID
* AlbumName
* AlbumDate
|
There are various schemas which are effective, each with their own performance implications for the common queries you'll need as the number of tagged items grows:
* <http://howto.philippkeller.com/2005/04/24/Tags-Database-schemas/>
* <http://howto.philippkeller.com/2005/06/19/Tagsystems-performance-tests/>
Personally, I like having a tag table and a link table which associates tags with items, as it's denormalized (no duplication of tag names) and I can store additional information in the link table (such as when the item was tagged) when necessary.
You can also add some denormalised data if you're feeling frisky and want simple selects at the cost of the additional data maintenance required by storing usage counts in the tag table, or storing tag names which were used in the item table itself to avoid hitting the link table and tag table for each item, which is useful for displaying multiple items with all their tags and for simple tag versioning... if you're into that sort of thing ;)
|
I've done this in a small system without very many users, but I've wondered before if there was an "accepted" way to manage tags. After reading through the links posted by insin and plenty of other blog posts on tagging, it seems that the accepted way is to store it fully normalized and cache certain things if your data set gets too big.
Since it's a many-many relationship (each tag can belong to any number of photos - each photo can have many tags), relational database theory has you create a photo table, a tag table and a cross-reference table to link them.
```
photos
photoid
caption
filename
date
tags
tagid
tagname
phototags
photoid
tagid
```
This has scaling problems selecting from really large datasets, but so do all the less-normalized schemas (sorting and filtering by a text field will probably always be slower than using an integer, for example). If you grow as large as delicious or maybe even StackOverflow you'll probably have to do some caching of your tag sets.
Another issue you'll have to face is the issue of tag normalization. This doesn't have anything to do with database normalization - it's just making sure that (for example) the "StackOverflow", "stackoverflow" and "stack overflow" tags are the same. Lots of places disallow whitespace or automatically strip it out. Sometimes you'll see the same thing for punctuation - making "StackOverflow" the same as "Stack-Overflow". Auto-lowercasing is pretty standard. You'll even see special case normalization - like making "c#" the same as "csharp".
Happy tagging!
|
Is there an agreed ideal schema for tagging
|
[
"",
"sql",
"schema",
"tagging",
""
] |
I'd like to eliminate dependencies on hardcoded paths for configuration data in my Java apps, I understand that using ResourceBundle will help me use the classloader to find resources.
Can someone tell me how I would replace a hardcoded path to a resource (say a .properties configuration data file required by a class) with appropriate use of ResourceBundle? Simple clear example if possible, thanks all.
|
Prior to Java 6, ResourceBundle typically allowed:
* Strings from a group of localised properties files, using [PropertyResourceBundle](http://java.sun.com/javase/6/docs/api/java/util/PropertyResourceBundle.html)
* Objects from a group of localised classes, using [ListResourceBundle](http://java.sun.com/javase/6/docs/api/java/util/ListResourceBundle.html)
Java 6 comes with the [ResourceBundle.Control](http://java.sun.com/javase/6/docs/api/java/util/ResourceBundle.Control.html) class which opens the door to other sources of ResourceBundles, for example:
* XML files (see example 2 in Javadoc)
* Database rows
Hope this helps.
|
You will want to examine [Resource.getBundle(String)](http://java.sun.com/javase/6/docs/api/java/util/ResourceBundle.html#getBundle(java.lang.String) "Resource Bundle Javadoc"). You pass it the fully qualified name of a resource on the classpath to load as a properties file.
|
How do I use ResourceBundle to avoid hardcoded config paths in Java apps?
|
[
"",
"java",
"config",
"resourcebundle",
""
] |
I am supposed to provide my users a really simple way of capturing video clips out of my OpenGL application's main window. I am thinking of adding buttons and/or keyboard shortcuts for starting and stopping the capture; when starting, I could ask for a filename and other options, if any. It has to run in Windows (XP/Vista), but I also wouldn't like to close the Linux door which I've so far been able to keep open.
The application uses OpenGL fragment and shader programs, the effects due to which I absolutely need to have in the eventual videos.
It looks to me like there might be even several different approaches that could potentially fulfill my requirements (but I don't really know where I should start):
* An encoding library with functions like startRecording(filename), stopRecording, and captureFrame. I could call captureFrame() after every frame rendered (or every second/third/whatever). If doing so makes my program run slower, it's not really a problem.
* A standalone external program that can be programmatically controlled from my application. After all, a standalone program that can *not* be controlled almost does what I need... But as said, it should be really simple for the users to operate, and I would appreciate seamlessness as well; my application typically runs full-screen. Additionally, it should be possible to distribute as part of the installation package for my application, which I currently prepare using NSIS.
* Use the Windows API to capture screenshots frame-by-frame, then employ (for example) one of the [libraries mentioned here](https://stackoverflow.com/questions/93954/how-to-programatically-create-videos). It seems to be easy enough to find examples of how to capture screenshots in Windows; however, I would love a solution which doesn't really force me to get my hands super-dirty on the WinAPI level.
* Use OpenGL to render into an offscreen target, then use a library to produce the video. I don't know if this is even possible, and I'm afraid it might not be the path of least pain anyway. In particular, I would not like the actual rendering to take a different execution path depending on whether video is being captured or not. Additionally, I would avoid anything that might decrease the frame rate in the normal, non-capture mode.
If the solution were free in either sense of the word, then that would be great, but it's not really an absolute requirement. In general, the less bloat there is, the better. On the other hand, for reasons beyond this question, I cannot link in any GPL-only code, unfortunately.
Regarding the file format, I cannot expect my users to start googling for any codecs, but as long as also *displaying* the videos is easy enough for a basic-level Windows user, I don't really care what the format is. However, it would be great if it were possible to control the compression quality of the output.
Just to clarify: I *don't* need to capture video from an external device like camcorder, nor am I really interested in mouse movements, even though getting them does not harm either. There are no requirements regarding audio; the application makes no noise whatsoever.
I write C++ using Visual Studio 2008, for this very application also taking benefit of GLUT and GLUI. I have a solid understanding regarding C++ and linking in libraries and that sort of stuff, but on the other hand OpenGL is quite new for me: so far, I've really only learnt the necessary bits to actually get my job done.
I don't need a solution super-urgently, so feel free to take your time :)
|
There are two different questions here - how to grab frames from an OpenGL application, and how to turn them into a movie file.
The first question is easy enough; you just grab each frame with glReadPixels() (via a PBO if you need the performance).
The second question is a little harder since the cross-platform solutions (ffmpeg) tend to be GPL'd or LGPL'd. Is LGPL acceptable for your project? The Windows way of doing this (DirectShow) is a bit of a headache to use.
**Edit:** Since LGPL is ok and you can use ffmpeg, see [here](http://www.irisa.fr/texmex/people/dufouil/ffmpegdoxy/apiexample_8c-source.html#l00190) for an example of how to encode video.
|
[This](http://www.codeproject.com/KB/audio-video/avigenerator.aspx) does look pretty relevant for merging into an AVI (as suggested by Andrew), however I was really hoping to avoid the LPBITMAPINFOHEADERs etc.
Thanks for the answers, I will report on the success if there is going to be any :)
In the meantime, additional tips for encoding the raw frames from `glReadPixels` into video clips would be appreciated.
**Edit:** So far, ffmpeg suggested by Mike F seems to be the way to go. However, I didn't get into the actual implementation yet, but hopefully that will change in the near future!
|
Capturing video out of an OpenGL window in Windows
|
[
"",
"c++",
"opengl",
"video",
"screenshot",
"video-capture",
""
] |
I have fname and lname in my database, and a name could be stored as JOHN DOE or john DOE or JoHN dOE, but ultimately I want to display it as John Doe
fname being John and lname being Doe
|
seeing it is tagged PHP:
either
> `string ucfirst ( string $str );`
to uppercase first letter of the first word
or
> `string ucwords ( string $str );`
to uppercase the first letter of every word
you might want to use those in combination with
> `string strtolower ( string $str );`
to normalize all names to lower case first.
|
Be aware that there are other capitalisation formats, such as John McDoe, John D'Oe, John de O, and John van den Doe.
|
How do I display the first letter as uppercase?
|
[
"",
"php",
"mysql",
""
] |
I'm attempting to use extension methods to add an operater overload to the C# `StringBuilder` class. Specifically, given `StringBuilder` `sb`, I'd like `sb += "text"` to become equivalent to `sb.Append("text")`.
Here's the syntax for creating an extension method for `StringBuilder`:
```
public static class sbExtensions
{
public static StringBuilder blah(this StringBuilder sb)
{
return sb;
}
}
```
It successfully adds the `blah` extension method to the `StringBuilder`.
Unfortunately, operator overloading does not seem to work:
```
public static class sbExtensions
{
public static StringBuilder operator +(this StringBuilder sb, string s)
{
return sb.Append(s);
}
}
```
Among other issues, the keyword `this` is not allowed in this context.
Are adding operator overloads via extension methods possible? If so, what's the proper way to go about it?
|
This is not currently possible, because extension methods must be in static classes, and static classes can't have operator overloads. But the [feature is being discussed for *some* future release of C#](https://github.com/dotnet/csharplang/issues/192). Mads talked a bit more about implementing it [in this video from 2017](https://channel9.msdn.com/Blogs/Seth-Juarez/A-Preview-of-C-8-with-Mads-Torgersen#time=32m11s).
On why it isn't currently implemented, Mads Torgersen, C# Language PM says:
> ...for the Orcas release we decided to
> take the cautious approach and add
> only regular extension methods, as
> opposed to extention properties,
> events, operators, static methods, etc
> etc. Regular extension methods were
> what we needed for LINQ, and they had
> a syntactically minimal design that
> could not be easily mimicked for some
> of the other member kinds.
>
> We are becoming increasingly aware
> that other kinds of extension members
> could be useful, and so we will return
> to this issue after Orcas. No
> guarantees, though!
Further below in the same article:
> I am sorry to report that we will not
> be doing this in the next release. We
> did take extension members very
> seriously in our plans, and spent a
> lot of effort trying to get them
> right, but in the end we couldn't get
> it smooth enough, and decided to give
> way to other interesting features.
>
> This is still on our radar for future
> releases. What will help is if we get
> a good amount of compelling scenarios
> that can help drive the right design.
|
If you control the places where you want to use this "extension operator" (which you normally do with extension methods anyway), you can do something like this:
```
class Program {
static void Main(string[] args) {
StringBuilder sb = new StringBuilder();
ReceiveImportantMessage(sb);
Console.WriteLine(sb.ToString());
}
// the important thing is to use StringBuilderWrapper!
private static void ReceiveImportantMessage(StringBuilderWrapper sb) {
sb += "Hello World!";
}
}
public class StringBuilderWrapper {
public StringBuilderWrapper(StringBuilder sb) { StringBuilder = sb; }
public StringBuilder StringBuilder { get; private set; }
public static implicit operator StringBuilderWrapper(StringBuilder sb) {
return new StringBuilderWrapper(sb);
}
public static StringBuilderWrapper operator +(StringBuilderWrapper sbw, string s) {
sbw.StringBuilder.Append(s);
return sbw;
}
}
```
The `StringBuilderWrapper` class declares an [implicit conversion operator](http://msdn.microsoft.com/en-us/library/85w54y0a.aspx) from a `StringBuilder` *and* declares the desired `+` operator. This way, a `StringBuilder` can be passed to `ReceiveImportantMessage`, which will be silently converted to a `StringBuilderWrapper`, where the `+` operator can be used.
To make this fact more transparent to callers, you can declare `ReceiveImportantMessage` as taking a `StringBuilder` and just use code like this:
```
private static void ReceiveImportantMessage(StringBuilder sb) {
StringBuilderWrapper sbw = sb;
sbw += "Hello World!";
}
```
Or, to use it inline where you're already using a `StringBuilder`, you can simply do this:
```
StringBuilder sb = new StringBuilder();
StringBuilderWrapper sbw = sb;
sbw += "Hello World!";
Console.WriteLine(sb.ToString());
```
I created [a post](http://codecrafter.blogspot.com/2010/04/more-understandable-icomparable.html) about using a similar approach to make `IComparable` more understandable.
|
Operator Overloading with C# Extension Methods
|
[
"",
"c#",
"extension-methods",
"operator-overloading",
""
] |
I have a project that I'm working on and I need to be able to print out ID cards from the program. Are there any products out there that are reasonably priced so I can design a document for print and use it in .NET? I'm trying to avoid using System.Drawing from having to do it manually because when the company I work for needs to make changes to the ID card it will be a pain to change it later.
|
You could use Adobe Acrobat and one of the libraries out there for writing PDFs. That would let you design the document template in Adobe Acrobat, fill it out in code, and print it in code. There are some open source PDF writers and some commercial ones. The differences lie in the feature sets.
I've used [PDFWriter](http://www.codeproject.com/KB/printing/PDFWriter.aspx) in the past.
|
I've done something similar using a PowerPoint document as a template. I put fields or labels on the PP document and then programmatically fill them in. Obviously, adding or removing fields would require code changes, but the layout of the PP document could be changed easily.
|
Visual Print Design for .NET
|
[
"",
"c#",
".net",
"vb.net",
"printing",
""
] |
C++ preprocessor `#define` is totally different.
Is the PHP `define()` any different than just creating a var?
```
define("SETTING", 0);
$something = SETTING;
```
vs
```
$setting = 0;
$something = $setting;
```
|
'define' operation itself is rather slow - confirmed by xdebug profiler.
Here is benchmarks from <http://t3.dotgnu.info/blog/php/my-first-php-extension.html>:
* pure 'define'
380.785 fetches/sec
14.2647 mean msecs/first-response
* constants defined with 'hidef' extension
930.783 fetches/sec
6.30279 mean msecs/first-response
---
**broken link update**
The blog post referenced above has left the internet. It can still be viewed [here via Wayback Machine](http://web.archive.org/web/20100504144640/http://t3.dotgnu.info/blog/php/my-first-php-extension.html). Here is another [similar article](http://shwup.blogspot.com/2010/04/about-constants.html).
The libraries the author references can be found [here (apc\_define\_constants)](http://sg.php.net/manual/en/function.apc-define-constants.php) and [here (hidef extension)](http://pecl.php.net/package/hidef).
|
In general, the idea of a constant is to be *constant*, (Sounds funny, right? ;)) inside your *program*. Which means that the compiler (interpreter) will replace "FOOBAR" with FOOBAR's value throughout your entire script.
So much for the theory and the advantages - if you compile. Now PHP is pretty dynamic and in most cases you will not notice a different because the PHP script is compiled with each run. Afai-can-tell you should not see a notable difference in speed between constants and variables unless you use a byte-code cache such as [APC](http://php.net/apc), [Zend Optimizer](http://www.zend.com/products/guard/optimizer/) or [eAccelerator](http://eaccelerator.net/). Then it can make sense.
All other advantages/disadvantages of constants have been already noted here and can be found in the [PHP manual](http://php.net/constants).
|
How efficient is define in PHP?
|
[
"",
"php",
"c-preprocessor",
""
] |
If I have two dates (ex. `'8/18/2008'` and `'9/26/2008'`), what is the best way to get the number of days between these two dates?
|
If you have two date objects, you can just subtract them, which computes a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) object.
```
from datetime import date
d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d1 - d0
print(delta.days)
```
The relevant section of the docs:
<https://docs.python.org/library/datetime.html>.
See [this answer](https://stackoverflow.com/a/8258465) for another example.
|
Using the power of datetime:
```
from datetime import datetime
date_format = "%m/%d/%Y"
a = datetime.strptime('8/18/2008', date_format)
b = datetime.strptime('9/26/2008', date_format)
delta = b - a
print(delta.days)
# that's it how to calculate number of days between two given dates
```
|
How to calculate number of days between two given dates
|
[
"",
"python",
"date",
"datetime",
""
] |
I've written a small service (plain Win32) and I'd like to know if it's possible to run multiple instances of it when multiple users are logged on.
Basically, let's say we've got UserA and UserB for UserA the service would log on as "domain\UserA" and for UserB the service would log on as "domain\UserB" - this is from the same executable of course. I can change the logon dynamically using the ChangeServiceConfig() function, but it changes it system-wide it seems, while I'd like each user to have his own copy of the service running only for him.
Thank you in advance for any pointers.
|
Win32 services are designed to be system-wide, and start running before any user is logged in. If you want something to run on a per-user basis, it's probably better to design it as a regular application and run it from the user's Startup group.
|
Running with different accounts is possible. In fact, this is common. See svchost.exe, which implements a bunch of OS services.
I just don't get how you determine which accounts. In a big company, many PCs are set up so all 100.000+ employees could use it. You don't want to run your service as the logged-in users, nor can you want to run it for all 100.000 users. So for which accounts, I have to ask?
|
Multiple services from the same executable
|
[
"",
"c++",
"winapi",
"service",
""
] |
last time I asked how to populate a data structure [here](https://stackoverflow.com/questions/144474/java-arrays-vectors). Now I would like to know if there's something in Java, like the [print\_r](http://www.php.net/print_r) I use in PHP, to represent what I have populated in the Maps and lists without having to do my own algorithm.
Any ideas?
|
Calling `toString` on the collection should return a string containing all the elements string representations.
This won't work with built-in arrays though, as they don't have a `toString` override and will just give you a memory address.
|
There is really difference between toString() in java and print\_r() in PHP.
Note that there is also \_\_toString() in php which is equivalent to toString() in java, so this is not really the answer.
print\_r is used when we have a structure of objects and we like quickly to see the complete graph of objects with their values.
Implementing toString in java for each object has not the power to compare with print\_r.
Instead use gson. It does the same job as print\_r
> Gson gson = new GsonBuilder().setPrettyPrinting().create();
> System.out.println(gson.toJson(someObject));
In this way you do not need to implement toString for every object you need to test it.
Here is the documentation:
<http://sites.google.com/site/gson/gson-user-guide>
Demo classes (in java):
> public class A {
>
> ```
> int firstParameter = 0;
> B secondObject = new B();
> ```
>
> }
>
> public class B {
>
> ```
> String myName = "this is my name";
> ```
>
> }
Here is the output in php with print\_r:
> Object
> (
> [firstParameter:private] => 0
> [secondObject:private] => B Object
> (
> [myName:private] => this is my name
> )
>
> )
Here is the output in java with gson:
> {
> "firstParameter": 0,
> "secondObject": {
> "myName": "this is my name"
> }
> }
|
Equivalent of PHP's print_r in Java?
|
[
"",
"java",
"data-structures",
""
] |
If you are creating a 1d array in Python, is there any benefit to using the NumPy package?
|
It all depends on what you plan to do with the array. If all you're doing is creating arrays of simple data types and doing I/O, the [array](https://docs.python.org/3/library/array.html) module will do just fine.
If, on the other hand, you want to do any kind of numerical calculations, the array module doesn't provide any help with that. [NumPy](https://numpy.org/) (and [SciPy](https://scipy.org)) give you a wide variety of operations between arrays and special functions that are useful not only for scientific work but for things like advanced image manipulation or in general anything where you need to perform efficient calculations with large amounts of data.
Numpy is also much more flexible, e.g. it supports arrays of any type of Python objects, and is also able to interact "natively" with your own objects if they conform to the [array interface](https://numpy.org/doc/stable/reference/arrays.interface.html).
|
Small bootstrapping for the benefit of whoever might find this useful (following the excellent answer by @dF.):
```
import numpy as np
from array import array
# Fixed size numpy array
def np_fixed(n):
q = np.empty(n)
for i in range(n):
q[i] = i
return q
# Resize with np.resize
def np_class_resize(isize, n):
q = np.empty(isize)
for i in range(n):
if i>=q.shape[0]:
q = np.resize(q, q.shape[0]*2)
q[i] = i
return q
# Resize with the numpy.array method
def np_method_resize(isize, n):
q = np.empty(isize)
for i in range(n):
if i>=q.shape[0]:
q.resize(q.shape[0]*2)
q[i] = i
return q
# Array.array append
def arr(n):
q = array('d')
for i in range(n):
q.append(i)
return q
isize = 1000
n = 10000000
```
The output gives:
```
%timeit -r 10 a = np_fixed(n)
%timeit -r 10 a = np_class_resize(isize, n)
%timeit -r 10 a = np_method_resize(isize, n)
%timeit -r 10 a = arr(n)
1 loop, best of 10: 868 ms per loop
1 loop, best of 10: 2.03 s per loop
1 loop, best of 10: 2.02 s per loop
1 loop, best of 10: 1.89 s per loop
```
It seems that array.array is slightly faster and the 'api' saves you some hassle, but if you need more than just storing doubles then numpy.resize is not a bad choice after all (if used correctly).
|
array.array versus numpy.array
|
[
"",
"python",
"arrays",
"numpy",
""
] |
I have an application written in java, and I want to add a flash front end to it. The flash front end will run on the same computer as the java app in the stand alone flash player. I need two way communication between the two parts, and have no idea how to even start going about this. I suppose I could open a socket between the two programs, but I feel that there must be an easier way. Is there a nice part of the api in actionscript 3.0 that will allow me to access java methods directly, or will I have to resort to sockets? I am relatively new to flash, by the way, so any good guides would be much appreciated!
Thanks
|
[AMF](http://en.wikipedia.org/wiki/Action_Message_Format) is a messaging protocol commonly used to talk between flash and a backend system. There're several Java implementations, but I haven't used any of them so can't tell you which is best.
* [Blaze DS](http://labs.adobe.com/technologies/blazeds/)
* [Red5](http://www.osflash.org/red5)
* [Granite DS](http://www.graniteds.org/)
Flash can also talk plain old XML, SOAP or REST to the backend, so depending on your codebase that might be easier.
|
There is also **[OpenAMF](http://sourceforge.net/projects/openamf/)**. It is *very* mature, stable, simple and lightweight relative to Blaze, Red5 and Granite.
**BUT**, it is also dated (AMF0 protocol only) and the project is no longer active. Lots of people are still using it out in the wild. And the documentation is borderline non-existent.
|
Getting java and flash to talk to each other
|
[
"",
"java",
"flash",
""
] |
I'm using the wxGlade designer to generate the GUI for a small application.
It generates a class, inherited from wxFrame, which is the main application window.
In order to facilitate the maintenance, I'd like to avoid writing additional code in this generated class.
But all the widgets created with the wxGlade are actually created in the auto-generated method do\_layout() and it is not possible to access them outside the scope of that generated method in the generated class.
Is there a way to get pointer of certain widget outside that generated class - by name, by type, by enumerating the children or something like that?
|
All classes inherited from wxWindow (wxFrame being one of them) have a function "[GetChildren](http://docs.wxwidgets.org/stable/wx_wxwindow.html#wxwindowgetchildren)", which returns a list of child windows that you can then enumerate over. If you are looking for a specific field by name then use the "[FindWindow](http://docs.wxwidgets.org/stable/wx_wxwindow.html#wxwindowfindwindow)" function.
|
Actually I found the answer myself:
```
wxWindowList & children = myframe->GetChildren();
for ( wxWindowList::Node *node = children.GetFirst(); node; node = node->GetNext() )
{
wxWindow *current = (wxWindow *)node->GetData();
// .. do something with current
}
```
|
Is it possible to enumerate the wxFrame children in wxWidgets?
|
[
"",
"c++",
"user-interface",
"wxwidgets",
"wxglade",
""
] |
Specifically MSSQL 2005.
|
Here's a solution that gives you the last second of the current month. You can extract the date part or modify it to return just the day. I tested this on SQL Server 2005.
```
select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );
```
To understand how it works we have to look at the [dateadd()](http://www.w3schools.com/sql/func_dateadd.asp) and [datediff()](http://www.w3schools.com/sql/func_datediff.asp) functions.
```
DATEADD(datepart, number, date)
DATEDIFF(datepart, startdate, enddate)
```
If you run just the most inner call to datediff(), you get the current month number since timestamp 0.
```
select datediff(m, 0, getdate() );
1327
```
The next part adds that number of months plus 1 to the 0 timestamp, giving you the starting point of the next calendar month.
```
select dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 );
2010-09-01 00:00:00.000
```
Finally, the outer dateadd() just subtracts one second from the beginning timestamp of next month, giving you the last second of the current month.
```
select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );
2010-08-31 23:59:59.000
```
---
**This old answer (below) has a bug where it doesn't work on the last day of a month that has more days than the next month. I'm leaving it here as a warning to others.**
Add one month to the current date, and then subtract the value returned by the DAY function applied to the current date using the functions DAY and DATEADD.
```
dateadd(day, -day(getdate()), dateadd(month, 1, getdate()))
```
|
```
SELECT DATEADD(M, DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP), '1990-01-31T00:00:00.000')
```
Explanation:
General approach: use temporal functionality.
```
SELECT '1990-01-01T00:00:00.000', '1990-01-31T00:00:00.000'
```
These are DATETIME literals, being the first time granule on the first day and last day respectively of the same 31-day month. Which month is chosen is entirely arbitrary.
```
SELECT DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP)
```
This is the difference in whole months between the first day of the reference month and the current timestamp. Let's call this `@calc`.
```
SELECT DATEADD(M, @calc, '1990-01-31T00:00:00.000')
```
This adds `@calc` month granules to the last day of the reference month, the result of which is the current timestamp 'rounded' to the last day of its month. Q.E. D.
|
How do I calculate the last day of the month in SQL?
|
[
"",
"sql",
"sql-server",
"t-sql",
"date",
""
] |
I'm getting an unexpected T\_CONCAT\_EQUAL error on a line of the following form:
```
$arg1 .= "arg2".$arg3."arg4";
```
I'm using PHP5. I could simply go an do the following:
```
$arg1 = $arg1."arg2".$arg3."arg4";
```
but I'd like to know whats going wrong in the first place. Any ideas?
Thanks,
sweeney
|
This would happen when $arg1 is undefined (doesn't have a value, was never set.)
|
So the most accurate reason is that the above posted line of code:
```
$arg1 .= "arg2".$arg3."arg4";
```
was actually as follows in my source:
```
arg1 .= "arg2".$arg3."arg4";
```
The $ was missing from arg1. I dont know why the interpreter did not catch that first, but whatever. Thanks for the input Jeremy and Bailey - it lead me right to the problem.
|
unexpected T_CONCAT_EQUAL
|
[
"",
"php",
"string",
"concatenation",
""
] |
I have a an HTML form which contains the YAHOO rich text editor on it.
When I display the form I want the YAHOO editor to have focus so that the cursor is ready to accept input without the user having to click on it or tab into it
|
I got this from the documenation over at the [YUI library](http://developer.yahoo.com/yui). Specifically at a sample titled [Editor - Basic Buttons](http://developer.yahoo.com/yui/examples/editor/editor_adv_editor.html)
> `var myEditor = new YAHOO.widget.Editor('editor', {focusAtStart:true});`
> `myEditor.render();`
The key here is the the "focusAtStart" attribute as part of the optional attributes object
|
Like roenving, I have never used the YAHOO rich text editor, but it should work with the `window.onload` event.
Let's say you specified `id="yahoo_text_editor"` for your YAHOO rich text editor.
Then, do
```
<body onload="document.getElementById('yahoo_text_editor').focus()">
```
Hope this helps.
|
How can I set the focus inside the Yahoo Rich Text Editor
|
[
"",
"javascript",
"html",
"richtext",
""
] |
I would like to format a price in JavaScript. I'd like a function which takes a `float` as an argument and returns a `string` formatted like this:
```
"$ 2,500.00"
```
How can I do this?
|
Ok, based on what you said, I'm using this:
```
var DecimalSeparator = Number("1.2").toLocaleString().substr(1,1);
var AmountWithCommas = Amount.toLocaleString();
var arParts = String(AmountWithCommas).split(DecimalSeparator);
var intPart = arParts[0];
var decPart = (arParts.length > 1 ? arParts[1] : '');
decPart = (decPart + '00').substr(0,2);
return '£ ' + intPart + DecimalSeparator + decPart;
```
I'm open to improvement suggestions (I'd prefer not to include [YUI](https://en.wikipedia.org/wiki/Yahoo!_UI_Library) just to do this :-) )
I already know I should be detecting the "." instead of just using it as the decimal separator...
|
# [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/NumberFormat)
JavaScript has a number formatter (part of the Internationalization API).
```
// Create our number formatter.
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
// These options are needed to round to whole numbers if that's what you want.
//minimumFractionDigits: 0, // (this suffices for whole numbers, but will print 2500.10 as $2,500.1)
//maximumFractionDigits: 0, // (causes 2500.99 to be printed as $2,501)
});
console.log(formatter.format(2500)); /* $2,500.00 */
```
Use `undefined` in place of the first argument (`'en-US'` in the example) to use the system locale (the user locale in case the code is running in a browser). [Further explanation of the locale code](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
Here's a [list of the currency codes](https://www.iban.com/currency-codes).
## Intl.NumberFormat vs Number.prototype.toLocaleString
A final note comparing this to the older .`toLocaleString`. They both offer essentially the same functionality. However, toLocaleString in its older incarnations (pre-Intl) [does not actually support locales](http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.4.3): it uses the system locale. So when debugging old browsers, be sure that you're using the correct version ([MDN suggests to check for the existence of `Intl`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Checking_for_support_for_locales_and_options_arguments)). There isn't any need to worry about this at all if you don't care about old browsers or just use the [shim](https://github.com/andyearnshaw/Intl.js).
Also, the performance of both is the same for a *single* item, but if you have a lot of numbers to format, using `Intl.NumberFormat` is ~70 times faster. Therefore, it's usually best to use `Intl.NumberFormat` and instantiate only once per page load. Anyway, here's the equivalent usage of `toLocaleString`:
```
console.log((2500).toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
})); /* $2,500.00 */
```
### Some notes on browser support and Node.js
* Browser support is no longer an issue nowadays with 99+% support globally
* There is a [shim](https://github.com/andyearnshaw/Intl.js) to support it on fossilized browsers (like [Internet Explorer 8](https://en.wikipedia.org/wiki/Internet_Explorer_8)), should you really need to
* Node.js before v13 only supports `en-US` out of the box. One solution is to install [full-icu](https://github.com/icu-project/full-icu-npm), see [here](https://stackoverflow.com/a/39626602/1000608) for more information
* Have a look at [CanIUse](https://caniuse.com/#feat=internationalization) for more information
|
How to format numbers as currency strings
|
[
"",
"javascript",
"formatting",
"currency",
""
] |
Suppose I have one long long int and want to take its bits and construct four unsigned short ints out of it.
Particular order doesn't matter much here.
I generally know that I need to shift bits and truncate to the size of unsigned short int. But I think I may make some weird mistake somewhere, so I ask.
|
```
#include <stdint.h>
#include <stdio.h>
union ui64 {
uint64_t one;
uint16_t four[4];
};
int
main()
{
union ui64 number = {0x123456789abcdef0};
printf("%x %x %x %x\n", number.four[0], number.four[1],
number.four[2], number.four[3]);
return 0;
}
```
|
```
(unsigned short)((((unsigned long long int)value)>>(x))&(0xFFFF))
```
where `value` is your `long long int`, and `x` is 0, 16, 32 or 48 for the four shorts.
|
How to extract four unsigned short ints from one long long int?
|
[
"",
"c++",
"c",
"64-bit",
"bit-manipulation",
""
] |
Is there a way to make a popup window maximised as soon as it is opened? If not that, at least make it screen-sized? This:
```
window.open(src, 'newWin', 'fullscreen="yes"')
```
apparently only worked for old version of IE.
|
Use `screen.availWidth` and `screen.availHeight` to calculate a suitable size for the height and width parameters in `window.open()`
Although this is likely to be close, it will not be maximised, nor accurate for everyone, especially if all the toolbars are shown.
|
What about this:
```
var popup = window.open(URL);
if (popup == null)
alert('Please change your popup settings');
else {
popup.moveTo(0, 0);
popup.resizeTo(screen.width, screen.height);
}
```
|
How to show fullscreen popup window in javascript?
|
[
"",
"javascript",
"html",
"popup",
""
] |
I am am trying to load a SQL table from a flat file. The flat i am talking about is a comma separated file. This has all the data required to populate a table will each column separated by a comma ",". I need some way by which i can load this content into the table faster.
|
If you are using SQL Server, use [`BULK INSERT`](http://msdn.microsoft.com/en-us/library/ms188365.aspx)
If you are using Oracle, see my answer [here](https://stackoverflow.com/questions/120001/load-excel-data-sheet-to-oracle-database#120021)
|
Regardless of what database management system you are using, you could use a scripting language (such as perl or php) to set up a connection to your database, parse the file, and then insert the data into your database. Of course, you would have to know a scripting language...
|
LOAD SQL Table from flat file
|
[
"",
"sql",
"sql-server-2005",
""
] |
In a C++ function I need the compiler to choose a different block if it is compiling for a 64 bit architecture.
I know a way to do it for MSVC++ and g++, so I'll post it as an answer. However I would like to know if there is a better way (more elegant that would work for all compilers/all 64 bits architectures). If there is not a better way, what other predefined macros should I look for in order to be compatible with other compiler/architectures?
|
Why are you choosing one block over the other? If your decision is based on the size of a pointer, use `sizeof(void*) == 8`. If your decision is based on the size of an integer, use `sizeof(int) == 8`.
My point is that the name of the architecture itself should rarely make any difference. You check only what you need to check, for the purposes of what you are going to do. Your question does not cover very clearly what your purpose of the check is. What you are asking is akin to trying to determine if DirectX is installed by querying the version of Windows. You have more portable and generic tools at your disposal.
|
An architecture-independent way to detect 32-bit and 64-bit builds in C and C++ looks like this:
```
// C
#include <stdint.h>
// C++
#include <cstdint>
#if INTPTR_MAX == INT64_MAX
// 64-bit
#elif INTPTR_MAX == INT32_MAX
// 32-bit
#else
#error Unknown pointer size or missing size macros!
#endif
```
|
How can I detect if I'm compiling for a 64bits architecture in C++
|
[
"",
"c++",
"64-bit",
"c-preprocessor",
""
] |
What is the easiest way to test (using reflection), whether given method (i.e. java.lang.Method instance) has a return type, which can be safely casted to List<String>?
Consider this snippet:
```
public static class StringList extends ArrayList<String> {}
public List<String> method1();
public ArrayList<String> method2();
public StringList method3();
```
All methods 1, 2, 3 fulfill the requirement. It's quite easy to test it for the method1 (via getGenericReturnType(), which returns instance of ParameterizedType), but for methods2 and 3, it's not so obvious. I imagine, that by traversing all getGenericSuperclass() and getGenericInterfaces(), we can get quite close, but I don't see, how to match the TypeVariable in List<E> (which occurs somewhere in the superclass interfaces) with the actual type parameter (i.e. where this E is matched to String).
Or maybe is there a completely different (easier) way, which I overlook?
**EDIT:** For those looking into it, here is method4, which also fulfills the requirement and which shows some more cases, which have to be investigated:
```
public interface Parametrized<T extends StringList> {
T method4();
}
```
|
Solving this in general is really not easy to do yourself using only the tools provided by Java itself. There are a lot of special cases (nested classes, type parameter bounds,...) to take care of.
That's why I wrote a library to make generic type reflection easier: [gentyref](http://code.google.com/p/gentyref/). I added sample code (in the form of a JUnit test) to show how to use it to solve this problem: [StackoverflowQ182872Test.java](http://code.google.com/p/gentyref/source/browse/trunk/gentyref/src/test/java/com/googlecode/gentyref/StackoverflowQ182872Test.java). Basically, you just call `GenericTypeReflector.isSuperType` using a `TypeToken` (idea from [Neil Gafter](http://gafter.blogspot.com/2006/12/super-type-tokens.html)) to see if `List<String>` is a supertype of the return type.
I also added a 5th test case, to show that an extra transformation on the return type (`GenericTypeReflector.getExactReturnType`) to replace type parameters with their values is sometimes needed.
|
I tried this code and it returns the actual generic type class so it seems the type info can be retrieved. However this only works for method 1 and 2. Method 3 does not seem to return a list typed String as the poster assumes and therefore fails.
```
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try{
Method m = Main.class.getDeclaredMethod("method1", new Class[]{});
instanceOf(m, List.class, String.class);
m = Main.class.getDeclaredMethod("method2", new Class[]{});
instanceOf(m, List.class, String.class);
m = Main.class.getDeclaredMethod("method3", new Class[]{});
instanceOf(m, List.class, String.class);
m = Main.class.getDeclaredMethod("method4", new Class[]{});
instanceOf(m, StringList.class);
}catch(Exception e){
System.err.println(e.toString());
}
}
public static boolean instanceOf (
Method m,
Class<?> returnedBaseClass,
Class<?> ... genericParameters) {
System.out.println("Testing method: " + m.getDeclaringClass().getName()+"."+ m.getName());
boolean instanceOf = false;
instanceOf = returnedBaseClass.isAssignableFrom(m.getReturnType());
System.out.println("\tReturn type test succesfull: " + instanceOf + " (expected '"+returnedBaseClass.getName()+"' found '"+m.getReturnType().getName()+"')");
System.out.print("\tNumber of generic parameters matches: ");
Type t = m.getGenericReturnType();
if(t instanceof ParameterizedType){
ParameterizedType pt = (ParameterizedType)t;
Type[] actualGenericParameters = pt.getActualTypeArguments();
instanceOf = instanceOf
&& actualGenericParameters.length == genericParameters.length;
System.out.println("" + instanceOf + " (expected "+ genericParameters.length +", found " + actualGenericParameters.length+")");
for (int i = 0; instanceOf && i < genericParameters.length; i++) {
if (actualGenericParameters[i] instanceof Class) {
instanceOf = instanceOf
&& genericParameters[i].isAssignableFrom(
(Class) actualGenericParameters[i]);
System.out.println("\tGeneric parameter no. " + (i+1) + " matches: " + instanceOf + " (expected '"+genericParameters[i].getName()+"' found '"+((Class) actualGenericParameters[i]).getName()+"')");
} else {
instanceOf = false;
System.out.println("\tFailure generic parameter is not a class");
}
}
} else {
System.out.println("" + true + " 0 parameters");
}
return instanceOf;
}
public List<String> method1() {
return null;
}
public ArrayList<String> method2() {
return new ArrayList<String>();
}
public StringList method3() {
return null;
}
public <T extends StringList> T method4() {
return null;
}
```
This outputs:
```
Testing method: javaapplication2.Main.method1
Return type test succesfull: true (expected 'java.util.List' found 'java.util.List')
Number of generic parameters matches: true (expected 1, found 1)
Generic parameter no. 1 matches: true (expected 'java.lang.String' found 'java.lang.String')
Testing method: javaapplication2.Main.method2
Return type test succesfull: true (expected 'java.util.List' found 'java.util.ArrayList')
Number of generic parameters matches: true (expected 1, found 1)
Generic parameter no. 1 matches: true (expected 'java.lang.String' found 'java.lang.String')
Testing method: javaapplication2.Main.method3
Return type test succesfull: false (expected 'java.util.List' found 'com.sun.org.apache.xerces.internal.xs.StringList')
Number of generic parameters matches: true 0 parameters
Testing method: javaapplication2.Main.method4
Return type test succesfull: true (expected 'com.sun.org.apache.xerces.internal.xs.StringList' found 'com.sun.org.apache.xerces.internal.xs.StringList')
Number of generic parameters matches: true 0 parameters
```
|
How to test whether method return type matches List<String>
|
[
"",
"java",
"generics",
"reflection",
""
] |
Often, I found OutOfMemoryException on IBM Websphere Application Server.
I think this exception occur because my application retrieve Huge data from database. So, I limit all query don't retreive data more than 1000 records and set JVM of WAS follow
```
+ Verbose garbage collection
+ Maximum Heap size = 1024 (RAM on my server is 16 GB and now I already change to 8192)
+ Debug arguments = -Djava.compiler=NONE -Xdebug -Xnoagent
-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=7777
+ Generic JVM arguments = -Dsun.rmi.dgc.server.gcInterval=60000
-Dsun.rmi.dgc.client.gcInterval=60000 -Xdisableexplicitgc
-Dws.log=E:\WebApp\log -Dws.log.level=debug
(ws.log and ws.log.level are my properties)
```
And I found **heapdump**, **javacore** and **snap** files in profiles folder I think them can tell me about cause of problem but I don't know how to read/use heapdump, javacore and snap files.
Please tell me how to prevent/avoid/fix OutOfMemoryException.
Thanks
|
The answer to this is dependent on the message associated with the OutOfMemoryException. You can also try -XX:MaxPermSize=... and set it to something larger like 256m.
Also, if you have a recursive function somewhere, that may be causing a stack overflow.
If you can, please post the message associated with the exception. Stacktrace might also help.
|
If you want to look at the heap dump files, IBM offers tools to analyze them [here](http://publib.boulder.ibm.com/infocenter/tivihelp/v3r1/index.jsp?topic=/com.ibm.itcamwas_b.doc_6.1/pdmst_basic56.htm).
|
IBM Websphere OutOfMemoryException
|
[
"",
"java",
"web-services",
"jakarta-ee",
"websphere",
""
] |
Is there a way to find the maximum and minimum defined values of an enum in c++?
|
No, there is no way to find the maximum and minimum defined values of any enum in C++. When this kind of information is needed, it is often good practice to define a Last and First value. For example,
```
enum MyPretendEnum
{
Apples,
Oranges,
Pears,
Bananas,
First = Apples,
Last = Bananas
};
```
There do not need to be named values for every value between `First` and `Last`.
|
No, not in standard C++. You could do it manually:
```
enum Name
{
val0,
val1,
val2,
num_values
};
```
`num_values` will contain the number of values in the enum.
|
Max and min values in a C++ enum
|
[
"",
"c++",
"enums",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.