qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
82,929 | <p>I have a PHP application that displays a list of options to a user. The list is generated from a simple query against SQL 2000. What I would like to do is have a specific option at the top of the list, and then have the remaining options sorted alphabetically.</p>
<p>For example, here's the options if sorted alphabetically: </p>
<pre><code>Calgary
Edmonton
Halifax
Montreal
Toronto
</code></pre>
<p>What I would like the list to be is more like this: </p>
<pre><code>**Montreal**
Calgary
Edmonton
Halifax
Toronto
</code></pre>
<p>Is there a way that I can do this using a single query? Or am I stuck running the query twice and appending the results?</p>
| [
{
"answer_id": 82944,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT name FROM options ORDER BY name = \"Montreal\", name;\n</code></pre>\n\n<p>Note: This works with MySQL, no... | 2008/09/17 | [
"https://Stackoverflow.com/questions/82929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37/"
] | I have a PHP application that displays a list of options to a user. The list is generated from a simple query against SQL 2000. What I would like to do is have a specific option at the top of the list, and then have the remaining options sorted alphabetically.
For example, here's the options if sorted alphabetically:
```
Calgary
Edmonton
Halifax
Montreal
Toronto
```
What I would like the list to be is more like this:
```
**Montreal**
Calgary
Edmonton
Halifax
Toronto
```
Is there a way that I can do this using a single query? Or am I stuck running the query twice and appending the results? | ```
SELECT name
FROM locations
ORDER BY
CASE
WHEN name = 'Montreal'
THEN 0
ELSE 1
END, name
``` |
82,949 | <p>I'm trying to preform setup and teardown for a set of integration tests, using jUnit 4.4 to execute the tests. The teardown needs to be run reliably. I'm having other problems with TestNG, so I'm looking to port back to jUnit. What hooks are available for execution before any tests are run and after all tests have completed?</p>
<p>Note: we're using maven 2 for our build. I've tried using maven's <code>pre-</code> & <code>post-integration-test</code> phases, but, if a test fails, maven stops and doesn't run <code>post-integration-test</code>, which is no help.</p>
| [
{
"answer_id": 83175,
"author": "user15299",
"author_id": 15299,
"author_profile": "https://Stackoverflow.com/users/15299",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I know there is no mechanism for doing this in JUnit, however you could try subclassing Suite and overriding... | 2008/09/17 | [
"https://Stackoverflow.com/questions/82949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] | I'm trying to preform setup and teardown for a set of integration tests, using jUnit 4.4 to execute the tests. The teardown needs to be run reliably. I'm having other problems with TestNG, so I'm looking to port back to jUnit. What hooks are available for execution before any tests are run and after all tests have completed?
Note: we're using maven 2 for our build. I've tried using maven's `pre-` & `post-integration-test` phases, but, if a test fails, maven stops and doesn't run `post-integration-test`, which is no help. | Yes, it is possible to reliably run set up and tear down methods before and after any tests in a test suite. Let me demonstrate in code:
```
package com.test;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({Test1.class, Test2.class})
public class TestSuite {
@BeforeClass
public static void setUp() {
System.out.println("setting up");
}
@AfterClass
public static void tearDown() {
System.out.println("tearing down");
}
}
```
So your `Test1` class would look something like:
```
package com.test;
import org.junit.Test;
public class Test1 {
@Test
public void test1() {
System.out.println("test1");
}
}
```
...and you can imagine that `Test2` looks similar. If you ran `TestSuite`, you would get:
```
setting up
test1
test2
tearing down
```
So you can see that the set up/tear down only run before and after all tests, respectively.
The catch: this only works if you're running the test suite, and not running Test1 and Test2 as individual JUnit tests. You mentioned you're using maven, and the maven surefire plugin likes to run tests individually, and not part of a suite. In this case, I would recommend creating a superclass that each test class extends. The superclass then contains the annotated @BeforeClass and @AfterClass methods. Although not quite as clean as the above method, I think it will work for you.
As for the problem with failed tests, you can set maven.test.error.ignore so that the build continues on failed tests. This is not recommended as a continuing practice, but it should get you functioning until all of your tests pass. For more detail, see the [maven surefire documentation](http://maven.apache.org/maven-1.x/plugins/test/properties.html). |
82,993 | <p>We need to programatically burn files to CD in a C\C++ Windows XP/Vista application we are developing using Borlands Turbo C++.</p>
<p>What is the simplest and best way to do this? We would prefer a native windows API (that doesnt rely on MFC) so as not to rely on any third party software/drivers if one is available.</p>
| [
{
"answer_id": 83211,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>You should be able to use the shell's ICDBurn interface. Back in the XP day MFC didn't even have any classes for cd burnin... | 2008/09/17 | [
"https://Stackoverflow.com/questions/82993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14260/"
] | We need to programatically burn files to CD in a C\C++ Windows XP/Vista application we are developing using Borlands Turbo C++.
What is the simplest and best way to do this? We would prefer a native windows API (that doesnt rely on MFC) so as not to rely on any third party software/drivers if one is available. | We used the following:
Store files in the directory returned by GetBurnPath, then write using Burn. GetCDRecordableInfo is used to check when the CD is ready.
```
#include <stdio.h>
#include <imapi.h>
#include <windows.h>
struct MEDIAINFO {
BYTE nSessions;
BYTE nLastTrack;
ULONG nStartAddress;
ULONG nNextWritable;
ULONG nFreeBlocks;
};
//==============================================================================
// Description: CD burning on Windows XP
//==============================================================================
#define CSIDL_CDBURN_AREA 0x003b
SHSTDAPI_(BOOL) SHGetSpecialFolderPathA(HWND hwnd, LPSTR pszPath, int csidl, BOOL fCreate);
SHSTDAPI_(BOOL) SHGetSpecialFolderPathW(HWND hwnd, LPWSTR pszPath, int csidl, BOOL fCreate);
#ifdef UNICODE
#define SHGetSpecialFolderPath SHGetSpecialFolderPathW
#else
#define SHGetSpecialFolderPath SHGetSpecialFolderPathA
#endif
//==============================================================================
// Interface IDiscMaster
const IID IID_IDiscMaster = {0x520CCA62,0x51A5,0x11D3,{0x91,0x44,0x00,0x10,0x4B,0xA1,0x1C,0x5E}};
const CLSID CLSID_MSDiscMasterObj = {0x520CCA63,0x51A5,0x11D3,{0x91,0x44,0x00,0x10,0x4B,0xA1,0x1C,0x5E}};
typedef interface ICDBurn ICDBurn;
// Interface ICDBurn
const IID IID_ICDBurn = {0x3d73a659,0xe5d0,0x4d42,{0xaf,0xc0,0x51,0x21,0xba,0x42,0x5c,0x8d}};
const CLSID CLSID_CDBurn = {0xfbeb8a05,0xbeee,0x4442,{0x80,0x4e,0x40,0x9d,0x6c,0x45,0x15,0xe9}};
MIDL_INTERFACE("3d73a659-e5d0-4d42-afc0-5121ba425c8d")
ICDBurn : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetRecorderDriveLetter(
/* [size_is][out] */ LPWSTR pszDrive,
/* [in] */ UINT cch) = 0;
virtual HRESULT STDMETHODCALLTYPE Burn(
/* [in] */ HWND hwnd) = 0;
virtual HRESULT STDMETHODCALLTYPE HasRecordableDrive(
/* [out] */ BOOL *pfHasRecorder) = 0;
};
//==============================================================================
// Description: Get burn pathname
// Parameters: pathname - must be at least MAX_PATH in size
// Returns: Non-zero for an error
// Notes: CoInitialize(0) must be called once in application
//==============================================================================
int GetBurnPath(char *path)
{
ICDBurn* pICDBurn;
int ret = 0;
if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&pICDBurn))) {
BOOL flag;
if (pICDBurn->HasRecordableDrive(&flag) == S_OK) {
if (SHGetSpecialFolderPath(0, path, CSIDL_CDBURN_AREA, 0)) {
strcat(path, "\\");
}
else {
ret = 1;
}
}
else {
ret = 2;
}
pICDBurn->Release();
}
else {
ret = 3;
}
return ret;
}
//==============================================================================
// Description: Get CD pathname
// Parameters: pathname - must be at least 5 bytes in size
// Returns: Non-zero for an error
// Notes: CoInitialize(0) must be called once in application
//==============================================================================
int GetCDPath(char *path)
{
ICDBurn* pICDBurn;
int ret = 0;
if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&pICDBurn))) {
BOOL flag;
WCHAR drive[5];
if (pICDBurn->GetRecorderDriveLetter(drive, 4) == S_OK) {
sprintf(path, "%S", drive);
}
else {
ret = 1;
}
pICDBurn->Release();
}
else {
ret = 3;
}
return ret;
}
//==============================================================================
// Description: Burn CD
// Parameters: None
// Returns: Non-zero for an error
// Notes: CoInitialize(0) must be called once in application
//==============================================================================
int Burn(void)
{
ICDBurn* pICDBurn;
int ret = 0;
if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&pICDBurn))) {
if (pICDBurn->Burn(NULL) != S_OK) {
ret = 1;
}
pICDBurn->Release();
}
else {
ret = 2;
}
return ret;
}
//==============================================================================
bool GetCDRecordableInfo(long *FreeSpaceSize)
{
bool Result = false;
IDiscMaster *idm = NULL;
IDiscRecorder *idr = NULL;
IEnumDiscRecorders *pEnumDiscRecorders = NULL;
ULONG cnt;
long type;
long mtype;
long mflags;
MEDIAINFO mi;
try {
CoCreateInstance(CLSID_MSDiscMasterObj, 0, CLSCTX_ALL, IID_IDiscMaster, (void**)&idm);
idm->Open();
idm->EnumDiscRecorders(&pEnumDiscRecorders);
pEnumDiscRecorders->Next(1, &idr, &cnt);
pEnumDiscRecorders->Release();
idr->OpenExclusive();
idr->GetRecorderType(&type);
idr->QueryMediaType(&mtype, &mflags);
idr->QueryMediaInfo(&mi.nSessions, &mi.nLastTrack, &mi.nStartAddress, &mi.nNextWritable, &mi.nFreeBlocks);
idr->Release();
idm->Close();
idm->Release();
Result = true;
}
catch (...) {
Result = false;
}
if (Result == true) {
Result = false;
if (mtype == 0) {
// No Media inserted
Result = false;
}
else {
if ((mflags & 0x04) == 0x04) {
// Writable Media
Result = true;
}
else {
Result = false;
}
if (Result == true) {
*FreeSpaceSize = (mi.nFreeBlocks * 2048);
}
else {
*FreeSpaceSize = 0;
}
}
}
return Result;
}
``` |
83,038 | <p>When supplying dates to a stored procedure via a parameter I'm a little confused over which format to use for the dates. My original VBA syntax used the ADO Connection object to execute the stored procedure:</p>
<pre><code>Set SentDetailRS = Me.ADOConnectionToIntegrity.Execute("dbo.s_SelectAggregatedSentDetailList '" & fCSQLDate(EffectiveDate) & "'", , adCmdText)
</code></pre>
<p>This works fine for me using the date syntax <code>yyyy-mm-dd</code> but when another user executes the code they recieve the error: 13 'Type Mismatch'. </p>
<p>After some experimentation I found that supplying the date in the format <code>dd/mm/yyyy</code> fixes this error for the user but now gives me the error! </p>
<p>Executing the stored procedure using a command object with parameters works regardless of the format of the date (I assume ADO is taking care of the formatting behind the scenes). I thought that using the format <code>yyyy-mm-dd</code> would work universally with SQL Server? </p>
<p>I'm also perplexed as to why this problem appears to be user specific? I noticed that my default language on SQL Server is 'English' whereas the other user's default language is 'British English', could that cause the problem? </p>
<p>I'm using ADO 2.8 with Access 2003 and SQL Server 2000, SQL Server login is via Windows integrated security.</p>
| [
{
"answer_id": 83164,
"author": "Sunny Milenov",
"author_id": 8220,
"author_profile": "https://Stackoverflow.com/users/8220",
"pm_score": 0,
"selected": false,
"text": "<p>I would guess that fCSQLDate function is culture-specific - i.e. it will parse the date based on the user's locale s... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | When supplying dates to a stored procedure via a parameter I'm a little confused over which format to use for the dates. My original VBA syntax used the ADO Connection object to execute the stored procedure:
```
Set SentDetailRS = Me.ADOConnectionToIntegrity.Execute("dbo.s_SelectAggregatedSentDetailList '" & fCSQLDate(EffectiveDate) & "'", , adCmdText)
```
This works fine for me using the date syntax `yyyy-mm-dd` but when another user executes the code they recieve the error: 13 'Type Mismatch'.
After some experimentation I found that supplying the date in the format `dd/mm/yyyy` fixes this error for the user but now gives me the error!
Executing the stored procedure using a command object with parameters works regardless of the format of the date (I assume ADO is taking care of the formatting behind the scenes). I thought that using the format `yyyy-mm-dd` would work universally with SQL Server?
I'm also perplexed as to why this problem appears to be user specific? I noticed that my default language on SQL Server is 'English' whereas the other user's default language is 'British English', could that cause the problem?
I'm using ADO 2.8 with Access 2003 and SQL Server 2000, SQL Server login is via Windows integrated security. | Be careful, and do not believe that ADO is taking care of the problem. Universal SQL date format is 'YYYYMMDD', while both SQL and ACCESS are influenced by the regional settings of the machine in the way they display dates and convert them in character strings.
Do not forget that Date separator is # in Access, while it is ' in SQL
My best advice will be to systematically convert your Access #MM-DD-YYYY# (or similar) into 'YYYYMMDD' before sending the instruction to your server. You could build a small function such as:
```
Public function SQLdateFormat(x_date) as string
SQLDateFormat = _
trim(str(datePart("yyyy",x_date))) & _
right(str(datePart("m",date)),2) & _
right(str(datePart("d",date)),2)
''be carefull, you might get something like '2008 9 3'
SQLDateFormat = replace(functionSQLDateFormat," ","0")
'' you will have the expected '20080903'
End function
```
If you do not programmatically build your INSERT/UPDATE string before sending it to the server, I will then advise you to turn the regional settings of all the machines to the regional settings of the machine hosting SQL. You might also have to check if there is a specific date format on your SQL server (I am not sure). Personnaly, I solved this kind of localisation problems (it also happens when coma is used as a decimal separator in French) or SQL specific characters problems (when quotes or double quotes are in a string) by retreating the SQL instructions before sending them to the server. |
83,045 | <p>I have a costumer showing Notepad with a large set of data that looks totally misaligned if word wrap is on and I want to force it off. Is there a command switch to do this?</p>
| [
{
"answer_id": 83091,
"author": "Neoaikon",
"author_id": 15837,
"author_profile": "https://Stackoverflow.com/users/15837",
"pm_score": 1,
"selected": false,
"text": "<p>you could just turn it off by going to Format -> Word Wrap.</p>\n"
},
{
"answer_id": 83127,
"author": "Cetr... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9077/"
] | I have a costumer showing Notepad with a large set of data that looks totally misaligned if word wrap is on and I want to force it off. Is there a command switch to do this? | I dont think there is a command switch to do this at all. If you want to force it off all the time then you may want to edit the registry:
```
Hive: HKEY_CURRENT_USER
Key: SOFTWARE\Microsoft\Notepad
Name: fWrap
Type: REG_DWORD
Value: 0
```
You could even create a .reg file and put it in a batch file to run it and reset it every time notepad runs.
Usually though if you have word wrap turned off, when you open it up again, it will still be turned off. |
83,050 | <p>I had this question in mind and since I just discovered this site I decided to post it here.</p>
<p>Let's say I have a table with a timestamp and a state for a given "object" (generic meaning, not OOP object); is there an optimal way to calculate the time between a state and the next occurrence of another (or same) state (what I call a "trip") with a single SQL statement (inner SELECTs and UNIONs aren't counted)?</p>
<p>Ex: For the following, the trip time between Initial and Done would be 6 days, but between Initial and Review it would be 2 days. </p>
<blockquote>
<p>2008-08-01 13:30:00 - Initial<br>
2008-08-02 13:30:00 - Work<br>
2008-08-03 13:30:00 - Review<br>
2008-08-04 13:30:00 - Work<br>
2008-08-05 13:30:00 - Review<br>
2008-08-06 13:30:00 - Accepted<br>
2008-08-07 13:30:00 - Done</p>
</blockquote>
<p>No need to be generic, just say what <a href="https://stackoverflow.com/questions/980813/what-is-sgbd">SGBD</a> your solution is specific to if not generic.</p>
| [
{
"answer_id": 83129,
"author": "GUI Junkie",
"author_id": 11498,
"author_profile": "https://Stackoverflow.com/users/11498",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think you can get that answer with one SQL statement as you are trying to obtain one result from many records... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15805/"
] | I had this question in mind and since I just discovered this site I decided to post it here.
Let's say I have a table with a timestamp and a state for a given "object" (generic meaning, not OOP object); is there an optimal way to calculate the time between a state and the next occurrence of another (or same) state (what I call a "trip") with a single SQL statement (inner SELECTs and UNIONs aren't counted)?
Ex: For the following, the trip time between Initial and Done would be 6 days, but between Initial and Review it would be 2 days.
>
> 2008-08-01 13:30:00 - Initial
>
> 2008-08-02 13:30:00 - Work
>
> 2008-08-03 13:30:00 - Review
>
> 2008-08-04 13:30:00 - Work
>
> 2008-08-05 13:30:00 - Review
>
> 2008-08-06 13:30:00 - Accepted
>
> 2008-08-07 13:30:00 - Done
>
>
>
No need to be generic, just say what [SGBD](https://stackoverflow.com/questions/980813/what-is-sgbd) your solution is specific to if not generic. | Here's an Oracle methodology using an analytic function.
```
with data as (
SELECT 1 trip_id, to_date('20080801 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Initial' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080802 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Work' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080803 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Review' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080804 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Work' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080805 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Review' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080806 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Accepted' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080807 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Done' step from dual )
select trip_id,
step,
dt - lag(dt) over (partition by trip_id order by dt) trip_time
from data
/
1 Initial
1 Work 1
1 Review 1
1 Work 1
1 Review 1
1 Accepted 1
1 Done 1
```
These are very commonly used in situations where traditionally we might use a self-join. |
83,093 | <p>is there a solution for batch insert via hibernate in partitioned postgresql table? currently i'm getting an error like this...</p>
<pre><code>ERROR org.hibernate.jdbc.AbstractBatcher - Exception executing batch:
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:61)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:46)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:68)....
</code></pre>
<p>i have found this link <a href="http://lists.jboss.org/pipermail/hibernate-dev/2007-October/002771.html" rel="nofollow noreferrer">http://lists.jboss.org/pipermail/hibernate-dev/2007-October/002771.html</a> but i can't find anywhere on the web is this problem solved or how it can be get around</p>
| [
{
"answer_id": 90031,
"author": "alexguev",
"author_id": 436199,
"author_profile": "https://Stackoverflow.com/users/436199",
"pm_score": 3,
"selected": true,
"text": "<p>You might want to try using a custom Batcher by setting the hibernate.jdbc.factory_class property. Making sure hiberna... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15878/"
] | is there a solution for batch insert via hibernate in partitioned postgresql table? currently i'm getting an error like this...
```
ERROR org.hibernate.jdbc.AbstractBatcher - Exception executing batch:
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:61)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:46)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:68)....
```
i have found this link <http://lists.jboss.org/pipermail/hibernate-dev/2007-October/002771.html> but i can't find anywhere on the web is this problem solved or how it can be get around | You might want to try using a custom Batcher by setting the hibernate.jdbc.factory\_class property. Making sure hibernate won't check the update count of batch operations might fix your problem, you can achieve that by making your custom Batcher extend the class BatchingBatcher, and then overriding the method doExecuteBatch(...) to look like:
```
@Override
protected void doExecuteBatch(PreparedStatement ps) throws SQLException, HibernateException {
if ( batchSize == 0 ) {
log.debug( "no batched statements to execute" );
}
else {
if ( log.isDebugEnabled() ) {
log.debug( "Executing batch size: " + batchSize );
}
try {
// checkRowCounts( ps.executeBatch(), ps );
ps.executeBatch();
}
catch (RuntimeException re) {
log.error( "Exception executing batch: ", re );
throw re;
}
finally {
batchSize = 0;
}
}
}
```
Note that the new method doesn't check the results of executing the prepared statements. Keep in mind that making this change might affect hibernate in some unexpected way (or maybe not). |
83,132 | <p>I thought I'd found the solution a while ago (see my <a href="https://tjrobinson.net/programming/technology/2006/09/03/cant-execute-code-from-a-freed-script.html" rel="noreferrer">blog</a>):</p>
<blockquote>
<p>If you ever get the JavaScript (or should that be JScript) error "Can't execute code from a freed script" - try moving any meta tags in the head so that they're before your script tags. </p>
</blockquote>
<p>...but based on one of the most recent blog comments, the fix I suggested may not work for everyone. I thought this would be a good one to open up to the StackOverflow community....</p>
<p>What causes the error "Can't execute code from a freed script" and what are the solutions/workarounds?</p>
| [
{
"answer_id": 83570,
"author": "pcorcoran",
"author_id": 15992,
"author_profile": "https://Stackoverflow.com/users/15992",
"pm_score": 3,
"selected": false,
"text": "<p>This error can occur in MSIE when a child window tries to communicate with a parent window which is no longer open.</p... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12124/"
] | I thought I'd found the solution a while ago (see my [blog](https://tjrobinson.net/programming/technology/2006/09/03/cant-execute-code-from-a-freed-script.html)):
>
> If you ever get the JavaScript (or should that be JScript) error "Can't execute code from a freed script" - try moving any meta tags in the head so that they're before your script tags.
>
>
>
...but based on one of the most recent blog comments, the fix I suggested may not work for everyone. I thought this would be a good one to open up to the StackOverflow community....
What causes the error "Can't execute code from a freed script" and what are the solutions/workarounds? | You get this error when you call a function that was created in a window or frame that no longer exists.
If you don't know in advance if the window still exists, you can do a try/catch to detect it:
```
try
{
f();
}
catch(e)
{
if (e.number == -2146823277)
// f is no longer available
...
}
``` |
83,152 | <p>Is there an open source library that will help me with reading/parsing PDF documents in .NET/C#?</p>
| [
{
"answer_id": 83166,
"author": "Alex Fort",
"author_id": 12624,
"author_profile": "https://Stackoverflow.com/users/12624",
"pm_score": 1,
"selected": false,
"text": "<p>You could look into this:\n<a href=\"http://www.codeproject.com/KB/showcase/pdfrasterizer.aspx\" rel=\"nofollow norefe... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6777/"
] | Is there an open source library that will help me with reading/parsing PDF documents in .NET/C#? | Since this question was last answered in 2008, iTextSharp has improved their api dramatically. If you download the latest version of their api from <http://sourceforge.net/projects/itextsharp/>, you can use the following snippet of code to extract all text from a pdf into a string.
```
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
namespace PdfParser
{
public static class PdfTextExtractor
{
public static string pdfText(string path)
{
PdfReader reader = new PdfReader(path);
string text = string.Empty;
for(int page = 1; page <= reader.NumberOfPages; page++)
{
text += PdfTextExtractor.GetTextFromPage(reader,page);
}
reader.Close();
return text;
}
}
}
``` |
83,156 | <p>Ok, I have been working with Solaris for a 10+ years, and have never seen this...</p>
<p>I have a directory listing which includes both a file and subdirectory with the same name:</p>
<pre><code>-rw-r--r-- 1 root other 15922214 Nov 29 2006 msheehan
drwxrwxrwx 12 msheehan sysadmin 2048 Mar 25 15:39 msheehan
</code></pre>
<p>I use file to discover contents of the file, and I get:</p>
<pre><code>bash-2.03# file msheehan
msheehan: directory
bash-2.03# file msh*
msheehan: ascii text
msheehan: directory
</code></pre>
<p>I am not worried about the file, but I want to keep the directory, so I try rm:</p>
<pre><code>bash-2.03# rm msheehan
rm: msheehan is a directory
</code></pre>
<p>So here is my two part question:</p>
<ol>
<li>What's up with this?</li>
<li>How do I carefully delete the file?</li>
</ol>
<p>Jonathan</p>
<p>Edit:
Thanks for the answers guys, both (so far) were helpful, but piping the listing to an editor did the trick, ala:</p>
<pre><code>bash-2.03# ls -l > jb.txt
bash-2.03# vi jb.txt
</code></pre>
<p>Which contained:</p>
<pre><code>-rw-r--r-- 1 root other 15922214 Nov 29 2006 msheehab^?n
drwxrwxrwx 12 msheehan sysadmin 2048 Mar 25 15:39 msheehan
</code></pre>
<p>Always be careful with the backspace key!</p>
| [
{
"answer_id": 83168,
"author": "Jonathan Bourke",
"author_id": 8361,
"author_profile": "https://Stackoverflow.com/users/8361",
"pm_score": 0,
"selected": false,
"text": "<p>And a quick answer to part 2 of my own question...</p>\n\n<p>I would imagine I could rename the directory, delete ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8361/"
] | Ok, I have been working with Solaris for a 10+ years, and have never seen this...
I have a directory listing which includes both a file and subdirectory with the same name:
```
-rw-r--r-- 1 root other 15922214 Nov 29 2006 msheehan
drwxrwxrwx 12 msheehan sysadmin 2048 Mar 25 15:39 msheehan
```
I use file to discover contents of the file, and I get:
```
bash-2.03# file msheehan
msheehan: directory
bash-2.03# file msh*
msheehan: ascii text
msheehan: directory
```
I am not worried about the file, but I want to keep the directory, so I try rm:
```
bash-2.03# rm msheehan
rm: msheehan is a directory
```
So here is my two part question:
1. What's up with this?
2. How do I carefully delete the file?
Jonathan
Edit:
Thanks for the answers guys, both (so far) were helpful, but piping the listing to an editor did the trick, ala:
```
bash-2.03# ls -l > jb.txt
bash-2.03# vi jb.txt
```
Which contained:
```
-rw-r--r-- 1 root other 15922214 Nov 29 2006 msheehab^?n
drwxrwxrwx 12 msheehan sysadmin 2048 Mar 25 15:39 msheehan
```
Always be careful with the backspace key! | I would guess that these are in fact two different filenames that "look" the same, as the command file was able to distinguish them when the shell passed the expanded versions of the name in. Try piping ls into od or another hex/octal dump utility to see if they really have the same name, or if there are non-printing characters involved. |
83,159 | <p>Some API returns me XmlCursor pointing on root of XML Document. I need to insert all of this into another org.w3c.DOM represented document.</p>
<p>At start:
XmlCursor poiting on
<code></p>
<p><a>
<b>
some text
</b>
</a>
</code></p>
<p>DOM Document:
<code></p>
<p><foo></p>
<p></foo>
</code></p>
<p>At the end I want to have original DOM document changed like this:
<code></p>
<p><foo></p>
<p> <someOtherInsertedElement></p>
<p> <a>
<b>
some text
</b>
</a></p>
<p> </someOtherInsertedElement></p>
<p></foo>
</code></p>
<p>NOTE: <code>document.importNode(cursor.getDomNode())</code> doesn't work - Exception is thrown: <em>NOT_SUPPORTED_ERR: The implementation does not support the requested type of object or operation.</em></p>
| [
{
"answer_id": 83256,
"author": "Sietse",
"author_id": 6400,
"author_profile": "https://Stackoverflow.com/users/6400",
"pm_score": 4,
"selected": true,
"text": "<p>Try something like this:</p>\n\n<pre><code>Node originalNode = cursor.getDomNode();\nNode importNode = document.importNode(o... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1128722/"
] | Some API returns me XmlCursor pointing on root of XML Document. I need to insert all of this into another org.w3c.DOM represented document.
At start:
XmlCursor poiting on
<a>
<b>
some text
</b>
</a>
DOM Document:
<foo>
</foo>
At the end I want to have original DOM document changed like this:
<foo>
<someOtherInsertedElement>
<a>
<b>
some text
</b>
</a>
</someOtherInsertedElement>
</foo>
NOTE: `document.importNode(cursor.getDomNode())` doesn't work - Exception is thrown: *NOT\_SUPPORTED\_ERR: The implementation does not support the requested type of object or operation.* | Try something like this:
```
Node originalNode = cursor.getDomNode();
Node importNode = document.importNode(originalNode.getFirstChild());
Node otherNode = document.createElement("someOtherInsertedElement");
otherNode.appendChild(importNode);
document.appendChild(otherNode);
```
So in other words:
1. Get the DOM Node from the cursor. In this case, it's a DOMDocument, so do getFirstChild() to get the root node.
2. Import it into the DOMDocument.
3. Do other stuff with the DOMDocument.
4. Append the imported node to the right Node.
The reason to import is that a node always "belongs" to a given DOMDocument. Just adding the original node would cause exceptions. |
83,232 | <p>I'm looking for a key/value pair object that I can include in a web service.</p>
<p>I tried using .NET's <a href="http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx" rel="noreferrer"><code>System.Collections.Generic.KeyValuePair<></code></a> class, but it does not properly serialize in a web service. In a web service, the Key and Value properties are not serialized, making this class useless, unless someone knows a way to fix this.</p>
<p>Is there any other generic class that can be used for this situation?</p>
<p>I'd use .NET's <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx" rel="noreferrer"><code>System.Web.UI.Pair</code></a> class, but it uses Object for its types. It would be nice to use a Generic class, if only for type safety.</p>
| [
{
"answer_id": 83265,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 8,
"selected": true,
"text": "<p>Just define a struct/class.</p>\n\n<pre><code>[Serializable]\npublic struct KeyValuePair<K,V>\n{\n public K Key {ge... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] | I'm looking for a key/value pair object that I can include in a web service.
I tried using .NET's [`System.Collections.Generic.KeyValuePair<>`](http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx) class, but it does not properly serialize in a web service. In a web service, the Key and Value properties are not serialized, making this class useless, unless someone knows a way to fix this.
Is there any other generic class that can be used for this situation?
I'd use .NET's [`System.Web.UI.Pair`](http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx) class, but it uses Object for its types. It would be nice to use a Generic class, if only for type safety. | Just define a struct/class.
```
[Serializable]
public struct KeyValuePair<K,V>
{
public K Key {get;set;}
public V Value {get;set;}
}
``` |
83,242 | <p>I have a RHEL 5 system with a fresh new hard drive I just dedicated to the MySQL server. To get things started, I used "mysqldump --host otherhost -A | mysql", even though I noticed the manpage never explicitly recommends trying this (mysqldump into a file is a no-go. We're talking 500G of database). </p>
<p>This process fails at random intervals, complaining that too many files are open (at which point mysqld gets the relevant signal, and dies and respawns). </p>
<p>I tried upping it at sysctl and ulimit, but the problem persists. What do I do about it? </p>
| [
{
"answer_id": 83381,
"author": "VolkerK",
"author_id": 4833,
"author_profile": "https://Stackoverflow.com/users/4833",
"pm_score": 4,
"selected": true,
"text": "<p>mysqldump by default performs a per-table lock of all involved tables. If you have many tables that can exceed the amount o... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15910/"
] | I have a RHEL 5 system with a fresh new hard drive I just dedicated to the MySQL server. To get things started, I used "mysqldump --host otherhost -A | mysql", even though I noticed the manpage never explicitly recommends trying this (mysqldump into a file is a no-go. We're talking 500G of database).
This process fails at random intervals, complaining that too many files are open (at which point mysqld gets the relevant signal, and dies and respawns).
I tried upping it at sysctl and ulimit, but the problem persists. What do I do about it? | mysqldump by default performs a per-table lock of all involved tables. If you have many tables that can exceed the amount of file descriptors of the mysql server process.
Try --skip-lock-tables or if locking is imperative --lock-all-tables.
<http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html>
>
> ```
> --lock-all-tables, -x
> ```
>
Lock all tables across all databases. This is achieved by acquiring a global read lock for the duration of the whole dump. This option automatically turns off --single-transaction and --lock-tables. |
83,260 | <p>Say I've got this array:
MyArray(0)="aaa"
MyArray(1)="bbb"
MyArray(2)="aaa"</p>
<p>Is there a .net function which can give me the unique values? I would like something like this as an output of the function:
OutputArray(0)="aaa"
OutputArray(1)="bbb"</p>
| [
{
"answer_id": 83280,
"author": "Stormenet",
"author_id": 2090,
"author_profile": "https://Stackoverflow.com/users/2090",
"pm_score": 2,
"selected": false,
"text": "<p>You could use a dictionary to add them with a key, and when you add them check if the key already exists.</p>\n\n<pre><c... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15928/"
] | Say I've got this array:
MyArray(0)="aaa"
MyArray(1)="bbb"
MyArray(2)="aaa"
Is there a .net function which can give me the unique values? I would like something like this as an output of the function:
OutputArray(0)="aaa"
OutputArray(1)="bbb" | Assuming you have .Net 3.5/LINQ:
```
string[] OutputArray = MyArray.Distinct().ToArray();
``` |
83,279 | <p>I'm developing a 3-column website using a layout like this:</p>
<pre><code> <div id='left' style='left: 0; width: 150px; '> ... </div>
<div id='middle' style='left: 150px; right: 200px' > ... </div>
<div id='right' style='right: 0; width: 200px; '> ... </div>
</code></pre>
<p>But, considering the default CSS 'position' property of <code><DIV>'s</code> is 'static', my <code><DIV>'s</code> were shown one below the other, as expected.</p>
<p>So I set the CSS property 'position' to 'relative', and changed the 'top' property of the 'middle' and 'right' <code><DIV>'s</code> to -(minus) the height of the preceding <code><DIV></code>. It worked fine, but this approach brought me two problems:</p>
<p>1) Even though Internet Explorer 7 shows three columns properly, it still keeps the vertical scrollbar as if the <code><DIV>'s</code> were positioned one below the other, and there is a lot of white space after the content is over. I would'n like to have that.</p>
<p>2) The height of these elements is variable, so I don't really know which value to set for each <code><DIV></code>'s 'top' property; and I wouldn't like to hardcode it.</p>
<p>So my question is, what would be the best (simple + elegant) way to implement this layout? I would like to avoid absolute positioning , and I also to keep my design tableless.</p>
| [
{
"answer_id": 83294,
"author": "Joshua",
"author_id": 11981,
"author_profile": "https://Stackoverflow.com/users/11981",
"pm_score": 0,
"selected": false,
"text": "<p>Try floating the div's to the left, that will keep them all on the same line - assuming there is enough spacing.</p>\n"
... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15931/"
] | I'm developing a 3-column website using a layout like this:
```
<div id='left' style='left: 0; width: 150px; '> ... </div>
<div id='middle' style='left: 150px; right: 200px' > ... </div>
<div id='right' style='right: 0; width: 200px; '> ... </div>
```
But, considering the default CSS 'position' property of `<DIV>'s` is 'static', my `<DIV>'s` were shown one below the other, as expected.
So I set the CSS property 'position' to 'relative', and changed the 'top' property of the 'middle' and 'right' `<DIV>'s` to -(minus) the height of the preceding `<DIV>`. It worked fine, but this approach brought me two problems:
1) Even though Internet Explorer 7 shows three columns properly, it still keeps the vertical scrollbar as if the `<DIV>'s` were positioned one below the other, and there is a lot of white space after the content is over. I would'n like to have that.
2) The height of these elements is variable, so I don't really know which value to set for each `<DIV>`'s 'top' property; and I wouldn't like to hardcode it.
So my question is, what would be the best (simple + elegant) way to implement this layout? I would like to avoid absolute positioning , and I also to keep my design tableless. | If you haven't already checked out [A List Apart](http://www.alistapart.com/) you should, as it contains some excellent tutorials and guidelines for website design.
[This article](http://alistapart.com/articles/holygrail) in particular should help you out. |
83,319 | <p>I'm trying to figure out why the control does not honor ZIndex.</p>
<p>Example 1 - which works fine</p>
<pre><code> <Canvas>
<Rectangle Canvas.ZIndex="1" Height="400" Width="600" Fill="Yellow"/>
<Rectangle Canvas.ZIndex="2" Height="100" Width="100" Fill="Red"/>
</Canvas>
</code></pre>
<p>Example 2 - which does not work</p>
<pre><code> <Canvas>
<WebBrowser Canvas.ZIndex="1" Height="400" Width="600" Source="http://www.stackoverflow.com"/>
<Rectangle Canvas.ZIndex="2" Height="100" Width="100" Fill="Red"/>
</Canvas>
</code></pre>
<p>Thanks,
-- Ed</p>
| [
{
"answer_id": 83338,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": 5,
"selected": true,
"text": "<p>Unfortunately this is because the WebBrowser control is a wrapper around the Internet Explorer COM control. This m... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15921/"
] | I'm trying to figure out why the control does not honor ZIndex.
Example 1 - which works fine
```
<Canvas>
<Rectangle Canvas.ZIndex="1" Height="400" Width="600" Fill="Yellow"/>
<Rectangle Canvas.ZIndex="2" Height="100" Width="100" Fill="Red"/>
</Canvas>
```
Example 2 - which does not work
```
<Canvas>
<WebBrowser Canvas.ZIndex="1" Height="400" Width="600" Source="http://www.stackoverflow.com"/>
<Rectangle Canvas.ZIndex="2" Height="100" Width="100" Fill="Red"/>
</Canvas>
```
Thanks,
-- Ed | Unfortunately this is because the WebBrowser control is a wrapper around the Internet Explorer COM control. This means that it gets its own HWND and does not allow WPF to draw anything over it. It has the same restrictions as hosting any other Win32 or WinForms control in WPF.
[MSDN](http://msdn.microsoft.com/en-us/library/ms742522.aspx) has more information about WPF/Win32 interop. |
83,329 | <p>I have a ~23000 line SQL dump containing several databases worth of data. I need to extract a certain section of this file (i.e. the data for a single database) and place it in a new file. I know both the start and end line numbers of the data that I want.</p>
<p>Does anyone know a Unix command (or series of commands) to extract all lines from a file between say line 16224 and 16482 and then redirect them into a new file?</p>
| [
{
"answer_id": 83344,
"author": "Mark Janssen",
"author_id": 15828,
"author_profile": "https://Stackoverflow.com/users/15828",
"pm_score": 5,
"selected": false,
"text": "<p>You could use 'vi' and then the following command:</p>\n\n<pre><code>:16224,16482w!/tmp/some-file\n</code></pre>\n\... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15676/"
] | I have a ~23000 line SQL dump containing several databases worth of data. I need to extract a certain section of this file (i.e. the data for a single database) and place it in a new file. I know both the start and end line numbers of the data that I want.
Does anyone know a Unix command (or series of commands) to extract all lines from a file between say line 16224 and 16482 and then redirect them into a new file? | ```
sed -n '16224,16482p;16483q' filename > newfile
```
From the [sed manual](https://www.gnu.org/software/sed/manual/sed.html#Common-Commands):
>
> **p** -
> Print out the pattern space (to the standard output). This command is usually only used in conjunction with the -n command-line option.
>
>
> **n** -
> If auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input. If
> there is no more input then sed exits without processing any more
> commands.
>
>
> **q** -
> Exit `sed` without processing any more commands or input.
> Note that the current pattern space is printed if auto-print is not disabled with the -n option.
>
>
>
[and](https://www.gnu.org/software/sed/manual/sed.html#Addresses)
>
> Addresses in a sed script can be in any of the following forms:
>
>
> **number**
> Specifying a line number will match only that line in the input.
>
>
> An address range can be specified by specifying two addresses
> separated by a comma (,). An address range matches lines starting from
> where the first address matches, and continues until the second
> address matches (inclusively).
>
>
> |
83,397 | <p>In php I have open a .php file and want to evaluate certain lines. Specifically when the $table_id and $line variables are assigned a value.</p>
<p>Within the text file I have:</p>
<pre><code>...
$table_id = 'crs_class'; // table name
$screen = 'crs_class.detail.screen.inc'; // file identifying screen structure
...
</code></pre>
<p>amongst other lines. The if statement below never detects the occurance of <code>$table_id</code> or <code>$screen</code> (even without the $ prepended). I can't understand why it won't work as the strpos statement below looking for 'require' works fine.</p>
<p>So, why isn't this if statement getting a hit?</p>
<pre><code>while ($line=fgets($fh)) {
//echo "Evaluating... $line <br>";
**if ((($pos = stripos($line, '$table_id')) === true) || (($pos = stripos($line, '$screen'))===true))**
{
// TODO: Not evaluating tableid and screen lines correctly fix.
// Set $table_id and $screen variables from task scripts
eval($line);
}
if (($pos=stripos($line, 'require')) === true) {
$controller = $line;
}
}
</code></pre>
| [
{
"answer_id": 83424,
"author": "VolkerK",
"author_id": 4833,
"author_profile": "https://Stackoverflow.com/users/4833",
"pm_score": 4,
"selected": true,
"text": "<p>use !==false instead of ===true<br />\nstripos returns the position as an integer if the needle is found. And that's never ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10583/"
] | In php I have open a .php file and want to evaluate certain lines. Specifically when the $table\_id and $line variables are assigned a value.
Within the text file I have:
```
...
$table_id = 'crs_class'; // table name
$screen = 'crs_class.detail.screen.inc'; // file identifying screen structure
...
```
amongst other lines. The if statement below never detects the occurance of `$table_id` or `$screen` (even without the $ prepended). I can't understand why it won't work as the strpos statement below looking for 'require' works fine.
So, why isn't this if statement getting a hit?
```
while ($line=fgets($fh)) {
//echo "Evaluating... $line <br>";
**if ((($pos = stripos($line, '$table_id')) === true) || (($pos = stripos($line, '$screen'))===true))**
{
// TODO: Not evaluating tableid and screen lines correctly fix.
// Set $table_id and $screen variables from task scripts
eval($line);
}
if (($pos=stripos($line, 'require')) === true) {
$controller = $line;
}
}
``` | use !==false instead of ===true
stripos returns the position as an integer if the needle is found. And that's never ===bool.
You might also be interested in PHP's [tokenizer module](http://de2.php.net/tokenizer) or the [lexer package](http://pear.php.net/package/PHP_LexerGenerator) in the pear repository. |
83,410 | <p>I have a large CSV file and I want to execute a stored procedure for each line.</p>
<p>What is the best way to execute a stored procedure from PowerShell?</p>
| [
{
"answer_id": 83425,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 2,
"selected": false,
"text": "<p>Consider calling osql.exe (the command line tool for SQL Server) passing as parameter a text file written for each ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12767/"
] | I have a large CSV file and I want to execute a stored procedure for each line.
What is the best way to execute a stored procedure from PowerShell? | This answer was pulled from <http://www.databasejournal.com/features/mssql/article.php/3683181>
This same example can be used for any adhoc queries. Let us execute the stored procedure “sp\_helpdb” as shown below.
```
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=HOME\SQLEXPRESS;Database=master;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "sp_helpdb"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]
``` |
83,439 | <p>What is the preferred way to remove spaces from a string in C++? I could loop through all the characters and build a new string, but is there a better way?</p>
| [
{
"answer_id": 83468,
"author": "rupello",
"author_id": 635,
"author_profile": "https://Stackoverflow.com/users/635",
"pm_score": 5,
"selected": false,
"text": "<p>From <a href=\"http://www.gamedev.net/community/forums/topic.asp?topic_id=359650\" rel=\"noreferrer\">gamedev</a></p>\n\n<pr... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15947/"
] | What is the preferred way to remove spaces from a string in C++? I could loop through all the characters and build a new string, but is there a better way? | The best thing to do is to use the algorithm [`remove_if`](http://en.cppreference.com/w/cpp/algorithm/remove) and isspace:
```
remove_if(str.begin(), str.end(), isspace);
```
Now the algorithm itself can't change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase to actually modify the length of the container:
```
str.erase(remove_if(str.begin(), str.end(), isspace), str.end());
```
We should also note that remove\_if will make at most one copy of the data. Here is a sample implementation:
```
template<typename T, typename P>
T remove_if(T beg, T end, P pred)
{
T dest = beg;
for (T itr = beg;itr != end; ++itr)
if (!pred(*itr))
*(dest++) = *itr;
return dest;
}
``` |
83,471 | <p>Working with a SqlCommand in C# I've created a query that contains a IN (list...) part in the where clause. Instead of looping through my string list generating the list I need for the query (dangerous if you think in sqlInjection). I thought that I could create a parameter like:</p>
<pre><code>SELECT blahblahblah WHERE blahblahblah IN @LISTOFWORDS
</code></pre>
<p>Then in the code I try to add a parameter like this: </p>
<pre><code>DataTable dt = new DataTable();
dt.Columns.Add("word", typeof(string));
foreach (String word in listOfWords)
{
dt.Rows.Add(word);
}
comm.Parameters.Add("LISTOFWORDS", System.Data.SqlDbType.Structured).Value = dt;
</code></pre>
<p>But this doesn't work. </p>
<p>Questions:</p>
<ul>
<li>Am I trying something impossible?</li>
<li>Did I took the wrong approach?</li>
<li>Do I have mistakes in this approach?</li>
</ul>
<p>Thanks for your time :)</p>
| [
{
"answer_id": 83525,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>You want to think about where that list comes from. Generally that information is in the database somewhere. For e... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15987/"
] | Working with a SqlCommand in C# I've created a query that contains a IN (list...) part in the where clause. Instead of looping through my string list generating the list I need for the query (dangerous if you think in sqlInjection). I thought that I could create a parameter like:
```
SELECT blahblahblah WHERE blahblahblah IN @LISTOFWORDS
```
Then in the code I try to add a parameter like this:
```
DataTable dt = new DataTable();
dt.Columns.Add("word", typeof(string));
foreach (String word in listOfWords)
{
dt.Rows.Add(word);
}
comm.Parameters.Add("LISTOFWORDS", System.Data.SqlDbType.Structured).Value = dt;
```
But this doesn't work.
Questions:
* Am I trying something impossible?
* Did I took the wrong approach?
* Do I have mistakes in this approach?
Thanks for your time :) | What you are trying to do is possible but not using your current approach. This is a very common problem with all possible solutions prior to SQL Server 2008 having trade offs related to performance, security and memory usage.
[This link shows some approaches for SQL Server 2000/2005](http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters)
[SQL Server 2008 supports passing a table value parameter.](http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters)
I hope this helps. |
83,531 | <p>I'm trying to write a stored procedure to select employees who have birthdays that are upcoming. </p>
<p><code>SELECT * FROM Employees WHERE Birthday > @Today AND Birthday < @Today + @NumDays</code></p>
<p>This will not work because the birth year is part of Birthday, so if my birthday was '09-18-1983' that will not fall between '09-18-2008' and '09-25-2008'. </p>
<p>Is there a way to ignore the year portion of date fields and just compare month/days? </p>
<p>This will be run every monday morning to alert managers of birthdays upcoming, so it possibly will span new years. </p>
<p>Here is the working solution that I ended up creating, thanks Kogus. </p>
<pre><code>SELECT * FROM Employees
WHERE Cast(DATEDIFF(dd, birthdt, getDate()) / 365.25 as int)
- Cast(DATEDIFF(dd, birthdt, futureDate) / 365.25 as int)
<> 0
</code></pre>
| [
{
"answer_id": 83559,
"author": "p4bl0",
"author_id": 12043,
"author_profile": "https://Stackoverflow.com/users/12043",
"pm_score": 0,
"selected": false,
"text": "<p>You could use <a href=\"http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html\" rel=\"nofollow noreferrer\">... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2460/"
] | I'm trying to write a stored procedure to select employees who have birthdays that are upcoming.
`SELECT * FROM Employees WHERE Birthday > @Today AND Birthday < @Today + @NumDays`
This will not work because the birth year is part of Birthday, so if my birthday was '09-18-1983' that will not fall between '09-18-2008' and '09-25-2008'.
Is there a way to ignore the year portion of date fields and just compare month/days?
This will be run every monday morning to alert managers of birthdays upcoming, so it possibly will span new years.
Here is the working solution that I ended up creating, thanks Kogus.
```
SELECT * FROM Employees
WHERE Cast(DATEDIFF(dd, birthdt, getDate()) / 365.25 as int)
- Cast(DATEDIFF(dd, birthdt, futureDate) / 365.25 as int)
<> 0
``` | *Note: I've edited this to fix what I believe was a significant bug. The currently posted version works for me.*
This should work after you modify the field and table names to correspond to your database.
```
SELECT
BRTHDATE AS BIRTHDAY
,FLOOR(DATEDIFF(dd,EMP.BRTHDATE,GETDATE()) / 365.25) AS AGE_NOW
,FLOOR(DATEDIFF(dd,EMP.BRTHDATE,GETDATE()+7) / 365.25) AS AGE_ONE_WEEK_FROM_NOW
FROM
"Database name".dbo.EMPLOYEES EMP
WHERE 1 = (FLOOR(DATEDIFF(dd,EMP.BRTHDATE,GETDATE()+7) / 365.25))
-
(FLOOR(DATEDIFF(dd,EMP.BRTHDATE,GETDATE()) / 365.25))
```
Basically, it gets the # of days from their birthday to now, and divides that by 365 (to avoid rounding issues that come up when you convert directly to years).
Then it gets the # of days from their birthday to a week from now, and divides that by 365 to get their age a week from now.
If their birthday is within a week, then the difference between those two values will be 1. So it returns all of those records. |
83,547 | <p>I have a decimal number (let's call it <strong>goal</strong>) and an array of other decimal numbers (let's call the array <strong>elements</strong>) and I need to find all the combinations of numbers from <strong>elements</strong> which sum to goal.</p>
<p>I have a preference for a solution in C# (.Net 2.0) but may the best algorithm win irrespective.</p>
<p>Your method signature might look something like:</p>
<pre><code>public decimal[][] Solve(decimal goal, decimal[] elements)
</code></pre>
| [
{
"answer_id": 83596,
"author": "Rob Dickerson",
"author_id": 7530,
"author_profile": "https://Stackoverflow.com/users/7530",
"pm_score": 2,
"selected": false,
"text": "<p>I think you've got a <a href=\"http://en.wikipedia.org/wiki/Bin_packing_problem\" rel=\"nofollow noreferrer\">bin pa... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16005/"
] | I have a decimal number (let's call it **goal**) and an array of other decimal numbers (let's call the array **elements**) and I need to find all the combinations of numbers from **elements** which sum to goal.
I have a preference for a solution in C# (.Net 2.0) but may the best algorithm win irrespective.
Your method signature might look something like:
```
public decimal[][] Solve(decimal goal, decimal[] elements)
``` | Interesting answers. Thank you for the pointers to Wikipedia - whilst interesting - they don't actually solve the problem as stated as I was looking for exact matches - more of an accounting/book balancing problem than a traditional bin-packing / knapsack problem.
I have been following the development of stack overflow with interest and wondered how useful it would be. This problem came up at work and I wondered whether stack overflow could provide a ready-made answer (or a better answer) quicker than I could write it myself. Thanks also for the comments suggesting this be tagged homework - I guess that is reasonably accurate in light of the above.
For those who are interested, here is my solution which uses recursion (naturally) I also changed my mind about the method signature and went for List> rather than decimal[][] as the return type:
```
public class Solver {
private List<List<decimal>> mResults;
public List<List<decimal>> Solve(decimal goal, decimal[] elements) {
mResults = new List<List<decimal>>();
RecursiveSolve(goal, 0.0m,
new List<decimal>(), new List<decimal>(elements), 0);
return mResults;
}
private void RecursiveSolve(decimal goal, decimal currentSum,
List<decimal> included, List<decimal> notIncluded, int startIndex) {
for (int index = startIndex; index < notIncluded.Count; index++) {
decimal nextValue = notIncluded[index];
if (currentSum + nextValue == goal) {
List<decimal> newResult = new List<decimal>(included);
newResult.Add(nextValue);
mResults.Add(newResult);
}
else if (currentSum + nextValue < goal) {
List<decimal> nextIncluded = new List<decimal>(included);
nextIncluded.Add(nextValue);
List<decimal> nextNotIncluded = new List<decimal>(notIncluded);
nextNotIncluded.Remove(nextValue);
RecursiveSolve(goal, currentSum + nextValue,
nextIncluded, nextNotIncluded, startIndex++);
}
}
}
}
```
If you want an app to test this works, try this console app code:
```
class Program {
static void Main(string[] args) {
string input;
decimal goal;
decimal element;
do {
Console.WriteLine("Please enter the goal:");
input = Console.ReadLine();
}
while (!decimal.TryParse(input, out goal));
Console.WriteLine("Please enter the elements (separated by spaces)");
input = Console.ReadLine();
string[] elementsText = input.Split(' ');
List<decimal> elementsList = new List<decimal>();
foreach (string elementText in elementsText) {
if (decimal.TryParse(elementText, out element)) {
elementsList.Add(element);
}
}
Solver solver = new Solver();
List<List<decimal>> results = solver.Solve(goal, elementsList.ToArray());
foreach(List<decimal> result in results) {
foreach (decimal value in result) {
Console.Write("{0}\t", value);
}
Console.WriteLine();
}
Console.ReadLine();
}
}
```
I hope this helps someone else get their answer more quickly (whether for homework or otherwise).
Cheers... |
83,553 | <p>I need to write a program used internally where different users will have different abilities within the program.</p>
<p>Rather than making users have a new username and password, how do I tie into an existing domain server's login system?</p>
<p>Assume .NET (C#, VB, ASP, etc)</p>
<p>-Adam</p>
| [
{
"answer_id": 83587,
"author": "Matt Everson",
"author_id": 7300,
"author_profile": "https://Stackoverflow.com/users/7300",
"pm_score": 3,
"selected": true,
"text": "<p>For WinForms, use System.Threading.Thread.CurrentPrincipal with the IsInRole() method to check which groups they are a... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
] | I need to write a program used internally where different users will have different abilities within the program.
Rather than making users have a new username and password, how do I tie into an existing domain server's login system?
Assume .NET (C#, VB, ASP, etc)
-Adam | For WinForms, use System.Threading.Thread.CurrentPrincipal with the IsInRole() method to check which groups they are a member of. You do need to set the principal policy of the AppDomain to WindowsPrincipal first.
Use this to get the current user name:
```
private string getWindowsUsername()
{
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
return Thread.CurrentPrincipal.Identity.Name;
}
```
And then something like this to check a role:
```
if (Thread.CurrentPrincipal.IsInRole("Domain Users") == true)
{}
```
In ASP.NET, the thread will belong to IIS, so instead you should
1. Set the virtual folder or website to require authentication
2. Get the user name supplied by the browser with Request.ServerVariables("LOGON\_USER")
3. Use the [DirectorySearcher](http://msdn.microsoft.com/en-us/library/system.directoryservices.directorysearcher.aspx) class to find the users groups |
83,653 | <p>The following returns </p>
<blockquote>
<p>Type of conditional expression cannot be determined because there is no implicit conversion between 'double' and '<null>'</p>
</blockquote>
<pre><code>aNullableDouble = (double.TryParse(aString, out aDouble) ? aDouble : null)
</code></pre>
<hr>
<p>The reason why I can't just use aNullableBool instead of the roundtrip with aDouble is because aNullableDouble is a property of a generated EntityFramework class which cannot be used as an out par.</p>
| [
{
"answer_id": 83664,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "<pre><code>aNullableDouble = (double.TryParse(aString, out aDouble)?new Nullable<double>(aDouble):null)\n</code>... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] | The following returns
>
> Type of conditional expression cannot be determined because there is no implicit conversion between 'double' and '<null>'
>
>
>
```
aNullableDouble = (double.TryParse(aString, out aDouble) ? aDouble : null)
```
---
The reason why I can't just use aNullableBool instead of the roundtrip with aDouble is because aNullableDouble is a property of a generated EntityFramework class which cannot be used as an out par. | ```
aNullableDouble = double.TryParse(aString, out aDouble) ? (double?)aDouble : null;
``` |
83,674 | <p>I want to find records on a combination of created_on >= some date AND name IN some list of names.</p>
<p>For ">=" I'd have to use sql condition. For "IN" I'd have to use a hash of conditions where the key is :name and the value is the array of names.</p>
<p>Is there a way to combine the two?</p>
| [
{
"answer_id": 83736,
"author": "Laurie Young",
"author_id": 7473,
"author_profile": "https://Stackoverflow.com/users/7473",
"pm_score": 6,
"selected": true,
"text": "<p>You can use named scopes in rails 2.1 and above</p>\n\n<pre><code>Class Test < ActiveRecord::Base\n named_scope :c... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1167846/"
] | I want to find records on a combination of created\_on >= some date AND name IN some list of names.
For ">=" I'd have to use sql condition. For "IN" I'd have to use a hash of conditions where the key is :name and the value is the array of names.
Is there a way to combine the two? | You can use named scopes in rails 2.1 and above
```
Class Test < ActiveRecord::Base
named_scope :created_after_2005, :conditions => "created_on > 2005-01-01"
named_scope :named_fred, :conditions => { :name => "fred"}
end
```
then you can do
```
Test.created_after_2005.named_fred
```
Or you can give named\_scope a lambda allowing you to pass in arguments
```
Class Test < ActiveRecord::Base
named_scope :created_after, lambda { |date| {:conditions => ["created_on > ?", date]} }
named_scope :named, lambda { |name| {:conditions => {:name => name}} }
end
```
then you can do
```
Test.created_after(Time.now-1.year).named("fred")
``` |
83,770 | <p>I'm trying to create a server control, which inherits from TextBox, that will automatically have a <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/Calendar/Calendar.aspx" rel="nofollow noreferrer">CalendarExtender</a> attached to it. Is it possible to do this, or does my new control need to inherit from CompositeControl instead? I've tried the former, but I'm not clear during which part of the control lifecycle I should create the new instance of the CalendarExtender, and what controls collection I should add it to. I don't seem to be able to add it to the Page or Form's controls collection, and if I add it to the (TextBox) control's collection, I get none of the pop-up calendar functionality.</p>
| [
{
"answer_id": 83951,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 3,
"selected": true,
"text": "<p>I accomplished this in a project a while back. To do it I created a CompositeControl that contains both the TextBox and... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13583/"
] | I'm trying to create a server control, which inherits from TextBox, that will automatically have a [CalendarExtender](http://www.asp.net/AJAX/AjaxControlToolkit/Samples/Calendar/Calendar.aspx) attached to it. Is it possible to do this, or does my new control need to inherit from CompositeControl instead? I've tried the former, but I'm not clear during which part of the control lifecycle I should create the new instance of the CalendarExtender, and what controls collection I should add it to. I don't seem to be able to add it to the Page or Form's controls collection, and if I add it to the (TextBox) control's collection, I get none of the pop-up calendar functionality. | I accomplished this in a project a while back. To do it I created a CompositeControl that contains both the TextBox and the CalendarExtender.
In the `CreateChildControls` method of the CompositeControl I use code similar to this:
```
TextBox textbox = new TextBox();
textbox.ID = this.ID + "Textbox";
textbox.Text = this.EditableField.TextValue;
textbox.TextChanged += new EventHandler(HandleTextboxTextChanged);
textbox.Width = new Unit(100, UnitType.Pixel);
CalendarExtender calExender = new CalendarExtender();
calExender.PopupButtonID = "Image1";
calExender.TargetControlID = textbox.ID;
this.Controls.Add(textbox);
this.Controls.Add(calExender);
```
Of course make sure that the form containing this CompositeControl has a toolkit script manager. |
83,807 | <p>All I know about the constraint is it's name (<code>SYS_C003415</code>), but I want to see it's definition.</p>
| [
{
"answer_id": 83811,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 5,
"selected": false,
"text": "<p>Looks like I should be querying <code>ALL_CONSTRAINTS</code>.</p>\n\n<pre><code>select OWNER, CONSTRAINT_NAME, CONSTRAINT... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4203/"
] | All I know about the constraint is it's name (`SYS_C003415`), but I want to see it's definition. | Another option would be to reverse engineer the DDL...
```
DBMS_METADATA.GET_DDL('CONSTRAINT', 'SYS_C003415')
```
Some examples here....
<http://www.psoug.org/reference/dbms_metadata.html> |
83,856 | <p>I have a string coming from a table like "can no pay{1},as your payment{2}due on {3}". I want to replace {1} with some value , {2} with some value and {3} with some value .</p>
<p>Is it Possible to replace all 3 in one replace function ? or is there any way I can directly write query and get replaced value ? I want to replace these strings in Oracle stored procedure the original string is coming from one of my table I am just doing select on that table </p>
<p>and then I want to replace {1},{2},{3} values from that string to the other value that I have from another table </p>
| [
{
"answer_id": 83910,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 5,
"selected": true,
"text": "<p>Although it is not one call, you can nest the <code>replace()</code> calls:</p>\n\n<pre><code>SET mycol = replace( replac... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14299/"
] | I have a string coming from a table like "can no pay{1},as your payment{2}due on {3}". I want to replace {1} with some value , {2} with some value and {3} with some value .
Is it Possible to replace all 3 in one replace function ? or is there any way I can directly write query and get replaced value ? I want to replace these strings in Oracle stored procedure the original string is coming from one of my table I am just doing select on that table
and then I want to replace {1},{2},{3} values from that string to the other value that I have from another table | Although it is not one call, you can nest the `replace()` calls:
```
SET mycol = replace( replace(mycol, '{1}', 'myoneval'), '{2}', mytwoval)
``` |
83,863 | <p>I want to find a way to develop database projects quickly in Visual Studio. Any ideas?</p>
| [
{
"answer_id": 83888,
"author": "Chris Woodruff",
"author_id": 7001,
"author_profile": "https://Stackoverflow.com/users/7001",
"pm_score": 3,
"selected": true,
"text": "<p>I have a method of creating and updating database projects in Visual Studio 2005 that I thought was common knowledge... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7001/"
] | I want to find a way to develop database projects quickly in Visual Studio. Any ideas? | I have a method of creating and updating database projects in Visual Studio 2005 that I thought was common knowledge. After asking a few coworkers if they knew how to update their database projects with this method and receiving no's, I thought I would blog about it and pass along some helpful hints and best practices.
I work a lot with databases and especially stored procedures that are built to be used with business logic/data access .NET framework. I enjoy working with databases and always create database projects to live with my .NET projects. I am psychotic about keeping database projects up to date. I have been burned too many time in my younger years where I needed to create a stored procedure that was deleted or was out of sync with the application using the database.
After creating your database project in Visual Studio 2005 as shown:
[alt text http://www.cloudsocket.com/images/image-thumb16.png](http://www.cloudsocket.com/images/image-thumb16.png)
Create 3 new directories in the projects: Tables, Stored Procedures and Functions. I usually only stored these for my projects.
[alt text http://www.cloudsocket.com/images/image-thumb17.png](http://www.cloudsocket.com/images/image-thumb17.png)
I now open the Server Explorer in Visual Studio and create a new connection to my desired database. I am using Northwind as my example. I am not going to walk through the creation of the connection for this example.
[alt text http://www.cloudsocket.com/images/image-thumb18.png](http://www.cloudsocket.com/images/image-thumb18.png)
I will use a stored procedure as my example on how to update the database project. First I expand the "Stored Procedures" directory in the Server Explorer for the Northwind database. I select a stored procedure.
[alt text http://www.cloudsocket.com/images/image-thumb19.png](http://www.cloudsocket.com/images/image-thumb19.png)
I drag the stored procedure to the "Stored Procedures" directory in the Solution Explorer and drop it.
[alt text http://www.cloudsocket.com/images/image-thumb20.png](http://www.cloudsocket.com/images/image-thumb20.png)
[alt text http://www.cloudsocket.com/images/image-thumb21.png](http://www.cloudsocket.com/images/image-thumb21.png)
If you open the file for the dragged stored procedures you will find that the IDE created the script as followed:
```
/****** Object: StoredProcedure [dbo].[CustOrdersOrders] Script Date: 08/25/2007 15:22:59 ******/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CustOrdersOrders]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CustOrdersOrders]
GO
/****** Object: StoredProcedure [dbo].[CustOrdersOrders] Script Date: 08/25/2007 15:22:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CustOrdersOrders]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE CustOrdersOrders @CustomerID nchar(5)
AS
SELECT OrderID,
OrderDate,
RequiredDate,
ShippedDate
FROM Orders
WHERE CustomerID = @CustomerID
ORDER BY OrderID
'
END
GO
```
You can now drag over all the tables, functions and remaining stored procedures from your database. You can also right click on each script in the Solution Explorer and run the scripts on your database project's referenced database. |
83,887 | <p>Below is an example class hierarchy and code. What I'm looking for is a way to determine if 'ChildClass1' or 'ChildClass2' had the static method whoAmI() called on it without re-implementing it in each child class.</p>
<pre><code><?php
abstract class ParentClass {
public static function whoAmI () {
// NOT correct, always gives 'ParentClass'
$class = __CLASS__;
// NOT correct, always gives 'ParentClass'.
// Also very round-about and likely slow.
$trace = debug_backtrace();
$class = $trace[0]['class'];
return $class;
}
}
class ChildClass1 extends ParentClass {
}
class ChildClass2 extends ParentClass {
}
// Shows 'ParentClass'
// Want to show 'ChildClass1'
print ChildClass1::whoAmI();
print "\n";
// Shows 'ParentClass'
// Want to show 'ChildClass2'
print ChildClass2::whoAmI();
print "\n";
</code></pre>
| [
{
"answer_id": 83902,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": false,
"text": "<p>I believe what you're referring to is a known php bug. Php 5.3 is aiming to address this issue with a new Late Stat... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15872/"
] | Below is an example class hierarchy and code. What I'm looking for is a way to determine if 'ChildClass1' or 'ChildClass2' had the static method whoAmI() called on it without re-implementing it in each child class.
```
<?php
abstract class ParentClass {
public static function whoAmI () {
// NOT correct, always gives 'ParentClass'
$class = __CLASS__;
// NOT correct, always gives 'ParentClass'.
// Also very round-about and likely slow.
$trace = debug_backtrace();
$class = $trace[0]['class'];
return $class;
}
}
class ChildClass1 extends ParentClass {
}
class ChildClass2 extends ParentClass {
}
// Shows 'ParentClass'
// Want to show 'ChildClass1'
print ChildClass1::whoAmI();
print "\n";
// Shows 'ParentClass'
// Want to show 'ChildClass2'
print ChildClass2::whoAmI();
print "\n";
``` | Now that PHP 5.3 is widely available in the wild, I wanted to put together a summary answer to this question to reflect newly available techniques.
As mentioned in the other answers, PHP 5.3 has introduced [Late Static Binding](http://php.benscom.com/manual/en/language.oop5.late-static-bindings.php) via a new [`static`](http://php.benscom.com/manual/en/language.oop5.static.php) keyword. As well, a new [`get_called_class()`](http://php.benscom.com/manual/en/function.get-called-class.php) function is also available that can only be used within a class method (instance or static).
For the purpose of determining the class as was asked in this question, the `get_called_class()` function is appropriate:
```
<?php
abstract class ParentClass {
public static function whoAmI () {
return get_called_class();
}
}
class ChildClass1 extends ParentClass {
}
class ChildClass2 extends ParentClass {
}
// Shows 'ChildClass1'
print ChildClass1::whoAmI();
print "\n";
// Shows 'ChildClass2'
print ChildClass2::whoAmI();
print "\n";
```
The [user contributed notes for `get_called_class()`](http://php.benscom.com/manual/en/function.get-called-class.php) include a few sample implementations that should work in PHP 5.2 as well by making use of `debug_backtrace()`. |
83,914 | <p>I've got a new varchar(10) field in a database with 1000+ records. I'd like to update the table so I can have random data in the field. I'm looking for a SQL solution.</p>
<p>I know I can use a cursor, but that seems inelegant.</p>
<p>MS-SQL 2000,BTW</p>
| [
{
"answer_id": 83932,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 1,
"selected": false,
"text": "<p>You might be able to adapt something <a href=\"http://www.mitchelsellers.com/blogs/articletype/articleview/artic... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4230/"
] | I've got a new varchar(10) field in a database with 1000+ records. I'd like to update the table so I can have random data in the field. I'm looking for a SQL solution.
I know I can use a cursor, but that seems inelegant.
MS-SQL 2000,BTW | ```
update MyTable Set RandomFld = CONVERT(varchar(10), NEWID())
``` |
83,918 | <p>We have several jobs that run concurrently that have to use the same config info for log4j. They are all dumping the logs into one file using the same appender. Is there a way to have each job dynamically name its log file so they stay seperate?</p>
<p>Thanks<BR>
Tom</p>
| [
{
"answer_id": 83998,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You could programmatically configure log4j when you initialize the job.</p>\n\n<p>You can also set the log4j.properties file... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5659/"
] | We have several jobs that run concurrently that have to use the same config info for log4j. They are all dumping the logs into one file using the same appender. Is there a way to have each job dynamically name its log file so they stay seperate?
Thanks
Tom | Can you pass a Java system property for each job? If so, you can parameterize like this:
```
java -Dmy_var=somevalue my.job.Classname
```
And then in your log4j.properties:
```
log4j.appender.A.File=${my_var}/A.log
```
You could populate the Java system property with a value from the host's environment (for example) that would uniquely identify the instance of the job. |
83,953 | <pre><code>foreach ($_GET as $field => $label)
{
$datarray[]=$_GET[$field];
echo "$_GET[$field]";
echo "<br>";
}
print_r($datarray);
</code></pre>
<hr>
<p>This is the output I am getting. I see the data is there in datarray but when
I <code>echo $_GET[$field]</code> </p>
<p>I only get "Array"</p>
<p>But <code>print_r($datarray)</code> prints all the data. Any idea how I pull those values?</p>
<h2>OUTPUT</h2>
<pre><code>Array (
[0] => Array (
[0] => Grade1
[1] => ln
[2] => North America
[3] => yuiyyu
[4] => iuy
[5] => uiyui
[6] => yui
[7] => uiy
[8] => 0:0:5
)
)
</code></pre>
| [
{
"answer_id": 84040,
"author": "Fernando Barrocal",
"author_id": 2274,
"author_profile": "https://Stackoverflow.com/users/2274",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code><pre></code> tags before <code>print_r</code>, then you will have a tree printed (or just look a... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
foreach ($_GET as $field => $label)
{
$datarray[]=$_GET[$field];
echo "$_GET[$field]";
echo "<br>";
}
print_r($datarray);
```
---
This is the output I am getting. I see the data is there in datarray but when
I `echo $_GET[$field]`
I only get "Array"
But `print_r($datarray)` prints all the data. Any idea how I pull those values?
OUTPUT
------
```
Array (
[0] => Array (
[0] => Grade1
[1] => ln
[2] => North America
[3] => yuiyyu
[4] => iuy
[5] => uiyui
[6] => yui
[7] => uiy
[8] => 0:0:5
)
)
``` | EDIT: When I completed your test, here was the final URL:
<http://hofstrateach.org/Roberto/process.php?keys=Grade1&keys=Nathan&keys=North%20America&keys=5&keys=3&keys=no&keys=foo&keys=blat&keys=0%3A0%3A24>
This is probably a malformed URL. When you pass duplicate keys in a query, PHP makes them an array. The above URL should probably be something like:
<http://hofstrateach.org/Roberto/process.php?grade=Grade1&schoolname=Nathan®ion=North%20America&answer[]=5&answer[]=3&answer[]=no&answer[]=foo&answer[]=blat&time=0%3A0%3A24>
This will create individual entries for most of the fields, and make $\_GET['answer'] be an array of the answers provided by the user.
Bottom line: fix your Flash file. |
83,962 | <p>Test the following code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
main()
{
const char *yytext="0";
const float f=(float)atof(yytext);
size_t t = *((size_t*)&f);
printf("t should be 0 but is %d\n", t);
}
</code></pre>
<p>Compile it with:</p>
<pre><code>gcc -O3 test.c
</code></pre>
<p>The GOOD output should be:</p>
<pre><code>"t should be 0 but is 0"
</code></pre>
<p>But with my gcc 4.1.3, I have:</p>
<pre><code>"t should be 0 but is -1209357172"
</code></pre>
| [
{
"answer_id": 83997,
"author": "Tobi",
"author_id": 5422,
"author_profile": "https://Stackoverflow.com/users/5422",
"pm_score": 5,
"selected": true,
"text": "<p>Use the compiler flag -fno-strict-aliasing.</p>\n\n<p>With strict aliasing enabled, as it is by default for at least -O3, in t... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6605/"
] | Test the following code:
```
#include <stdio.h>
#include <stdlib.h>
main()
{
const char *yytext="0";
const float f=(float)atof(yytext);
size_t t = *((size_t*)&f);
printf("t should be 0 but is %d\n", t);
}
```
Compile it with:
```
gcc -O3 test.c
```
The GOOD output should be:
```
"t should be 0 but is 0"
```
But with my gcc 4.1.3, I have:
```
"t should be 0 but is -1209357172"
``` | Use the compiler flag -fno-strict-aliasing.
With strict aliasing enabled, as it is by default for at least -O3, in the line:
```
size_t t = *((size_t*)&f);
```
the compiler assumes that the size\_t\* does NOT point to the same memory area as the float\*. As far as I know, this is standards-compliant behaviour (adherence with strict aliasing rules in the ANSI standard start around gcc-4, as Thomas Kammeyer pointed out).
If I recall correctly, you can use an intermediate cast to char\* to get around this. (compiler assumes char\* can alias anything)
In other words, try this (can't test it myself right now but I think it will work):
```
size_t t = *((size_t*)(char*)&f);
``` |
83,983 | <p>example:</p>
<pre><code>a_list = [1, 2, 3]
a_list.len() # doesn't work
len(a_list) # works
</code></pre>
<p>Python being (very) object oriented, I don't understand why the 'len' function isn't inherited by the object.
Plus I keep trying the wrong solution since it appears as the logical one to me</p>
| [
{
"answer_id": 84016,
"author": "Bill Barksdale",
"author_id": 16113,
"author_profile": "https://Stackoverflow.com/users/16113",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe you're looking for <code>__len__</code>. If that method exists, then len(a) calls it:</p>\n\n<pre><code>&g... | 2008/09/17 | [
"https://Stackoverflow.com/questions/83983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16070/"
] | example:
```
a_list = [1, 2, 3]
a_list.len() # doesn't work
len(a_list) # works
```
Python being (very) object oriented, I don't understand why the 'len' function isn't inherited by the object.
Plus I keep trying the wrong solution since it appears as the logical one to me | Guido's explanation is [here](http://mail.python.org/pipermail/python-3000/2006-November/004643.html):
>
> First of all, I chose len(x) over x.len() for HCI reasons (def \_\_len\_\_() came much later). There are two intertwined reasons actually, both HCI:
>
>
> (a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x\*(a+b) into x\*a + x\*b to the clumsiness of doing the same thing using a raw OO notation.
>
>
> (b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isn’t a file has a write() method.
>
>
> Saying the same thing in another way, I see ‘len‘ as a built-in operation. I’d hate to lose that. /…/
>
>
> |
84,007 | <p>Do you guys know how I can use the Curl command line to POST SOAP to test a web service?</p>
<p>I have a file (soap.xml) which has all the soap message attached to it I just don't seem to be able to properly post it.</p>
<p>Thanks!</p>
| [
{
"answer_id": 84046,
"author": "lbz",
"author_id": 11530,
"author_profile": "https://Stackoverflow.com/users/11530",
"pm_score": 6,
"selected": true,
"text": "<p>Posting a string:</p>\n\n<pre><code>curl -d \"String to post\" \"http://www.example.com/target\"\n</code></pre>\n\n<p>Posting... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13469/"
] | Do you guys know how I can use the Curl command line to POST SOAP to test a web service?
I have a file (soap.xml) which has all the soap message attached to it I just don't seem to be able to properly post it.
Thanks! | Posting a string:
```
curl -d "String to post" "http://www.example.com/target"
```
Posting the contents of a file:
```
curl -d @soap.xml "http://www.example.com/target"
``` |
84,064 | <p>I'm trying to use <code>SQLBindParameter</code> to prepare my driver for input via <code>SQLPutData</code>. The field in the database is a <code>TEXT</code> field. My function is crafted based on MS's example here:
<a href="http://msdn.microsoft.com/en-us/library/ms713824(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms713824(VS.85).aspx</a>.</p>
<p>I've setup the environment, made the connection, and prepared my statement successfully but when I call <code>SQLBindParam</code> (using code below) it consistently fails reporting: <code>[Microsoft][SQL Native Client]Invalid precision value</code></p>
<pre><code>int col_num = 1;
SQLINTEGER length = very_long_string.length( );
retcode = SQLBindParameter( StatementHandle,
col_num,
SQL_PARAM_INPUT,
SQL_C_BINARY,
SQL_LONGVARBINARY,
NULL,
NULL,
(SQLPOINTER) col_num,
NULL,
&length );
</code></pre>
<p>The above relies on the driver in use returning "N" for the <code>SQL_NEED_LONG_DATA_LEN</code> information type in <code>SQLGetInfo</code>. My driver returns "Y". How do I bind so that I can use <code>SQLPutData</code>?</p>
| [
{
"answer_id": 85102,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 2,
"selected": true,
"text": "<p>you're passing NULL as the buffer length, this is an in/out param that shoudl be the size of the col_num parameter. Also... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1625/"
] | I'm trying to use `SQLBindParameter` to prepare my driver for input via `SQLPutData`. The field in the database is a `TEXT` field. My function is crafted based on MS's example here:
<http://msdn.microsoft.com/en-us/library/ms713824(VS.85).aspx>.
I've setup the environment, made the connection, and prepared my statement successfully but when I call `SQLBindParam` (using code below) it consistently fails reporting: `[Microsoft][SQL Native Client]Invalid precision value`
```
int col_num = 1;
SQLINTEGER length = very_long_string.length( );
retcode = SQLBindParameter( StatementHandle,
col_num,
SQL_PARAM_INPUT,
SQL_C_BINARY,
SQL_LONGVARBINARY,
NULL,
NULL,
(SQLPOINTER) col_num,
NULL,
&length );
```
The above relies on the driver in use returning "N" for the `SQL_NEED_LONG_DATA_LEN` information type in `SQLGetInfo`. My driver returns "Y". How do I bind so that I can use `SQLPutData`? | you're passing NULL as the buffer length, this is an in/out param that shoudl be the size of the col\_num parameter. Also, you should pass a value for the ColumnSize or DecimalDigits parameters.
<http://msdn.microsoft.com/en-us/library/ms710963(VS.85).aspx> |
84,096 | <p>ssh will look for its keys by default in the ~/.ssh folder. I want to force it to always look in another location.</p>
<p>The workaround I'm using is to add the keys from the non-standard location to the agent:</p>
<pre><code>ssh-agent
ssh-add /path/to/where/keys/really/are/id_rsa
</code></pre>
<p>(on Linux and MingW32 shell on Windows)</p>
| [
{
"answer_id": 84212,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 5,
"selected": false,
"text": "<p><code>man ssh</code> gives me this options would could be useful.</p>\n<blockquote>\n<p>-i identity_file\nSelects a file from wh... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6329/"
] | ssh will look for its keys by default in the ~/.ssh folder. I want to force it to always look in another location.
The workaround I'm using is to add the keys from the non-standard location to the agent:
```
ssh-agent
ssh-add /path/to/where/keys/really/are/id_rsa
```
(on Linux and MingW32 shell on Windows) | If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry:
```
IdentityFile ~/.foo/identity
```
`man ssh_config` to find other config options. |
84,102 | <p>I'd be interested in some before-and-after c# examples, some non-idiomatic vs idiomatic examples. Non-c# examples would be fine as well if they get the idea across. Thanks.</p>
| [
{
"answer_id": 84140,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 4,
"selected": false,
"text": "<p>Idiomatic code is code that does a common task in the common way for your language. It's similar to a design patt... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13578/"
] | I'd be interested in some before-and-after c# examples, some non-idiomatic vs idiomatic examples. Non-c# examples would be fine as well if they get the idea across. Thanks. | Idiomatic means following the conventions of the language. You want to find the easiest and most common ways of accomplishing a task rather than porting your knowledge from a different language.
non-idiomatic python using a loop with append:
```
mylist = [1, 2, 3, 4]
newlist = []
for i in mylist:
newlist.append(i * 2)
```
idiomatic python using a list comprehension:
```
mylist = [1, 2, 3, 4]
newlist = [(i * 2) for i in mylist]
``` |
84,149 | <p>What is a good way to render data produced by a Java process in the browser? </p>
<p>I've made extensive use of JSP and the various associated frameworks (<a href="http://java.sun.com/products/jsp/jstl/" rel="nofollow noreferrer">JSTL</a>, <a href="http://struts.apache.org/" rel="nofollow noreferrer">Struts</a>, <a href="http://tapestry.apache.org/" rel="nofollow noreferrer">Tapestry</a>, etc), as well as more comprehensive frameworks not related to JSP (<a href="http://code.google.com/webtoolkit/" rel="nofollow noreferrer">GWT</a>, <a href="http://www.openlaszlo.org/" rel="nofollow noreferrer">OpenLaszlo</a>). None of the solutions have ever been entirely satisfactory - in most cases the framework is too constrained or too complex for my needs, while others would require extensive refactoring of existing code. Additionally, most frameworks seem to have performance problems.</p>
<p>Currently I'm leaning towards the solution of exposing my java data via a simple servlet that returns JSON, and then rendering the data using PHP or Ruby. This has the added benefit of instantly exposing my service as a web service as well, but I'm wondering if I'm reinventing the wheel here.</p>
| [
{
"answer_id": 84203,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps you could generate the data as XML and render it using XSLT?</p>\n\n<p>I'm not sure PHP or Ruby are the answer if Ja... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12457/"
] | What is a good way to render data produced by a Java process in the browser?
I've made extensive use of JSP and the various associated frameworks ([JSTL](http://java.sun.com/products/jsp/jstl/), [Struts](http://struts.apache.org/), [Tapestry](http://tapestry.apache.org/), etc), as well as more comprehensive frameworks not related to JSP ([GWT](http://code.google.com/webtoolkit/), [OpenLaszlo](http://www.openlaszlo.org/)). None of the solutions have ever been entirely satisfactory - in most cases the framework is too constrained or too complex for my needs, while others would require extensive refactoring of existing code. Additionally, most frameworks seem to have performance problems.
Currently I'm leaning towards the solution of exposing my java data via a simple servlet that returns JSON, and then rendering the data using PHP or Ruby. This has the added benefit of instantly exposing my service as a web service as well, but I'm wondering if I'm reinventing the wheel here. | I personally use [Tapestry 5](http://tapestry.apache.org/tapestry5/) for creating webpages with Java, but I agree that it can sometimes be a bit overkill. I would look into using JAX-RS ([java.net project](https://jsr311.dev.java.net/), [jsr311](http://jcp.org/en/jsr/detail?id=311)) it is pretty simple to use, it supports marshalling and unmarshalling objects to/from XML out of the box. It is possible to extend it to support JSON via [Jettison](http://jettison.codehaus.org/).
There are two implementations that I have tried:
* [Jersey](http://jersey.java.net/) - the reference implementation for JAX-RS.
* [Resteasy](http://www.jboss.org/resteasy/) - the implementation I prefer, good support for marshalling and unmarshalling a wide-range of formats. Also pretty stable and has more features that Jersey.
Take a look at the following code to get a feeling for what JAX-RS can do for you:
```
@Path("/")
class TestClass {
@GET
@Path("text")
@Produces("text/plain")
String getText() {
return "String value";
}
}
```
This tiny class will expose itself at the root of the server (@Path on the class), then expose the getText() method at the URI /text and allow access to it via HTTP GET. The @Produces annotation tells the JAX-RS framework to attempt to turn the result of the method into plain text.
The easiest way to learn about what is possible with JAX-RS is to read the [specification](http://jcp.org/en/jsr/detail?id=311). |
84,163 | <p>Here's a challenge that I was tasked with recently. I still haven't figured out the best way to do it, maybe someone else has an idea. </p>
<p>Using PHP and/or HTML, create a page that cycles through any number of other pages at a given interval.</p>
<p>For instance, we would load this page and it would take us to google for 20 seconds, then on to yahoo for 10 seconds, then on to stackoverflow for 180 seconds and so on an so forth. </p>
| [
{
"answer_id": 84190,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 1,
"selected": false,
"text": "<p>Use a separate iframe for the content, then use Javascript to <code>delay()</code> a period of time and set the iframe... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13399/"
] | Here's a challenge that I was tasked with recently. I still haven't figured out the best way to do it, maybe someone else has an idea.
Using PHP and/or HTML, create a page that cycles through any number of other pages at a given interval.
For instance, we would load this page and it would take us to google for 20 seconds, then on to yahoo for 10 seconds, then on to stackoverflow for 180 seconds and so on an so forth. | ```
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>Dashboard Example</title>
<style type="text/css">
body, html { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; }
iframe { border: none; }
</style>
<script type="text/javascript">
var Dash = {
nextIndex: 0,
dashboards: [
{url: "http://www.google.com", time: 5},
{url: "http://www.yahoo.com", time: 10},
{url: "http://www.stackoverflow.com", time: 15}
],
display: function()
{
var dashboard = Dash.dashboards[Dash.nextIndex];
frames["displayArea"].location.href = dashboard.url;
Dash.nextIndex = (Dash.nextIndex + 1) % Dash.dashboards.length;
setTimeout(Dash.display, dashboard.time * 1000);
}
};
window.onload = Dash.display;
</script>
</head>
<body>
<iframe name="displayArea" width="100%" height="100%"></iframe>
</body>
</html>
``` |
84,174 | <p>I have been trying out <a href="http://www.codeplex.com/servicefactory" rel="nofollow noreferrer">Service Factory</a> and have run into some problems in regards to long filenames - surpassing the limit in Vista/XP. The problem is that when generating code from the models service factory prefixes everything with the namespace specified. Making the folder structure huge. For example starting in</p>
<p>c:\work\sftest\MyWebService</p>
<p>I create each of the models with moderate length of names in data contracts and service interface. I set the namespace to be MyCompany.SFTest.MyWebservice</p>
<p>After generating code I end up with </p>
<pre>
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Business Logic
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Resource Access
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.DataContracts
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.FaultContracts
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.MessageContracts
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.ServiceContracts
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.ServiceImplementation
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Tests
</pre>
<p>Under each of the folders is a project file with the same prefix </p>
<pre>
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.ServiceImplementation\MyCompany.SFTest.MyWebService.ServiceImplementation.proj
</pre>
<p>This blows up the recipe as windows can't accept filenames exceeding a specific length.</p>
<p>Is it necessary to explicitly include the namespace in each of the foldernames?
Obviously at some point I might want to branch a service to another location but for the same reason as above might be unable to.
Is there a workaround for this?</p>
| [
{
"answer_id": 84250,
"author": "Loofer",
"author_id": 5552,
"author_profile": "https://Stackoverflow.com/users/5552",
"pm_score": 2,
"selected": false,
"text": "<p>I have always been in the fortunate position to have Red Gate <a href=\"http://www.red-gate.com/products/SQL_Compare/index.... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15771/"
] | I have been trying out [Service Factory](http://www.codeplex.com/servicefactory) and have run into some problems in regards to long filenames - surpassing the limit in Vista/XP. The problem is that when generating code from the models service factory prefixes everything with the namespace specified. Making the folder structure huge. For example starting in
c:\work\sftest\MyWebService
I create each of the models with moderate length of names in data contracts and service interface. I set the namespace to be MyCompany.SFTest.MyWebservice
After generating code I end up with
```
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Business Logic
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Resource Access
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.DataContracts
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.FaultContracts
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.MessageContracts
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.ServiceContracts
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.ServiceImplementation
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Tests
```
Under each of the folders is a project file with the same prefix
```
c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.ServiceImplementation\MyCompany.SFTest.MyWebService.ServiceImplementation.proj
```
This blows up the recipe as windows can't accept filenames exceeding a specific length.
Is it necessary to explicitly include the namespace in each of the foldernames?
Obviously at some point I might want to branch a service to another location but for the same reason as above might be unable to.
Is there a workaround for this? | I have always been in the fortunate position to have Red Gate [Schema compare](http://www.red-gate.com/products/SQL_Compare/index.htm) which i think would do what you ask. Cheap at twice the price! |
84,178 | <p>I'm running in a windows environment with Trac / SVN and I want commits to the repository to integrate to Trac and close the bugs that were noted in the SVN Comment.</p>
<p>I know there's some post commit hooks to do that, but there's not much information about how to do it on windows.</p>
<p>Anyone done it successfully? And what were the steps you followed to achive it?</p>
<p>Here's the hook I need to put in place in SVN, but I'm not exactly sure how to do this in the Windows environment.</p>
<p><a href="http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook?rev=920" rel="nofollow noreferrer">Trac Post Commit Hook</a></p>
| [
{
"answer_id": 84301,
"author": "Benjamin W. Smith",
"author_id": 1068060,
"author_profile": "https://Stackoverflow.com/users/1068060",
"pm_score": 0,
"selected": false,
"text": "<p>Post commit hooks live in the \"hooks\" directory where ever you have the repository living on the server ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5462/"
] | I'm running in a windows environment with Trac / SVN and I want commits to the repository to integrate to Trac and close the bugs that were noted in the SVN Comment.
I know there's some post commit hooks to do that, but there's not much information about how to do it on windows.
Anyone done it successfully? And what were the steps you followed to achive it?
Here's the hook I need to put in place in SVN, but I'm not exactly sure how to do this in the Windows environment.
[Trac Post Commit Hook](http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook?rev=920) | Alright, now that I've got some time to post my experience after figuring this all out, and thanks to Craig for getting me on the right track. Here's what you need to do (at least with SVN v1.4 and Trac v0.10.3):
1. Locate your SVN repository that you want to enable the Post Commit Hook for.
2. inside the SVN repository there's a directory called hooks, this is where you'll be placing the post commit hook.
3. create a file post-commit.bat (this is the batch file that's automatically called by SVN post commit).
4. Place the following code inside the post-commit.bat file ( this will call your post commit cmd file passing in the parameters that SVN automatically passes %1 is the repository, %2 is the revision that was committed.
%~dp0\trac-post-commit-hook.cmd %1 %2
5. Now create the trac-post-commit-hook.cmd file as follows:
>
> @ECHO OFF
> ::
> :: Trac
> post-commit-hook script for
> Windows
> ::
> :: Contributed by
> markus, modified by cboos.
>
> ::
> Usage:
> ::
> :: 1) Insert the
> following line in your post-commit.bat
> script
> ::
> :: call
> %~dp0\trac-post-commit-hook.cmd %1
> %2
> ::
> :: 2) Check the 'Modify
> paths' section below, be sure to set
> at least TRAC\_ENV
>
>
> ::
> ----------------------------------------------------------
> :: Modify paths here:
>
> :: --
> this one *must* be set
> SET
> TRAC\_ENV=C:\trac\MySpecialProject
>
>
> :: -- set if Python is not in the
> system path
> :: SET
> PYTHON\_PATH=
>
> :: -- set to the
> folder containing trac/ if installed
> in a non-standard location
> :: SET
> TRAC\_PATH=
> ::
> ----------------------------------------------------------
>
> :: Do not execute hook if trac
> environment does not exist
> IF NOT
> EXIST %TRAC\_ENV% GOTO :EOF
>
>
> set PATH=%PYTHON\_PATH%;%PATH%
> set
> PYTHONPATH=%TRAC\_PATH%;%PYTHONPATH%
>
>
> SET REV=%2
>
> :: GET THE
> AUTHOR AND THE LOG MESSAGE
> for /F
> %%A in ('svnlook author -r %REV% %1')
> do set AUTHOR=%%A
> for /F
> "delims==" %%B in ('svnlook log -r
> %REV% %1') do set LOG=%%B
>
> ::
> CALL THE PYTHON SCRIPT
> Python
> "%~dp0\trac-post-commit-hook" -p
> "%TRAC\_ENV%" -r "%REV%" -u "%AUTHOR%"
> -m "%LOG%"
>
>
>
>
The most important parts here are to set your TRAC\_ENV which is the path to the repository root (SET TRAC\_ENV=C:\trac\MySpecialProject)
The next MAJORLY IMPORTANT THING in this script is to do the following:
>
> :: GET THE AUTHOR AND THE LOG
> MESSAGE
> for /F %%A in ('svnlook
> author -r %REV% %1') do set
> AUTHOR=%%A
> for /F "delims==" %%B
> in ('svnlook log -r %REV% %1') do set
> LOG=%%B
>
>
>
>
if you see in the script file above I'm using svnlook (which is a command line utility with SVN) to get the LOG message and the author that made the commit to the repository.
Then, the next line of the script is actually calling the Python code to perform the closing of the tickets and parse the log message. I had to modify this to pass in the Log message and the author (which the usernames I use in Trac match the usernames in SVN so that was easy).
>
> CALL THE PYTHON SCRIPT
> Python
> "%~dp0\trac-post-commit-hook" -p
> "%TRAC\_ENV%" -r "%REV%" -u "%AUTHOR%"
> -m "%LOG%"
>
>
>
>
The above line in the script will pass into the python script the Trac Environment, the revision, the person that made the commit, and their comment.
Here's the Python script that I used. One thing that I did additional to the regular script is we use a custom field (fixed\_in\_ver) which is used by our QA team to tell if the fix they're validating is in the version of code that they're testing in QA. So, I modified the code in the python script to update that field on the ticket. You can remove that code as you won't need it, but it's a good example of what you can do to update custom fields in Trac if you also want to do that.
I did that by having the users optionally include in their comment something like:
>
> (version 2.1.2223.0)
>
>
>
I then use the same technique that the python script uses with regular expressions to get the information out. It wasn't too bad.
Anyway, here's the python script I used, Hopefully this is a good tutorial on exactly what I did to get it to work in the windows world so you all can leverage this in your own shop...
If you don't want to deal with my additional code for updating the custom field, get the base script from this location as mentioned by Craig above ([Script From Edgewall](http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook?rev=920))
```
#!/usr/bin/env python
# trac-post-commit-hook
# ----------------------------------------------------------------------------
# Copyright (c) 2004 Stephen Hansen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# ----------------------------------------------------------------------------
# This Subversion post-commit hook script is meant to interface to the
# Trac (http://www.edgewall.com/products/trac/) issue tracking/wiki/etc
# system.
#
# It should be called from the 'post-commit' script in Subversion, such as
# via:
#
# REPOS="$1"
# REV="$2"
# LOG=`/usr/bin/svnlook log -r $REV $REPOS`
# AUTHOR=`/usr/bin/svnlook author -r $REV $REPOS`
# TRAC_ENV='/somewhere/trac/project/'
# TRAC_URL='http://trac.mysite.com/project/'
#
# /usr/bin/python /usr/local/src/trac/contrib/trac-post-commit-hook \
# -p "$TRAC_ENV" \
# -r "$REV" \
# -u "$AUTHOR" \
# -m "$LOG" \
# -s "$TRAC_URL"
#
# It searches commit messages for text in the form of:
# command #1
# command #1, #2
# command #1 & #2
# command #1 and #2
#
# You can have more then one command in a message. The following commands
# are supported. There is more then one spelling for each command, to make
# this as user-friendly as possible.
#
# closes, fixes
# The specified issue numbers are closed with the contents of this
# commit message being added to it.
# references, refs, addresses, re
# The specified issue numbers are left in their current status, but
# the contents of this commit message are added to their notes.
#
# A fairly complicated example of what you can do is with a commit message
# of:
#
# Changed blah and foo to do this or that. Fixes #10 and #12, and refs #12.
#
# This will close #10 and #12, and add a note to #12.
import re
import os
import sys
import time
from trac.env import open_environment
from trac.ticket.notification import TicketNotifyEmail
from trac.ticket import Ticket
from trac.ticket.web_ui import TicketModule
# TODO: move grouped_changelog_entries to model.py
from trac.util.text import to_unicode
from trac.web.href import Href
try:
from optparse import OptionParser
except ImportError:
try:
from optik import OptionParser
except ImportError:
raise ImportError, 'Requires Python 2.3 or the Optik option parsing library.'
parser = OptionParser()
parser.add_option('-e', '--require-envelope', dest='env', default='',
help='Require commands to be enclosed in an envelope. If -e[], '
'then commands must be in the form of [closes #4]. Must '
'be two characters.')
parser.add_option('-p', '--project', dest='project',
help='Path to the Trac project.')
parser.add_option('-r', '--revision', dest='rev',
help='Repository revision number.')
parser.add_option('-u', '--user', dest='user',
help='The user who is responsible for this action')
parser.add_option('-m', '--msg', dest='msg',
help='The log message to search.')
parser.add_option('-c', '--encoding', dest='encoding',
help='The encoding used by the log message.')
parser.add_option('-s', '--siteurl', dest='url',
help='The base URL to the project\'s trac website (to which '
'/ticket/## is appended). If this is not specified, '
'the project URL from trac.ini will be used.')
(options, args) = parser.parse_args(sys.argv[1:])
if options.env:
leftEnv = '\\' + options.env[0]
rghtEnv = '\\' + options.env[1]
else:
leftEnv = ''
rghtEnv = ''
commandPattern = re.compile(leftEnv + r'(?P<action>[A-Za-z]*).?(?P<ticket>#[0-9]+(?:(?:[, &]*|[ ]?and[ ]?)#[0-9]+)*)' + rghtEnv)
ticketPattern = re.compile(r'#([0-9]*)')
versionPattern = re.compile(r"\(version[ ]+(?P<version>([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+))\)")
class CommitHook:
_supported_cmds = {'close': '_cmdClose',
'closed': '_cmdClose',
'closes': '_cmdClose',
'fix': '_cmdClose',
'fixed': '_cmdClose',
'fixes': '_cmdClose',
'addresses': '_cmdRefs',
're': '_cmdRefs',
'references': '_cmdRefs',
'refs': '_cmdRefs',
'see': '_cmdRefs'}
def __init__(self, project=options.project, author=options.user,
rev=options.rev, msg=options.msg, url=options.url,
encoding=options.encoding):
msg = to_unicode(msg, encoding)
self.author = author
self.rev = rev
self.msg = "(In [%s]) %s" % (rev, msg)
self.now = int(time.time())
self.env = open_environment(project)
if url is None:
url = self.env.config.get('project', 'url')
self.env.href = Href(url)
self.env.abs_href = Href(url)
cmdGroups = commandPattern.findall(msg)
tickets = {}
for cmd, tkts in cmdGroups:
funcname = CommitHook._supported_cmds.get(cmd.lower(), '')
if funcname:
for tkt_id in ticketPattern.findall(tkts):
func = getattr(self, funcname)
tickets.setdefault(tkt_id, []).append(func)
for tkt_id, cmds in tickets.iteritems():
try:
db = self.env.get_db_cnx()
ticket = Ticket(self.env, int(tkt_id), db)
for cmd in cmds:
cmd(ticket)
# determine sequence number...
cnum = 0
tm = TicketModule(self.env)
for change in tm.grouped_changelog_entries(ticket, db):
if change['permanent']:
cnum += 1
# get the version number from the checkin... and update the ticket with it.
version = versionPattern.search(msg)
if version != None and version.group("version") != None:
ticket['fixed_in_ver'] = version.group("version")
ticket.save_changes(self.author, self.msg, self.now, db, cnum+1)
db.commit()
tn = TicketNotifyEmail(self.env)
tn.notify(ticket, newticket=0, modtime=self.now)
except Exception, e:
# import traceback
# traceback.print_exc(file=sys.stderr)
print>>sys.stderr, 'Unexpected error while processing ticket ' \
'ID %s: %s' % (tkt_id, e)
def _cmdClose(self, ticket):
ticket['status'] = 'closed'
ticket['resolution'] = 'fixed'
def _cmdRefs(self, ticket):
pass
if __name__ == "__main__":
if len(sys.argv) < 5:
print "For usage: %s --help" % (sys.argv[0])
else:
CommitHook()
``` |
84,209 | <p><strong>Introduction</strong></p>
<p>I've always been searching for a way to make Visual Studio draw a line after a certain amount of characters.</p>
<p>Below is a guide to enable these so called <em>guidelines</em> for various versions of Visual Studio.</p>
<p><strong>Visual Studio 2013 or later</strong></p>
<p>Install Paul Harrington's <a href="http://visualstudiogallery.msdn.microsoft.com/da227a0b-0e31-4a11-8f6b-3a149cf2e459/view/Reviews" rel="noreferrer">Editor Guidelines extension</a>.</p>
<p><strong>Visual Studio 2010 and 2012</strong></p>
<ol>
<li>Install Paul Harrington's Editor Guidelines extension for <a href="http://visualstudiogallery.msdn.microsoft.com/0fbf2878-e678-4577-9fdb-9030389b338c" rel="noreferrer">VS 2010</a> or <a href="http://visualstudiogallery.msdn.microsoft.com/da227a0b-0e31-4a11-8f6b-3a149cf2e459?SRC=Home" rel="noreferrer">VS 2012</a>.</li>
<li>Open the registry at:
<br />VS 2010: <code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Text Editor</code>
<br />VS 2012: <code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\Text Editor</code>
<br />and add a new string called <code>Guides</code> with the value <code>RGB(100,100,100), 80</code>. The
first part specifies the color, while the other one (<code>80</code>) is the column the line will be displayed.</li>
<li>Or install the <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/7f2a6727-2993-4c1d-8f58-ae24df14ea91" rel="noreferrer">Guidelines UI</a> extension (which is also a part of the <a href="http://visualstudiogallery.msdn.microsoft.com/d0d33361-18e2-46c0-8ff2-4adea1e34fef/" rel="noreferrer">Productivity Power Tools</a>), which will add entries to the editor's context menu for adding/removing the entries without needing to edit the registry directly. The current disadvantage of this method is that you can't specify the column directly.</li>
</ol>
<p><strong>Visual Studio 2008 and Other Versions</strong></p>
<p>If you are using Visual Studio 2008 open the registry at <code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor</code> and add a new string called <code>Guides</code> with the value <code>RGB(100,100,100), 80</code>. The first part specifies the color, while the other one (<code>80</code>) is the column the line will be displayed. The vertical line will appear, when you restart Visual Studio.</p>
<p>This trick also works for various other version of Visual Studio, as long as you use the correct path:</p>
<pre><code>2003: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\7.1\Text Editor
2005: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\Text Editor
2008: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor
2008 Express: HKEY_CURRENT_USER\Software\Microsoft\VCExpress\9.0\Text Editor
</code></pre>
<p><a href="https://stackoverflow.com/a/332577/11387">This also works in SQL Server 2005 and probably other versions.</a></p>
| [
{
"answer_id": 84325,
"author": "Rory MacLeod",
"author_id": 1016,
"author_profile": "https://Stackoverflow.com/users/1016",
"pm_score": 2,
"selected": false,
"text": "<p>The registry path for Visual Studio 2008 is the same, but with 9.0 as the version number:</p>\n\n<pre><code>HKEY_CURR... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11387/"
] | **Introduction**
I've always been searching for a way to make Visual Studio draw a line after a certain amount of characters.
Below is a guide to enable these so called *guidelines* for various versions of Visual Studio.
**Visual Studio 2013 or later**
Install Paul Harrington's [Editor Guidelines extension](http://visualstudiogallery.msdn.microsoft.com/da227a0b-0e31-4a11-8f6b-3a149cf2e459/view/Reviews).
**Visual Studio 2010 and 2012**
1. Install Paul Harrington's Editor Guidelines extension for [VS 2010](http://visualstudiogallery.msdn.microsoft.com/0fbf2878-e678-4577-9fdb-9030389b338c) or [VS 2012](http://visualstudiogallery.msdn.microsoft.com/da227a0b-0e31-4a11-8f6b-3a149cf2e459?SRC=Home).
2. Open the registry at:
VS 2010: `HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Text Editor`
VS 2012: `HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\Text Editor`
and add a new string called `Guides` with the value `RGB(100,100,100), 80`. The
first part specifies the color, while the other one (`80`) is the column the line will be displayed.
3. Or install the [Guidelines UI](http://visualstudiogallery.msdn.microsoft.com/en-us/7f2a6727-2993-4c1d-8f58-ae24df14ea91) extension (which is also a part of the [Productivity Power Tools](http://visualstudiogallery.msdn.microsoft.com/d0d33361-18e2-46c0-8ff2-4adea1e34fef/)), which will add entries to the editor's context menu for adding/removing the entries without needing to edit the registry directly. The current disadvantage of this method is that you can't specify the column directly.
**Visual Studio 2008 and Other Versions**
If you are using Visual Studio 2008 open the registry at `HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor` and add a new string called `Guides` with the value `RGB(100,100,100), 80`. The first part specifies the color, while the other one (`80`) is the column the line will be displayed. The vertical line will appear, when you restart Visual Studio.
This trick also works for various other version of Visual Studio, as long as you use the correct path:
```
2003: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\7.1\Text Editor
2005: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\Text Editor
2008: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor
2008 Express: HKEY_CURRENT_USER\Software\Microsoft\VCExpress\9.0\Text Editor
```
[This also works in SQL Server 2005 and probably other versions.](https://stackoverflow.com/a/332577/11387) | This is originally from Sara's [blog](https://web.archive.org/web/20160221095812/http://blogs.msdn.com:80/b/saraford/archive/2004/11/15/257953.aspx).
It also works with almost any version of Visual Studio, you just need to change the "8.0" in the registry key to the appropriate version number for your version of Visual Studio.
The guide line shows up in the Output window too. (Visual Studio 2010 corrects this, and the line only shows up in the code editor window.)
You can also have the guide in multiple columns by listing more than one number after the color specifier:
```
RGB(230,230,230), 4, 80
```
Puts a white line at column 4 and column 80. This should be the value of a string value `Guides` in "Text Editor" key (see bellow).
Be sure to pick a line color that will be visisble on your background. This color won't show up on the default background color in VS. This is the value for a light grey: RGB(221, 221, 221).
Here are the registry keys that I know of:
**Visual Studio 2010**: HKCU\Software\Microsoft\VisualStudio\10.0\Text Editor
**Visual Studio 2008**: HKCU\Software\Microsoft\VisualStudio\9.0\Text Editor
**Visual Studio 2005**: HKCU\Software\Microsoft\VisualStudio\8.0\Text Editor
**Visual Studio 2003**: HKCU\Software\Microsoft\VisualStudio\7.1\Text Editor
For those running Visual Studio 2010, you may want to install the following extensions rather than changing the registry yourself:
* <http://visualstudiogallery.msdn.microsoft.com/en-us/0fbf2878-e678-4577-9fdb-9030389b338c>
* <http://visualstudiogallery.msdn.microsoft.com/en-us/7f2a6727-2993-4c1d-8f58-ae24df14ea91>
These are also part of the [Productivity Power Tools](https://web.archive.org/web/20110119025922/http://visualstudiogallery.msdn.microsoft.com:80/en-us/d0d33361-18e2-46c0-8ff2-4adea1e34fef), which includes many other very useful extensions. |
84,278 | <p>How do I use <code>RelativeSource</code> with WPF bindings and what are the different use-cases?</p>
| [
{
"answer_id": 84314,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 5,
"selected": false,
"text": "<p>Don't forget TemplatedParent:</p>\n\n<pre><code><Binding RelativeSource=\"{RelativeSource TemplatedParent}\"/>\n</c... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4918/"
] | How do I use `RelativeSource` with WPF bindings and what are the different use-cases? | If you want to bind to another property on the object:
```
{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}
```
If you want to get a property on an ancestor:
```
{Binding Path=PathToProperty,
RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}
```
If you want to get a property on the templated parent (so you can do 2 way bindings in a ControlTemplate)
```
{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}
```
or, shorter (this only works for OneWay bindings):
```
{TemplateBinding Path=PathToProperty}
``` |
84,290 | <p>How do I get a a complete list of all the urls that my rails application could generate? </p>
<p>I don't want the routes that I get get form rake routes, instead I want to get the actul URLs corrosponding to all the dynmically generated pages in my application...</p>
<p>Is this even possible?</p>
<p>(Background: I'm doing this because I want a complete list of URLs for some load testing I want to do, which has to cover the entire breadth of the application)</p>
| [
{
"answer_id": 84482,
"author": "Jeremiah Peschka",
"author_id": 11780,
"author_profile": "https://Stackoverflow.com/users/11780",
"pm_score": 1,
"selected": false,
"text": "<p>You could pretty quickly hack together a program that grabs the output of <code>rake routes</code> and then par... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7473/"
] | How do I get a a complete list of all the urls that my rails application could generate?
I don't want the routes that I get get form rake routes, instead I want to get the actul URLs corrosponding to all the dynmically generated pages in my application...
Is this even possible?
(Background: I'm doing this because I want a complete list of URLs for some load testing I want to do, which has to cover the entire breadth of the application) | I was able to produce useful output with the following command:
```
$ wget --spider -r -nv -nd -np http://localhost:3209/ 2>&1 | ack -o '(?<=URL:)\S+'
http://localhost:3209/
http://localhost:3209/robots.txt
http://localhost:3209/agenda/2008/08
http://localhost:3209/agenda/2008/10
http://localhost:3209/agenda/2008/09/01
http://localhost:3209/agenda/2008/09/02
http://localhost:3209/agenda/2008/09/03
^C
```
### A quick reference of the `wget` arguments:
```
# --spider don't download anything.
# -r, --recursive specify recursive download.
# -nv, --no-verbose turn off verboseness, without being quiet.
# -nd, --no-directories don't create directories.
# -np, --no-parent don't ascend to the parent directory.
```
### About `ack`
`ack` is like `grep` but use `perl` regexps, which are more complete/powerful.
`-o` tells `ack` to only output the matched substring, and the pattern I used looks for anything non-space preceded by `'URL:'` |
84,310 | <p>I'm connecting to an AS/400 stored procedure layer using the IBM iSeries Access for Windows package. This provides a .NET DLL with classes similar to those in the <code>System.Data</code> namespace. As such we use their implementation of the connection class and provide it with a connection string.</p>
<p>Does anyone know how I can amend the connection string to indicate the default library it should use?</p>
| [
{
"answer_id": 84374,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 1,
"selected": false,
"text": "<p>Are you using the Catalog Library List parameter for OLE DB? This is what my connection string typically looks like:</p>\n\n<... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12277/"
] | I'm connecting to an AS/400 stored procedure layer using the IBM iSeries Access for Windows package. This provides a .NET DLL with classes similar to those in the `System.Data` namespace. As such we use their implementation of the connection class and provide it with a connection string.
Does anyone know how I can amend the connection string to indicate the default library it should use? | Snippet from some Delphi source code using the Client Access Express Driver. Probably not exactly what you are looking for, but it may help others that stumble upon this post. **The `DBQ` part is the default library, and the `System` part is the AS400/DB2 host name.**
```
ConnectionString :=
'Driver={Client Access ODBC Driver (32-bit)};' +
'System=' + System + ';' +
'DBQ=' + Lib + ';' +
'TRANSLATE=1;' +
'CMT=0;' +
//'DESC=Client Access Express ODBC data source;' +
'QAQQINILIB=;' +
'PKG=QGPL/DEFAULT(IBM),2,0,1,0,512;' +
'SORTTABLE=;' +
'LANGUAGEID=ENU;' +
'XLATEDLL=;' +
'DFTPKGLIB=QGPL;';
``` |
84,322 | <p>It appears that using perldoc perl gives the list of, e.g. perlre, perlvar, etc.</p>
<p>Is this the best place to find the list of what's available as an overview or tutorial or reference manual section? Is there another, better list?</p>
| [
{
"answer_id": 84367,
"author": "szabgab",
"author_id": 11827,
"author_profile": "https://Stackoverflow.com/users/11827",
"pm_score": 1,
"selected": false,
"text": "<p>See also <a href=\"https://stackoverflow.com/questions/70573/best-online-source-to-learn-perl\">best online source to le... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8763/"
] | It appears that using perldoc perl gives the list of, e.g. perlre, perlvar, etc.
Is this the best place to find the list of what's available as an overview or tutorial or reference manual section? Is there another, better list? | ```
perldoc perltoc
```
is a bit more verbose about the various documentation files. If you want a list of core modules, try
```
perldoc perlmodlib
``` |
84,330 | <p><strong>Here is the updated question:</strong></p>
<p>the current query is doing something like:<br></p>
<pre><code>$sql1 = "TRUNCATE TABLE fubar";
$sql2 = "CREATE TEMPORARY TABLE IF NOT EXISTS fubar SELECT id, name FROM barfu";
</code></pre>
<p>The first time the method containing this is run, it generates an error message on the truncate since the table doesn't exist yet.</p>
<p>Is my only option to do the <code>CREATE TABLE</code>, run the <code>TRUNCATE TABLE</code>, and then fill the table? (3 separate queries)</p>
<p><strong>original question was:</strong></p>
<p>
I've been having a hard time trying to figure out if the following is possible in MySql without having to write block sql:</p>
<pre><code>CREATE TABLE fubar IF NOT EXISTS ELSE TRUNCATE TABLE fubar
</code></pre>
<p>If I run truncate separately before the create table, and the table doesn't exist, then I get an error message. I'm trying to eliminate that error message without having to add any more queries.</p>
<p>This code will be executed using PHP.</p>
| [
{
"answer_id": 84396,
"author": "Ben",
"author_id": 11522,
"author_profile": "https://Stackoverflow.com/users/11522",
"pm_score": 2,
"selected": false,
"text": "<p>how about:</p>\n\n<pre><code>DROP TABLE IF EXISTS fubar;\nCREATE TABLE fubar;\n</code></pre>\n\n<p>Or did you mean you just ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16186/"
] | **Here is the updated question:**
the current query is doing something like:
```
$sql1 = "TRUNCATE TABLE fubar";
$sql2 = "CREATE TEMPORARY TABLE IF NOT EXISTS fubar SELECT id, name FROM barfu";
```
The first time the method containing this is run, it generates an error message on the truncate since the table doesn't exist yet.
Is my only option to do the `CREATE TABLE`, run the `TRUNCATE TABLE`, and then fill the table? (3 separate queries)
**original question was:**
I've been having a hard time trying to figure out if the following is possible in MySql without having to write block sql:
```
CREATE TABLE fubar IF NOT EXISTS ELSE TRUNCATE TABLE fubar
```
If I run truncate separately before the create table, and the table doesn't exist, then I get an error message. I'm trying to eliminate that error message without having to add any more queries.
This code will be executed using PHP. | shmuel613, it would be better to update your original question rather than replying. It's best if there's a single place containing the complete question rather than having it spread out in a discussion.
Ben's answer is reasonable, except he seems to have a 'not' where he doesn't want one. Dropping the table only if it **doesn't** exist isn't quite right.
You will indeed need multiple statements. Either conditionally create then populate:
1. CREATE TEMPORARY TABLE IF NOT EXISTS fubar ( id int, name varchar(80) )
2. TRUNCATE TABLE fubar
3. INSERT INTO fubar SELECT \* FROM barfu
or just drop and recreate
1. DROP TABLE IF EXISTS fubar
2. CREATE TEMPORARY TABLE fubar SELECT id, name FROM barfu
With pure SQL those are your two real classes of solutions. I like the second better.
(With a stored procedure you could reduce it to a single statement. Something like: TruncateAndPopulate(fubar) But by the time you write the code for TruncateAndPopulate() you'll spend more time than just using the SQL above.) |
84,331 | <p>Is there a macro or a way to conditionally copy rows from one worksheet to another in Excel 2003?</p>
<p>I'm pulling a list of data from SharePoint via a web query into a blank worksheet in Excel, and then I want to copy the rows for a particular month to a particular worksheet (for example, all July data from a SharePoint worksheet to the Jul worksheet, all June data from a SharePoint worksheet to Jun worksheet, etc.).</p>
<p><strong>Sample data</strong></p>
<pre><code>Date - Project - ID - Engineer
8/2/08 - XYZ - T0908-5555 - JS
9/4/08 - ABC - T0908-6666 - DF
9/5/08 - ZZZ - T0908-7777 - TS
</code></pre>
<p>It's not a one-off exercise. I'm trying to put together a dashboard that my boss can pull the latest data from SharePoint and see the monthly results, so it needs to be able to do it all the time and organize it cleanly.</p>
| [
{
"answer_id": 84430,
"author": "RickL",
"author_id": 7261,
"author_profile": "https://Stackoverflow.com/users/7261",
"pm_score": -1,
"selected": false,
"text": "<p>If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy an... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Is there a macro or a way to conditionally copy rows from one worksheet to another in Excel 2003?
I'm pulling a list of data from SharePoint via a web query into a blank worksheet in Excel, and then I want to copy the rows for a particular month to a particular worksheet (for example, all July data from a SharePoint worksheet to the Jul worksheet, all June data from a SharePoint worksheet to Jun worksheet, etc.).
**Sample data**
```
Date - Project - ID - Engineer
8/2/08 - XYZ - T0908-5555 - JS
9/4/08 - ABC - T0908-6666 - DF
9/5/08 - ZZZ - T0908-7777 - TS
```
It's not a one-off exercise. I'm trying to put together a dashboard that my boss can pull the latest data from SharePoint and see the monthly results, so it needs to be able to do it all the time and organize it cleanly. | This works: The way it's set up I called it from the immediate pane, but you can easily create a sub() that will call MoveData once for each month, then just invoke the sub.
You may want to add logic to sort your monthly data after it's all been copied
```
Public Sub MoveData(MonthNumber As Integer, SheetName As String)
Dim sharePoint As Worksheet
Dim Month As Worksheet
Dim spRange As Range
Dim cell As Range
Set sharePoint = Sheets("Sharepoint")
Set Month = Sheets(SheetName)
Set spRange = sharePoint.Range("A2")
Set spRange = sharePoint.Range("A2:" & spRange.End(xlDown).Address)
For Each cell In spRange
If Format(cell.Value, "MM") = MonthNumber Then
copyRowTo sharePoint.Range(cell.Row & ":" & cell.Row), Month
End If
Next cell
End Sub
Sub copyRowTo(rng As Range, ws As Worksheet)
Dim newRange As Range
Set newRange = ws.Range("A1")
If newRange.Offset(1).Value <> "" Then
Set newRange = newRange.End(xlDown).Offset(1)
Else
Set newRange = newRange.Offset(1)
End If
rng.Copy
newRange.PasteSpecial (xlPasteAll)
End Sub
``` |
84,341 | <p>I have a core file generated on a remote system that I don't have direct access to. I also have local copies of the library files from the remote system, and the executable file for the crashing program.</p>
<p>I'd like to analyse this core dump in gdb.</p>
<p>For example:</p>
<pre><code>gdb path/to/executable path/to/corefile
</code></pre>
<p>My libraries are in the current directory.</p>
<p>In the past I've seen debuggers implement this by supplying the option "-p ." or "-p /=."; so my question is:</p>
<p>How can I specify that libraries be loaded first from paths relative to my current directory when analysing a corefile in gdb?</p>
| [
{
"answer_id": 84546,
"author": "Drew Frezell",
"author_id": 10954,
"author_profile": "https://Stackoverflow.com/users/10954",
"pm_score": 7,
"selected": true,
"text": "<p>Start gdb without specifying the executable or core file, then type the following commands:</p>\n\n<pre><code>set so... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13956/"
] | I have a core file generated on a remote system that I don't have direct access to. I also have local copies of the library files from the remote system, and the executable file for the crashing program.
I'd like to analyse this core dump in gdb.
For example:
```
gdb path/to/executable path/to/corefile
```
My libraries are in the current directory.
In the past I've seen debuggers implement this by supplying the option "-p ." or "-p /=."; so my question is:
How can I specify that libraries be loaded first from paths relative to my current directory when analysing a corefile in gdb? | Start gdb without specifying the executable or core file, then type the following commands:
```
set solib-absolute-prefix ./usr
file path/to/executable
core-file path/to/corefile
```
You will need to make sure to mirror your library path exactly from the target system. The above is meant for debugging targets that don't match your host, that is why it's important to replicate your root filesystem structure containing your libraries.
If you are remote debugging a server that is the same architecture and Linux/glibc version as your host, then you can do as [fd](https://stackoverflow.com/users/13956/fd) suggested:
```
set solib-search-path <path>
```
If you are trying to override some of the libraries, but not all then you can copy the target library directory structure into a temporary place and use the `solib-absolute-prefix` solution described above. |
84,421 | <p>Is there a built in way to convert an integer in Ruby into its hexadecimal equivalent?</p>
<p>Something like the opposite of <a href="http://ruby-doc.org/core-2.0.0/String.html#method-i-to_i" rel="noreferrer"><code>String#to_i</code></a>:</p>
<pre><code>"0A".to_i(16) #=>10
</code></pre>
<p>Like perhaps:</p>
<pre><code>"0A".hex #=>10
</code></pre>
<p>I know how to roll my own, but it's probably more efficient to use a built in Ruby function.</p>
| [
{
"answer_id": 84455,
"author": "flxkid",
"author_id": 13036,
"author_profile": "https://Stackoverflow.com/users/13036",
"pm_score": 6,
"selected": false,
"text": "<p>How about using <a href=\"http://ruby-doc.org/core-2.0.0/String.html#method-i-25\" rel=\"noreferrer\"><code>%</code></a>/... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6106/"
] | Is there a built in way to convert an integer in Ruby into its hexadecimal equivalent?
Something like the opposite of [`String#to_i`](http://ruby-doc.org/core-2.0.0/String.html#method-i-to_i):
```
"0A".to_i(16) #=>10
```
Like perhaps:
```
"0A".hex #=>10
```
I know how to roll my own, but it's probably more efficient to use a built in Ruby function. | You can give [`to_s`](http://www.ruby-doc.org/core/classes/Integer.html#method-i-to_s) a base other than 10:
```
10.to_s(16) #=> "a"
```
Note that in ruby 2.4 `FixNum` and `BigNum` were unified in the `Integer` class.
If you are using an older ruby check the documentation of [FixNum#`to_s`](https://ruby-doc.org/core-2.3.8/Fixnum.html#method-i-to_s) and [BigNum#`to_s`](https://ruby-doc.org/core-2.3.8/Bignum.html#method-i-to_s) |
84,427 | <p>Specifically, is the following legal C++?</p>
<pre>class A{};
void foo(A*);
void bar(const A&);
int main(void)
{
foo(&A()); // 1
bar(A()); // 2
}</pre>
<p>It appears to work correctly, but that doesn't mean it's necessarily legal. Is it?</p>
<p><i>Edit - changed <code>A&</code> to <code>const A&</code></i></p>
| [
{
"answer_id": 84457,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": -1,
"selected": false,
"text": "<p>Perfectly legal.</p>\n\n<p>The object will exist on the stack during the function call, just like any other lo... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9530/"
] | Specifically, is the following legal C++?
```
class A{};
void foo(A*);
void bar(const A&);
int main(void)
{
foo(&A()); // 1
bar(A()); // 2
}
```
It appears to work correctly, but that doesn't mean it's necessarily legal. Is it?
*Edit - changed `A&` to `const A&`* | 1: Taking the address of a temporary is not allowed. Visual C++ allows it as a language extension (language extensions are on by default).
2: This is perfectly legal. |
84,449 | <p>The XML Schema Part 2 specifies that an instance of a datatype that is defined as boolean can have the following legal literals {true, false, 1, 0}.
The following XML, for example, when deserialized, sets the boolean property "Emulate" to <code>true</code>.</p>
<pre><code><root>
<emulate>1</emulate>
</root>
</code></pre>
<p>However, when I serialize the object back to the XML, I get <code>true</code> instead of the numerical value. My question is, is there a way that I can control the boolean representation in the XML?</p>
| [
{
"answer_id": 84514,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 1,
"selected": false,
"text": "<p>No, not using the default System.Xml.XmlSerializer: you'd need to change the data type to an int to achieve that, or muck arou... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8205/"
] | The XML Schema Part 2 specifies that an instance of a datatype that is defined as boolean can have the following legal literals {true, false, 1, 0}.
The following XML, for example, when deserialized, sets the boolean property "Emulate" to `true`.
```
<root>
<emulate>1</emulate>
</root>
```
However, when I serialize the object back to the XML, I get `true` instead of the numerical value. My question is, is there a way that I can control the boolean representation in the XML? | You can implement IXmlSerializable which will allow you to alter the serialized output of your class however you want. This will entail creating the 3 methods GetSchema(), ReadXml(XmlReader r) and WriteXml(XmlWriter r). When you implement the interface, these methods are called instead of .NET trying to serialize the object itself.
Examples can be found at:
<http://www.developerfusion.co.uk/show/4639/> and
<http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx> |
84,460 | <p>I've been using Destop.open() to launch a .pdf viewer on Windows machines, both Vista and XP, and most of them work just fine. However, on one XP machine the call does not work, simply returning without throwing any exceptions, and the viewer does not launch. On that machine the file association is properly set up as far as I can tell: double-clicking a .pdf works, as does the "start xxx.pdf" command on the command prompt. I'm thinking it must be a Windows configuration issue, but can't put my finger on it.</p>
<p>Has anyone else seen this problem?</p>
| [
{
"answer_id": 84529,
"author": "Martin Spamer",
"author_id": 15527,
"author_profile": "https://Stackoverflow.com/users/15527",
"pm_score": 2,
"selected": false,
"text": "<p>This is a known problem with early versions of XP SP2, the ShellExecute function stopped accepting URIs; bring the... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16213/"
] | I've been using Destop.open() to launch a .pdf viewer on Windows machines, both Vista and XP, and most of them work just fine. However, on one XP machine the call does not work, simply returning without throwing any exceptions, and the viewer does not launch. On that machine the file association is properly set up as far as I can tell: double-clicking a .pdf works, as does the "start xxx.pdf" command on the command prompt. I'm thinking it must be a Windows configuration issue, but can't put my finger on it.
Has anyone else seen this problem? | This is a known problem with early versions of XP SP2, the ShellExecute function stopped accepting URIs; bring the XP machines patches up to date.
To view the exceptions make sure the Java Console is turned on:
```
Control Panel->Java Control Panel->Advanced->Java Console.
``` |
84,463 | <p>For example I want to be able to programatically hit a line of code like the following where the function name is dynamically assigned without using Evaluate(). The code below of course doesn't work but represents what I would like to do.</p>
<pre><code>application.obj[funcName](argumentCollection=params)
</code></pre>
<p>The only way I can find to call a function dynamically is by using cfinvoke, but as far as I can tell that instantiates the related cfc/function on the fly and can't use a previously instantiated cfc.</p>
<p>Thanks</p>
| [
{
"answer_id": 84836,
"author": "Ben Doom",
"author_id": 12267,
"author_profile": "https://Stackoverflow.com/users/12267",
"pm_score": 4,
"selected": true,
"text": "<p>According to the docs, you can do something like this:</p>\n\n<pre><code><!--- Create the component instance. --->... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8345/"
] | For example I want to be able to programatically hit a line of code like the following where the function name is dynamically assigned without using Evaluate(). The code below of course doesn't work but represents what I would like to do.
```
application.obj[funcName](argumentCollection=params)
```
The only way I can find to call a function dynamically is by using cfinvoke, but as far as I can tell that instantiates the related cfc/function on the fly and can't use a previously instantiated cfc.
Thanks | According to the docs, you can do something like this:
```
<!--- Create the component instance. --->
<cfobject component="tellTime2" name="tellTimeObj">
<!--- Invoke the methods. --->
<cfinvoke component="#tellTimeObj#" method="getLocalTime" returnvariable="localTime">
<cfinvoke component="#tellTimeObj#" method="getUTCTime" returnvariable="UTCTime">
```
You should be able to simply call it with method="#myMethod#" to dynamically call a particular function. |
84,486 | <p>I've spent far too much time trying to figure this out. This should be the simplest thing and everyone who distributes Java applications in jars must have to deal with it.</p>
<p>I just want to know the proper way to add versioning to my Java app so that I can access the version information when I'm testing, e.g. debugging in Eclipse <strong>and</strong> running from a jar.</p>
<p>Here's what I have in my build.xml:</p>
<pre><code><target name="jar" depends = "compile">
<property name="version.num" value="1.0.0"/>
<buildnumber file="build.num"/>
<tstamp>
<format property="TODAY" pattern="yyyy-MM-dd HH:mm:ss" />
</tstamp>
<manifest file="${build}/META-INF/MANIFEST.MF">
<attribute name="Built-By" value="${user.name}" />
<attribute name="Built-Date" value="${TODAY}" />
<attribute name="Implementation-Title" value="MyApp" />
<attribute name="Implementation-Vendor" value="MyCompany" />
<attribute name="Implementation-Version" value="${version.num}-b${build.number}"/>
</manifest>
<jar destfile="${build}/myapp.jar" basedir="${build}" excludes="*.jar" />
</target>
</code></pre>
<p>This creates /META-INF/MANIFEST.MF and I can read the values when I'm debugging in Eclipse thusly:</p>
<pre><code>public MyClass()
{
try
{
InputStream stream = getClass().getResourceAsStream("/META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(stream);
Attributes attributes = manifest.getMainAttributes();
String implementationTitle = attributes.getValue("Implementation-Title");
String implementationVersion = attributes.getValue("Implementation-Version");
String builtDate = attributes.getValue("Built-Date");
String builtBy = attributes.getValue("Built-By");
}
catch (IOException e)
{
logger.error("Couldn't read manifest.");
}
</code></pre>
<p>}</p>
<p>But, when I create the jar file, it loads the manifest of another jar (presumably the first jar loaded by the application - in my case, activation.jar).</p>
<p>Also, the following code doesn't work either although all the proper values are in the manifest file.</p>
<pre><code> Package thisPackage = getClass().getPackage();
String implementationVersion = thisPackage.getImplementationVersion();
</code></pre>
<p>Any ideas?</p>
| [
{
"answer_id": 84606,
"author": "Juan Pablo Morales",
"author_id": 16238,
"author_profile": "https://Stackoverflow.com/users/16238",
"pm_score": 0,
"selected": false,
"text": "<p>Just don't use the manifest. Create a foo.properties.original file, with a content such as\nversion=@VERSION@... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16216/"
] | I've spent far too much time trying to figure this out. This should be the simplest thing and everyone who distributes Java applications in jars must have to deal with it.
I just want to know the proper way to add versioning to my Java app so that I can access the version information when I'm testing, e.g. debugging in Eclipse **and** running from a jar.
Here's what I have in my build.xml:
```
<target name="jar" depends = "compile">
<property name="version.num" value="1.0.0"/>
<buildnumber file="build.num"/>
<tstamp>
<format property="TODAY" pattern="yyyy-MM-dd HH:mm:ss" />
</tstamp>
<manifest file="${build}/META-INF/MANIFEST.MF">
<attribute name="Built-By" value="${user.name}" />
<attribute name="Built-Date" value="${TODAY}" />
<attribute name="Implementation-Title" value="MyApp" />
<attribute name="Implementation-Vendor" value="MyCompany" />
<attribute name="Implementation-Version" value="${version.num}-b${build.number}"/>
</manifest>
<jar destfile="${build}/myapp.jar" basedir="${build}" excludes="*.jar" />
</target>
```
This creates /META-INF/MANIFEST.MF and I can read the values when I'm debugging in Eclipse thusly:
```
public MyClass()
{
try
{
InputStream stream = getClass().getResourceAsStream("/META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(stream);
Attributes attributes = manifest.getMainAttributes();
String implementationTitle = attributes.getValue("Implementation-Title");
String implementationVersion = attributes.getValue("Implementation-Version");
String builtDate = attributes.getValue("Built-Date");
String builtBy = attributes.getValue("Built-By");
}
catch (IOException e)
{
logger.error("Couldn't read manifest.");
}
```
}
But, when I create the jar file, it loads the manifest of another jar (presumably the first jar loaded by the application - in my case, activation.jar).
Also, the following code doesn't work either although all the proper values are in the manifest file.
```
Package thisPackage = getClass().getPackage();
String implementationVersion = thisPackage.getImplementationVersion();
```
Any ideas? | You can get the manifest for an arbitrary class in an arbitrary jar without parsing the class url (which could be brittle). Just locate a resource that you know is in the jar you want, and then cast the connection to JarURLConnection.
If you want the code to work when the class is not bundled in a jar, add an instanceof check on the type of URL connection returned. Classes in an unpacked class hierarchy will return a internal Sun FileURLConnection instead of the JarUrlConnection. Then you can load the Manifest using one of the InputStream methods described in other answers.
```
@Test
public void testManifest() throws IOException {
URL res = org.junit.Assert.class.getResource(org.junit.Assert.class.getSimpleName() + ".class");
JarURLConnection conn = (JarURLConnection) res.openConnection();
Manifest mf = conn.getManifest();
Attributes atts = mf.getMainAttributes();
for (Object v : atts.values()) {
System.out.println(v);
}
}
``` |
84,506 | <p>I find from reading perldoc perlvar, about a thousand lines in is help for %ENV. Is there a way to find that from the command line directly?</p>
<p>On my Windows machine, I've tried the following</p>
<pre><code>perldoc ENV
perldoc %ENV
perldoc %%ENV
perldoc -r ENV (returns info about Use Env)
perldoc -r %ENV
perldoc -r %%%ENV
perldoc -r %%%%ENV (says No documentation found for "%ENV")
</code></pre>
<p>None actually return information about the %ENV variable.</p>
<p>How do I use perldoc to find out about %ENV, if I don't want to have to eye-grep through thousands of line?</p>
<p>I've tried the suggested "perldoc perlvar" and then typing /%ENV, but nothing happens. </p>
<pre><code>perl -v: This is perl, v5.8.0 built for MSWin32-x86-multi-thread
</code></pre>
<p>Though I've asked about %ENV, this also applies to any general term, so knowing that %ENV is in perlvar for this one example won't help me next time when I don't know which section.</p>
<p>Is there a way to get perldoc to dump everything (ugh) and I can grep the output?</p>
| [
{
"answer_id": 84741,
"author": "amoore",
"author_id": 7573,
"author_profile": "https://Stackoverflow.com/users/7573",
"pm_score": -1,
"selected": false,
"text": "<p>If you'd like to see the contents of your %ENV, you can use Data::Dumper to print it out in a rather readable format:</p>\... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8763/"
] | I find from reading perldoc perlvar, about a thousand lines in is help for %ENV. Is there a way to find that from the command line directly?
On my Windows machine, I've tried the following
```
perldoc ENV
perldoc %ENV
perldoc %%ENV
perldoc -r ENV (returns info about Use Env)
perldoc -r %ENV
perldoc -r %%%ENV
perldoc -r %%%%ENV (says No documentation found for "%ENV")
```
None actually return information about the %ENV variable.
How do I use perldoc to find out about %ENV, if I don't want to have to eye-grep through thousands of line?
I've tried the suggested "perldoc perlvar" and then typing /%ENV, but nothing happens.
```
perl -v: This is perl, v5.8.0 built for MSWin32-x86-multi-thread
```
Though I've asked about %ENV, this also applies to any general term, so knowing that %ENV is in perlvar for this one example won't help me next time when I don't know which section.
Is there a way to get perldoc to dump everything (ugh) and I can grep the output? | perldoc doesn't have an option to search for a particular entry in perlvar (like -f does for perlfunc). General searching is dependent on your pager (specified in the PAGER environment variable). Personally, I like "less." You can get [less for windows](http://gnuwin32.sourceforge.net/packages/less.htm) from the [GnuWin32](http://gnuwin32.sourceforge.net/) project. |
84,615 | <p>If one wants to paginate results from a data source that supports pagination we have to go to a process of:</p>
<ol>
<li>defining the page size - that is the number of results to show per page;</li>
<li>fetch each page requested by the user using an offset = page number (0 based) * page size</li>
<li>show the results of the fetched page.</li>
</ol>
<p>All this is works just fine not considering the fact that an operation may affect the backend system that screws up the pagination taking place. I am talking about someone inserting data between page fetches or deleting data.</p>
<pre><code>page_size = 10;
get page 0 -> results from 0 to 9;
user inserts a record that due to the query being executed goes to page 0 - the one just shown;
get page 1 -> results from 10 to 19 - the first results on the page is the result on the old page 0.
</code></pre>
<p>The described behavior can cause confusion to the viewer. Do you know any practical solution to workaround this problem.</p>
| [
{
"answer_id": 84665,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 3,
"selected": true,
"text": "<p>There are a few schools of thought o this.</p>\n\n<ol>\n<li>data gets updated let it be</li>\n<li>You could imple... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6508/"
] | If one wants to paginate results from a data source that supports pagination we have to go to a process of:
1. defining the page size - that is the number of results to show per page;
2. fetch each page requested by the user using an offset = page number (0 based) \* page size
3. show the results of the fetched page.
All this is works just fine not considering the fact that an operation may affect the backend system that screws up the pagination taking place. I am talking about someone inserting data between page fetches or deleting data.
```
page_size = 10;
get page 0 -> results from 0 to 9;
user inserts a record that due to the query being executed goes to page 0 - the one just shown;
get page 1 -> results from 10 to 19 - the first results on the page is the result on the old page 0.
```
The described behavior can cause confusion to the viewer. Do you know any practical solution to workaround this problem. | There are a few schools of thought o this.
1. data gets updated let it be
2. You could implement some sort of caching method that will hold the
entire result set (This might not be
an option if working with really
large Datasets)
3. You could do a comparison on each page operation and notify the
user if the total record count
changes
. |
84,641 | <p>I have the following code:</p>
<pre><code>$bind = new COM("LDAP://CN=GroupName,OU=Groups,OU=Division,DC=company,DC=local");
</code></pre>
<p>When I execute it from a command-prompt, it runs fine. When it runs under IIS/PHP/ISAPI, it barfs.</p>
<pre><code>Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `LDAP://CN=...[cut]...,DC=local':
An operations error occurred. ' in index.php
Stack trace:
#0 index.php: com->com('LDAP://CN=...')
#1 {main} thrown
</code></pre>
<p>IIS is configured for Windows Authentication (no anonymous, no basic, no digest) and I am connecting as the same user as the command prompt. I cannot find any specific errors in the IIS logfiles or the eventlog.</p>
<p>The main purpose of this exercise is to refrain from keeping user credentials in my script and relying on IIS authentication to pass them through to the active directory. I understand that you can use LDAP to accomplish the same thing, but as far as I know credentials cannot be passed through.</p>
<p>Perhaps it is in some way related to the error I get when I try to port it to ASP. I get error 80072020 (which I'm currently looking up).</p>
<p>The event logs show nothing out of the ordinary. No warnings, no errors. Full security auditing is enabled (success and failure on every item in the security policy), and it shows successful Windows logons for every user I authenticate against the web page (which is expected.)</p>
| [
{
"answer_id": 84808,
"author": "CodeRot",
"author_id": 14134,
"author_profile": "https://Stackoverflow.com/users/14134",
"pm_score": 3,
"selected": true,
"text": "<p>Since you're using Windows Authentication in IIS, you may have some security events in the Windows Event log. I would che... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2581/"
] | I have the following code:
```
$bind = new COM("LDAP://CN=GroupName,OU=Groups,OU=Division,DC=company,DC=local");
```
When I execute it from a command-prompt, it runs fine. When it runs under IIS/PHP/ISAPI, it barfs.
```
Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `LDAP://CN=...[cut]...,DC=local':
An operations error occurred. ' in index.php
Stack trace:
#0 index.php: com->com('LDAP://CN=...')
#1 {main} thrown
```
IIS is configured for Windows Authentication (no anonymous, no basic, no digest) and I am connecting as the same user as the command prompt. I cannot find any specific errors in the IIS logfiles or the eventlog.
The main purpose of this exercise is to refrain from keeping user credentials in my script and relying on IIS authentication to pass them through to the active directory. I understand that you can use LDAP to accomplish the same thing, but as far as I know credentials cannot be passed through.
Perhaps it is in some way related to the error I get when I try to port it to ASP. I get error 80072020 (which I'm currently looking up).
The event logs show nothing out of the ordinary. No warnings, no errors. Full security auditing is enabled (success and failure on every item in the security policy), and it shows successful Windows logons for every user I authenticate against the web page (which is expected.) | Since you're using Windows Authentication in IIS, you may have some security events in the Windows Event log. I would check the Event log for Security Events as well as Application Events and see if you're hitting any sort of permissions issues.
Also, since you're basically just communicating to AD via LDAP...you might look into using the a native LDAP library for PHP rather than a COM.
You'll have to enable the extension probably in your php.ini. Worth looking at probably. |
84,644 | <p>To make it short: hibernate doesn't support projections and query by example? I found this post:</p>
<p>The code is this:</p>
<pre><code>User usr = new User();
usr.setCity = 'TEST';
getCurrentSession().createCriteria(User.class)
.setProjection( Projections.distinct( Projections.projectionList()
.add( Projections.property("name"), "name")
.add( Projections.property("city"), "city")))
.add( Example.create(usr))
</code></pre>
<p>Like the other poster said, The generated sql keeps having a where class refering to just <strong>y0_= ? instead of this_.city</strong>. </p>
<p>I already tried several approaches, and searched the issue tracker but found nothing about this.</p>
<p>I even tried to use Projection alias and Transformers, but it does not work:</p>
<pre><code>User usr = new User();
usr.setCity = 'TEST';
getCurrentSession().createCriteria(User.class)
.setProjection( Projections.distinct( Projections.projectionList()
.add( Projections.property("name"), "name")
.add( Projections.property("city"), "city")))
.add( Example.create(usr)).setResultTransformer(Transformers.aliasToBean(User.class));
</code></pre>
<p>Has anyone used projections and query by example ?</p>
| [
{
"answer_id": 86752,
"author": "Arthur Thomas",
"author_id": 14009,
"author_profile": "https://Stackoverflow.com/users/14009",
"pm_score": 5,
"selected": true,
"text": "<p>Can I see your User class? This is just using restrictions below. I don't see why Restrictions would be really an... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | To make it short: hibernate doesn't support projections and query by example? I found this post:
The code is this:
```
User usr = new User();
usr.setCity = 'TEST';
getCurrentSession().createCriteria(User.class)
.setProjection( Projections.distinct( Projections.projectionList()
.add( Projections.property("name"), "name")
.add( Projections.property("city"), "city")))
.add( Example.create(usr))
```
Like the other poster said, The generated sql keeps having a where class refering to just **y0\_= ? instead of this\_.city**.
I already tried several approaches, and searched the issue tracker but found nothing about this.
I even tried to use Projection alias and Transformers, but it does not work:
```
User usr = new User();
usr.setCity = 'TEST';
getCurrentSession().createCriteria(User.class)
.setProjection( Projections.distinct( Projections.projectionList()
.add( Projections.property("name"), "name")
.add( Projections.property("city"), "city")))
.add( Example.create(usr)).setResultTransformer(Transformers.aliasToBean(User.class));
```
Has anyone used projections and query by example ? | Can I see your User class? This is just using restrictions below. I don't see why Restrictions would be really any different than Examples (I think null fields get ignored by default in examples though).
```
getCurrentSession().createCriteria(User.class)
.setProjection( Projections.distinct( Projections.projectionList()
.add( Projections.property("name"), "name")
.add( Projections.property("city"), "city")))
.add( Restrictions.eq("city", "TEST")))
.setResultTransformer(Transformers.aliasToBean(User.class))
.list();
```
I've never used the alaistToBean, but I just read about it. You could also just loop over the results..
```
List<Object> rows = criteria.list();
for(Object r: rows){
Object[] row = (Object[]) r;
Type t = ((<Type>) row[0]);
}
```
If you have to you can manually populate User yourself that way.
Its sort of hard to look into the issue without some more information to diagnose the issue. |
84,661 | <p>Sometimes, in PL SQL you want to add a parameter to a Package, Function or Procedure in order to prepare future functionality. For example:</p>
<pre><code>create or replace function doGetMyAccountMoney( Type_Of_Currency IN char := 'EUR') return number
is
Result number(12,2);
begin
Result := 10000;
IF char <> 'EUR' THEN
-- ERROR NOT IMPLEMENTED YET
END IF;
return(Result);
end doGetMyAccountMoney;also
</code></pre>
<p>It can lead to lots of warnings like</p>
<pre><code>Compilation errors for FUNCTION APPUEMP_PRAC.DOGETMYACCOUNTMONEY
Error: Hint: Parameter 'Currency' is declared but never used in 'doGetMyAccountMoney'
Line: 1
</code></pre>
<p>What would be the best way to avoid those warnings? </p>
| [
{
"answer_id": 84695,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>Well, are you sure you have the name and the right in the correct order in that declaration?</p>\n\n<p>It complains... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16206/"
] | Sometimes, in PL SQL you want to add a parameter to a Package, Function or Procedure in order to prepare future functionality. For example:
```
create or replace function doGetMyAccountMoney( Type_Of_Currency IN char := 'EUR') return number
is
Result number(12,2);
begin
Result := 10000;
IF char <> 'EUR' THEN
-- ERROR NOT IMPLEMENTED YET
END IF;
return(Result);
end doGetMyAccountMoney;also
```
It can lead to lots of warnings like
```
Compilation errors for FUNCTION APPUEMP_PRAC.DOGETMYACCOUNTMONEY
Error: Hint: Parameter 'Currency' is declared but never used in 'doGetMyAccountMoney'
Line: 1
```
What would be the best way to avoid those warnings? | I believe that this is controlled by the parameter PLSQL\_WARNINGS, documented for 10gR2 here: <http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/initparams166.htm#REFRN10249> |
84,680 | <p>I'm writing a Spring web application that requires users to login. My company has an Active Directory server that I'd like to make use of for this purpose. However, I'm having trouble using Spring Security to connect to the server.</p>
<p>I'm using Spring 2.5.5 and Spring Security 2.0.3, along with Java 1.6.</p>
<p>If I change the LDAP URL to the wrong IP address, it doesn't throw an exception or anything, so I'm wondering if it's even <em>trying</em> to connect to the server to begin with.</p>
<p>Although the web application starts up just fine, any information I enter into the login page is rejected. I had previously used an InMemoryDaoImpl, which worked fine, so the rest of my application seems to be configured correctly.</p>
<p>Here are my security-related beans:</p>
<pre><code> <beans:bean id="ldapAuthProvider" class="org.springframework.security.providers.ldap.LdapAuthenticationProvider">
<beans:constructor-arg>
<beans:bean class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator">
<beans:constructor-arg ref="initialDirContextFactory" />
<beans:property name="userDnPatterns">
<beans:list>
<beans:value>CN={0},OU=SBSUsers,OU=Users,OU=MyBusiness,DC=Acme,DC=com</beans:value>
</beans:list>
</beans:property>
</beans:bean>
</beans:constructor-arg>
</beans:bean>
<beans:bean id="userDetailsService" class="org.springframework.security.userdetails.ldap.LdapUserDetailsManager">
<beans:constructor-arg ref="initialDirContextFactory" />
</beans:bean>
<beans:bean id="initialDirContextFactory" class="org.springframework.security.ldap.DefaultInitialDirContextFactory">
<beans:constructor-arg value="ldap://192.168.123.456:389/DC=Acme,DC=com" />
</beans:bean>
</code></pre>
| [
{
"answer_id": 86367,
"author": "delfuego",
"author_id": 16414,
"author_profile": "https://Stackoverflow.com/users/16414",
"pm_score": 6,
"selected": true,
"text": "<p>I had the same banging-my-head-against-the-wall experience you did, and ended up writing a custom authentication provide... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13379/"
] | I'm writing a Spring web application that requires users to login. My company has an Active Directory server that I'd like to make use of for this purpose. However, I'm having trouble using Spring Security to connect to the server.
I'm using Spring 2.5.5 and Spring Security 2.0.3, along with Java 1.6.
If I change the LDAP URL to the wrong IP address, it doesn't throw an exception or anything, so I'm wondering if it's even *trying* to connect to the server to begin with.
Although the web application starts up just fine, any information I enter into the login page is rejected. I had previously used an InMemoryDaoImpl, which worked fine, so the rest of my application seems to be configured correctly.
Here are my security-related beans:
```
<beans:bean id="ldapAuthProvider" class="org.springframework.security.providers.ldap.LdapAuthenticationProvider">
<beans:constructor-arg>
<beans:bean class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator">
<beans:constructor-arg ref="initialDirContextFactory" />
<beans:property name="userDnPatterns">
<beans:list>
<beans:value>CN={0},OU=SBSUsers,OU=Users,OU=MyBusiness,DC=Acme,DC=com</beans:value>
</beans:list>
</beans:property>
</beans:bean>
</beans:constructor-arg>
</beans:bean>
<beans:bean id="userDetailsService" class="org.springframework.security.userdetails.ldap.LdapUserDetailsManager">
<beans:constructor-arg ref="initialDirContextFactory" />
</beans:bean>
<beans:bean id="initialDirContextFactory" class="org.springframework.security.ldap.DefaultInitialDirContextFactory">
<beans:constructor-arg value="ldap://192.168.123.456:389/DC=Acme,DC=com" />
</beans:bean>
``` | I had the same banging-my-head-against-the-wall experience you did, and ended up writing a custom authentication provider that does an LDAP query against the Active Directory server.
So my security-related beans are:
```
<beans:bean id="contextSource"
class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<beans:constructor-arg value="ldap://hostname.queso.com:389/" />
</beans:bean>
<beans:bean id="ldapAuthenticationProvider"
class="org.queso.ad.service.authentication.LdapAuthenticationProvider">
<beans:property name="authenticator" ref="ldapAuthenticator" />
<custom-authentication-provider />
</beans:bean>
<beans:bean id="ldapAuthenticator"
class="org.queso.ad.service.authentication.LdapAuthenticatorImpl">
<beans:property name="contextFactory" ref="contextSource" />
<beans:property name="principalPrefix" value="QUESO\" />
</beans:bean>
```
Then the LdapAuthenticationProvider class:
```
/**
* Custom Spring Security authentication provider which tries to bind to an LDAP server with
* the passed-in credentials; of note, when used with the custom {@link LdapAuthenticatorImpl},
* does <strong>not</strong> require an LDAP username and password for initial binding.
*
* @author Jason
*/
public class LdapAuthenticationProvider implements AuthenticationProvider {
private LdapAuthenticator authenticator;
public Authentication authenticate(Authentication auth) throws AuthenticationException {
// Authenticate, using the passed-in credentials.
DirContextOperations authAdapter = authenticator.authenticate(auth);
// Creating an LdapAuthenticationToken (rather than using the existing Authentication
// object) allows us to add the already-created LDAP context for our app to use later.
LdapAuthenticationToken ldapAuth = new LdapAuthenticationToken(auth, "ROLE_USER");
InitialLdapContext ldapContext = (InitialLdapContext) authAdapter
.getObjectAttribute("ldapContext");
if (ldapContext != null) {
ldapAuth.setContext(ldapContext);
}
return ldapAuth;
}
public boolean supports(Class clazz) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(clazz));
}
public LdapAuthenticator getAuthenticator() {
return authenticator;
}
public void setAuthenticator(LdapAuthenticator authenticator) {
this.authenticator = authenticator;
}
}
```
Then the LdapAuthenticatorImpl class:
```
/**
* Custom Spring Security LDAP authenticator which tries to bind to an LDAP server using the
* passed-in credentials; does <strong>not</strong> require "master" credentials for an
* initial bind prior to searching for the passed-in username.
*
* @author Jason
*/
public class LdapAuthenticatorImpl implements LdapAuthenticator {
private DefaultSpringSecurityContextSource contextFactory;
private String principalPrefix = "";
public DirContextOperations authenticate(Authentication authentication) {
// Grab the username and password out of the authentication object.
String principal = principalPrefix + authentication.getName();
String password = "";
if (authentication.getCredentials() != null) {
password = authentication.getCredentials().toString();
}
// If we have a valid username and password, try to authenticate.
if (!("".equals(principal.trim())) && !("".equals(password.trim()))) {
InitialLdapContext ldapContext = (InitialLdapContext) contextFactory
.getReadWriteContext(principal, password);
// We need to pass the context back out, so that the auth provider can add it to the
// Authentication object.
DirContextOperations authAdapter = new DirContextAdapter();
authAdapter.addAttributeValue("ldapContext", ldapContext);
return authAdapter;
} else {
throw new BadCredentialsException("Blank username and/or password!");
}
}
/**
* Since the InitialLdapContext that's stored as a property of an LdapAuthenticationToken is
* transient (because it isn't Serializable), we need some way to recreate the
* InitialLdapContext if it's null (e.g., if the LdapAuthenticationToken has been serialized
* and deserialized). This is that mechanism.
*
* @param authenticator
* the LdapAuthenticator instance from your application's context
* @param auth
* the LdapAuthenticationToken in which to recreate the InitialLdapContext
* @return
*/
static public InitialLdapContext recreateLdapContext(LdapAuthenticator authenticator,
LdapAuthenticationToken auth) {
DirContextOperations authAdapter = authenticator.authenticate(auth);
InitialLdapContext context = (InitialLdapContext) authAdapter
.getObjectAttribute("ldapContext");
auth.setContext(context);
return context;
}
public DefaultSpringSecurityContextSource getContextFactory() {
return contextFactory;
}
/**
* Set the context factory to use for generating a new LDAP context.
*
* @param contextFactory
*/
public void setContextFactory(DefaultSpringSecurityContextSource contextFactory) {
this.contextFactory = contextFactory;
}
public String getPrincipalPrefix() {
return principalPrefix;
}
/**
* Set the string to be prepended to all principal names prior to attempting authentication
* against the LDAP server. (For example, if the Active Directory wants the domain-name-plus
* backslash prepended, use this.)
*
* @param principalPrefix
*/
public void setPrincipalPrefix(String principalPrefix) {
if (principalPrefix != null) {
this.principalPrefix = principalPrefix;
} else {
this.principalPrefix = "";
}
}
}
```
And finally, the LdapAuthenticationToken class:
```
/**
* <p>
* Authentication token to use when an app needs further access to the LDAP context used to
* authenticate the user.
* </p>
*
* <p>
* When this is the Authentication object stored in the Spring Security context, an application
* can retrieve the current LDAP context thusly:
* </p>
*
* <pre>
* LdapAuthenticationToken ldapAuth = (LdapAuthenticationToken) SecurityContextHolder
* .getContext().getAuthentication();
* InitialLdapContext ldapContext = ldapAuth.getContext();
* </pre>
*
* @author Jason
*
*/
public class LdapAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = -5040340622950665401L;
private Authentication auth;
transient private InitialLdapContext context;
private List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
/**
* Construct a new LdapAuthenticationToken, using an existing Authentication object and
* granting all users a default authority.
*
* @param auth
* @param defaultAuthority
*/
public LdapAuthenticationToken(Authentication auth, GrantedAuthority defaultAuthority) {
this.auth = auth;
if (auth.getAuthorities() != null) {
this.authorities.addAll(Arrays.asList(auth.getAuthorities()));
}
if (defaultAuthority != null) {
this.authorities.add(defaultAuthority);
}
super.setAuthenticated(true);
}
/**
* Construct a new LdapAuthenticationToken, using an existing Authentication object and
* granting all users a default authority.
*
* @param auth
* @param defaultAuthority
*/
public LdapAuthenticationToken(Authentication auth, String defaultAuthority) {
this(auth, new GrantedAuthorityImpl(defaultAuthority));
}
public GrantedAuthority[] getAuthorities() {
GrantedAuthority[] authoritiesArray = this.authorities.toArray(new GrantedAuthority[0]);
return authoritiesArray;
}
public void addAuthority(GrantedAuthority authority) {
this.authorities.add(authority);
}
public Object getCredentials() {
return auth.getCredentials();
}
public Object getPrincipal() {
return auth.getPrincipal();
}
/**
* Retrieve the LDAP context attached to this user's authentication object.
*
* @return the LDAP context
*/
public InitialLdapContext getContext() {
return context;
}
/**
* Attach an LDAP context to this user's authentication object.
*
* @param context
* the LDAP context
*/
public void setContext(InitialLdapContext context) {
this.context = context;
}
}
```
You'll notice that there are a few bits in there that you might not need.
For example, my app needed to retain the successfully-logged-in LDAP context for further use by the user once logged in -- the app's purpose is to let users log in via their AD credentials and then perform further AD-related functions. So because of that, I have a custom authentication token, LdapAuthenticationToken, that I pass around (rather than Spring's default Authentication token) which allows me to attach the LDAP context. In LdapAuthenticationProvider.authenticate(), I create that token and pass it back out; in LdapAuthenticatorImpl.authenticate(), I attach the logged-in context to the return object so that it can be added to the user's Spring authentication object.
Also, in LdapAuthenticationProvider.authenticate(), I assign all logged-in users the ROLE\_USER role -- that's what lets me then test for that role in my intercept-url elements. You'll want to make this match whatever role you want to test for, or even assign roles based on Active Directory groups or whatever.
Finally, and a corollary to that, the way I implemented LdapAuthenticationProvider.authenticate() gives all users with valid AD accounts the same ROLE\_USER role. Obviously, in that method, you can perform further tests on the user (i.e., is the user in a specific AD group?) and assign roles that way, or even test for some condition before even granting the user access at *all*. |
84,716 | <p>I use the jQuery <a href="http://docs.jquery.com/Utilities/jQuery.extend" rel="nofollow noreferrer">extend</a> function to extend a class prototype.</p>
<p>For example:</p>
<pre><code>MyWidget = function(name_var) {
this.init(name_var);
}
$.extend(MyWidget.prototype, {
// object variables
widget_name: '',
init: function(widget_name) {
// do initialization here
this.widget_name = widget_name;
},
doSomething: function() {
// an example object method
alert('my name is '+this.widget_name);
}
});
// example of using the class built above
var widget1 = new MyWidget('widget one');
widget1.doSomething();
</code></pre>
<p>Is there a better way to do this? Is there a cleaner way to create the class above with only one statement instead of two?</p>
| [
{
"answer_id": 84824,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 6,
"selected": false,
"text": "<p>I quite like John Resig's <a href=\"http://ejohn.org/blog/simple-javascript-inheritance/\" rel=\"noreferrer\">Simpl... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13850/"
] | I use the jQuery [extend](http://docs.jquery.com/Utilities/jQuery.extend) function to extend a class prototype.
For example:
```
MyWidget = function(name_var) {
this.init(name_var);
}
$.extend(MyWidget.prototype, {
// object variables
widget_name: '',
init: function(widget_name) {
// do initialization here
this.widget_name = widget_name;
},
doSomething: function() {
// an example object method
alert('my name is '+this.widget_name);
}
});
// example of using the class built above
var widget1 = new MyWidget('widget one');
widget1.doSomething();
```
Is there a better way to do this? Is there a cleaner way to create the class above with only one statement instead of two? | I quite like John Resig's [Simple JavaScript Inheritance](http://ejohn.org/blog/simple-javascript-inheritance/).
```
var MyWidget = Class.extend({
init: function(widget_name){
this.widget_name = widget_name;
},
doSomething: function() {
alert('my name is ' + this.widget_name);
}
});
```
NB: The "Class" object demonstrated above isn't included in jQuery itself - it's a 25 line snippet from Mr. jQuery himself, provided in the article above. |
84,717 | <p>What are the best conventions of naming testing-assemblies in .NET (or any other language or platform)?</p>
<p>What I'm mainly split between are these options (please provide others!):</p>
<ul>
<li><strong>Company.Website</strong> - <em>the project</em></li>
<li><strong>Company.Website.Tests</strong></li>
</ul>
<p><em>or</em></p>
<ul>
<li><strong>Company.Website</strong></li>
<li><strong>Company.WebsiteTests</strong></li>
</ul>
<p>The problem with the first solution is that it looks like .Tests are a sub-namespace to the site, while they really are more parallel in my mind. What happens when a new sub-namespace comes into play, like <strong>Company.Website.Controls</strong>, where should I put the tests for that namespace, for instance?</p>
<p>Maybe it should even be: <strong>Tests.Company.Website</strong> and <strong>Tests.Company.Website.Controls</strong>, and so on.</p>
| [
{
"answer_id": 84742,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 4,
"selected": false,
"text": "<p>I personally would go with</p>\n\n<p>Company.Tests.Website</p>\n\n<p>That way you have a common tests namespace ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2429/"
] | What are the best conventions of naming testing-assemblies in .NET (or any other language or platform)?
What I'm mainly split between are these options (please provide others!):
* **Company.Website** - *the project*
* **Company.Website.Tests**
*or*
* **Company.Website**
* **Company.WebsiteTests**
The problem with the first solution is that it looks like .Tests are a sub-namespace to the site, while they really are more parallel in my mind. What happens when a new sub-namespace comes into play, like **Company.Website.Controls**, where should I put the tests for that namespace, for instance?
Maybe it should even be: **Tests.Company.Website** and **Tests.Company.Website.Controls**, and so on. | I will go with
```
* Company.Website - the project
* Company.Website.Tests
```
The short reason and answer is simple, testing and project are linked in code, therefore it should share namespace.
If you want splitting of code and testing in a solution you have that option anyway. e.g. you can set up a solution with
-Code Folder
* Company.Website
-Tests Folder
* Company.Website.Tests |
84,759 | <p>This is an Eclipse question, and you can assume the Java package for all these Eclipse classes is <code>org.eclipse.core.resources</code>. </p>
<p>I want to get an <code>IFile</code> corresponding to a location <code>String</code> I have:</p>
<pre><code> "platform:/resource/Tracbility_All_Supported_lib/processes/gastuff/globalht/GlobalHTInterface.wsdl"
</code></pre>
<p>I have the enclosing <code>IWorkspace</code> and <code>IWorkspaceRoot</code>. If I had the <code>IPath</code> corresponding to the location above, I could simply call <code>IWorkspaceRoot.getFileForLocation(IPath)</code>.</p>
<p>How do I get the corresponding <code>IPath</code> from the location <code>String</code>? Or is there some other way to get the corresponding <code>IFile</code>?</p>
| [
{
"answer_id": 85074,
"author": "Paul Reiners",
"author_id": 7648,
"author_profile": "https://Stackoverflow.com/users/7648",
"pm_score": 2,
"selected": false,
"text": "<pre><code>String platformLocationString = portTypeContainer\n .getLocation();\nString locationString = platformL... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7648/"
] | This is an Eclipse question, and you can assume the Java package for all these Eclipse classes is `org.eclipse.core.resources`.
I want to get an `IFile` corresponding to a location `String` I have:
```
"platform:/resource/Tracbility_All_Supported_lib/processes/gastuff/globalht/GlobalHTInterface.wsdl"
```
I have the enclosing `IWorkspace` and `IWorkspaceRoot`. If I had the `IPath` corresponding to the location above, I could simply call `IWorkspaceRoot.getFileForLocation(IPath)`.
How do I get the corresponding `IPath` from the location `String`? Or is there some other way to get the corresponding `IFile`? | org.eclipse.core.runtime.Path implements IPath.
```
IPath p = new Path(locationString);
IWorkspaceRoot.getFileForLocation(p);
```
This would have worked had the location string not been a URL of type "platform:"
For this particular case, notes in org.eclipse.core.runtime.Platform javadoc indicate that the "correct" solution is something like
```
fileUrl = FileLocator.toFileURL(new URL(locationString));
IWorkspaceRoot.getFileForLocation(fileUrl.getPath());
```
@[Paul Reiners] your solution apparently assumes that the workspace root is going to be in the "resources" folder |
84,782 | <p>I am writting JAVA programme using JDBC for database conntectivity , I am calling one stored procedure in that which is returning ORACLE REF CURSOR , IS there any way I can handle that without importing ORACLE PACKAGES ?</p>
| [
{
"answer_id": 85766,
"author": "jwiklund",
"author_id": 4208,
"author_profile": "https://Stackoverflow.com/users/4208",
"pm_score": 2,
"selected": true,
"text": "<p>I think I tried to do this a while ago and kind of gave up (I guess you could figure out what int value the OracleTypes.RE... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14299/"
] | I am writting JAVA programme using JDBC for database conntectivity , I am calling one stored procedure in that which is returning ORACLE REF CURSOR , IS there any way I can handle that without importing ORACLE PACKAGES ? | I think I tried to do this a while ago and kind of gave up (I guess you could figure out what int value the OracleTypes.REF\_CURSOR is and then use that int value, but that's a hack). If you got the patience you could define a record (or object) type and define the the cursor as a cursor with type since that can be cast using table to a value that is selectable like regular tables, ie
```
select * from table( sp_returning( ? ) )
```
I did a quick google on ref cursor and jdbc and it looks like it might be an oracle extension which would explain why there is no standard way to access the data. |
84,795 | <p>How can I optimize the following code, which currently takes over 2 minutes to retrieve and loop through 800+ records from a pool of over 100K records, returning 6 fields per record (adds approximately 20 seconds per additional field):</p>
<pre><code><cfset dllPath="C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.DirectoryServices.dll" />
<cfset LDAPPath="LDAP://" & arguments.searchPath />
<cfset theLookUp=CreateObject(".NET","System.DirectoryServices.DirectoryEntry", dllPath).init(LDAPPath) />
<cfset theSearch=CreateObject(".NET","System.DirectoryServices.DirectorySearcher", dllPath).init(theLookUp) />
<cfset theSearch.Set_Filter(arguments.theFilter) />
<cfset theObject = theSearch.FindAll() />
<cfloop index="row" from="#startRow#" to="#endRow#">
<cfset QueryAddRow(theQuery) />
<cfloop list="#columnList#" index="col">
<cfloop from="0" to="#theObject.Get_Item(row).Get_Properties().Get_Item(col).Get_Count()-1#" index="item">
<cftry>
<cfset theQuery[col][theQuery.recordCount]=ListAppend(theQuery[col][theQuery.recordCount],theObject.Get_Item(row).Get_Properties().Get_Item(col).Get_Item(item),"|") />
<cfcatch type="any">
</cfcatch>
</cftry>
</cfloop>
</cfloop>
</cfloop>
</code></pre>
| [
{
"answer_id": 85077,
"author": "x0n",
"author_id": 6920,
"author_profile": "https://Stackoverflow.com/users/6920",
"pm_score": 2,
"selected": false,
"text": "<p>It's been a long time since I touched CF, but I can give some hints in pseudo-code. For one thing, this expression is extremel... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16289/"
] | How can I optimize the following code, which currently takes over 2 minutes to retrieve and loop through 800+ records from a pool of over 100K records, returning 6 fields per record (adds approximately 20 seconds per additional field):
```
<cfset dllPath="C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.DirectoryServices.dll" />
<cfset LDAPPath="LDAP://" & arguments.searchPath />
<cfset theLookUp=CreateObject(".NET","System.DirectoryServices.DirectoryEntry", dllPath).init(LDAPPath) />
<cfset theSearch=CreateObject(".NET","System.DirectoryServices.DirectorySearcher", dllPath).init(theLookUp) />
<cfset theSearch.Set_Filter(arguments.theFilter) />
<cfset theObject = theSearch.FindAll() />
<cfloop index="row" from="#startRow#" to="#endRow#">
<cfset QueryAddRow(theQuery) />
<cfloop list="#columnList#" index="col">
<cfloop from="0" to="#theObject.Get_Item(row).Get_Properties().Get_Item(col).Get_Count()-1#" index="item">
<cftry>
<cfset theQuery[col][theQuery.recordCount]=ListAppend(theQuery[col][theQuery.recordCount],theObject.Get_Item(row).Get_Properties().Get_Item(col).Get_Item(item),"|") />
<cfcatch type="any">
</cfcatch>
</cftry>
</cfloop>
</cfloop>
</cfloop>
``` | How large is the list of items for the inner loop?
Switching to an array *might* be faster if there is a significantly large number of items.
I have implemented this alongside x0n's suggestions...
```
<cfset dllPath="C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.DirectoryServices.dll" />
<cfset LDAPPath="LDAP://" & arguments.searchPath />
<cfset theLookUp=CreateObject(".NET","System.DirectoryServices.DirectoryEntry", dllPath).init(LDAPPath) />
<cfset theSearch=CreateObject(".NET","System.DirectoryServices.DirectorySearcher", dllPath).init(theLookUp) />
<cfset theSearch.Set_Filter(arguments.theFilter) />
<cfset theObject = theSearch.FindAll() />
<cfloop index="row" from="#startRow#" to="#endRow#">
<cfset Props = theObject.get_item(row).get_properties() />
<cfset QueryAddRow(theQuery) />
<cfloop list="#columnList#" index="col">
<cfset CurrentCol = Props.getItem(col) />
<cfset ItemArray = ArrayNew(1)/>
<cfloop from="0" to="#CurrentCol.getcount() - 1#" index="item">
<cftry>
<cfset ArrayAppend( ItemArray , CurrentCol.Get_Item(item) )/>
<cfcatch type="any">
</cfcatch>
</cftry>
</cfloop>
<cfset theQuery[col][theQuery.recordCount] = ArrayToList( ItemArray , '|' )/>
</cfloop>
</cfloop>
``` |
84,800 | <p>I am looking for an efficient way to pull the data I want out of an array called $submission_info so I can easily auto-fill my form fields. The array size is about 120.</p>
<p>I want to find the field name and extract the content. In this case, the field name is <strong>loanOfficer</strong> and the content is <strong>John Doe</strong>.</p>
<pre><code>Output of Print_r($submission_info[1]):
Array (
[field_id] => 2399
[form_id] => 4
[field_name] => loanOfficer
[field_test_value] => ABCDEFGHIJKLMNOPQRSTUVWXYZ
[field_size] => medium
[field_type] => other
[data_type] => string
[field_title] => LoanOfficer
[col_name] => loanOfficer
[list_order] => 2
[admin_display] => yes
[is_sortable] => yes
[include_on_redirect] => yes
[option_orientation] => vertical
[file_upload_dir] =>
[file_upload_url] =>
[file_upload_max_size] => 1000000
[file_upload_types] =>
[content] => John Doe
)
</code></pre>
<p>I want to find the field name and extract the content. In this case, the field name is <strong>loanOfficer</strong> and the content is <strong>John Doe</strong>.</p>
| [
{
"answer_id": 85069,
"author": "Michael Brown",
"author_id": 14359,
"author_profile": "https://Stackoverflow.com/users/14359",
"pm_score": 0,
"selected": false,
"text": "<p>I'm assuming that php has an associative array (commonly called dictionary or hashtable). The most efficient routi... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16292/"
] | I am looking for an efficient way to pull the data I want out of an array called $submission\_info so I can easily auto-fill my form fields. The array size is about 120.
I want to find the field name and extract the content. In this case, the field name is **loanOfficer** and the content is **John Doe**.
```
Output of Print_r($submission_info[1]):
Array (
[field_id] => 2399
[form_id] => 4
[field_name] => loanOfficer
[field_test_value] => ABCDEFGHIJKLMNOPQRSTUVWXYZ
[field_size] => medium
[field_type] => other
[data_type] => string
[field_title] => LoanOfficer
[col_name] => loanOfficer
[list_order] => 2
[admin_display] => yes
[is_sortable] => yes
[include_on_redirect] => yes
[option_orientation] => vertical
[file_upload_dir] =>
[file_upload_url] =>
[file_upload_max_size] => 1000000
[file_upload_types] =>
[content] => John Doe
)
```
I want to find the field name and extract the content. In this case, the field name is **loanOfficer** and the content is **John Doe**. | You're probably best off going through each entry and creating a new associative array out of it.
```
foreach($submission_info as $elem) {
$newarray[$elem["field_name"]] = $elem["content"];
}
```
Then you can just find the form fields by getting the value from $newarray[*<field you're filling in>*]. Otherwise, you're going to have to search $submission\_info each time for the correct field. |
84,842 | <p>I'm programmatically adding ToolStripButton items to a context menu.</p>
<p>That part is easy.</p>
<pre><code>this.tsmiDelete.DropDownItems.Add("The text on the item.");
</code></pre>
<p>However, I also need to wire up the events so that when the user clicks the item something actually happens!</p>
<p>How do I do this? The method that handles the click also needs to receive some sort of id or object that relates to the particular ToolStripButton that the user clicked.</p>
| [
{
"answer_id": 84909,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 3,
"selected": true,
"text": "<p>Couldn't you just subscribe to the Click event? Something like this:</p>\n\n<pre><code>ToolStripButton btn = new ToolStripButt... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7837/"
] | I'm programmatically adding ToolStripButton items to a context menu.
That part is easy.
```
this.tsmiDelete.DropDownItems.Add("The text on the item.");
```
However, I also need to wire up the events so that when the user clicks the item something actually happens!
How do I do this? The method that handles the click also needs to receive some sort of id or object that relates to the particular ToolStripButton that the user clicked. | Couldn't you just subscribe to the Click event? Something like this:
```
ToolStripButton btn = new ToolStripButton("The text on the item.");
this.tsmiDelete.DropDownItems.Add(btn);
btn.Click += new EventHandler(OnBtnClicked);
```
And OnBtnClicked would be declared like this:
```
private void OnBtnClicked(object sender, EventArgs e)
{
ToolStripButton btn = sender as ToolStripButton;
// handle the button click
}
```
The sender should be the ToolStripButton, so you can cast it and do whatever you need to do with it. |
84,847 | <p>How do I create a self-signed certificate for code signing using tools from the Windows SDK?</p>
| [
{
"answer_id": 201277,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 10,
"selected": true,
"text": "<h2>Updated Answer</h2>\n<p>If you are using the following Windows versions or later: Windows Server 2012, Windows S... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446/"
] | How do I create a self-signed certificate for code signing using tools from the Windows SDK? | Updated Answer
--------------
If you are using the following Windows versions or later: Windows Server 2012, Windows Server 2012 R2, or Windows 8.1 then [MakeCert is now deprecated](https://msdn.microsoft.com/en-us/library/windows/desktop/aa386968(v=vs.85).aspx), and Microsoft recommends using [the PowerShell Cmdlet **New-SelfSignedCertificate**](https://learn.microsoft.com/en-us/powershell/module/pki/new-selfsignedcertificate).
If you're using an older version such as Windows 7, you'll need to stick with MakeCert or another solution. Some people [suggest](https://www.reddit.com/r/PowerShell/comments/3190yr/powershell_40_but_no_newselfsignedcertificate/) the [Public Key Infrastructure Powershell (PSPKI) Module](https://github.com/PKISolutions/PSPKI).
Original Answer
---------------
While you can create a self-signed code-signing certificate (SPC - [Software Publisher Certificate](http://msdn.microsoft.com/en-us/library/8s9b9yaz.aspx)) in one go, I prefer to do the following:
### Creating a self-signed certificate authority (CA)
```
makecert -r -pe -n "CN=My CA" -ss CA -sr CurrentUser ^
-a sha256 -cy authority -sky signature -sv MyCA.pvk MyCA.cer
```
(^ = allow batch command-line to wrap line)
This creates a self-signed (-r) certificate, with an exportable private key (-pe). It's named "My CA", and should be put in the CA store for the current user. We're using the [SHA-256](http://en.wikipedia.org/wiki/SHA-2) algorithm. The key is meant for signing (-sky).
The private key should be stored in the MyCA.pvk file, and the certificate in the MyCA.cer file.
### Importing the CA certificate
Because there's no point in having a CA certificate if you don't trust it, you'll need to import it into the Windows certificate store. You *can* use the Certificates MMC snapin, but from the command line:
```
certutil -user -addstore Root MyCA.cer
```
### Creating a code-signing certificate (SPC)
```
makecert -pe -n "CN=My SPC" -a sha256 -cy end ^
-sky signature ^
-ic MyCA.cer -iv MyCA.pvk ^
-sv MySPC.pvk MySPC.cer
```
It is pretty much the same as above, but we're providing an issuer key and certificate (the -ic and -iv switches).
We'll also want to convert the certificate and key into a PFX file:
```
pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx
```
If you are using a password please use the below
```
pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx -po fess
```
If you want to protect the PFX file, add the -po switch, otherwise PVK2PFX creates a PFX file with no passphrase.
### Using the certificate for signing code
```
signtool sign /v /f MySPC.pfx ^
/t http://timestamp.url MyExecutable.exe
```
([See why timestamps may matter](https://stackoverflow.com/a/4417466/57611))
If you import the PFX file into the certificate store (you can use PVKIMPRT or the MMC snapin), you can sign code as follows:
```
signtool sign /v /n "Me" /s SPC ^
/t http://timestamp.url MyExecutable.exe
```
Some possible timestamp URLs for `signtool /t` are:
* `http://timestamp.verisign.com/scripts/timstamp.dll`
* `http://timestamp.globalsign.com/scripts/timstamp.dll`
* `http://timestamp.comodoca.com/authenticode`
* `http://timestamp.digicert.com`
### Full Microsoft documentation
* [signtool](http://msdn.microsoft.com/en-us/library/8s9b9yaz.aspx)
* [makecert](http://msdn.microsoft.com/en-us/library/bfsktky3.aspx)
* [pvk2pfx](http://msdn.microsoft.com/en-us/library/windows/hardware/ff550672(v=vs.85).aspx)
### Downloads
For those who are not .NET developers, you will need a copy of the Windows SDK and .NET framework. A current link is available here: [SDK & .NET][5] (which installs makecert in `C:\Program Files\Microsoft SDKs\Windows\v7.1`). Your mileage may vary.
MakeCert is available from the Visual Studio Command Prompt. Visual Studio 2015 does have it, and it can be launched from the Start Menu in Windows 7 under "Developer Command Prompt for VS 2015" or "VS2015 x64 Native Tools Command Prompt" (probably all of them in the same folder). |
84,882 | <p>This is a pretty simple question, at least it seems like it should be, about sudo permissions in Linux.</p>
<p>There are a lot of times when I just want to append something to <code>/etc/hosts</code> or a similar file but end up not being able to because both <code>></code> and <code>>></code> are not allowed, even with root.</p>
<p>Is there someway to make this work without having to <code>su</code> or <code>sudo su</code> into root?</p>
| [
{
"answer_id": 84898,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "<pre><code>sudo sh -c \"echo 127.0.0.1 localhost >> /etc/hosts\"\n</code></pre>\n"
},
{
"answer_id": 84... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9908/"
] | This is a pretty simple question, at least it seems like it should be, about sudo permissions in Linux.
There are a lot of times when I just want to append something to `/etc/hosts` or a similar file but end up not being able to because both `>` and `>>` are not allowed, even with root.
Is there someway to make this work without having to `su` or `sudo su` into root? | Use `tee --append` or `tee -a`.
```
echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list
```
Make sure to avoid quotes inside quotes.
To avoid printing data back to the console, redirect the output to /dev/null.
```
echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list > /dev/null
```
Remember about the (`-a`/`--append`) flag!
Just `tee` works like `>` and will overwrite your file. `tee -a` works like `>>` and will write at the end of the file. |
84,885 | <p>Wondering if anybody out there has any success in using the JDEdwards XMLInterop functionality. I've been using it for a while (with a simple PInvoke, will post code later). I'm looking to see if there's a better and/or more robust way.</p>
<p>Thanks.</p>
| [
{
"answer_id": 154634,
"author": "Jon Dewees",
"author_id": 1365,
"author_profile": "https://Stackoverflow.com/users/1365",
"pm_score": 4,
"selected": true,
"text": "<p>As promised, here is the code for integrating with JDEdewards using XML. It's a webservice, but could be used as you se... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365/"
] | Wondering if anybody out there has any success in using the JDEdwards XMLInterop functionality. I've been using it for a while (with a simple PInvoke, will post code later). I'm looking to see if there's a better and/or more robust way.
Thanks. | As promised, here is the code for integrating with JDEdewards using XML. It's a webservice, but could be used as you see fit.
```
namespace YourNameSpace
```
{
```
/// <summary>
/// This webservice allows you to submit JDE XML CallObject requests via a c# webservice
/// </summary>
[WebService(Namespace = "http://WebSite.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class JdeBFService : System.Web.Services.WebService
{
private string _strServerName;
private UInt16 _intServerPort;
private Int16 _intServerTimeout;
public JdeBFService()
{
// Load JDE ServerName, Port, & Connection Timeout from the Web.config file.
_strServerName = ConfigurationManager.AppSettings["JdeServerName"];
_intServerPort = Convert.ToUInt16(ConfigurationManager.AppSettings["JdePort"], CultureInfo.InvariantCulture);
_intServerTimeout = Convert.ToInt16(ConfigurationManager.AppSettings["JdeTimeout"], CultureInfo.InvariantCulture);
}
/// <summary>
/// This webmethod allows you to submit an XML formatted jdeRequest document
/// that will call any Master Business Function referenced in the XML document
/// and return a response.
/// </summary>
/// <param name="Xml"> The jdeRequest XML document </param>
[WebMethod]
public XmlDocument JdeXmlRequest(XmlDocument xmlInput)
{
try
{
string outputXml = string.Empty;
outputXml = NativeMethods.JdeXmlRequest(xmlInput, _strServerName, _intServerPort, _intServerTimeout);
XmlDocument outputXmlDoc = new XmlDocument();
outputXmlDoc.LoadXml(outputXml);
return outputXmlDoc;
}
catch (Exception ex)
{
ErrorReporting.SendEmail(ex);
throw;
}
}
}
/// <summary>
/// This interop class uses pinvoke to call the JDE C++ dll. It only has one static function.
/// </summary>
/// <remarks>
/// This class calls the xmlinterop.dll which can be found in the B9/system/bin32 directory.
/// Copy the dll to the webservice project's /bin directory before running the project.
/// </remarks>
internal static class NativeMethods
{
[DllImport("xmlinterop.dll",
EntryPoint = "_jdeXMLRequest@20",
CharSet = CharSet.Auto,
ExactSpelling = false,
CallingConvention = CallingConvention.StdCall,
SetLastError = true)]
private static extern IntPtr jdeXMLRequest([MarshalAs(UnmanagedType.LPWStr)] StringBuilder server, UInt16 port, Int32 timeout, [MarshalAs(UnmanagedType.LPStr)] StringBuilder buf, Int32 length);
public static string JdeXmlRequest(XmlDocument xmlInput, string strServerName, UInt16 intPort, Int32 intTimeout)
{
StringBuilder sbServerName = new StringBuilder(strServerName);
StringBuilder sbXML = new StringBuilder();
XmlWriter xWriter = XmlWriter.Create(sbXML);
xmlInput.WriteTo(xWriter);
xWriter.Close();
string result = Marshal.PtrToStringAnsi(jdeXMLRequest(sbServerName, intPort, intTimeout, sbXML, sbXML.Length));
return result;
}
}
```
}
You have to send it messages like the following one:
```
<jdeRequest type='callmethod' user='USER' pwd='PWD' environment='ENV'>
<callMethod name='GetEffectiveAddress' app='JdeWebRequest' runOnError='no'>
<params>
<param name='mnAddressNumber'>10000</param>
</params>
</callMethod>
</jdeRequest>
``` |
84,932 | <p>I have Perl script and need to determine the full path and filename of the script during execution. I discovered that depending on how you call the script <code>$0</code> varies and sometimes contains the <code>fullpath+filename</code> and sometimes just <code>filename</code>. Because the working directory can vary as well I can't think of a way to reliably get the <code>fullpath+filename</code> of the script.</p>
<p>Anyone got a solution?</p>
| [
{
"answer_id": 84952,
"author": "foxxtrot",
"author_id": 10369,
"author_profile": "https://Stackoverflow.com/users/10369",
"pm_score": -1,
"selected": false,
"text": "<p>On *nix, you likely have the \"whereis\" command, which searches your $PATH looking for a binary with a given name. I... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16331/"
] | I have Perl script and need to determine the full path and filename of the script during execution. I discovered that depending on how you call the script `$0` varies and sometimes contains the `fullpath+filename` and sometimes just `filename`. Because the working directory can vary as well I can't think of a way to reliably get the `fullpath+filename` of the script.
Anyone got a solution? | There are a few ways:
* [`$0`](http://perldoc.perl.org/perlvar.html#$0) is the currently executing script as provided by POSIX, relative to the current working directory if the script is at or below the CWD
* Additionally, `cwd()`, `getcwd()` and `abs_path()` are provided by the [`Cwd`](http://perldoc.perl.org/Cwd.html) module and tell you where the script is being run from
* The module [`FindBin`](http://perldoc.perl.org/FindBin.html) provides the `$Bin` & `$RealBin` variables that *usually* are the path to the executing script; this module also provides `$Script` & `$RealScript` that are the name of the script
* [`__FILE__`](http://perldoc.perl.org/perldata.html#Special-Literals) is the actual file that the Perl interpreter deals with during compilation, including its full path.
I've seen the first three ([`$0`](http://perldoc.perl.org/perlvar.html#$0), the [`Cwd`](http://perldoc.perl.org/Cwd.html) module and the [`FindBin`](http://perldoc.perl.org/FindBin.html) module) fail under `mod_perl` spectacularly, producing worthless output such as `'.'` or an empty string. In such environments, I use [`__FILE__`](http://perldoc.perl.org/perldata.html#Special-Literals) and get the path from that using the [`File::Basename`](http://perldoc.perl.org/File/Basename.html) module:
```
use File::Basename;
my $dirname = dirname(__FILE__);
``` |
84,978 | <p>Excel usually treats Conditional Formatting formulas as if they are array formulas, <strong>except</strong> when loading them from an Excel 2002/2003 XML Spreadsheet file.</p>
<p>This is only an issue with the Excel 2002/2003 XML Spreadsheet format... the native Excel format works fine, as does the newer Excel 2007 XML format (xlsx).</p>
<p>After loading the spreadsheet, it is possible to make it work correctly by selecting the formatted range, going to the Conditional Formatting dialog, and clicking OK--but this only fixes the problem for the session.</p>
<p><strong>Test case:</strong></p>
<p>Enter the following into a new sheet:</p>
<pre><code> A B C
1 N N N
2 x x x
3 x x x</code></pre>
<p>Create this conditional format formula on cells A1:C1 (your choice of pretty colors for the format):</p>
<pre><code>=(SUM(($A1:$C1="N")*($A$2:$C$2=A$3))>0)</code></pre>
<p>This is an array formula that activates for A1, B1, and C1 whenever any of them has an "N" and the cell in row 2 below the "N" is equal to the cell in row 3 of the current column. </p>
<p>(This has been simplified from a real-world business spreadsheet. Sorry for the complexity of the test case, I am trying to find an easier test case to present here.)</p>
<p>And it works... you can alter the N's or the x's in any way you want and the formatting works just fine.</p>
<p>Save this as an XML Spreadsheet. Close Excel, and re-open the file. Formatting is now broken. Now, you can only activate conditional formatting if A1 is an "N" and A2 is the same as A3, B3, or C3. The values of B1, B2, C1, and C2 have no effect on the formatting.</p>
<p>Now, select A1:C1 and look at the conditional formatting formula. Exactly the same as before. Hit OK. Conditional formatting starts working again, and will work during the entire session the file is open.</p>
<p><strong>Workarounds considered:</strong></p>
<ol>
<li><p>Providing the file in native (BIFF) Excel format. Not an option, these spreadsheets are generated on the fly by a web server and this is only one of dozens of types of workbooks generated dynamically by our system.</p></li>
<li><p>Providing the file in the Excel 2007 native XML format (xlsx). Not an option, current user base does not have Office 2007 or the compatibility plug-in.</p></li>
<li><p>Asking users to select the range, enter the Conditional Formatting dialog, and hitting ok. Not an option in this case, unsophisticated users.</p></li>
<li><p>Asking users to open the XML spreadsheet, save as native XLS, close, and re-open the XLS file. <strong>This does not work!</strong> Formatting remains broken in the native XLS format if it was loaded broken from an XML file. If (3) above is performed before saving, the XLS file will work properly.</p></li>
</ol>
<p><strong>I ended up rewriting the conditional formatting to not use array formulas. So I guess this is "answered" to some degree, but it's still an undocumented, if obscure, bug in Excel 2002/2003's handling of XML files.</strong></p>
| [
{
"answer_id": 86251,
"author": "TMarshall",
"author_id": 8847,
"author_profile": "https://Stackoverflow.com/users/8847",
"pm_score": 2,
"selected": true,
"text": "<p>I tried to recreate the problem you describe. Here is what I found.</p>\n\n<ul>\n<li><p>Could consistently recreate the\n... | 2008/09/17 | [
"https://Stackoverflow.com/questions/84978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16306/"
] | Excel usually treats Conditional Formatting formulas as if they are array formulas, **except** when loading them from an Excel 2002/2003 XML Spreadsheet file.
This is only an issue with the Excel 2002/2003 XML Spreadsheet format... the native Excel format works fine, as does the newer Excel 2007 XML format (xlsx).
After loading the spreadsheet, it is possible to make it work correctly by selecting the formatted range, going to the Conditional Formatting dialog, and clicking OK--but this only fixes the problem for the session.
**Test case:**
Enter the following into a new sheet:
```
A B C
1 N N N
2 x x x
3 x x x
```
Create this conditional format formula on cells A1:C1 (your choice of pretty colors for the format):
```
=(SUM(($A1:$C1="N")*($A$2:$C$2=A$3))>0)
```
This is an array formula that activates for A1, B1, and C1 whenever any of them has an "N" and the cell in row 2 below the "N" is equal to the cell in row 3 of the current column.
(This has been simplified from a real-world business spreadsheet. Sorry for the complexity of the test case, I am trying to find an easier test case to present here.)
And it works... you can alter the N's or the x's in any way you want and the formatting works just fine.
Save this as an XML Spreadsheet. Close Excel, and re-open the file. Formatting is now broken. Now, you can only activate conditional formatting if A1 is an "N" and A2 is the same as A3, B3, or C3. The values of B1, B2, C1, and C2 have no effect on the formatting.
Now, select A1:C1 and look at the conditional formatting formula. Exactly the same as before. Hit OK. Conditional formatting starts working again, and will work during the entire session the file is open.
**Workarounds considered:**
1. Providing the file in native (BIFF) Excel format. Not an option, these spreadsheets are generated on the fly by a web server and this is only one of dozens of types of workbooks generated dynamically by our system.
2. Providing the file in the Excel 2007 native XML format (xlsx). Not an option, current user base does not have Office 2007 or the compatibility plug-in.
3. Asking users to select the range, enter the Conditional Formatting dialog, and hitting ok. Not an option in this case, unsophisticated users.
4. Asking users to open the XML spreadsheet, save as native XLS, close, and re-open the XLS file. **This does not work!** Formatting remains broken in the native XLS format if it was loaded broken from an XML file. If (3) above is performed before saving, the XLS file will work properly.
**I ended up rewriting the conditional formatting to not use array formulas. So I guess this is "answered" to some degree, but it's still an undocumented, if obscure, bug in Excel 2002/2003's handling of XML files.** | I tried to recreate the problem you describe. Here is what I found.
* Could consistently recreate the
problem using Excel 2003 on Windows
XP when saving as an XML
spreadsheet.
* Could **not** reproduce the problem
using Excel 2003 on Windows XP when
saving as a standard xls
spreadsheet.
* Could **not** reproduce the problem
using Excel 2007 on Windows Vista
when saving the file in the native
xlsx format.
* Could **not** reproduce the problem
using Excel 2007 on Windows Vista
when saving the file in the Excel
97-2003 xls format.
(Note: *All instances of Excel and Windows are current with all Windows updates.*)
I also added a simple conditional formatting formula to each test. In every case, it worked as expected after saving the file, closing Excel, and reopening the file.
So the answer seems to be to use the standard Excel 2003 file format when saving the file.
BTW, this is a very odd formatting formula. It is difficult to imagine how you would use it. It must be a very specific & unusual business case. I also have the feeling something is missing in your post. (I'm not accusing you of being dishonest – just wondering if you may have shortened the formula for readability.) If this is not the *exact* formula you are using, please edit your original post with the complete formula and I will be happy to revisit this issue. |
85,006 | <p>I have loaded image into a new, initialized Oracle ORDImage object and am processing it by PL/SQL. I can read its properties, but cannot process it with the process() method. </p>
<pre><code>vLocalImage ORDImage := ORDImage.init();
...
vLocalImage.source.localdata := PORTAL.wwdoc_admin.get_document_blob_content(pFile);
vLocalImage.setProperties();
...
if vLocalImage.width > lMaxWidth
then
vLocalImage.process('maxScale 534 401');
end if;
</code></pre>
<p>This should scale the image down, conserving aspect ratio, so that it is no more than 534 px wide and no more than 401 px high. </p>
<p>However, I get the following error stack:</p>
<pre><code>Internal error: ORA-29400: data cartridge error
IMG-00710: unable to write to destination image
ORA-01031: insufficient privileges
</code></pre>
<p>Trying other operations (like 'rotate 90') gives same errors.</p>
| [
{
"answer_id": 91876,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 0,
"selected": false,
"text": "<p>Can you please show the select statement you use to get l_ordimage? The main cause of this error seems to be if you... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9363/"
] | I have loaded image into a new, initialized Oracle ORDImage object and am processing it by PL/SQL. I can read its properties, but cannot process it with the process() method.
```
vLocalImage ORDImage := ORDImage.init();
...
vLocalImage.source.localdata := PORTAL.wwdoc_admin.get_document_blob_content(pFile);
vLocalImage.setProperties();
...
if vLocalImage.width > lMaxWidth
then
vLocalImage.process('maxScale 534 401');
end if;
```
This should scale the image down, conserving aspect ratio, so that it is no more than 534 px wide and no more than 401 px high.
However, I get the following error stack:
```
Internal error: ORA-29400: data cartridge error
IMG-00710: unable to write to destination image
ORA-01031: insufficient privileges
```
Trying other operations (like 'rotate 90') gives same errors. | Even though the documentation states that it should be possible to edit an ORDImage "in-place", I was unable to make it work.
Instead, I created a new ORDImage object and used processCopy:
```
vNewImage ORDImage;
...
vLocalImage.processCopy('maxScale 534 401', vNewImage);
``` |
85,019 | <p>Google Maps used to do this bit where when you hit the "Print" link, what would be sent to the printer wasn't exactly what you had on the screen, but rather a differently-formatted version of mostly the same information.</p>
<p>It appears that they've largely moved away from this concept (I guess people didn't understand it) and most websites have a "print version" of things like articles and so forth.</p>
<p>But if you wanted to make a webpage such that a "printer friendly" version of the page is what gets sent to the printer without having to make a separate page for it, how would you do that?</p>
| [
{
"answer_id": 85026,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this with the css when you specify media as print.</p>\n"
},
{
"answer_id": 85039,
"author": "Jim"... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2577/"
] | Google Maps used to do this bit where when you hit the "Print" link, what would be sent to the printer wasn't exactly what you had on the screen, but rather a differently-formatted version of mostly the same information.
It appears that they've largely moved away from this concept (I guess people didn't understand it) and most websites have a "print version" of things like articles and so forth.
But if you wanted to make a webpage such that a "printer friendly" version of the page is what gets sent to the printer without having to make a separate page for it, how would you do that? | You can achieve this effect by creating a css stylesheet which is targeted directly to printing, and another targeted directly for the screen.
Use the link tag:
```
<link rel="stylesheet" type="text/css" href="print.css" media="print, handheld" />
<link rel="stylesheet" type="text/css" href="screen.css" media="screen" />
```
to embed your stylesheet into your document.
To hide is easy, just set your block style to hidden in whatever stylesheet you want and it wont be displayed. For example:
```css
.newStyle1 {
display: none;
}
```
Then anything set to the style of `newStyle1` will not be displayed. |
85,033 | <p>I am wrapping a native C++ class, which has the following methods:</p>
<pre><code>class Native
{
public:
class Local
{
std::string m_Str;
int m_Int;
};
typedef std::vector<Local> LocalVec;
typedef LocalVec::iterator LocalIter;
LocalIter BeginLocals();
LocalIter EndLocals();
private:
LocalVec m_Locals;
};
</code></pre>
<p>1) What is the ".NET way" of representing this same kind of interface? A single method returning an array<>? Does the array<> generic have iterators, so that I could implement BeginLocals() and EndLocals()? </p>
<p>2) Should Local be declared as a <strong>value struct</strong> in the .NET wrapper?</p>
<p>I'd really like to represent the wrapped class with a .NET flavor, but I'm very new to the managed world - and this type of information is frustrating to google for...</p>
| [
{
"answer_id": 85402,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 4,
"selected": true,
"text": "<p>Iterators aren't exactly translatable to \"the .net way\", but they are roughly replaced by IEnumerable < T > and... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114/"
] | I am wrapping a native C++ class, which has the following methods:
```
class Native
{
public:
class Local
{
std::string m_Str;
int m_Int;
};
typedef std::vector<Local> LocalVec;
typedef LocalVec::iterator LocalIter;
LocalIter BeginLocals();
LocalIter EndLocals();
private:
LocalVec m_Locals;
};
```
1) What is the ".NET way" of representing this same kind of interface? A single method returning an array<>? Does the array<> generic have iterators, so that I could implement BeginLocals() and EndLocals()?
2) Should Local be declared as a **value struct** in the .NET wrapper?
I'd really like to represent the wrapped class with a .NET flavor, but I'm very new to the managed world - and this type of information is frustrating to google for... | Iterators aren't exactly translatable to "the .net way", but they are roughly replaced by IEnumerable < T > and IEnumerator < T >.
Rather than
```
vector<int> a_vector;
vector<int>::iterator a_iterator;
for(int i= 0; i < 100; i++)
{
a_vector.push_back(i);
}
int total = 0;
a_iterator = a_vector.begin();
while( a_iterator != a_vector.end() ) {
total += *a_iterator;
a_iterator++;
}
```
you would see (in c#)
```
List<int> a_list = new List<int>();
for(int i=0; i < 100; i++)
{
a_list.Add(i);
}
int total = 0;
foreach( int item in a_list)
{
total += item;
}
```
Or more explicitly (without hiding the IEnumerator behind the foreach syntax sugar):
```
List<int> a_list = new List<int>();
for (int i = 0; i < 100; i++)
{
a_list.Add(i);
}
int total = 0;
IEnumerator<int> a_enumerator = a_list.GetEnumerator();
while (a_enumerator.MoveNext())
{
total += a_enumerator.Current;
}
```
As you can see, foreach just hides the .net enumerator for you.
So really, the ".net way" would be to simply allow people to create List< Local > items for themselves. If you do want to control iteration or make the collection a bit more custom, have your collection implement the IEnumerable< T > and/or ICollection< T > interfaces as well.
A near direct translation to c# would be pretty much what you assumed:
```
public class Native
{
public class Local
{
public string m_str;
public int m_int;
}
private List<Local> m_Locals = new List<Local>();
public List<Local> Locals
{
get{ return m_Locals;}
}
}
```
Then a user would be able to
```
foreach( Local item in someNative.Locals)
{
...
}
``` |
85,034 | <p>I want to make a table in SqlServer that will add, on insert, a auto incremented primary key. This should be an autoincremented id similar to MySql auto_increment functionality. (Below)</p>
<pre><code>create table foo
(
user_id int not null auto_increment,
name varchar(50)
)
</code></pre>
<p>Is there a way of doing this with out creating an insert trigger?</p>
| [
{
"answer_id": 85038,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "<p>Just set the field as an <a href=\"http://msdn.microsoft.com/en-us/library/aa933196.aspx\" rel=\"nofollow noreferrer\">ide... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12942/"
] | I want to make a table in SqlServer that will add, on insert, a auto incremented primary key. This should be an autoincremented id similar to MySql auto\_increment functionality. (Below)
```
create table foo
(
user_id int not null auto_increment,
name varchar(50)
)
```
Is there a way of doing this with out creating an insert trigger? | Like this
```
create table foo
(
user_id int not null identity,
name varchar(50)
)
``` |
85,036 | <p>I need to manually migrate modified stored procedures from a DEV SQL Server 2005 database instance to a TEST instance. Except for the changes I'm migrating, the databases have the same schemas. How can I quickly identify which stored procedures have been modified in the DEV database for migration to the TEST instance?</p>
<p>I assume I can write a query against some of the system tables to view database objects of type stored procedure, sorting by some sort of last modified or compiled data, but I'm not sure. Maybe there is some sort of free utility someone can point me to.</p>
| [
{
"answer_id": 85075,
"author": "Craig",
"author_id": 7861,
"author_profile": "https://Stackoverflow.com/users/7861",
"pm_score": 2,
"selected": false,
"text": "<p>Although not free I have had good experience using Red-Gates <a href=\"http://www.red-gate.com/products/SQL_Compare/index.ht... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16137/"
] | I need to manually migrate modified stored procedures from a DEV SQL Server 2005 database instance to a TEST instance. Except for the changes I'm migrating, the databases have the same schemas. How can I quickly identify which stored procedures have been modified in the DEV database for migration to the TEST instance?
I assume I can write a query against some of the system tables to view database objects of type stored procedure, sorting by some sort of last modified or compiled data, but I'm not sure. Maybe there is some sort of free utility someone can point me to. | instead of using sysobjects which is not recommended anymore use sys.procedures
```
select name,create_date,modify_date
from sys.procedures
order by modify_date desc
```
you can do the where clause yourself but this will list it in order of modification date descending |
85,058 | <p>I see <a href="http://www.is-research.de/info/vmlanguages/index.html" rel="noreferrer">here</a> that there are a load of languages aside from Java that run on the JVM. I'm a bit confused about the whole concept of other languages running in the JVM. So:</p>
<p>What is the advantage in having other languages for the JVM?</p>
<p>What is required (in high level terms) to write a language/compiler for the JVM? </p>
<p>How do you write/compile/run code in a language (other than Java) in the JVM?</p>
<hr>
<p><strong>EDIT:</strong> There were 3 follow up questions (originally comments) that were answered in the accepted answer. They are reprinted here for legibility:</p>
<p>How would an app written in, say, JPython, interact with a Java app? </p>
<p>Also, Can that JPython application use any of the JDK functions/objects?? </p>
<p>What if it was Jaskell code, would the fact that it is a functional language not make it incompatible with the JDK?</p>
| [
{
"answer_id": 85072,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>They do it to keep up with .Net. .Net allows C#, VB, J# (formerly), F#, Python, Ruby (coming soon), and c++. I'm p... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142/"
] | I see [here](http://www.is-research.de/info/vmlanguages/index.html) that there are a load of languages aside from Java that run on the JVM. I'm a bit confused about the whole concept of other languages running in the JVM. So:
What is the advantage in having other languages for the JVM?
What is required (in high level terms) to write a language/compiler for the JVM?
How do you write/compile/run code in a language (other than Java) in the JVM?
---
**EDIT:** There were 3 follow up questions (originally comments) that were answered in the accepted answer. They are reprinted here for legibility:
How would an app written in, say, JPython, interact with a Java app?
Also, Can that JPython application use any of the JDK functions/objects??
What if it was Jaskell code, would the fact that it is a functional language not make it incompatible with the JDK? | To address your three questions separately:
>
> What is the advantage in having other languages for the JVM?
>
>
>
There are two factors here. (1) Why have a language other than Java for the JVM, and (2) why have another language run on the JVM, instead of a different runtime?
1. Other languages can satisfy other needs. For example, Java has no built-in support for [closures](http://en.wikipedia.org/wiki/Closure_(computer_science)), a feature that is often very useful.
2. A language that runs on the JVM is bytecode compatible with any other language that runs on the JVM, meaning that code written in one language can interact with a library written in another language.
>
> What is required (in high level terms) to write a language/compiler for the JVM?
>
>
>
The JVM reads bytecode (.class) files to obtain the instructions it needs to perform. Thus any language that is to be run on the JVM needs to be compiled to bytecode adhering to the [Sun specification](http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html). This process is similar to compiling to native code, except that instead of compiling to instructions understood by the CPU, the code is compiled to instructions that are interpreted by the JVM.
>
> How do you write/compile/run code in a language (other than Java) in the JVM?
>
>
>
Very much in the same way you write/compile/run code in Java. To get your feet wet, I'd recommend looking at [Scala](http://www.scala-lang.org/), which runs flawlessly on the JVM.
Answering your follow up questions:
>
> How would an app written in, say, JPython, interact with a Java app?
>
>
>
This depends on the implementation's choice of bridging the language gap. In your example, [Jython project](http://www.jython.org/Project/) has a straightforward means of doing this ([see here](http://wiki.python.org/jython/UserGuide#accessing-java-from-jython)):
```
from java.net import URL
u = URL('http://jython.org')
```
>
> Also, can that JPython application use any of the JDK functions/objects?
>
>
>
Yes, see above.
>
> What if it was Jaskell code, would the fact that it is a functional language not make it incompatible with the JDK?
>
>
>
No. Scala (link above) for example implements functional features while maintaining compatibility with Java. For example:
```
object Timer {
def oncePerSecond(callback: () => unit) {
while (true) { callback(); Thread sleep 1000 }
}
def timeFlies() {
println("time flies like an arrow...")
}
def main(args: Array[String]) {
oncePerSecond(timeFlies)
}
}
``` |
85,085 | <p>I've got an RMI call defined as:</p>
<pre><code>public void remoteGetCustomerNameNumbers(ArrayList<String> customerNumberList, ArrayList<String> customerNameList) throws java.rmi.RemoteException;
</code></pre>
<p>The function does a database lookup and populates the two ArrayLists. The calling function gets nothing. I believe this works with Vector types.</p>
<p>Do I need to use the Vector, or is there a way to get this to work without making two calls. I've got some other ideas that I'd probably use, like returning a key/value pair, but I'd like to know if I can get this to work.</p>
<p>Update:<br/>
I would accept all of the answers given so far if I could. I hadn't known the network cost, so It makes sense to rework the function to return a LinkedHashMap instead of the two ArrayLists.</p>
| [
{
"answer_id": 85126,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 1,
"selected": false,
"text": "<p>You lose your references when you make the remote call. You'll need to return the lists rather than expect them to be po... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16345/"
] | I've got an RMI call defined as:
```
public void remoteGetCustomerNameNumbers(ArrayList<String> customerNumberList, ArrayList<String> customerNameList) throws java.rmi.RemoteException;
```
The function does a database lookup and populates the two ArrayLists. The calling function gets nothing. I believe this works with Vector types.
Do I need to use the Vector, or is there a way to get this to work without making two calls. I've got some other ideas that I'd probably use, like returning a key/value pair, but I'd like to know if I can get this to work.
Update:
I would accept all of the answers given so far if I could. I hadn't known the network cost, so It makes sense to rework the function to return a LinkedHashMap instead of the two ArrayLists. | As Tom mentions, you can pass remote objects. You'd have to create a class to hold your list that implements Remote. Anytime you pass something that implements Remote as an argument, whenever the receiving side uses it, it turns around and makes a remote call *back* to the caller to work with that object. |
85,091 | <p>OK, this begins to drive me crazy. I have an asp.net webapp. Pretty straightforward, most of the code in the .aspx.vb, and a few classes in App_Code.</p>
<p>The problem, which has begun to occur only today (even though most of the code was already written), is that once in a while, I have this error message :</p>
<blockquote>
<p>Error BC30002: Type ‘XXX’ is not defined</p>
</blockquote>
<p>The error occurs about every time I modify the files in the App_Code folder. EDIT : OK, this happens also if I don't touch anything for a while then refresh the page. I'm still trying to figure out exactly how to trigger this error.</p>
<p>I just have to wait a little bit without touching anything, then refresh the page and it works, but it's very annoying.</p>
<p>So I searched a little bit, but nothing came up except imports missing. Any idea ?</p>
| [
{
"answer_id": 85333,
"author": "HaveThunk",
"author_id": 14515,
"author_profile": "https://Stackoverflow.com/users/14515",
"pm_score": 3,
"selected": false,
"text": "<p>Sounds like a pre compile issue, particularly because you mention that you get the error and then wait and it disappea... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6776/"
] | OK, this begins to drive me crazy. I have an asp.net webapp. Pretty straightforward, most of the code in the .aspx.vb, and a few classes in App\_Code.
The problem, which has begun to occur only today (even though most of the code was already written), is that once in a while, I have this error message :
>
> Error BC30002: Type ‘XXX’ is not defined
>
>
>
The error occurs about every time I modify the files in the App\_Code folder. EDIT : OK, this happens also if I don't touch anything for a while then refresh the page. I'm still trying to figure out exactly how to trigger this error.
I just have to wait a little bit without touching anything, then refresh the page and it works, but it's very annoying.
So I searched a little bit, but nothing came up except imports missing. Any idea ? | I think I found the problem.
My code was like that :
```
Imports CMS
Sub Whatever()
Dim a as new Arbo.MyObject() ' Arbo is a namespace inside CMS
Dim b as new Util.MyOtherObject() ' Util is a namespace inside Util
End Sub
```
I'm not sure why I wrote it like that, but it turns out the fact I was calling classes without either calling their whole namespace or importing their whole namespace was triggering the error.
I rewrote it like this :
```
Imports CMS.Arbo
Imports CMS.Util
Sub Whatever()
Dim a as new MyObject()
Dim b as new MyOtherObject()
End Sub
```
And now it works... |
85,116 | <p>I want the server to always serve dates in UTC in the HTML, and have JavaScript on the client site convert it to the user's local timezone.</p>
<p>Bonus if I can output in the user's locale date format.</p>
| [
{
"answer_id": 85161,
"author": "japollock",
"author_id": 1210318,
"author_profile": "https://Stackoverflow.com/users/1210318",
"pm_score": -1,
"selected": false,
"text": "<p>Don't know how to do locale, but javascript is a client side technology.</p>\n\n<pre><code>usersLocalTime = new D... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13989/"
] | I want the server to always serve dates in UTC in the HTML, and have JavaScript on the client site convert it to the user's local timezone.
Bonus if I can output in the user's locale date format. | Seems the most foolproof way to start with a UTC date is to create a new `Date` object and use the `setUTC…` methods to set it to the date/time you want.
Then the various `toLocale…String` methods will provide localized output.
### Example:
```js
// This would come from the server.
// Also, this whole block could probably be made into an mktime function.
// All very bare here for quick grasping.
d = new Date();
d.setUTCFullYear(2004);
d.setUTCMonth(1);
d.setUTCDate(29);
d.setUTCHours(2);
d.setUTCMinutes(45);
d.setUTCSeconds(26);
console.log(d); // -> Sat Feb 28 2004 23:45:26 GMT-0300 (BRT)
console.log(d.toLocaleString()); // -> Sat Feb 28 23:45:26 2004
console.log(d.toLocaleDateString()); // -> 02/28/2004
console.log(d.toLocaleTimeString()); // -> 23:45:26
```
### Some references:
* [toLocaleString](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/toLocaleString)
* [toLocaleDateString](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/toLocaleDateString)
* [toLocaleTimeString](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/toLocaleTimeString)
* [getTimezoneOffset](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/getTimezoneOffset) |
85,119 | <p>I know you can do redirection based on the domain or path to rewrite the URI to point at a site-specific location and I've also seen some brutish <code>if</code> and <code>elif</code> statements for every site as shown in the following code, which I would like to avoid.</p>
<pre class="lang-py prettyprint-override"><code>if site == 'site1':
...
elif site == 'site2:
...
</code></pre>
<p>What are some good and clever ways of running multiple sites from a single, common Python web framework (i.e., Pylons, TurboGears, etc)?</p>
| [
{
"answer_id": 85134,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 5,
"selected": true,
"text": "<p>Django has this built in. See <a href=\"http://docs.djangoproject.com/en/dev/ref/contrib/sites/#ref-contrib-sites\" rel=\"nore... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4919/"
] | I know you can do redirection based on the domain or path to rewrite the URI to point at a site-specific location and I've also seen some brutish `if` and `elif` statements for every site as shown in the following code, which I would like to avoid.
```py
if site == 'site1':
...
elif site == 'site2:
...
```
What are some good and clever ways of running multiple sites from a single, common Python web framework (i.e., Pylons, TurboGears, etc)? | Django has this built in. See [the sites framework](http://docs.djangoproject.com/en/dev/ref/contrib/sites/#ref-contrib-sites).
As a general technique, include a 'host' column in your database schema attached to the data you want to be host-specific, then include the `Host` HTTP header in the query when you are retrieving data. |
85,122 | <p>On Windows I have a problem I never encountered on Unix. That is how to get a thread to sleep for less than one millisecond. On Unix you typically have a number of choices (sleep, usleep and nanosleep) to fit your needs. On Windows, however, there is only <em>Sleep</em> with millisecond granularity. </p>
<p>On Unix, I can use the use the <code>select</code> system call to create a microsecond sleep which is pretty straightforward:</p>
<pre><code>int usleep(long usec)
{
struct timeval tv;
tv.tv_sec = usec/1000000L;
tv.tv_usec = usec%1000000L;
return select(0, 0, 0, 0, &tv);
}
</code></pre>
<p>How can I achieve the same on Windows?</p>
| [
{
"answer_id": 85143,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": -1,
"selected": true,
"text": "<p>On Windows the use of <code>select</code> forces you to include the <a href=\"https://msdn.microsoft.com/en-us/libr... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6508/"
] | On Windows I have a problem I never encountered on Unix. That is how to get a thread to sleep for less than one millisecond. On Unix you typically have a number of choices (sleep, usleep and nanosleep) to fit your needs. On Windows, however, there is only *Sleep* with millisecond granularity.
On Unix, I can use the use the `select` system call to create a microsecond sleep which is pretty straightforward:
```
int usleep(long usec)
{
struct timeval tv;
tv.tv_sec = usec/1000000L;
tv.tv_usec = usec%1000000L;
return select(0, 0, 0, 0, &tv);
}
```
How can I achieve the same on Windows? | On Windows the use of `select` forces you to include the [Winsock](https://msdn.microsoft.com/en-us/library/windows/desktop/ms740673(v=vs.85).aspx) library which has to be initialized like this in your application:
```
WORD wVersionRequested = MAKEWORD(1,0);
WSADATA wsaData;
WSAStartup(wVersionRequested, &wsaData);
```
And then the select won't allow you to be called without any socket so you have to do a little more to create a microsleep method:
```
int usleep(long usec)
{
struct timeval tv;
fd_set dummy;
SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
FD_ZERO(&dummy);
FD_SET(s, &dummy);
tv.tv_sec = usec/1000000L;
tv.tv_usec = usec%1000000L;
return select(0, 0, 0, &dummy, &tv);
}
```
All these created usleep methods return zero when successful and non-zero for errors. |
85,137 | <p>Say I have a class named Frog, it looks like:</p>
<pre><code>public class Frog
{
public int Location { get; set; }
public int JumpCount { get; set; }
public void OnJump()
{
JumpCount++;
}
}
</code></pre>
<p>I need help with 2 things:</p>
<ol>
<li>I want to create an event named Jump in the class definition.</li>
<li>I want to create an instance of the Frog class, and then create another method that will be called when the Frog jumps.</li>
</ol>
| [
{
"answer_id": 85188,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": 7,
"selected": true,
"text": "<pre><code>public event EventHandler Jump;\npublic void OnJump()\n{\n EventHandler handler = Jump;\n if (null... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
] | Say I have a class named Frog, it looks like:
```
public class Frog
{
public int Location { get; set; }
public int JumpCount { get; set; }
public void OnJump()
{
JumpCount++;
}
}
```
I need help with 2 things:
1. I want to create an event named Jump in the class definition.
2. I want to create an instance of the Frog class, and then create another method that will be called when the Frog jumps. | ```
public event EventHandler Jump;
public void OnJump()
{
EventHandler handler = Jump;
if (null != handler) handler(this, EventArgs.Empty);
}
```
then
```
Frog frog = new Frog();
frog.Jump += new EventHandler(yourMethod);
private void yourMethod(object s, EventArgs e)
{
Console.WriteLine("Frog has Jumped!");
}
``` |
85,159 | <p>Is there any way to parse a string in the format HH:MM into a Date (or other) object using the standard libraries?</p>
<p>I know that I can parse something like "9/17/2008 10:30" into a Date object using</p>
<pre><code>var date:Date = new Date(Date.parse("9/17/2008 10:30");
</code></pre>
<p>But I want to parse just 10:30 by itself. The following code will not work.</p>
<pre><code>var date:Date = new Date(Date.parse("10:30");
</code></pre>
<p>I know I can use a custom RegEx to do this fairly easily, but it seems like this should be possible using the existing Flex API.</p>
| [
{
"answer_id": 85174,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 1,
"selected": false,
"text": "<p>Have you considered prepending \"01/01/2000 \" to the time string and then applying Date?</p>\n\n<p>Alternately there's... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1247/"
] | Is there any way to parse a string in the format HH:MM into a Date (or other) object using the standard libraries?
I know that I can parse something like "9/17/2008 10:30" into a Date object using
```
var date:Date = new Date(Date.parse("9/17/2008 10:30");
```
But I want to parse just 10:30 by itself. The following code will not work.
```
var date:Date = new Date(Date.parse("10:30");
```
I know I can use a custom RegEx to do this fairly easily, but it seems like this should be possible using the existing Flex API. | To answer your specific question: no, there's no library function to do what you want to do, but then there's no library function for parsing dates on the ISO format, on the German format, on the Swedish format, dates where the years are in roman numerals etc.
Why not use regular expressions? That's what they are for. |
85,179 | <p>I've long been a fan of Stored Procedure Keyboard Accelerators, as described in <a href="http://blogs.msdn.com/irenak/archive/2006/10/27/sysk-228-get-table-columns-or-rows-with-single-key-press.aspx" rel="nofollow noreferrer">this article</a>. When we moved from SQL 2000 to 2005, though, and from Query Analyzer to Management Studio, the handling of the arguments changed. In QA, comma-separated arguments were automatically read as two separate arguments. In SSMS -- at least for me -- it's being read as one argument, with commas in it. Similarly, if I pass in a single argument with single quotes in it, I get a syntax error, <em>unless I escape the quotes</em> (' -> ''). In the article linked above, the author implies that this should not be the case for SSMS, but even with her exact example, comma-separated arguments are still being interpreted as one argument on every SSMS installation I've tried it on (3 of them), running against every SQL Server installation I've tried (4 of them).</p>
<p>E.g., typing the following into SSMS, </p>
<pre><code>Person,4
</code></pre>
<p>then selecting it and running the shortcut, I get the error message "Invalid object name 'Person,4'.</p>
<p>Does anybody have any idea how to fix this? Does anybody even use these shortcuts? I've Googled this problem several times over the past two years, and have had no luck.</p>
<p>Edit: May be an issue with a specific build of SSMS. I have a follow-up post below.</p>
| [
{
"answer_id": 85976,
"author": "Tim Lentine",
"author_id": 2833,
"author_profile": "https://Stackoverflow.com/users/2833",
"pm_score": 1,
"selected": false,
"text": "<p>I had never tried this until I read your question and then read the article you referenced, so take this with a grain ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1818/"
] | I've long been a fan of Stored Procedure Keyboard Accelerators, as described in [this article](http://blogs.msdn.com/irenak/archive/2006/10/27/sysk-228-get-table-columns-or-rows-with-single-key-press.aspx). When we moved from SQL 2000 to 2005, though, and from Query Analyzer to Management Studio, the handling of the arguments changed. In QA, comma-separated arguments were automatically read as two separate arguments. In SSMS -- at least for me -- it's being read as one argument, with commas in it. Similarly, if I pass in a single argument with single quotes in it, I get a syntax error, *unless I escape the quotes* (' -> ''). In the article linked above, the author implies that this should not be the case for SSMS, but even with her exact example, comma-separated arguments are still being interpreted as one argument on every SSMS installation I've tried it on (3 of them), running against every SQL Server installation I've tried (4 of them).
E.g., typing the following into SSMS,
```
Person,4
```
then selecting it and running the shortcut, I get the error message "Invalid object name 'Person,4'.
Does anybody have any idea how to fix this? Does anybody even use these shortcuts? I've Googled this problem several times over the past two years, and have had no luck.
Edit: May be an issue with a specific build of SSMS. I have a follow-up post below. | Tim's suggestion didn't solve my problem on my development PC, but it did convince me to try again from a different PC. When using a different PC's SSMS to log into the development PC's database and trying exactly what Tim describes, I'm having the same behavior Tim describes.
I was also able to re-replicate the argument parsing issue on the other PCs I had tried in the past. I'm hoping Tim can let me know what's the version and build number on his SSMS installation, because my current theory is that the problem is just from the specific build that my coworkers and I have on our dev PCs -- the version string is "Microsoft SQL Server Management Studio 9.00.1399.00". All of our installs of that version took place well over a year ago, so I don't know that I can trace back what disk it's from.
The one that is NOT having the problem is actually our development server, which has "Microsoft SQL Server Management Studio 9.00.3042.00" installed. I don't know if this might be something I can make go away by patching or something, but it currently looks like 1399 reads the entire selection as a single argument, while 3042 does some pre-parsing. I've also recently found that when I pass in a string that contains "--" (comment token) in 3042, everything after the "--" is ignored, while in 1399, it's all included in the first argument. |
85,181 | <p>This is pretty weird.</p>
<p>I have my Profiler open and it obviously shows that a stored procedure is called. I open the database and the SP list, but the SP doesn't exist. However, there's another SP whose name is the same except it has a prefix 'x'</p>
<p>Is SQL Server 2005 mapping the SP name to a different one for security purposes?</p>
<p>EDIT: I found out it's a Synonym, whatever that is. </p>
| [
{
"answer_id": 85245,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 1,
"selected": false,
"text": "<p>Possibly silly questions, but just in case... have you refreshed the SP list? Have you checked for a stored procedure ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10088/"
] | This is pretty weird.
I have my Profiler open and it obviously shows that a stored procedure is called. I open the database and the SP list, but the SP doesn't exist. However, there's another SP whose name is the same except it has a prefix 'x'
Is SQL Server 2005 mapping the SP name to a different one for security purposes?
EDIT: I found out it's a Synonym, whatever that is. | In general, when you know an object exists because it's been used in a query, and you can't find it in the object tree in Management Studio, you can do this to find it.
```
select *
from sys.objects
where name = 'THE_NAME_YOU_WANT'
```
I just checked, and it works with Synonyms. |
85,183 | <p>I have an object that implements IDisposable that is registered with the Windsor Container and I would like to dispose of it so it's Dispose method is called and next time Resolve is called it fetches a new instance.</p>
<p>Does </p>
<pre><code>container.Release(obj);
</code></pre>
<p>automatically call Dispose() immediately? Or do I need to do</p>
<pre><code>obj.Dispose();
container.Release(obj);
</code></pre>
<p>Couldn't find anything in the documentation on what exactly Release does</p>
<p><strong>EDIT:</strong>
See my answer below for the results of tests I ran. Now the question becomes, how do I force the container to release an instance of a component with a singleton lifecycle? This only needs to be done in one place and writing a custom lifecycle seems far too heavyweight, is there no built in way of doing it?</p>
| [
{
"answer_id": 85498,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 2,
"selected": false,
"text": "<p>It depends on the lifestyle of the component you specified when you added it to the container.</p>\n\n<p>You would ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | I have an object that implements IDisposable that is registered with the Windsor Container and I would like to dispose of it so it's Dispose method is called and next time Resolve is called it fetches a new instance.
Does
```
container.Release(obj);
```
automatically call Dispose() immediately? Or do I need to do
```
obj.Dispose();
container.Release(obj);
```
Couldn't find anything in the documentation on what exactly Release does
**EDIT:**
See my answer below for the results of tests I ran. Now the question becomes, how do I force the container to release an instance of a component with a singleton lifecycle? This only needs to be done in one place and writing a custom lifecycle seems far too heavyweight, is there no built in way of doing it? | This is something I think people aren't really aware of when working with the Windsor container - especially the often ***surprising*** behavior that disposable transient components are held onto by the container for the lifetime of the kernel until it's disposed unless you release them yourself - though it is documented - take a look [here](https://github.com/castleproject/Windsor/blob/master/docs/release-policy.md) - but to quickly quote:
>
> the MicroKernel has a pluggable release policy that can hook up and implement some
> routing to dispose the components. The MicroKernel comes with three IReleasePolicy implementations:
>
>
> * AllComponentsReleasePolicy: track all components to enforce correct disposal upon the MicroKernel instance disposal
> * LifecycledComponentsReleasePolicy: only track components that have a decommission lifecycle associated
> * NoTrackingReleasePolicy: does not perform any tracking
>
>
> You can also implement your own release policy by using the interface IReleasePolicy.
>
>
>
What you might find easier is to change the policy to a **NoTrackingReleasePolicy** and then handle the disposing yourself - this is potentially risky as well, but if your lifestyles are largely transient (or if when your container is disposed your application is about to close anyway) it's probably not a big deal. Remember however that any components which have already been injected with the singleton will hold a reference, so you could end up causing problems trying to "refresh" your singletons - it seems like a bad practice, and I wonder if perhaps you can avoid having to do this in the first place by improving the way your applications put together.
Other approaches are to build a custom lifecycle with it's own decommission implementation (so releasing the singleton would actually dispose of the component, much like the transient lifecycle does).
Alternatively another approach is to have a decorator for your service registered in the container with a singleton lifestyle, but your actual underlying service registered in the container with a transient lifestyle - then when you need to refresh the component just dispose of the transient underlying component held by the decorator and replace it with a freshly resolved instance (resolve it using the components key, rather then the service, to avoid getting the decorator) - this avoids issues with other singleton services (which aren't being "refreshed") from holding onto stale services which have been disposed of making them unusable, but does require a bit of casting etc. to make it work. |
85,190 | <p>Consider:</p>
<pre><code>List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
</code></pre>
<pre><code>for (String item : someList) {
System.out.println(item);
}
</code></pre>
<p>What would the equivalent <code>for</code> loop look like without using the <em>for each</em> syntax?</p>
| [
{
"answer_id": 85206,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 11,
"selected": true,
"text": "<pre><code>for (Iterator<String> i = someIterable.iterator(); i.hasNext();) {\n String item = i.next();\n System... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5074/"
] | Consider:
```
List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
```
```
for (String item : someList) {
System.out.println(item);
}
```
What would the equivalent `for` loop look like without using the *for each* syntax? | ```
for (Iterator<String> i = someIterable.iterator(); i.hasNext();) {
String item = i.next();
System.out.println(item);
}
```
Note that if you need to use `i.remove();` in your loop, or access the actual iterator in some way, you cannot use the `for ( : )` idiom, since the actual iterator is merely inferred.
As was noted by Denis Bueno, this code works for any object that implements the [`Iterable` interface](http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html).
Also, if the right-hand side of the `for (:)` idiom is an `array` rather than an `Iterable` object, the internal code uses an int index counter and checks against `array.length` instead. See the [Java Language Specification](http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2). |
85,282 | <p>In C# you can make a block inside of a method that is not attached to any other statement.</p>
<pre><code> public void TestMethod()
{
{
string x = "test";
string y = x;
{
int z = 42;
int zz = z;
}
}
}
</code></pre>
<p>This code compiles and runs just as if the braces inside the main method weren't there. Also notice the block inside of a block.</p>
<p>Is there a scenario where this would be valuable? I haven't found any yet, but am curious to hear of other people's findings.</p>
| [
{
"answer_id": 85311,
"author": "junkforce",
"author_id": 2153,
"author_profile": "https://Stackoverflow.com/users/2153",
"pm_score": 1,
"selected": false,
"text": "<p>As far as I can see, it'd only be useful from an organizational standpoint. I can't really conceive of any logical value... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3289/"
] | In C# you can make a block inside of a method that is not attached to any other statement.
```
public void TestMethod()
{
{
string x = "test";
string y = x;
{
int z = 42;
int zz = z;
}
}
}
```
This code compiles and runs just as if the braces inside the main method weren't there. Also notice the block inside of a block.
Is there a scenario where this would be valuable? I haven't found any yet, but am curious to hear of other people's findings. | Scope and garbage collection: When you leave the unattached block, any variables declared in it go out of scope. That lets the garbage collector clean up those objects.
[Ray Hayes](https://stackoverflow.com/users/7093/ray-hayes) points out that the .NET garbage collector will not immediately collect the out-of-scope objects, so scoping is the main benefit. |
85,353 | <p>What is the best (or as good as possible) general SVN ignore pattern to use? </p>
<p>There are a number of different IDE, editor, compiler, plug-in, platform, etc. specific files and some file types that "overlap" (i.e. desirable for some types projects and not for others). </p>
<p><strong>There are however, a large number of file types that you just never want included in source control automatically regardless the specifics of your development environment.</strong></p>
<p>The answer to this question would serve as a good starting point for any project - only requiring them to add the few environment specific items they need. It could be adapted for other Version Control Systems (VCS) as well.</p>
| [
{
"answer_id": 85371,
"author": "icelava",
"author_id": 2663,
"author_profile": "https://Stackoverflow.com/users/2663",
"pm_score": 3,
"selected": false,
"text": "<p>Used for my Visual Studio projects</p>\n\n<pre><code>*/bin */obj *.user *.suo\n</code></pre>\n\n<p>You can expand more fil... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2233/"
] | What is the best (or as good as possible) general SVN ignore pattern to use?
There are a number of different IDE, editor, compiler, plug-in, platform, etc. specific files and some file types that "overlap" (i.e. desirable for some types projects and not for others).
**There are however, a large number of file types that you just never want included in source control automatically regardless the specifics of your development environment.**
The answer to this question would serve as a good starting point for any project - only requiring them to add the few environment specific items they need. It could be adapted for other Version Control Systems (VCS) as well. | I'll add my own two cents to this question:
I use the following SVN ignore pattern with TortoiseSVN and Subversion CLI for native C++, C#/VB.NET, and PERL projects on both Windows and Linux platforms. It works well for me!
Formatted for copy and paste:
```
*.o *.lo *.la #*# .*.rej *.rej .*~ *~ .#* .DS_Store thumbs.db Thumbs.db *.bak *.class *.exe *.dll *.mine *.obj *.ncb *.lib *.log *.idb *.pdb *.ilk *.msi* .res *.pch *.suo *.exp *.*~ *.~* ~*.* cvs CVS .CVS .cvs release Release debug Debug ignore Ignore bin Bin obj Obj *.csproj.user *.user *.generated.cs
```
Formatted for readability:
```
*.o *.lo *.la #*# .*.rej *.rej
.*~ *~ .#* .DS_Store thumbs.db
Thumbs.db *.bak *.class *.exe *.dll
*.mine *.obj *.ncb *.lib *.log
*.idb *.pdb *.ilk *.msi* .res *.pch *.suo
*.exp *.*~ *.~* ~*.* cvs CVS .CVS .cvs
release Release debug Debug
ignore Ignore bin Bin obj Obj
*.csproj.user *.user
*.generated.cs
``` |
85,373 | <p>In SQL Server, how do I "floor" a DATETIME to the second/minute/hour/day/year?</p>
<p>Let's say that I have a date of <strong>2008-09-17 12:56:53.430</strong>, then the output of flooring should be:</p>
<ul>
<li>Year: 2008-01-01 00:00:00.000</li>
<li>Month: 2008-09-01 00:00:00.000</li>
<li>Day: 2008-09-17 00:00:00.000</li>
<li>Hour: 2008-09-17 12:00:00.000</li>
<li>Minute: 2008-09-17 12:56:00.000</li>
<li>Second: 2008-09-17 12:56:53.000</li>
</ul>
| [
{
"answer_id": 85379,
"author": "Portman",
"author_id": 1690,
"author_profile": "https://Stackoverflow.com/users/1690",
"pm_score": 8,
"selected": true,
"text": "<p>The key is to use <a href=\"http://msdn.microsoft.com/en-us/library/ms186819.aspx\" rel=\"noreferrer\">DATEADD</a> and <a h... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1690/"
] | In SQL Server, how do I "floor" a DATETIME to the second/minute/hour/day/year?
Let's say that I have a date of **2008-09-17 12:56:53.430**, then the output of flooring should be:
* Year: 2008-01-01 00:00:00.000
* Month: 2008-09-01 00:00:00.000
* Day: 2008-09-17 00:00:00.000
* Hour: 2008-09-17 12:00:00.000
* Minute: 2008-09-17 12:56:00.000
* Second: 2008-09-17 12:56:53.000 | The key is to use [DATEADD](http://msdn.microsoft.com/en-us/library/ms186819.aspx) and [DATEDIFF](http://msdn.microsoft.com/en-us/library/ms189794.aspx) along with the appropriate SQL timespan enumeration.
```
declare @datetime datetime;
set @datetime = getdate();
select @datetime;
select dateadd(year,datediff(year,0,@datetime),0);
select dateadd(month,datediff(month,0,@datetime),0);
select dateadd(day,datediff(day,0,@datetime),0);
select dateadd(hour,datediff(hour,0,@datetime),0);
select dateadd(minute,datediff(minute,0,@datetime),0);
select dateadd(second,datediff(second,'2000-01-01',@datetime),'2000-01-01');
select dateadd(week,datediff(week,0,@datetime),-1); --Beginning of week is Sunday
select dateadd(week,datediff(week,0,@datetime),0); --Beginning of week is Monday
```
Note that when you are flooring by the second, you will often get an arithmetic overflow if you use 0. So pick a known value that is guaranteed to be lower than the datetime you are attempting to floor. |
85,427 | <p>Is the documentation for Rich Edit Controls really as bad (wrong?) as it seems to be? Right now I'm manually calling LoadLibrary("riched20.dll") in order to get a Rich Edit Control to show up. The documentation for Rich Edit poorly demonstrates this in the first code sample for using Rich Edit controls.</p>
<p>It talks about calling InitCommonControlsEx() to add visual styles, but makes no mention of which flags to pass in.</p>
<p>Is there a better way to load a Rich Edit control?</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb787877(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bb787877(VS.85).aspx</a></p>
<p>Here's the only code I could write to make it work:</p>
<pre><code>#include "Richedit.h"
#include "commctrl.h"
INITCOMMONCONTROLSEX icex;
icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
icex.dwICC = ICC_USEREX_CLASSES; //Could be 0xFFFFFFFF and it still wouldn't work
InitCommonControlsEx(&icex); //Does nothing for Rich Edit controls
LoadLibrary("riched20.dll"); //Manually? For real?
hWndRichEdit = CreateWindowEx(
ES_SUNKEN,
RICHEDIT_CLASS,
"",
WS_BORDER | WS_VISIBLE | WS_CHILD,
2, 2, 100, 24,
hWnd, (HMENU) ID_RICH_EDIT, hInst, NULL);
</code></pre>
| [
{
"answer_id": 85497,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 1,
"selected": false,
"text": "<p>Isn't there an import library (maybe riched20.lib) that you can link to. Then you won't have to load it \"manually\" at ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16408/"
] | Is the documentation for Rich Edit Controls really as bad (wrong?) as it seems to be? Right now I'm manually calling LoadLibrary("riched20.dll") in order to get a Rich Edit Control to show up. The documentation for Rich Edit poorly demonstrates this in the first code sample for using Rich Edit controls.
It talks about calling InitCommonControlsEx() to add visual styles, but makes no mention of which flags to pass in.
Is there a better way to load a Rich Edit control?
<http://msdn.microsoft.com/en-us/library/bb787877(VS.85).aspx>
Here's the only code I could write to make it work:
```
#include "Richedit.h"
#include "commctrl.h"
INITCOMMONCONTROLSEX icex;
icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
icex.dwICC = ICC_USEREX_CLASSES; //Could be 0xFFFFFFFF and it still wouldn't work
InitCommonControlsEx(&icex); //Does nothing for Rich Edit controls
LoadLibrary("riched20.dll"); //Manually? For real?
hWndRichEdit = CreateWindowEx(
ES_SUNKEN,
RICHEDIT_CLASS,
"",
WS_BORDER | WS_VISIBLE | WS_CHILD,
2, 2, 100, 24,
hWnd, (HMENU) ID_RICH_EDIT, hInst, NULL);
``` | Using MFC, RichEdit controls just work.
Loading with InitCommonControlsEx() - ICC\_USEREX\_CLASSES doesn't load RichEdit AFAIK, you don't need it as it only does the 'standard' common controls, which don't include richedit. Apparently you only need to call this to enable 'visual styles' in Windows, not to get RichEdits working.
If you're using 2008, you want to include Msftedit.dll and use the MSFTEDIT\_CLASS instead (MS are rubbish for backward compatibilty sometimes).
The [docs](http://msdn.microsoft.com/en-us/library/bb787877(VS.85).aspx#creating_re_control) do suggest you're doing it right for Win32 programming. |
85,450 | <p>I have a SQL Server 2005 machine with a JDE DB2 set up as a linked server.</p>
<p>For some reason the performance of any queries from this box to the db2 box are horrible.</p>
<p>For example. The following takes 7 mins to run from Management Studio</p>
<pre><code>SELECT *
FROM F42119
WHERE SDUPMJ >= 107256
</code></pre>
<p>Whereas it takes seconds to run in iSeries Navigator</p>
<p>Any thoughts? I'm assuming some config issue.</p>
| [
{
"answer_id": 88059,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 0,
"selected": false,
"text": "<p>My first thought would go to the drivers. Years ago I had to link DB2 to SQL Server 2000 and it was extremely difficult to... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a SQL Server 2005 machine with a JDE DB2 set up as a linked server.
For some reason the performance of any queries from this box to the db2 box are horrible.
For example. The following takes 7 mins to run from Management Studio
```
SELECT *
FROM F42119
WHERE SDUPMJ >= 107256
```
Whereas it takes seconds to run in iSeries Navigator
Any thoughts? I'm assuming some config issue. | In certain searches SQL Server will decide to pull the entire table down to itself and sort and search the data within SQL Server instead of sending the query to the remote server. This is usually a problem with collation settings.
Make sure the provider has the following options set:
Data Access,
Collation Compatible,
Use Remote Collation
Then create a new Linked Server using the provider and select the following provider options
Dynamic Parameters,
Nested Queries,
Allow In Process
After setting the options change the query slightly to get a new query plan. |
85,451 | <p>Which is better to use for timing in Python? time.clock() or time.time()? Which one provides more accuracy?</p>
<p>for example:</p>
<pre><code>start = time.clock()
... do something
elapsed = (time.clock() - start)
</code></pre>
<p>vs.</p>
<pre><code>start = time.time()
... do something
elapsed = (time.time() - start)
</code></pre>
| [
{
"answer_id": 85480,
"author": "user15910",
"author_id": 15910,
"author_profile": "https://Stackoverflow.com/users/15910",
"pm_score": 4,
"selected": false,
"text": "<p>Depends on what you care about. If you mean WALL TIME (as in, the time on the clock on your wall), time.clock() provid... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16148/"
] | Which is better to use for timing in Python? time.clock() or time.time()? Which one provides more accuracy?
for example:
```
start = time.clock()
... do something
elapsed = (time.clock() - start)
```
vs.
```
start = time.time()
... do something
elapsed = (time.time() - start)
``` | As of 3.3, [*time.clock()* is deprecated](https://docs.python.org/3/library/time.html#time.clock), and it's suggested to use **[time.process\_time()](https://docs.python.org/3/library/time.html#time.process_time)** or **[time.perf\_counter()](https://docs.python.org/3/library/time.html#time.perf_counter)** instead.
Previously in 2.7, according to the **[time module docs](https://docs.python.org/2.7/library/time.html#time.clock)**:
>
> **time.clock()**
>
>
> On Unix, return the current processor time as a floating point number
> expressed in seconds. The precision, and in fact the very definition
> of the meaning of “processor time”, depends on that of the C function
> of the same name, but in any case, **this is the function to use for
> benchmarking Python or timing algorithms.**
>
>
> On Windows, this function returns wall-clock seconds elapsed since the
> first call to this function, as a floating point number, based on the
> Win32 function QueryPerformanceCounter(). The resolution is typically
> better than one microsecond.
>
>
>
Additionally, there is the [timeit](https://docs.python.org/2/library/timeit.html) module for benchmarking code snippets. |
85,457 | <p>I am trying to inherit from my generated datacontext in LinqToSQL - something like this </p>
<pre><code>public class myContext : dbDataContext {
public System.Data.Linq.Table<User>() Users {
return (from x in base.Users() where x.DeletedOn.HasValue == false select x);
}
}
</code></pre>
<p>But my Linq statement returns IQueryable which cannot cast to Table - does anyone know a way to limit the contents of a Linq.Table - I am trying to be certain that anywhere my Users table is accessed, it doesn't return those marked deleted. Perhaps I am going about this all wrong - any suggestions would be greatly appreciated.</p>
<p>Hal</p>
| [
{
"answer_id": 85507,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 1,
"selected": false,
"text": "<p>You could use discriminator column inheritance on the table, ie. a DeletedUsers table and ActiveUsers table where th... | 2008/09/17 | [
"https://Stackoverflow.com/questions/85457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16416/"
] | I am trying to inherit from my generated datacontext in LinqToSQL - something like this
```
public class myContext : dbDataContext {
public System.Data.Linq.Table<User>() Users {
return (from x in base.Users() where x.DeletedOn.HasValue == false select x);
}
}
```
But my Linq statement returns IQueryable which cannot cast to Table - does anyone know a way to limit the contents of a Linq.Table - I am trying to be certain that anywhere my Users table is accessed, it doesn't return those marked deleted. Perhaps I am going about this all wrong - any suggestions would be greatly appreciated.
Hal | Another approach would to be use views..
```
CREATE VIEW ActiveUsers as SELECT * FROM Users WHERE IsDeleted = 0
```
As far as linq to sql is concerned, that is just the same as a table. For any table that you needed the DeletedOn filtering, just create a view that uses the filter and use that in place of the table in your data context. |