qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
95,886
|
<p>I'm writing a report view of an audit trail, and I need to display this in a .jsp. What's the "best" way to get the data from the database to the screen?</p>
<p>We're using Spring for dependency injection, Data Access Objects, and Hibernate.
I can use hibernate or straight jdbc for this report.</p>
<p>If I load all the records into memory I run out of memory.</p>
<p>Any ideas that don't involve running the query in the jsp?</p>
|
[
{
"answer_id": 98137,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 2,
"selected": false,
"text": "org.displaytag.pagination.PaginatedList"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/95886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
] |
95,895
|
<p>I have two <code>DateTime</code> objects: <code>StartDate</code> and <code>EndDate</code>. I want to make sure <code>StartDate</code> is before <code>EndDate</code>. How is this done in C#?</p>
|
[
{
"answer_id": 95921,
"author": "Ryan Rinaldi",
"author_id": 2278,
"author_profile": "https://Stackoverflow.com/users/2278",
"pm_score": 5,
"selected": false,
"text": "if(StartDate < EndDate)\n{}\n"
},
{
"answer_id": 95926,
"author": "Rob Gray",
"author_id": 5691,
"author_profile": "https://Stackoverflow.com/users/5691",
"pm_score": 3,
"selected": false,
"text": "StartDate < EndDate\n"
},
{
"answer_id": 95928,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 9,
"selected": true,
"text": "if (StartDate < EndDate)\n // code\n if (StartDate.Date < EndDate.Date)\n // code\n"
},
{
"answer_id": 95933,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 5,
"selected": false,
"text": "DateTime d1 = new DateTime(2008, 1, 1);\nDateTime d2 = new DateTime(2008, 1, 2);\nif (d1 < d2) { ...\n"
},
{
"answer_id": 95934,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 3,
"selected": false,
"text": "if (StartDate>=EndDate)\n{\n throw new InvalidOperationException(\"Ack! StartDate is not before EndDate!\");\n}\n"
},
{
"answer_id": 95936,
"author": "Loren Segal",
"author_id": 6436,
"author_profile": "https://Stackoverflow.com/users/6436",
"pm_score": 2,
"selected": false,
"text": " if (new DateTime(5000) > new DateTime(1000))\n {\n Console.WriteLine(\"i win\");\n }\n"
},
{
"answer_id": 10873953,
"author": "John J Smith",
"author_id": 367698,
"author_profile": "https://Stackoverflow.com/users/367698",
"pm_score": 2,
"selected": false,
"text": " public DateTime Start\n {\n get { return _start; }\n set\n {\n if (_end.Equals(DateTime.MinValue))\n {\n _start = value;\n }\n else if (value.Date < _end.Date)\n {\n _start = value;\n }\n else\n {\n throw new ArgumentException(\"Start date must be before the End date.\");\n }\n }\n }\n\n\n public DateTime End\n {\n get { return _end; }\n set\n {\n if (_start.Equals(DateTime.MinValue))\n {\n _end = value;\n }\n else if (value.Date > _start.Date)\n {\n _end = value;\n }\n else\n {\n throw new ArgumentException(\"End date must be after the Start date.\");\n }\n }\n }\n"
},
{
"answer_id": 32119337,
"author": "rottenbanana",
"author_id": 5006471,
"author_profile": "https://Stackoverflow.com/users/5006471",
"pm_score": 3,
"selected": false,
"text": "IComparable public static class BetweenExtension\n {\n public static bool IsBetween<T>(this T value, T min, T max) where T : IComparable\n {\n return (min.CompareTo(value) <= 0) && (value.CompareTo(max) <= 0);\n }\n }\n IComparable DateTime start = new DateTime(2015,1,1);\nDateTime end = new DateTime(2015,12,31);\nDateTime now = new DateTime(2015,8,20);\n\nif(now.IsBetween(start, end))\n{\n //Your code here\n}\n"
},
{
"answer_id": 43349468,
"author": "sapbucket",
"author_id": 855203,
"author_profile": "https://Stackoverflow.com/users/855203",
"pm_score": 0,
"selected": false,
"text": " [Test]\n public void ConvertToDateWillHaveTwoDatesEqual()\n {\n DateTime d1 = new DateTime(2008, 1, 1);\n DateTime d2 = new DateTime(2008, 1, 2);\n Assert.IsTrue(d1 < d2);\n\n DateTime d3 = new DateTime(2008, 1, 1,7,0,0);\n DateTime d4 = new DateTime(2008, 1, 1,10,0,0);\n Assert.IsTrue(d3 < d4);\n Assert.IsFalse(d3.Date < d4.Date);\n }\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/95895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
95,909
|
<p>First let me say that I really feel directionless on this question. I am using windows integrated security, and I can use vb.net to look up information about a user from AD. I also have other information about users I can look up from a MS SQL 2005 server by getting the logon identity name.</p>
<p>What I would like to do is display information about all the users actively viewing the web page to any one of the users viewing the web page. The information comes both from AD and SQL, and I have no problem retrieving it.</p>
<p>My route so far has been using SQL to store when the user first loads the page. I am stuck not knowing how to show when the user <em>leaves</em> the page. I tried using an ajax timer to update a timestamp for the user's visit every one second that also triggers the table to change the status to inactive of any record that has not been updated in 5 seconds. This works with only a few users, but I find when I have more than a few people viewing the page the 1 second update is not reliable. I also seem to have problems when the user minimizes the page. This sometimes stops the updates from the ajax timer and kicks the user off the list while they are still viewing the page.</p>
<p>This feature is not important to the function of the site it would be on, so I'd given up on it over a year ago. Since then it has really been a pain to me that I can not figure a way to make this work. My searches have led me down many fruitless paths, so I really will appreciate any help that can be offered even if it's only a lead in the correct direction.</p>
|
[
{
"answer_id": 95965,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 1,
"selected": false,
"text": "threshold threshold"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/95909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16771/"
] |
95,910
|
<p>Given this class</p>
<pre><code>class Foo
{
// Want to find _bar with reflection
[SomeAttribute]
private string _bar;
public string BigBar
{
get { return this._bar; }
}
}
</code></pre>
<p>I want to find the private item _bar that I will mark with a attribute. Is that possible? </p>
<p>I have done this with properties where I have looked for an attribute, but never a private member field.</p>
<p>What are the binding flags that I need to set to get the private fields?</p>
|
[
{
"answer_id": 95948,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 4,
"selected": false,
"text": "typeof(MyType).GetField(\"fieldName\", BindingFlags.NonPublic | BindingFlags.Instance)\n"
},
{
"answer_id": 95964,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": 7,
"selected": false,
"text": "FieldInfo fi = typeof(Foo).GetField(\"_bar\", BindingFlags.NonPublic | BindingFlags.Instance);\nif (fi.GetCustomAttributes(typeof(SomeAttribute)) != null)\n ...\n"
},
{
"answer_id": 95973,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 9,
"selected": true,
"text": "BindingFlags.NonPublic BindingFlags.Instance FieldInfo[] fields = myType.GetFields(\n BindingFlags.NonPublic | \n BindingFlags.Instance);\n"
},
{
"answer_id": 5499329,
"author": "Gunner",
"author_id": 45279,
"author_profile": "https://Stackoverflow.com/users/45279",
"pm_score": 2,
"selected": false,
"text": "typeof(Foo).GetFields(BindingFlags.NonPublic | BindingFlags.Instance)\n.Where(x => x.GetCustomAttributes(typeof(SomeAttribute), false).Length > 0);\n"
},
{
"answer_id": 8442803,
"author": "Suriya",
"author_id": 332437,
"author_profile": "https://Stackoverflow.com/users/332437",
"pm_score": 6,
"selected": false,
"text": "var _barVariable = typeof(Foo).GetField(\"_bar\", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectForFooClass);\n typeof(Foo).GetField(\"_bar\", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectForFoocClass, \"newValue\");\n"
},
{
"answer_id": 13539377,
"author": "sa_ddam213",
"author_id": 1849109,
"author_profile": "https://Stackoverflow.com/users/1849109",
"pm_score": 3,
"selected": false,
"text": "if (typeof(Foo).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Any(c => c.GetCustomAttributes(typeof(SomeAttribute), false).Any()))\n{ \n // do stuff\n}\n"
},
{
"answer_id": 23953996,
"author": "epsi1on",
"author_id": 1106889,
"author_profile": "https://Stackoverflow.com/users/1106889",
"pm_score": 3,
"selected": false,
"text": " public class Foo\n {\n private int Bar = 5;\n }\n\n var targetObject = new Foo();\n var barValue = targetObject.GetMemberValue(\"Bar\");//Result is 5\n targetObject.SetMemberValue(\"Bar\", 10);//Sets Bar to 10\n /// <summary>\n /// Extensions methos for using reflection to get / set member values\n /// </summary>\n public static class ReflectionExtensions\n {\n /// <summary>\n /// Gets the public or private member using reflection.\n /// </summary>\n /// <param name=\"obj\">The source target.</param>\n /// <param name=\"memberName\">Name of the field or property.</param>\n /// <returns>the value of member</returns>\n public static object GetMemberValue(this object obj, string memberName)\n {\n var memInf = GetMemberInfo(obj, memberName);\n\n if (memInf == null)\n throw new System.Exception(\"memberName\");\n\n if (memInf is System.Reflection.PropertyInfo)\n return memInf.As<System.Reflection.PropertyInfo>().GetValue(obj, null);\n\n if (memInf is System.Reflection.FieldInfo)\n return memInf.As<System.Reflection.FieldInfo>().GetValue(obj);\n\n throw new System.Exception();\n }\n\n /// <summary>\n /// Gets the public or private member using reflection.\n /// </summary>\n /// <param name=\"obj\">The target object.</param>\n /// <param name=\"memberName\">Name of the field or property.</param>\n /// <returns>Old Value</returns>\n public static object SetMemberValue(this object obj, string memberName, object newValue)\n {\n var memInf = GetMemberInfo(obj, memberName);\n\n\n if (memInf == null)\n throw new System.Exception(\"memberName\");\n\n var oldValue = obj.GetMemberValue(memberName);\n\n if (memInf is System.Reflection.PropertyInfo)\n memInf.As<System.Reflection.PropertyInfo>().SetValue(obj, newValue, null);\n else if (memInf is System.Reflection.FieldInfo)\n memInf.As<System.Reflection.FieldInfo>().SetValue(obj, newValue);\n else\n throw new System.Exception();\n\n return oldValue;\n }\n\n /// <summary>\n /// Gets the member info\n /// </summary>\n /// <param name=\"obj\">source object</param>\n /// <param name=\"memberName\">name of member</param>\n /// <returns>instanse of MemberInfo corresponsing to member</returns>\n private static System.Reflection.MemberInfo GetMemberInfo(object obj, string memberName)\n {\n var prps = new System.Collections.Generic.List<System.Reflection.PropertyInfo>();\n\n prps.Add(obj.GetType().GetProperty(memberName,\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance |\n System.Reflection.BindingFlags.FlattenHierarchy));\n prps = System.Linq.Enumerable.ToList(System.Linq.Enumerable.Where( prps,i => !ReferenceEquals(i, null)));\n if (prps.Count != 0)\n return prps[0];\n\n var flds = new System.Collections.Generic.List<System.Reflection.FieldInfo>();\n\n flds.Add(obj.GetType().GetField(memberName,\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance |\n System.Reflection.BindingFlags.FlattenHierarchy));\n\n //to add more types of properties\n\n flds = System.Linq.Enumerable.ToList(System.Linq.Enumerable.Where(flds, i => !ReferenceEquals(i, null)));\n\n if (flds.Count != 0)\n return flds[0];\n\n return null;\n }\n\n [System.Diagnostics.DebuggerHidden]\n private static T As<T>(this object obj)\n {\n return (T)obj;\n }\n }\n"
},
{
"answer_id": 46488844,
"author": "Bruno Zell",
"author_id": 5185376,
"author_profile": "https://Stackoverflow.com/users/5185376",
"pm_score": 5,
"selected": false,
"text": "Foo foo = new Foo();\nstring c = foo.GetFieldValue<string>(\"_bar\");\n public static class ReflectionExtensions {\n public static T GetFieldValue<T>(this object obj, string name) {\n // Set the flags so that private and public fields from instances will be found\n var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n var field = obj.GetType().GetField(name, bindingFlags);\n return (T)field?.GetValue(obj);\n }\n}\n"
},
{
"answer_id": 72934049,
"author": "Ashwin Rajaram",
"author_id": 14238575,
"author_profile": "https://Stackoverflow.com/users/14238575",
"pm_score": 0,
"selected": false,
"text": "var foo = new Foo();\nvar fooFields = foo.GetType().GetRuntimeFields()\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/95910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
] |
95,912
|
<p>My Vista application needs to know whether the user has launched it "as administrator" (elevated) or as a standard user (non-elevated). How can I detect that at run time? </p>
|
[
{
"answer_id": 95918,
"author": "Andrei Belogortseff",
"author_id": 17037,
"author_profile": "https://Stackoverflow.com/users/17037",
"pm_score": 5,
"selected": true,
"text": "HRESULT GetElevationType( __out TOKEN_ELEVATION_TYPE * ptet );\n\n/*\nParameters:\n\nptet\n [out] Pointer to a variable that receives the elevation type of the current process.\n\n The possible values are:\n\n TokenElevationTypeDefault - This value indicates that either UAC is disabled, \n or the process is started by a standard user (not a member of the Administrators group).\n\n The following two values can be returned only if both the UAC is enabled\n and the user is a member of the Administrator's group:\n\n TokenElevationTypeFull - the process is running elevated. \n\n TokenElevationTypeLimited - the process is not running elevated.\n\nReturn Values:\n\n If the function succeeds, the return value is S_OK. \n If the function fails, the return value is E_FAIL. To get extended error information, call GetLastError().\n\nImplementation:\n*/\n\nHRESULT GetElevationType( __out TOKEN_ELEVATION_TYPE * ptet )\n{\n if ( !IsVista() )\n return E_FAIL;\n\n HRESULT hResult = E_FAIL; // assume an error occurred\n HANDLE hToken = NULL;\n\n if ( !::OpenProcessToken( \n ::GetCurrentProcess(), \n TOKEN_QUERY, \n &hToken ) )\n {\n return hResult;\n }\n\n DWORD dwReturnLength = 0;\n\n if ( ::GetTokenInformation(\n hToken,\n TokenElevationType,\n ptet,\n sizeof( *ptet ),\n &dwReturnLength ) )\n {\n ASSERT( dwReturnLength == sizeof( *ptet ) );\n hResult = S_OK;\n }\n\n ::CloseHandle( hToken );\n\n return hResult;\n}\n"
},
{
"answer_id": 114696,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 5,
"selected": false,
"text": "private bool IsAdministrator\n{\n get\n {\n WindowsIdentity wi = WindowsIdentity.GetCurrent();\n WindowsPrincipal wp = new WindowsPrincipal(wi);\n\n return wp.IsInRole(WindowsBuiltInRole.Administrator);\n }\n}\n"
},
{
"answer_id": 21296802,
"author": "Guy Glirbas",
"author_id": 2137952,
"author_profile": "https://Stackoverflow.com/users/2137952",
"pm_score": 2,
"selected": false,
"text": "function TMyAppInfo.RunningAsAdmin: boolean;\nvar\n hToken, hProcess: THandle;\n pTokenInformation: pointer;\n ReturnLength: DWord;\n TokenInformation: TTokenElevation;\nbegin\n hProcess := GetCurrentProcess;\n try\n if OpenProcessToken(hProcess, TOKEN_QUERY, hToken) then try\n TokenInformation.TokenIsElevated := 0;\n pTokenInformation := @TokenInformation;\n GetTokenInformation(hToken, TokenElevation, pTokenInformation, sizeof(TokenInformation), ReturnLength);\n result := (TokenInformation.TokenIsElevated > 0);\n finally\n CloseHandle(hToken);\n end;\n except\n result := false;\n end;\nend;\n"
},
{
"answer_id": 27988836,
"author": "wqw",
"author_id": 40691,
"author_profile": "https://Stackoverflow.com/users/40691",
"pm_score": 1,
"selected": false,
"text": "Option Explicit\n\n'--- for OpenProcessToken\nPrivate Const TOKEN_QUERY As Long = &H8\nPrivate Const TokenElevation As Long = 20\n\nPrivate Declare Function GetCurrentProcess Lib \"kernel32\" () As Long\nPrivate Declare Function OpenProcessToken Lib \"advapi32\" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, TokenHandle As Long) As Long\nPrivate Declare Function GetTokenInformation Lib \"advapi32\" (ByVal TokenHandle As Long, ByVal TokenInformationClass As Long, TokenInformation As Any, ByVal TokenInformationLength As Long, ReturnLength As Long) As Long\nPrivate Declare Function CloseHandle Lib \"kernel32\" (ByVal hObject As Long) As Long\n\n\nPublic Function IsElevated(Optional ByVal hProcess As Long) As Boolean\n Dim hToken As Long\n Dim dwIsElevated As Long\n Dim dwLength As Long\n\n If hProcess = 0 Then\n hProcess = GetCurrentProcess()\n End If\n If OpenProcessToken(hProcess, TOKEN_QUERY, hToken) <> 0 Then\n If GetTokenInformation(hToken, TokenElevation, dwIsElevated, 4, dwLength) <> 0 Then\n IsElevated = (dwIsElevated <> 0)\n End If\n Call CloseHandle(hToken)\n End If\nEnd Function\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/95912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17037/"
] |
95,950
|
<p>On my desktop I have written a small Pylons app that connects to Oracle. I'm now trying to deploy it to my server which is running Win2k3 x64. (My desktop is 32-bit XP) The Oracle installation on the server is also 64-bit.</p>
<p>I was getting errors about loading the OCI dll, so I installed the 32 bit client into <code>C:\oracle32</code>.</p>
<p>If I add this to the <code>PATH</code> environment variable, it works great. But I also want to run the Pylons app as a service (<a href="http://wiki.pylonshq.com/display/pylonscookbook/How+to+run+Pylons+as+a+Windows+service" rel="nofollow noreferrer">using this recipe</a>) and don't want to put this 32-bit library on the path for all other applications. </p>
<p>I tried using <code>sys.path.append("C:\\oracle32\\bin")</code> but that doesn't seem to work.</p>
|
[
{
"answer_id": 96016,
"author": "Moe",
"author_id": 3051,
"author_profile": "https://Stackoverflow.com/users/3051",
"pm_score": 2,
"selected": false,
"text": "import os\nos.environ['PATH'] += os.pathsep + \"C:\\\\oracle32\\\\bin\"\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/95950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1566663/"
] |
95,956
|
<p>using C++Builder 2007, the FindFirstFile and FindNextFile functions doesn't seem to be able to find some files on 64-bit versions of Vista and XP. My test application is 32-bit.</p>
<p>If I use them to iterate through the folder C:\Windows\System32\Drivers they only find a handful of files although there are 185 when I issue a dir command in a command prompt. Using the same example code lists all files fine on a 32-bit version of XP.</p>
<p>Here is a small example program:</p>
<pre><code>int main(int argc, char* argv[])
{
HANDLE hFind;
WIN32_FIND_DATA FindData;
int ErrorCode;
bool cont = true;
cout << "FindFirst/Next demo." << endl << endl;
hFind = FindFirstFile("*.*", &FindData);
if(hFind == INVALID_HANDLE_VALUE)
{
ErrorCode = GetLastError();
if (ErrorCode == ERROR_FILE_NOT_FOUND)
{
cout << "There are no files matching that path/mask\n" << endl;
}
else
{
cout << "FindFirstFile() returned error code " << ErrorCode << endl;
}
cont = false;
}
else
{
cout << FindData.cFileName << endl;
}
if (cont)
{
while (FindNextFile(hFind, &FindData))
{
cout << FindData.cFileName << endl;
}
ErrorCode = GetLastError();
if (ErrorCode == ERROR_NO_MORE_FILES)
{
cout << endl << "All files logged." << endl;
}
else
{
cout << "FindNextFile() returned error code " << ErrorCode << endl;
}
if (!FindClose(hFind))
{
ErrorCode = GetLastError();
cout << "FindClose() returned error code " << ErrorCode << endl;
}
}
return 0;
}
</code></pre>
<p>Running it in the C:\Windows\System32\Drivers folder on 64-bit XP returns this:</p>
<pre><code>C:\WINDOWS\system32\drivers>t:\Project1.exe
FindFirst/Next demo.
.
..
AsIO.sys
ASUSHWIO.SYS
hfile.txt
raspti.zip
stcp2v30.sys
truecrypt.sys
All files logged.
</code></pre>
<p>A dir command on the same system returns this:</p>
<pre><code>C:\WINDOWS\system32\drivers>dir/p
Volume in drive C has no label.
Volume Serial Number is E8E1-0F1E
Directory of C:\WINDOWS\system32\drivers
16-09-2008 23:12 <DIR> .
16-09-2008 23:12 <DIR> ..
17-02-2007 00:02 80.384 1394bus.sys
16-09-2008 23:12 9.453 a.txt
17-02-2007 00:02 322.560 acpi.sys
29-03-2006 14:00 18.432 acpiec.sys
24-03-2005 17:11 188.928 aec.sys
21-06-2008 15:07 291.840 afd.sys
29-03-2006 14:00 51.712 amdk8.sys
17-02-2007 00:03 111.104 arp1394.sys
08-05-2006 20:19 8.192 ASACPI.sys
29-03-2006 14:00 25.088 asyncmac.sys
17-02-2007 00:03 150.016 atapi.sys
17-02-2007 00:03 106.496 atmarpc.sys
29-03-2006 14:00 57.344 atmepvc.sys
17-02-2007 00:03 91.648 atmlane.sys
17-02-2007 00:03 569.856 atmuni.sys
24-03-2005 19:12 5.632 audstub.sys
29-03-2006 14:00 6.144 beep.sys
Press any key to continue . . .
etc.
</code></pre>
<p>I'm puzzled. What is the reason for this?</p>
<p>Brian</p>
|
[
{
"answer_id": 96179,
"author": "JubbaJubba",
"author_id": 18145,
"author_profile": "https://Stackoverflow.com/users/18145",
"pm_score": 1,
"selected": false,
"text": "%windir%\\system32\\catroot\n%windir%\\system32\\catroot2\n%windir%\\system32\\drivers\\etc\n%windir%\\system32\\logfiles\n%windir%\\system32\\spool \n %windir%\\SysWOW64\\catroot\n%windir%\\SysWOW64\\catroot2\n%windir%\\SysWOW64\\drivers\\etc\n%windir%\\SysWOW64\\logfiles\n%windir%\\SysWOW64\\spool \n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/95956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18145/"
] |
95,967
|
<p>Simple question, how do you list the primary key of a table with T-SQL? I know how to get indexes on a table, but can't remember how to get the PK.</p>
|
[
{
"answer_id": 95982,
"author": "boes",
"author_id": 17746,
"author_profile": "https://Stackoverflow.com/users/17746",
"pm_score": 2,
"selected": false,
"text": "sp_help execute sp_help table_name\n"
},
{
"answer_id": 96049,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 8,
"selected": true,
"text": "SELECT Col.Column_Name from \n INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, \n INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col \nWHERE \n Col.Constraint_Name = Tab.Constraint_Name\n AND Col.Table_Name = Tab.Table_Name\n AND Tab.Constraint_Type = 'PRIMARY KEY'\n AND Col.Table_Name = '<your table name>'\n"
},
{
"answer_id": 96072,
"author": "Dwight T",
"author_id": 2526,
"author_profile": "https://Stackoverflow.com/users/2526",
"pm_score": 3,
"selected": false,
"text": "-- List all tables primary keys\nSELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS\nWHERE CONSTRAINT_TYPE = 'PRIMARY KEY'\n"
},
{
"answer_id": 96079,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 0,
"selected": false,
"text": "SELECT\n CONSTRAINT_CATALOG AS DataBaseName,\n CONSTRAINT_SCHEMA AS SchemaName,\n TABLE_NAME AS TableName,\n CONSTRAINT_Name AS PrimaryKey\nFROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS \nWHERE CONSTRAINT_TYPE = 'Primary Key' and Table_Name = 'YourTable'\n"
},
{
"answer_id": 96366,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "SELECT t.name AS 'table', i.name AS 'index', it.xtype,\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 1 \n AND k.id = t.id)\n AS 'column1',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 2 \n AND k.id = t.id)\n AS 'column2',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 3\n AND k.id = t.id)\n AS 'column3',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 4\n AND k.id = t.id)\n AS 'column4',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 5\n AND k.id = t.id)\n AS 'column5',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 6\n AND k.id = t.id)\n AS 'column6',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 7\n AND k.id = t.id)\n AS 'column7',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 8 \n AND k.id = t.id)\n AS 'column8',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 9 \n AND k.id = t.id)\n AS 'column9',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 10\n AND k.id = t.id)\n AS 'column10',\n\nFROM sysobjects t\n INNER JOIN sysindexes i ON i.id = t.id \n INNER JOIN sysobjects it ON it.parent_obj = t.id AND it.name = i.name\n\nWHERE it.xtype = 'PK'\nORDER BY t.name, i.name\n"
},
{
"answer_id": 179210,
"author": "user12861",
"author_id": 12861,
"author_profile": "https://Stackoverflow.com/users/12861",
"pm_score": 3,
"selected": false,
"text": "exec sp_pkeys 'table'\n"
},
{
"answer_id": 2098765,
"author": "MartinC",
"author_id": 171240,
"author_profile": "https://Stackoverflow.com/users/171240",
"pm_score": 1,
"selected": false,
"text": "SELECT A.Name,Col.Column_Name from \n INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, \n INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col ,\n (select NAME from dbo.sysobjects where xtype='u') AS A\nWHERE \n Col.Constraint_Name = Tab.Constraint_Name\n AND Col.Table_Name = Tab.Table_Name\n AND Constraint_Type = 'PRIMARY KEY '\n AND Col.Table_Name = A.Name\n"
},
{
"answer_id": 7551259,
"author": "Manjunath C Bhat",
"author_id": 964486,
"author_profile": "https://Stackoverflow.com/users/964486",
"pm_score": 1,
"selected": false,
"text": "SELECT A.TABLE_NAME as [Table_name], A.CONSTRAINT_NAME as [Primary_Key]\n FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS A, INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE B\n WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND A.CONSTRAINT_NAME = B.CONSTRAINT_NAME\n"
},
{
"answer_id": 7551392,
"author": "Manjunath C Bhat",
"author_id": 964486,
"author_profile": "https://Stackoverflow.com/users/964486",
"pm_score": 2,
"selected": false,
"text": "SELECT TC.TABLE_NAME as [Table_name], TC.CONSTRAINT_NAME as [Primary_Key]\n FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC\n INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CCU\n ON TC.CONSTRAINT_NAME = CCU.CONSTRAINT_NAME\n WHERE TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND\n TC.TABLE_NAME IN\n (SELECT [NAME] AS [TABLE_NAME] FROM SYS.OBJECTS \n WHERE TYPE = 'U')\n"
},
{
"answer_id": 15797448,
"author": "aked",
"author_id": 1060656,
"author_profile": "https://Stackoverflow.com/users/1060656",
"pm_score": 2,
"selected": false,
"text": "/* CAST IS DONE , SO THAT OUTPUT INTEXT FILE REMAINS WITH SCREEN LIMIT*/\nWITH ALL_KEYS_IN_TABLE (CONSTRAINT_NAME,CONSTRAINT_TYPE,PARENT_TABLE_NAME,PARENT_COL_NAME,PARENT_COL_NAME_DATA_TYPE,REFERENCE_TABLE_NAME,REFERENCE_COL_NAME) \nAS\n(\nSELECT CONSTRAINT_NAME= CAST (PKnUKEY.name AS VARCHAR(30)) ,\n CONSTRAINT_TYPE=CAST (PKnUKEY.type_desc AS VARCHAR(30)) ,\n PARENT_TABLE_NAME=CAST (PKnUTable.name AS VARCHAR(30)) ,\n PARENT_COL_NAME=CAST ( PKnUKEYCol.name AS VARCHAR(30)) ,\n PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE, \n REFERENCE_TABLE_NAME='' ,\n REFERENCE_COL_NAME='' \n\nFROM sys.key_constraints as PKnUKEY\n INNER JOIN sys.tables as PKnUTable\n ON PKnUTable.object_id = PKnUKEY.parent_object_id\n INNER JOIN sys.index_columns as PKnUColIdx\n ON PKnUColIdx.object_id = PKnUTable.object_id\n AND PKnUColIdx.index_id = PKnUKEY.unique_index_id\n INNER JOIN sys.columns as PKnUKEYCol\n ON PKnUKEYCol.object_id = PKnUTable.object_id\n AND PKnUKEYCol.column_id = PKnUColIdx.column_id\n INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl\n ON oParentColDtl.TABLE_NAME=PKnUTable.name\n AND oParentColDtl.COLUMN_NAME=PKnUKEYCol.name\nUNION ALL\nSELECT CONSTRAINT_NAME= CAST (oConstraint.name AS VARCHAR(30)) ,\n CONSTRAINT_TYPE='FK',\n PARENT_TABLE_NAME=CAST (oParent.name AS VARCHAR(30)) ,\n PARENT_COL_NAME=CAST ( oParentCol.name AS VARCHAR(30)) ,\n PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE, \n REFERENCE_TABLE_NAME=CAST ( oReference.name AS VARCHAR(30)) ,\n REFERENCE_COL_NAME=CAST (oReferenceCol.name AS VARCHAR(30)) \nFROM sys.foreign_key_columns FKC\n INNER JOIN sys.sysobjects oConstraint\n ON FKC.constraint_object_id=oConstraint.id \n INNER JOIN sys.sysobjects oParent\n ON FKC.parent_object_id=oParent.id\n INNER JOIN sys.all_columns oParentCol\n ON FKC.parent_object_id=oParentCol.object_id /* ID of the object to which this column belongs.*/\n AND FKC.parent_column_id=oParentCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/\n INNER JOIN sys.sysobjects oReference\n ON FKC.referenced_object_id=oReference.id\n INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl\n ON oParentColDtl.TABLE_NAME=oParent.name\n AND oParentColDtl.COLUMN_NAME=oParentCol.name\n INNER JOIN sys.all_columns oReferenceCol\n ON FKC.referenced_object_id=oReferenceCol.object_id /* ID of the object to which this column belongs.*/\n AND FKC.referenced_column_id=oReferenceCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/\n\n)\n\nselect * from ALL_KEYS_IN_TABLE\nwhere \n PARENT_TABLE_NAME in ('YOUR_TABLE_NAME') \n or REFERENCE_TABLE_NAME in ('YOUR_TABLE_NAME')\nORDER BY PARENT_TABLE_NAME,CONSTRAINT_NAME;\n"
},
{
"answer_id": 24045346,
"author": "KyleMit",
"author_id": 1366033,
"author_profile": "https://Stackoverflow.com/users/1366033",
"pm_score": 3,
"selected": false,
"text": "SELECT COLUMN_NAME\nFROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE\nWHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA+'.'+CONSTRAINT_NAME), 'IsPrimaryKey') = 1\n AND TABLE_NAME = '<your table name>'\n KEY_COLUMN_USAGE OBJECTPROPERTY(id, 'IsPrimaryKey')"
},
{
"answer_id": 30927788,
"author": "Pricey",
"author_id": 98706,
"author_profile": "https://Stackoverflow.com/users/98706",
"pm_score": 0,
"selected": false,
"text": "SELECT T.TABLE_SCHEMA, T.TABLE_NAME, \nSTUFF((\n SELECT ', ' + C.COLUMN_NAME\n FROM INFORMATION_SCHEMA.COLUMNS C\n WHERE C.TABLE_SCHEMA = T.TABLE_SCHEMA\n AND T.TABLE_NAME = C.TABLE_NAME\n FOR XML PATH ('')\n ), 1, 2, '') AS Columns,\nSTUFF((\nSELECT ', ' + C.COLUMN_NAME \nFROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE C\nINNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC\n ON C.TABLE_SCHEMA = TC.TABLE_SCHEMA\n AND C.TABLE_NAME = TC.TABLE_NAME\n WHERE C.TABLE_SCHEMA = T.TABLE_SCHEMA\n AND T.TABLE_NAME = C.TABLE_NAME\n AND TC.CONSTRAINT_TYPE = 'PRIMARY KEY'\n FOR XML PATH ('')\n), 1, 2, '') AS [Key]\nFROM INFORMATION_SCHEMA.TABLES T\nORDER BY T.TABLE_SCHEMA, T.TABLE_NAME\n"
},
{
"answer_id": 31083875,
"author": "Tanner Ornelas",
"author_id": 4682491,
"author_profile": "https://Stackoverflow.com/users/4682491",
"pm_score": 2,
"selected": false,
"text": "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = 'TableName'\n"
},
{
"answer_id": 32511025,
"author": "Dave Zych",
"author_id": 1630665,
"author_profile": "https://Stackoverflow.com/users/1630665",
"pm_score": 5,
"selected": false,
"text": "sys.* INFORMATION_SCHEMA sys.* SELECT \n c.name AS column_name,\n i.name AS index_name,\n c.is_identity\nFROM sys.indexes i\n inner join sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id\n inner join sys.columns c ON ic.object_id = c.object_id AND c.column_id = ic.column_id\nWHERE i.is_primary_key = 1\n and i.object_ID = OBJECT_ID('<schema>.<tablename>');\n"
},
{
"answer_id": 37250483,
"author": "SQL Police",
"author_id": 2504785,
"author_profile": "https://Stackoverflow.com/users/2504785",
"pm_score": 5,
"selected": false,
"text": "SchemaName TableName select \n s.name as SchemaName,\n t.name as TableName,\n tc.name as ColumnName,\n ic.key_ordinal as KeyOrderNr\nfrom \n sys.schemas s \n inner join sys.tables t on s.schema_id=t.schema_id\n inner join sys.indexes i on t.object_id=i.object_id\n inner join sys.index_columns ic on i.object_id=ic.object_id \n and i.index_id=ic.index_id\n inner join sys.columns tc on ic.object_id=tc.object_id \n and ic.column_id=tc.column_id\nwhere i.is_primary_key=1 \norder by t.name, ic.key_ordinal ;\n"
},
{
"answer_id": 39851081,
"author": "Anjan Kant",
"author_id": 919643,
"author_profile": "https://Stackoverflow.com/users/919643",
"pm_score": 1,
"selected": false,
"text": "SELECT DISTINCT\n CONSTRAINT_NAME AS [Constraint],\n TABLE_SCHEMA AS [Schema],\n TABLE_NAME AS TableName\nFROM\n INFORMATION_SCHEMA.KEY_COLUMN_USAGE\nWHERE\n TABLE_NAME = 'mytablename'\n"
},
{
"answer_id": 42985271,
"author": "Soenhay",
"author_id": 1339704,
"author_profile": "https://Stackoverflow.com/users/1339704",
"pm_score": 0,
"selected": false,
"text": "DECLARE @TableName VARCHAR(100) = '';\nWITH Sysinfo\n AS (SELECT Kcu.Table_Name\n , Kcu.Table_Schema AS Schema_Name\n , Kcu.Column_Name\n , Kcu.Ordinal_Position\n FROM [LinkServer].Information_Schema.Key_Column_Usage Kcu\n JOIN [LinkServer].Information_Schema.Table_Constraints AS Tc ON Tc.Constraint_Name = Kcu.Constraint_Name\n WHERE Tc.Constraint_Type = 'Primary Key')\n SELECT Schema_Name\n ,Table_Name\n , STUFF(\n (\n SELECT ', '\n , REPLACE(Si1.Column_Name, '', '')\n FROM Sysinfo Si1\n WHERE Si1.Table_Name = Si2.Table_Name\n ORDER BY Si1.Table_Name\n , Si1.Ordinal_Position\n FOR XML PATH('')\n ), 1, 2, '') AS Primary_Keys\n FROM Sysinfo Si2\n WHERE Table_Name = CASE\n WHEN @TableName NOT IN( '', 'All')\n THEN @TableName\n ELSE Table_Name\n END\n GROUP BY Si2.Table_Name, Si2.Schema_Name;\n DECLARE @TableName VARCHAR(100) = '';\nWITH Sysinfo\n AS (SELECT S.Name AS Schema_Name\n , T.Name AS Table_Name\n , Tc.Name AS Column_Name\n , Ic.Key_Ordinal AS Ordinal_Position\n FROM [LinkServer].Sys.Schemas S\n JOIN [LinkServer].Sys.Tables T ON S.Schema_Id = T.Schema_Id\n JOIN [LinkServer].Sys.Indexes I ON T.Object_Id = I.Object_Id\n JOIN [LinkServer].Sys.Index_Columns Ic ON I.Object_Id = Ic.Object_Id\n AND I.Index_Id = Ic.Index_Id\n JOIN [LinkServer].Sys.Columns Tc ON Ic.Object_Id = Tc.Object_Id\n AND Ic.Column_Id = Tc.Column_Id\n WHERE I.Is_Primary_Key = 1)\n SELECT Schema_Name\n ,Table_Name\n , STUFF(\n (\n SELECT ', '\n , REPLACE(Si1.Column_Name, '', '')\n FROM Sysinfo Si1\n WHERE Si1.Table_Name = Si2.Table_Name\n ORDER BY Si1.Table_Name\n , Si1.Ordinal_Position\n FOR XML PATH('')\n ), 1, 2, '') AS Primary_Keys\n FROM Sysinfo Si2\n WHERE Table_Name = CASE\n WHEN @TableName NOT IN('', 'All')\n THEN @TableName\n ELSE Table_Name\n END\n GROUP BY Si2.Table_Name, Si2.Schema_Name;\n"
},
{
"answer_id": 45452479,
"author": "UJS",
"author_id": 3373795,
"author_profile": "https://Stackoverflow.com/users/3373795",
"pm_score": 0,
"selected": false,
"text": "declare @TableName nvarchar(50)='TblInvoice' -- your table name\ndeclare @TypeOfKey nvarchar(50)='PK' -- For Primary key\n\nSELECT Name FROM sys.objects\nWHERE type = @TypeOfKey \nAND parent_object_id = OBJECT_ID (@TableName)\n"
},
{
"answer_id": 47091245,
"author": "Bha15",
"author_id": 8119464,
"author_profile": "https://Stackoverflow.com/users/8119464",
"pm_score": 3,
"selected": false,
"text": "SP_HELP 'table_name'\n"
},
{
"answer_id": 48573015,
"author": "Saxman",
"author_id": 8206858,
"author_profile": "https://Stackoverflow.com/users/8206858",
"pm_score": 0,
"selected": false,
"text": "SELECT \nKEYS.table_schema, KEYS.table_name, KEYS.column_name, KEYS.ORDINAL_POSITION \nFROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE keys\nINNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS CONS \n ON cons.TABLE_SCHEMA = keys.TABLE_SCHEMA \n AND cons.TABLE_NAME = keys.TABLE_NAME \n AND cons.CONSTRAINT_NAME = keys.CONSTRAINT_NAME\nWHERE cons.CONSTRAINT_TYPE = 'PRIMARY KEY'\n"
},
{
"answer_id": 49913195,
"author": "Humayoun_Kabir",
"author_id": 1427614,
"author_profile": "https://Stackoverflow.com/users/1427614",
"pm_score": 0,
"selected": false,
"text": "SELECT schema_name(t.schema_id) AS [schema_name], t.name AS TableName, \n COL_NAME(ic.OBJECT_ID,ic.column_id) AS PrimaryKeyColumnName,\n i.name AS PrimaryKeyConstraintName\nFROM sys.tables t \nINNER JOIN sys.indexes AS i on t.object_id=i.object_id \nINNER JOIN sys.index_columns AS ic ON i.OBJECT_ID = ic.OBJECT_ID\n AND i.index_id = ic.index_id \nWHERE OBJECT_NAME(ic.OBJECT_ID) = 'YourTableNameHere'\n SELECT\nf.name as ForeignKeyConstraintName\n,OBJECT_NAME(f.parent_object_id) AS ReferencingTableName\n,COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ReferencingColumnName\n,OBJECT_NAME (f.referenced_object_id) AS ReferencedTableName\n,COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS \n ReferencedColumnName ,delete_referential_action_desc AS \nDeleteReferentialActionDesc ,update_referential_action_desc AS \nUpdateReferentialActionDesc\nFROM sys.foreign_keys AS f\nINNER JOIN sys.foreign_key_columns AS fc\nON f.object_id = fc.constraint_object_id\n --WHERE OBJECT_NAME(f.parent_object_id) = 'YourTableNameHere' \n --If you want to know referecing table details \n WHERE OBJECT_NAME(f.referenced_object_id) = 'YourTableNameHere' \n --If you want to know refereced table details \nORDER BY f.name\n"
},
{
"answer_id": 50014472,
"author": "WEshruth",
"author_id": 1699472,
"author_profile": "https://Stackoverflow.com/users/1699472",
"pm_score": 0,
"selected": false,
"text": "SELECT tc.constraint_name AS IndexName,tc.table_name AS TableName,tc.table_schema\nAS SchemaName,kc.column_name AS COLUMN_NAME\nFROM information_schema.table_constraints tc,information_schema.key_column_usage kc\nWHERE tc.constraint_type = 'PRIMARY KEY' AND kc.table_name = tc.table_name AND kc.table_schema = tc.table_schema\nAND kc.constraint_name = tc.constraint_name AND tc.table_schema='<SCHEMA_NAME>'\n"
},
{
"answer_id": 50209394,
"author": "user3248578",
"author_id": 1051237,
"author_profile": "https://Stackoverflow.com/users/1051237",
"pm_score": 1,
"selected": false,
"text": "declare @table varchar(100) = 'mytable';\n\nwith cte as\n(\n select \n tc.CONSTRAINT_SCHEMA\n , tc.CONSTRAINT_TYPE\n , tc.TABLE_NAME\n , ccu.COLUMN_NAME\n , IS_NULLABLE\n , DATA_TYPE\n , CHARACTER_MAXIMUM_LENGTH\n , NUMERIC_PRECISION\n from \n INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \n inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu on tc.TABLE_NAME=ccu.TABLE_NAME and tc.TABLE_SCHEMA=ccu.TABLE_SCHEMA\n inner join information_schema.COLUMNS c on ccu.COLUMN_NAME=c.COLUMN_NAME and ccu.TABLE_NAME=c.TABLE_NAME and ccu.TABLE_SCHEMA=c.TABLE_SCHEMA\n where \n tc.table_name=@table\n and \n ccu.CONSTRAINT_NAME=tc.CONSTRAINT_NAME\n union \n select TABLE_SCHEMA,'COLUMN', TABLE_NAME, COLUMN_NAME, IS_NULLABLE, DATA_TYPE,CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@table\n and COLUMN_NAME not in (select COLUMN_NAME from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = @table)\n)\nselect \n cast(iif(CONSTRAINT_TYPE='PRIMARY KEY',1,0) as bit) PrimaryKey\n ,cast(iif(CONSTRAINT_TYPE='FOREIGN KEY',1,0) as bit) ForeignKey\n ,cast(iif(CONSTRAINT_TYPE='COLUMN',1,0) as bit) NotKey\n ,COLUMN_NAME\n ,cast(iif(is_nullable='NO',0,1) as bit) IsNullable\n , DATA_TYPE\n , CHARACTER_MAXIMUM_LENGTH\n , NUMERIC_PRECISION \nfrom \n cte \norder by \n case CONSTRAINT_TYPE \n when 'PRIMARY KEY' then 1 \n when 'FOREIGN KEY' then 2 \n else 3 end\n , COLUMN_NAME\n <table cellspacing=0 border=1>\n <tr>\n <td style=min-width:50px>PrimaryKey</td>\n <td style=min-width:50px>ForeignKey</td>\n <td style=min-width:50px>NotKey</td>\n <td style=min-width:50px>COLUMN_NAME</td>\n <td style=min-width:50px>IsNullable</td>\n <td style=min-width:50px>DATA_TYPE</td>\n <td style=min-width:50px>CHARACTER_MAXIMUM_LENGTH</td>\n <td style=min-width:50px>NUMERIC_PRECISION</td>\n </tr>\n <tr>\n <td style=min-width:50px>1</td>\n <td style=min-width:50px>0</td>\n <td style=min-width:50px>0</td>\n <td style=min-width:50px>LectureNoteID</td>\n <td style=min-width:50px>0</td>\n <td style=min-width:50px>int</td>\n <td style=min-width:50px>NULL</td>\n <td style=min-width:50px>10</td>\n </tr>\n <tr>\n <td style=min-width:50px>0</td>\n <td style=min-width:50px>1</td>\n <td style=min-width:50px>0</td>\n <td style=min-width:50px>LectureId</td>\n <td style=min-width:50px>0</td>\n <td style=min-width:50px>int</td>\n <td style=min-width:50px>NULL</td>\n <td style=min-width:50px>10</td>\n </tr>\n <tr>\n <td style=min-width:50px>0</td>\n <td style=min-width:50px>1</td>\n <td style=min-width:50px>0</td>\n <td style=min-width:50px>NoteTypeID</td>\n <td style=min-width:50px>0</td>\n <td style=min-width:50px>int</td>\n <td style=min-width:50px>NULL</td>\n <td style=min-width:50px>10</td>\n </tr>\n <tr>\n <td style=min-width:50px>0</td>\n <td style=min-width:50px>0</td>\n <td style=min-width:50px>1</td>\n <td style=min-width:50px>Body</td>\n <td style=min-width:50px>0</td>\n <td style=min-width:50px>nvarchar</td>\n <td style=min-width:50px>-1</td>\n <td style=min-width:50px>NULL</td>\n </tr>\n <tr>\n <td style=min-width:50px>0</td>\n <td style=min-width:50px>0</td>\n <td style=min-width:50px>1</td>\n <td style=min-width:50px>DisplayOrder</td>\n <td style=min-width:50px>0</td>\n <td style=min-width:50px>int</td>\n <td style=min-width:50px>NULL</td>\n <td style=min-width:50px>10</td>\n </tr>\n </table>\n "
},
{
"answer_id": 51226788,
"author": "Hamed Nikzad",
"author_id": 5974407,
"author_profile": "https://Stackoverflow.com/users/5974407",
"pm_score": 1,
"selected": false,
"text": "SELECT L.TABLE_SCHEMA, L.TABLE_NAME, L.COLUMN_NAME, R.TypeName\nFROM(\n SELECT COLUMN_NAME, TABLE_NAME, TABLE_SCHEMA\n FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE\n WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1\n)L\nLEFT JOIN (\n SELECT\n OBJECT_NAME(c.OBJECT_ID) TableName ,c.name AS ColumnName ,t.name AS TypeName\n FROM sys.columns AS c\n JOIN sys.types AS t ON c.user_type_id=t.user_type_id\n)R ON L.COLUMN_NAME = R.ColumnName AND L.TABLE_NAME = R.TableName\n"
},
{
"answer_id": 57650846,
"author": "Allan F",
"author_id": 5315581,
"author_profile": "https://Stackoverflow.com/users/5315581",
"pm_score": 1,
"selected": false,
"text": "Select distinct SUBSTRING ( stuff(( select distinct ',' + [COLUMN_NAME] \n from INFORMATION_SCHEMA.KEY_COLUMN_USAGE \n where OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1 \n AND TABLE_NAME = 'TableName' AND TABLE_SCHEMA = 'Schema' \n order by 1 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,0,'' ) \n ,2,9999) \n"
},
{
"answer_id": 68347950,
"author": "happybits",
"author_id": 653281,
"author_profile": "https://Stackoverflow.com/users/653281",
"pm_score": 0,
"selected": false,
"text": "EXEC sp_pkeys YourTable"
},
{
"answer_id": 69543595,
"author": "Msfata",
"author_id": 11402186,
"author_profile": "https://Stackoverflow.com/users/11402186",
"pm_score": -1,
"selected": false,
"text": "SELECT `Constraint_Name`\n FROM `All_Constraints`\n WHERE `Constraint_Type` = `'P'`\n AND `Owner` = `'your schema here';`\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/95967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/736/"
] |
95,988
|
<p>I'm inserting multiple records into a table A from another table B. Is there a way to get the identity value of table A record and update table b record with out doing a cursor?</p>
<pre><code>Create Table A
(id int identity,
Fname nvarchar(50),
Lname nvarchar(50))
Create Table B
(Fname nvarchar(50),
Lname nvarchar(50),
NewId int)
Insert into A(fname, lname)
SELECT fname, lname
FROM B
</code></pre>
<p>I'm using MS SQL Server 2005.</p>
|
[
{
"answer_id": 96084,
"author": "Cory",
"author_id": 8207,
"author_profile": "https://Stackoverflow.com/users/8207",
"pm_score": 1,
"selected": false,
"text": "Insert into A(identity, fname, lname) SELECT newid, fname, lname FROM B\n set identity_insert A on\n"
},
{
"answer_id": 96212,
"author": "njr101",
"author_id": 9625,
"author_profile": "https://Stackoverflow.com/users/9625",
"pm_score": 3,
"selected": false,
"text": "UPDATE B\nSET NewID = A.ID\nFROM B INNER JOIN A\n ON (B.FName = A.Fname AND B.LName = A.LName)\n"
},
{
"answer_id": 96232,
"author": "Dmitry Khalatov",
"author_id": 18174,
"author_profile": "https://Stackoverflow.com/users/18174",
"pm_score": 1,
"selected": false,
"text": "update B set NewID = NEWID()\n\ninsert into A(fname,lname,id) select fname,lname,NewID from B\n"
},
{
"answer_id": 100669,
"author": "Andy Irving",
"author_id": 8553,
"author_profile": "https://Stackoverflow.com/users/8553",
"pm_score": 7,
"selected": false,
"text": "DECLARE @output TABLE (id int)\n\nInsert into A (fname, lname)\nOUTPUT inserted.ID INTO @output\nSELECT fname, lname FROM B\n\nselect * from @output\n"
},
{
"answer_id": 65305608,
"author": "R.Akhlaghi",
"author_id": 2830315,
"author_profile": "https://Stackoverflow.com/users/2830315",
"pm_score": 0,
"selected": false,
"text": "-- first create a table for show how its works\nCREATE TABLE [dbo].[myTable]\n (\n [id] [INT] IDENTITY(1, 1) NOT NULL,\n [text] [VARCHAR](10) NULL\n )\nON [PRIMARY]\n\nGO\n\n-- var table for keep new inserted id\nDECLARE @tblNewInserted TABLE\n (\n newids INT\n )\n\n--use the output clause in insert statement\nINSERT INTO [dbo].[myTable]\noutput inserted.id\nINTO @tblNewInserted\nVALUES ('aa'),('bb'),('cc')\n\nSELECT *\nFROM @tblNewInserted \n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/95988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2526/"
] |
96,003
|
<p>Let's say I have two models, Classes and People. A Class might have one or two People as instructors, and twenty people as students. So, I need to have multiple relationships between the models -- one where it's 1->M for instructors, and one where it's 1->M for students.</p>
<p>Edit: Instructors and Students <em>must</em> be the same; instructors could be students in other classes, and vice versa.</p>
<p>I'm sure this is quite easy, but Google isn't pulling up anything relevant and I'm just not finding it in my books.</p>
|
[
{
"answer_id": 96055,
"author": "kch",
"author_id": 13989,
"author_profile": "https://Stackoverflow.com/users/13989",
"pm_score": 5,
"selected": true,
"text": "class Person < ActiveRecord::Base; end # btw, model names are singular in rails\nclass Student < Person; end\nclass Instructor < Person; end\n class Course < ActiveRecord::Base # renamed here because class Class already exists in ruby\n has_many :students\n has_many :instructors\nend\n type people class Course < ActiveRecord::Base\n has_many :studentships\n has_many :instructorships\n has_many :students, :through => :studentships\n has_many :instructors, :through => :instructorships\nend\n\nclass Studentship < ActiveRecord::Base\n belongs_to :course\n belongs_to :student, :class_name => \"Person\", :foreign_key => \"student_id\"\nend\n\nclass Instructorship < ActiveRecord::Base\n belongs_to :course\n belongs_to :instructor, :class_name => \"Person\", :foreign_key => \"instructor_id\"\nend\n"
},
{
"answer_id": 5580850,
"author": "Naveed",
"author_id": 671046,
"author_profile": "https://Stackoverflow.com/users/671046",
"pm_score": 3,
"selected": false,
"text": "class Asset < ActiveRecord::Base\n\nbelongs_to :creator ,:class_name=>'User'\nbelongs_to :assigned_to, :class_name=>'User' \n\nend\n user.rb\n\nclass User < ActiveRecord::Base\n\nhas_many :created_assets, :foreign_key => 'creator_id', :class_name => 'Asset'\nhas_many :assigned_assets , :foreign_key => 'assigned_to_id', :class_name => 'Asset'\n\nend\n class Course < ActiveRecord::Base\nhas_many :students ,:foreign_key => 'student_id', :class_name => 'Person'\nhas_many :teachers, :foreign_key => 'teacher_id', :class_name => 'Person'\n\nend\n class Person < ActiveRecord::Base\nbelongs_to :course_enrolled,:class_name=>'Course'\nbelongs_to :course_instructor,:class_name=>'Course'\n\nend\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/722/"
] |
96,027
|
<p>For example, given a type param method i'm looking for something like the part in bold</p>
<blockquote>
<p>void MyMethod< T >() {<br>
if ( <strong>typeof(T).Implements( <em>IMyInterface</em> )</strong> )
{</p>
<pre><code> //Do something
</code></pre>
<p>else</p>
<pre><code> //Do something else
</code></pre>
<p>}</p>
</blockquote>
<p>Anwers using C# 3.0 are also welcome, but first drop the .NET 2.0 ones please ;)</p>
|
[
{
"answer_id": 96057,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 4,
"selected": true,
"text": "if(typeof(IMyInterface).IsAssignableFrom(typeof(T)))\n{\n // something\n}\nelse\n{\n // something else\n}\n"
},
{
"answer_id": 96065,
"author": "MADMap",
"author_id": 17558,
"author_profile": "https://Stackoverflow.com/users/17558",
"pm_score": 1,
"selected": false,
"text": "if (typeof (IMyInterFace).IsAssignableFrom(typeof(T))\n"
},
{
"answer_id": 96095,
"author": "Ricardo Amores",
"author_id": 10136,
"author_profile": "https://Stackoverflow.com/users/10136",
"pm_score": 0,
"selected": false,
"text": "if( typeof(T).Equals(typeof(IMyInterface) ) \n ...\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10136/"
] |
96,029
|
<p>I have an ASP.Net page that will be hosted on a couple different servers, and I want to get the URL of the page (or even better: the site where the page is hosted) as a string for use in the code-behind. Any ideas?</p>
|
[
{
"answer_id": 96063,
"author": "Mikey",
"author_id": 13347,
"author_profile": "https://Stackoverflow.com/users/13347",
"pm_score": 9,
"selected": true,
"text": "Request.Url.AbsoluteUri"
},
{
"answer_id": 1534478,
"author": "William",
"author_id": 98740,
"author_profile": "https://Stackoverflow.com/users/98740",
"pm_score": 7,
"selected": false,
"text": "Request.Url.GetLeftPart(UriPartial.Authority)\n"
},
{
"answer_id": 1820060,
"author": "pub",
"author_id": 221370,
"author_profile": "https://Stackoverflow.com/users/221370",
"pm_score": 3,
"selected": false,
"text": "new Uri(Request.Url,Request.ApplicationPath)\n Request.Url.GetLeftPart(UriPartial.Authority)+Request.ApplicationPath\n"
},
{
"answer_id": 1827149,
"author": "corey",
"author_id": 222224,
"author_profile": "https://Stackoverflow.com/users/222224",
"pm_score": 3,
"selected": false,
"text": "Request.Url.GetLeftPart(UriPartial.Authority) + Request.FilePath + \"?theme=blue\";\n"
},
{
"answer_id": 3385986,
"author": "Ivan Stefanov",
"author_id": 364657,
"author_profile": "https://Stackoverflow.com/users/364657",
"pm_score": 5,
"selected": false,
"text": "Request.Url.GetLeftPart(UriPartial.Authority) +\n VirtualPathUtility.ToAbsolute(\"~/\")\n"
},
{
"answer_id": 11000840,
"author": "Ben Petersen",
"author_id": 876796,
"author_profile": "https://Stackoverflow.com/users/876796",
"pm_score": 2,
"selected": false,
"text": "Dim rawUrl As String = Request.RawUrl.ToString()\n"
},
{
"answer_id": 11184525,
"author": "REEP",
"author_id": 1479202,
"author_profile": "https://Stackoverflow.com/users/1479202",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javascript\">\n alert('Server: ' + window.location.hostname);\n alert('Full path: ' + window.location.href);\n alert('Virtual path: ' + window.location.pathname);\n alert('HTTP path: ' + \n window.location.href.replace(window.location.pathname, '')); \n</script>\n"
},
{
"answer_id": 12039172,
"author": "Prescient",
"author_id": 1303402,
"author_profile": "https://Stackoverflow.com/users/1303402",
"pm_score": 4,
"selected": false,
"text": "// get a sites base urll ex: example.com\npublic static string BaseSiteUrl\n{\n get\n {\n HttpContext context = HttpContext.Current;\n string baseUrl = context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/');\n return baseUrl;\n }\n\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
96,041
|
<p>For a developer in the Java eco-system, there is a handful of choices when it comes to UI design. The best known are:</p>
<ul>
<li>Swing (preferred when used with Netbeans and its GUI builder)</li>
<li>Eclipse's SWT (mostly preferred for Eclipse plug-ins)</li>
</ul>
<p>Now, are there any frameworks or design alternatives to this which target JRuby / Groovy / Jython or other "dynamic" JVM languages ?</p>
<p>Some UI frameworks are layers over Swing or SWT, for example, a framework could read a description of a Screen in XML and instantiate the corresponding Swing components.</p>
<p>If you know a framework like that but which targets JVM "dynamic" languages, I'd like to see them in the answers as well.</p>
|
[
{
"answer_id": 9295296,
"author": "mikera",
"author_id": 214010,
"author_profile": "https://Stackoverflow.com/users/214010",
"pm_score": 2,
"selected": false,
"text": "(defn -main [& args]\n (invoke-later \n (-> (frame :title \"Hello\", \n :content \"Hello, Seesaw\",\n :on-close :exit)\n pack!\n show!)))\n ;; show a histogram of 1000 samples from a normal distribution\n(view (histogram (sample-normal 1000)))\n (defn -start [app stage]\n (eval\n (fx Stage :visible true :width 300 :height 200 :title \"hello world\"\n :scene (fx Scene\n (fx BorderPane :left (fx Text \"hello\")\n :right (fx Text \"Right\")\n :top (fx Text \"top\")\n :bottom (fx Text \"Bottom\")\n :center (fx Text \"In the middle!\"))))))\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15649/"
] |
96,042
|
<p>I'm working on the creation of an ActiveX EXE using VB6, and the only example I got is all written in Delphi.</p>
<p>Reading the example code, I noticed there are some functions whose signatures are followed by the <strong>safecall</strong> keyword. Here's an example:</p>
<pre><code>function AddSymbol(ASymbol: OleVariant): WordBool; safecall;
</code></pre>
<p>What is the purpose of this keyword?</p>
|
[
{
"answer_id": 96646,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 2,
"selected": false,
"text": "function AddSymbol(ASymbol: OleVariant; out Result: WordBool): HResult; stdcall;\n"
},
{
"answer_id": 50373314,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 2,
"selected": false,
"text": "HRESULT IThingy = interface\n ['{357D8D61-0504-446F-BE13-4A3BBE699B05}']\n function AddSymbol(ASymbol: OleVariant; out RetValue: WordBool): HRESULT; stdcall;\nend;\n function AddSymbol(ASymbol: OleVariant): WordBool; WordBool AddSymbol(OleVariant ASymbol); IThingy = interface\n ['{357D8D61-0504-446F-BE13-4A3BBE699B05}']\n function AddSymbol(ASymbol: OleVariant; out RetValue: WordBool): HRESULT; stdcall;\nend;\n bAdded: WordBool;\nthingy: IThingy;\nhr: HRESULT;\n\nhr := thingy.AddSymbol('Seven', {out}bAdded);\nif Failed(hr) then\n OleError(hr);\n bAdded: WordBool;\nthingy: IThingy;\nhr: HRESULT;\n\nhr := thingy.AddSymbol('Seven', {out}bAdded);\nOleCheck(hr);\n bAdded: WordBool;\nthingy: IThingy;\n\nOleCheck(thingy.AddSymbol('Seven'), {out}bAdded);\n IThingy = interface\n ['{357D8D61-0504-446F-BE13-4A3BBE699B05}']\n function AddSymbol(ASymbol: OleVariant): WordBool; safecall;\nend;\n EOleSysError function AddSymbol(ASymbol: OleVariant): WordBool; safecall;\nvar\n hr: HRESULT;\nbegin\n hr := AddSymbol(ASymbol, {out}Result);\n OleCheck(hr);\nend;\n bAdded: WordBool;\nthingy: IThingy;\n\nbAdded := thingy.AddSymbol('Seven');\n function AddSymbol(ASymbol: OleVariant; out RetValue: WordBool): HRESULT; stdcall;\nfunction AddSymbol(ASymbol: OleVariant): WordBool; safecall;\n IThingy = interface\n ['{357D8D61-0504-446F-BE13-4A3BBE699B05}']\n function AddSymbol(ASymbol: OleVariant; out RetValue: WordBool): HRESULT; stdcall;\nend;\n\nIThingySC = interface\n ['{357D8D61-0504-446F-BE13-4A3BBE699B05}']\n function AddSymbol(ASymbol: OleVariant): WordBool); safecall;\nend;\n ITransaction = interface(IUnknown)\n ['{0FB15084-AF41-11CE-BD2B-204C4F4F5020}']\n function Commit(fRetaining: BOOL; grfTC: UINT; grfRM: UINT): HResult; stdcall;\n function Abort(pboidReason: PBOID; fRetaining: BOOL; fAsync: BOOL): HResult; stdcall;\n function GetTransactionInfo(out pinfo: XACTTRANSINFO): HResult; stdcall;\n end;\n\n { Safecall Version }\n ITransactionSC = interface(IUnknown)\n ['{0FB15084-AF41-11CE-BD2B-204C4F4F5020}']\n procedure Commit(fRetaining: BOOL; grfTC: UINT; grfRM: UINT); safecall;\n procedure Abort(pboidReason: PBOID; fRetaining: BOOL; fAsync: BOOL); safecall;\n procedure GetTransactionInfo(out pinfo: XACTTRANSINFO); safecall;\n end;\n //thingy: IThingy;\nthingy: IThingySC;\n thingy: IThingSC;\nbAdded: WordBool;\n\nthingy := CreateOleObject('Supercool.Thingy') as TThingySC;\n\nif Failed(IThingy(thingy).AddSymbol('Seven', {out}bAdded) then\nbegin\n //Couldn't seven? No sixty-nine for you\n thingy.SubtractSymbol('Sixty-nine');\nend;\n [ComImport]\n[Guid(\"{357D8D61-0504-446F-BE13-4A3BBE699B05}\")]\n[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\npublic interface IThingy\n{\n WordBool AddSymbol(OleVariant ASymbol);\n WordBool SubtractSymbol(OleVariant ASymbol);\n}\n HRESULT [ComImport]\n[Guid(\"{357D8D61-0504-446F-BE13-4A3BBE699B05}\")]\n[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\npublic interface IThingy\n{\n [PreserveSig]\n HRESULT AddSymbol(OleVariant ASymbol, out WordBool RetValue);\n\n WordBool SubtractSymbol(OleVariant ASymbol);\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/431/"
] |
96,054
|
<p>I have huge 3D arrays of numbers in my .NET application. I need to convert them to a 1D array to pass it to a COM library. Is there a way to convert the array without making a copy of all the data?</p>
<p>I can do the conversion like this, but then I use twice the ammount of memory which is an issue in my application:</p>
<pre><code> double[] result = new double[input.GetLength(0) * input.GetLength(1) * input.GetLength(2)];
for (i = 0; i < input.GetLength(0); i++)
for (j = 0; j < input.GetLength(1); j++)
for (k = 0; k < input.GetLength(2); k++)
result[i * input.GetLength(1) * input.GetLength(2) + j * input.GetLength(2) + k)] = input[i,j,l];
return result;
</code></pre>
|
[
{
"answer_id": 96603,
"author": "Aaron",
"author_id": 14153,
"author_profile": "https://Stackoverflow.com/users/14153",
"pm_score": 2,
"selected": false,
"text": "class Matrix3\n{\n // referece-to-element object\n public struct Matrix3Elem{\n private Matrix3Impl impl;\n private uint dim0, dim1, dim2;\n // other constructors\n Matrix3Elem(Matrix3Impl impl_, uint dim0_, uint dim1_, uint dim2_) {\n impl = impl_; dim0 = dim0_; dim1 = dim1_; dim2 = dim2_;\n }\n public double Value{\n get { return impl.GetAt(dim0,dim1,dim2); }\n set { impl.SetAt(dim0, dim1, dim2, value); }\n }\n }\n\n // implementation object\n internal class Matrix3Impl\n {\n private double[] data;\n uint dsize0, dsize1, dsize2; // dimension sizes\n // .. Resize() \n public double GetAt(uint dim0, uint dim1, uint dim2) {\n // .. check bounds\n return data[ (dim2 * dsize1 + dim1) * dsize0 + dim0 ];\n }\n public void SetAt(uint dim0, uint dim1, uint dim2, double value) {\n // .. check bounds\n data[ (dim2 * dsize1 + dim1) * dsize0 + dim0 ] = value;\n }\n }\n\n private Matrix3Impl impl;\n\n public Matrix3Elem Elem(uint dim0, uint dim1, uint dim2){\n return new Matrix2Elem(dim0, dim1, dim2);\n }\n // .. Resize\n // .. GetLength0(), GetLength1(), GetLength1()\n}\n void normalize(Matrix3 m){\n\n double s = 0;\n for (i = 0; i < input.GetLength0; i++) \n for (j = 0; j < input.GetLength(1); j++) \n for (k = 0; k < input.GetLength(2); k++)\n {\n s += m.Elem(i,j,k).Value;\n }\n for (i = 0; i < input.GetLength0; i++) \n for (j = 0; j < input.GetLength(1); j++) \n for (k = 0; k < input.GetLength(2); k++)\n {\n m.Elem(i,j,k).Value /= s;\n }\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15454/"
] |
96,059
|
<p>Suppose I want to store many small configuration objects in XML, and I don't care too much about the format. The <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/beans/XMLDecoder.html" rel="nofollow noreferrer">XMLDecoder</a> class built into the JDK would work, and from what I hear, <a href="http://xstream.codehaus.org/" rel="nofollow noreferrer">XStream</a> works in a similar way.</p>
<p>What are the advantages to each library?</p>
|
[
{
"answer_id": 97182,
"author": "Jay R.",
"author_id": 5074,
"author_profile": "https://Stackoverflow.com/users/5074",
"pm_score": 3,
"selected": false,
"text": "// define your classes\npublic class Person {\n private String firstname;\n private PhoneNumber phone;\n // ... constructors and methods\n}\n\npublic class PhoneNumber {\n private int code;\n private String number;\n // ... constructors and methods\n}\n // initial the libray\nXStream xstream = new XStream();\nxstream.alias(\"person\", Person.class); // elementName, Class\nxstream.alias(\"phone\", PhoneNumber.class); \n\n// make your objects\nPerson joe = new Person(\"Joe\");\njoe.setPhone(new PhoneNumber(123, \"1234-456\"));\n\n// convert xml\nString xml = xstream.toXML(joe);\n <person>\n <firstname>Joe</firstname>\n <phone>\n <code>123</code>\n <number>1234-456</number>\n </phone>\n</person>\n Person newJoe = (Person)xstream.fromXML(xml); package example;"
},
{
"answer_id": 23431074,
"author": "Elf",
"author_id": 2404453,
"author_profile": "https://Stackoverflow.com/users/2404453",
"pm_score": 1,
"selected": false,
"text": "PortfolioAlternateIdentifier identifier = new PortfolioAlternateIdentifier();\nidentifier.setEffectiveDate(new Date());\nidentifier.setSchemeCode(\"AAA\");\nidentifier.setIdentifier(\"123456\");\n <PortfolioAlternateIdentifier>\n <effectiveDate>2014-05-02 20:14:15.961 IST</effectiveDate>\n <schemeCode>AAA</schemeCode>\n <identifier>123456</identifier>\n</PortfolioAlternateIdentifier> \n <?xml version=\"1.0\" encoding=\"UTF-8\"?> \n <java version=\"1.6.0_38\" class=\"java.beans.XMLDecoder\"> \n <object class=\"PortfolioAlternateIdentifier\"> \n <void property=\"effectiveDate\"> \n <object class=\"java.util.Date\"> \n <long>1399041855961</long> \n </object> \n </void> \n <void property=\"identifier\"> \n <string>123456</string> \n </void> \n <void property=\"schemeCode\"> \n <string>AAA</string> \n </void> \n </object> \n</java> \n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3474/"
] |
96,066
|
<p>I'm trying to incorporate some JavaScript unit testing into my automated build process. Currently JSUnit works well with JUnit, but it seems to be abandonware and lacks good support for Ajax, debugging, and timeouts.</p>
<p>Has anyone had any luck automating (with <a href="https://en.wikipedia.org/wiki/Apache_Ant" rel="nofollow noreferrer">Ant</a>) a unit testing library such as <a href="https://en.wikipedia.org/wiki/Yahoo!_UI_Library" rel="nofollow noreferrer">YUI</a> test, jQuery's <a href="https://code.jquery.com/qunit/" rel="nofollow noreferrer">QUnit</a>, or <a href="http://code.google.com/p/jqunit/" rel="nofollow noreferrer">jQUnit</a>?</p>
<p>Note: I use a custom built Ajax library, so the problem with Dojo's DOH is that it requires you to use their own Ajax function calls and event handlers to work with any Ajax unit testing.</p>
|
[
{
"answer_id": 1891305,
"author": "Josh",
"author_id": 224929,
"author_profile": "https://Stackoverflow.com/users/224929",
"pm_score": 2,
"selected": false,
"text": "var yui_instance; // The YUI instance\nvar runner; // The YAHOO.Test.Runner\nvar Assert; // An instance of YAHOO.Test.Assert to save coding\nvar testSuite; // The YAHOO.Test.Suite that will get run.\n\n/**\n * Sets the required value for the name property on the given template, creates\n * and returns a new YUI Test.Case object.\n *\n * @param template the template object containing all of the tests\n */\nfunction setupTestCase(template) {\n template.name = \"jsTestCase\";\n var test_case = new yui_instance.Test.Case(template);\n return test_case;\n}\n\n/**\n * Sets up the test suite with a single test case using the given\n * template.\n *\n * @param template the template object containing all of the tests\n */\nfunction setupTestSuite(template) {\n var test_case = setupTestCase(template);\n testSuite = new yui_instance.Test.Suite(\"Bond JS Test Suite\");\n testSuite.add(test_case);\n}\n\n/**\n * Runs the YAHOO.Test.Suite\n */\nfunction runTestSuite() {\n runner = yui_instance.Test.Runner;\n Assert = yui_instance.Assert;\n\n runner.clear();\n runner.add(testSuite);\n runner.run();\n}\n\n/**\n * Used to see if the YAHOO.Test.Runner is still running. The\n * test results are not available until it is done running.\n */\nfunction isRunning() {\n return runner.isRunning();\n}\n\n/**\n * Gets the results from the YAHOO.Test.Runner\n */\nfunction getTestResults() {\n return runner.getResults(yui_instance.Test.Format.JSON);\n}\n @Parameters\npublic static List<Object[]> data() throws Exception {\n yui_test_codebase = \"file:///c://myapppath/yui/tests\";\n\n List<Object[]> testResults = new ArrayList<Object[]>();\n\n pageNames = new ArrayList<String>();\n pageNames.add(\"yuiTest1.html\");\n pageNames.add(\"yuiTest2.html\");\n\n testResults.addAll(runJSTestsInBrowser(IE_NOPROXY));\n testResults.addAll(runJSTestsInBrowser(FIREFOX));\n return testResults;\n}\n\n/**\n * Creates a Selenium instance for the given browser, and runs each\n * YUI Test page.\n *\n * @param aBrowser\n * @return\n */\nprivate static List<Object[]> runJSTestsInBrowser(Browser aBrowser) {\n String yui_test_codebase = \"file:///c://myapppath/yui/tests/\";\n String browser_bot = \"this.browserbot.getCurrentWindow()\"\n List<Object[]> testResults = new ArrayList<Object[]>();\n selenium = new DefaultSelenium(APPLICATION_SERVER, REMOTE_CONTROL_PORT, aBrowser.getCommand(), yui_test_codebase);\n try {\n selenium.start();\n\n /*\n * Run the test here\n */\n for (String page_name : pageNames) {\n selenium.open(yui_test_codebase + page_name);\n //Wait for the YAHOO instance to be available\n selenium.waitForCondition(browser_bot + \".yui_instance != undefined\", \"10000\");\n selenium.getEval(\"dom=runYUITestSuite(\" + browser_bot + \")\");\n\n // Output from the tests is not available until\n // the YAHOO.Test.Runner is done running the suite\n selenium.waitForCondition(\"!\" + browser_bot + \".isRunning()\", \"10000\");\n String output = selenium.getEval(\"dom=getYUITestResults(\" + browser_bot + \")\");\n\n JSONObject results = JSONObject.fromObject(output);\n JSONObject test_case = results.getJSONObject(\"jsTestCase\");\n JSONArray testCasePropertyNames = test_case.names();\n Iterator itr = testCasePropertyNames.iterator();\n\n /*\n * From the output, build an array with the following:\n * Test file\n * Test name\n * status (result)\n * message\n */\n while(itr.hasNext()) {\n String name = (String)itr.next();\n if(name.startsWith(\"test\")) {\n JSONObject testResult = test_case.getJSONObject(name);\n String test_name = testResult.getString(\"name\");\n String test_result = testResult.getString(\"result\");\n String test_message = testResult.getString(\"message\");\n Object[] testResultObject = {aBrowser.getCommand(), page_name, test_name, test_result, test_message};\n testResults.add(testResultObject);\n }\n }\n }\n } finally {\n // If an exception is thrown, this will guarantee that the selenium instance\n // is shut down properly\n selenium.stop();\n selenium = null;\n }\n return testResults;\n}\n\n/**\n * Inspects each test result and fails if the testResult was not \"pass\"\n */\n@Test\npublic void inspectTestResults() {\n if(!this.testResult.equalsIgnoreCase(\"pass\")) {\n fail(String.format(MESSAGE_FORMAT, this.browser, this.pageName, this.testName, this.message));\n }\n}\n"
},
{
"answer_id": 9886420,
"author": "liammclennan",
"author_id": 2785,
"author_profile": "https://Stackoverflow.com/users/2785",
"pm_score": 1,
"selected": false,
"text": "var browsertest = require('../browsertest.js').browsertest;\n\ndescribe('browser tests', function () {\n\n it('should properly report the result of a mocha test page', function (done) {\n browsertest({\n url: \"file:///home/liam/work/browser-js-testing/tests.html\",\n callback: function() {\n done();\n }\n });\n });\n\n});\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18146/"
] |
96,086
|
<p>I've had a lot of trouble trying to come up with the best way to properly follow TDD principles while developing UI in JavaScript. What's the best way to go about this?</p>
<p>Is it best to separate the visual from the functional? Do you develop the visual elements first, and then write tests and then code for functionality?</p>
|
[
{
"answer_id": 98475,
"author": "Kris Gray",
"author_id": 1302167,
"author_profile": "https://Stackoverflow.com/users/1302167",
"pm_score": 5,
"selected": true,
"text": "<html>\n<head>\n<script src=\"jsunit.js\"></script>\n<script src=\"mootools.js\"></script>\n<script src=\"yourcontrol.js\"></script>\n</head>\n<body>\n <ul id=\"mockList\">\n <li>red</li>\n <li>green</li>\n </ul> \n</body>\n<script>\n function testListColor() {\n assertNotEqual( $$(\"#mockList li\")[0].getStyle(\"background-color\", \"red\") );\n\n var colorInst = new ColorCtrl( \"mockList\" );\n\n assertEqual( $$(\"#mockList li\")[0].getStyle(\"background-color\", \"red\") );\n }\n</script>\n\n\n</html>\n function ColorCtrl( id ) {\n /* Fail! */ \n}\n function ColorCtrl( id ) {\n $$(\"#mockList li\").forEach(function(item, index) {\n item.setStyle(\"backgrond-color\", item.getText());\n });\n /* Success! */\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18146/"
] |
96,107
|
<p>I'm working with an mpeg stream that uses a IBBP... GOP sequence. The <code>(DTS,PTS)</code> values returned for the first 4 AVPackets are as follows: <code>I=(0,3) B=(1,1) B=(2,2) P=(3,6)</code></p>
<p>The PTS on the I frame looks like it is legit, but then the PTS on the B frames cannot be right, since the B frames shouldn't be displayed before the I frame as their PTS values indicate. I've also tried decoding the packets and using the pts value in the resulting AVFrame, put that PTS is always set to zero.</p>
<p>Is there any way to get an accurate PTS out of ffmpeg? If not, what's the best way to sync audio then?</p>
|
[
{
"answer_id": 96939,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "0, 3, 1, 2, 6, 4, 5, ...\n I, P, B, B, I, B, B, ...\n"
},
{
"answer_id": 104883,
"author": "hobb0001",
"author_id": 18156,
"author_profile": "https://Stackoverflow.com/users/18156",
"pm_score": 4,
"selected": false,
"text": "| I B B P B B P\n| DTS: 0 1 2 3 4 5 6\n| decode() result: I B B P\n | I P B B P B B\n| DTS: 0 1 2 3 4 5 6\n| decode() result: I B B P\n"
},
{
"answer_id": 108466,
"author": "Jere.Jones",
"author_id": 19476,
"author_profile": "https://Stackoverflow.com/users/19476",
"pm_score": 0,
"selected": false,
"text": "P(-3,-2) B(-2,-1) B(-1,0)\n Start GOP: IPBBPBBPBB...\n Start GOP: IBBPBBPBBPBB\nStart GOP: IBBPBBPBBPBB\nStart GOP: IBB... \n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18156/"
] |
96,114
|
<p>I'm currently modifying a Java script in Rational Functional Tester and I'm trying to tell RFT to wait for an object with a specified set of properties to appear. Specifically, I want to wait until a table with X number of rows appear. The only way I have been able to do it so far is to add a verification point that just verifies that the table has X number of rows, but I have not been able to utilize the wait for object type of VP, so this seems a little bit hacky. Is there a better way to do this?</p>
<p>Jeff</p>
|
[
{
"answer_id": 164822,
"author": "Tom E",
"author_id": 9267,
"author_profile": "https://Stackoverflow.com/users/9267",
"pm_score": 2,
"selected": false,
"text": "find() doc TestObject[] tables = doc.find(atDescendant(\".rowCount\", x), false);\n find() find()"
},
{
"answer_id": 784820,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "while (!flag) {\n if (obj.getproperty(\".text\").equals(\"Desired Text\")) {\n flag = true\n }\n}\n"
},
{
"answer_id": 1659476,
"author": "Rational ",
"author_id": 200744,
"author_profile": "https://Stackoverflow.com/users/200744",
"pm_score": 0,
"selected": false,
"text": "getobject.gettext();\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17601/"
] |
96,123
|
<pre><code>Shell ("explorer.exe www.google.com")
</code></pre>
<p>is how I'm currently opening my products ad page after successful install. However I think it would look much nicer if I could do it more like Avira does, or even a popup where there are no address bar links etc. Doing this via an inbrowser link is easy enough</p>
<pre><code><a href="http://page.com"
onClick="javascript:window.open('http://page.com','windows','width=650,height=350,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,directories=no,status=no'); return false")">Link text</a>
</code></pre>
<p>But how would I go about adding this functionality in VB?</p>
|
[
{
"answer_id": 164822,
"author": "Tom E",
"author_id": 9267,
"author_profile": "https://Stackoverflow.com/users/9267",
"pm_score": 2,
"selected": false,
"text": "find() doc TestObject[] tables = doc.find(atDescendant(\".rowCount\", x), false);\n find() find()"
},
{
"answer_id": 784820,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "while (!flag) {\n if (obj.getproperty(\".text\").equals(\"Desired Text\")) {\n flag = true\n }\n}\n"
},
{
"answer_id": 1659476,
"author": "Rational ",
"author_id": 200744,
"author_profile": "https://Stackoverflow.com/users/200744",
"pm_score": 0,
"selected": false,
"text": "getobject.gettext();\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
96,133
|
<p>I have uncovered another problem in the effort that we are making to port several hundreds of ksh scripts from AIX, Solaris and HPUX to Linux. See <a href="https://stackoverflow.com/questions/74372/how-to-overcome-an-incompatibility-between-the-ksh-on-linux-vs-that-installed-o">here</a> for the previous problem.</p>
<p>This code:</p>
<pre><code>#!/bin/ksh
if [ -a k* ]; then
echo "Oh yeah!"
else
echo "No way!"
fi
exit 0
</code></pre>
<p>(when run in a directory with several files whose name starts with k) produces "Oh yeah!" when called with the AT&T ksh variants (ksh88 and ksh93). On the other hand it produces and error message followed by "No way!" on the other ksh variants (pdksh, MKS ksh and bash).</p>
<p>Again, my question are: </p>
<ul>
<li>Is there an environment variable that will cause pdksh to behave like ksh93? Failing that:</li>
<li>Is there an option on pdksh to get the required behavior?</li>
</ul>
|
[
{
"answer_id": 96857,
"author": "pjz",
"author_id": 8002,
"author_profile": "https://Stackoverflow.com/users/8002",
"pm_score": 0,
"selected": false,
"text": "/usr/bin/test /usr/bin/test /usr/bin/test /usr/bin/test"
},
{
"answer_id": 2711586,
"author": "masta",
"author_id": 325609,
"author_profile": "https://Stackoverflow.com/users/325609",
"pm_score": 0,
"selected": false,
"text": "for K in /etc/rc2.d/K* ; do test -a $K && echo heck-yea ; done\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13029/"
] |
96,137
|
<p>There are lots of people out there asking "why shouldn't we use tables for structuring our HTML" and while a lot of answers come in, I rarely see anyone being converted to the world of semantics. That said, I've yet to see any convincing rebuttals to support the rationale for why we should (or might) use tables.</p>
<p>Anyone care to offer a rationale for when tables are valid structural markup?</p>
<hr>
<p>Nov 7, 2008</p>
<p>Considering that this question didn't go away like I thought it would, I suppose I'd better clarify my question and explain its existence.</p>
<p>Through frustration having read the "tables are easier" argument once too many times following the "DIVs vs. TABLEs" question I wanted to expose the question a little more and not let the table lovers get let off the hook so easily.</p>
<p>Each to their own others might say, but I'm forever being given some application to put on our sites that's been created by some 'tables are easier' developer that dumps a chunk of crappy HTML into my pages, and to be honest, I'm just not seeing enough of the table lovers listening to the arguments.</p>
<p>Anyone use Mambo back in the day? Anyone had to take a bash at putting a design on the top of Microsoft's Sharepoint? Having to fight your way through all that nested table crap was hell, and considering that it was written by some bloody good coders annoys the heck out of me. Reasonable semantic markup has been around for long enough that there should be no reason for developers to still be championing "tables are easier". Tables are not easier - they are lazy!</p>
<p>My question deserved the negative rep for the negative manner in which it was presented, but I'm still waiting for people to accept that the only reason they use tables is because THEY DON'T KNOW HTML. Because if they did, then they'd understand, as jjrv says, that tables are for tabular data.</p>
|
[
{
"answer_id": 8315039,
"author": "Rebecca",
"author_id": 119624,
"author_profile": "https://Stackoverflow.com/users/119624",
"pm_score": 2,
"selected": false,
"text": "<table width=\"100%\">\n<tr><td valign=\"top\">Left nav</td><td valign=\"top\">Main content</td></tr>\n</table>\n <div id=\"content\">\n <div id=\"mainContent\">\n <section>\n <!-- Blog post -->\n </section>\n <section id=\"comments\">\n <!-- Comments -->\n </section>\n <form>\n <!-- Comment form -->\n </form>\n </div>\n <aside>\n <!-- Sidebar -->\n </aside>\n</div>\n #content {\n display: table;\n}\n\n #mainContent {\n display: table-cell;\n width: 620px;\n padding-right: 22px;\n }\n\n aside {\n display: table-cell;\n width: 300px;\n }\n display: table; display: table-cell;"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16124/"
] |
96,150
|
<p>I have an application that uploads an Excel .xls file to the file system, opens the file with an oledbconnection object using the .open() method on the object instance and then stores the data in a database. The upload and writing of the file to the file system works fine but I get an error when trying to open the file on our production server <strong>only</strong>. The application works fine on two other servers (development and testing servers).</p>
<p>The following code generates an 'Unspecified Error' in the Exception.Message.</p>
<p><strong>Quote:</strong></p>
<pre><code> System.Data.OleDb.OleDbConnection x = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + location + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'");
try
{
x.Open();
}
catch (Exception exp)
{
string errorEmailBody = " OpenExcelSpreadSheet() in Utilities.cs. " + exp.Message;
Utilities.SendErrorEmail(errorEmailBody);
}
</code></pre>
<p><strong>:End Quote</strong></p>
<p>The server's c:\\temp and c:\Documents and Settings\\aspnet\local settings\temp folder both give \aspnet full control.</p>
<p>I believe that there is some kind of permissions issue but can't seem to find any difference between the permissions on the noted folders and the folder/directory where the Excel file is uploaded. The same location is used to save the file and open it and the methods do work on my workstation and two web servers. Windows 2000 SP4 servers.</p>
|
[
{
"answer_id": 255298,
"author": "Joshua Turner",
"author_id": 820,
"author_profile": "https://Stackoverflow.com/users/820",
"pm_score": 1,
"selected": false,
"text": "System.Data.OleDb.OleDbConnection x = new System.Data.OleDb.OleDbConnection(@\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='\" + location + \"';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'\");\n"
},
{
"answer_id": 2169874,
"author": "domoaringatoo",
"author_id": 4361,
"author_profile": "https://Stackoverflow.com/users/4361",
"pm_score": 2,
"selected": false,
"text": "Conn.close();"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18164/"
] |
96,153
|
<p>I am trying to figure out how to click a button on a web page programmatically.</p>
<p>Specifically, I have a WinForm with a WebBrowser control. Once it navigates to the target ASP.NET login page I'm trying to work with, in the DocumentCompleted event handler I have the following coded:</p>
<pre><code>HtmlDocument doc = webBrowser1.Document;
HtmlElement userID = doc.GetElementById("userIDTextBox");
userID.InnerText = "user1";
HtmlElement password = doc.GetElementById("userPasswordTextBox");
password.InnerText = "password";
HtmlElement button = doc.GetElementById("logonButton");
button.RaiseEvent("onclick");
</code></pre>
<p>This fills the userid and password text boxes fine, but I am not having any success getting that darned button to click; I've also tried "click", "Click", and "onClick" -- what else is there?. A search of msdn of course gives me no clues, nor groups.google.com. I gotta be close. Or maybe not -- somebody told me I should call the POST method of the page, but how this is done was not part of the advice given. </p>
<p>BTW The button is coded:</p>
<pre><code><input type="submit" name="logonButton" value="Login" onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(); " language="javascript" id="logonButton" tabindex="4" />
</code></pre>
|
[
{
"answer_id": 96172,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": 1,
"selected": false,
"text": "mshtml.IHTMLWindow2 myBroserWindow = (mshtml.IHTMLWindow2)MyWebBrowser.Document.Window.DomWindow;\nmyBroserWindow.execScript(\"Page_ClientValidate();\", \"javascript\");\n"
},
{
"answer_id": 140581,
"author": "Starwatcher",
"author_id": 21264,
"author_profile": "https://Stackoverflow.com/users/21264",
"pm_score": 4,
"selected": true,
"text": "HtmlDocument doc = webBrowser1.Document;\n\ndoc.All[\"userIDTextBox\"].SetAttribute(\"Value\", \"user1\");\ndoc.All[\"userPasswordTextBox\"].SetAttribute(\"Value\", \"Password!\");\ndoc.All[\"logonButton\"].InvokeMember(\"Click\");\n"
},
{
"answer_id": 12495060,
"author": "MonsCamus",
"author_id": 1259649,
"author_profile": "https://Stackoverflow.com/users/1259649",
"pm_score": 1,
"selected": false,
"text": " private HtmlElement GetInputElement(string name, HtmlDocument doc) {\n HtmlElementCollection elems = doc.GetElementsByTagName(\"input\");\n\n foreach (HtmlElement elem in elems)\n {\n String nameStr = elem.GetAttribute(\"value\");\n if (!String.IsNullOrEmpty (nameStr) && nameStr.Equals (name))\n {\n return elem;\n }\n }\n return null;\n }\n GetInputElement(\"Login\", webBrowser1.Document).InvokeMember(\"Click\");\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16964/"
] |
96,156
|
<p>Is it possible to use chapters in videos for the iPhone in an application?</p>
<p>For example:
I have a 3 minutes video to play. I have chapter 1 starting at 0s, chapter 2 at 50s, chapter 3 at 95s.</p>
<p>Can I start plating the video at 50s (chapter 2) until the end? Can I make it play just the chapter 2 from 50s to 95s?</p>
<p>My question is not about how to add chapters to a video. I want to know if this behaviour is available on the iphone.</p>
|
[
{
"answer_id": 891987,
"author": "Vladimir Grigorov",
"author_id": 22764,
"author_profile": "https://Stackoverflow.com/users/22764",
"pm_score": 0,
"selected": false,
"text": "@interface MPMoviePlayerController (extended)\n-(void)setCurrentTime:(double)seconds;\n@end\n MPMoviePlayerController* player = [[ MPMoviePlayerController alloc] initWithContentURL:url ];\n[ player setCurrentTime:95.0 ];\n[ player play ];\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044/"
] |
96,164
|
<p>I'm attempting to convert a home-grown login system to the standard asp.net login control included in .net. I want all communication on the website for a user not logged in to be in clear text, but lock everything in SSL once the user logs in - including the transmission of the username and password.</p>
<p>I had this working before by loading a second page - "loginaction.aspx" - with a https: prefix, then pulling out the username and password by looking for the proper textbox controls in Request.Form.Keys. Is there a way to do something similar using the .net login controls? I dont want to have a seperate login page, but rather include this control (within a loginview) on every page on the site.</p>
|
[
{
"answer_id": 3780392,
"author": "FarReachChad",
"author_id": 456398,
"author_profile": "https://Stackoverflow.com/users/456398",
"pm_score": 1,
"selected": false,
"text": "function forceSSLSubmit() \n{\n\n var strAction = document.forms[0].action.toString();\n\n if (strAction.toLowerCase().indexOf(\"http:\") == 0) {\n strAction = \"https\" + strAction.substring(4);\n\n document.forms[0].action = strAction;\n }\n\n }\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3259/"
] |
96,185
|
<p>I believe the question says it all ... (I'll update if needed)</p>
|
[
{
"answer_id": 3780392,
"author": "FarReachChad",
"author_id": 456398,
"author_profile": "https://Stackoverflow.com/users/456398",
"pm_score": 1,
"selected": false,
"text": "function forceSSLSubmit() \n{\n\n var strAction = document.forms[0].action.toString();\n\n if (strAction.toLowerCase().indexOf(\"http:\") == 0) {\n strAction = \"https\" + strAction.substring(4);\n\n document.forms[0].action = strAction;\n }\n\n }\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9411/"
] |
96,196
|
<p>The <strong>C</strong> preprocessor is justifiably feared and shunned by the C++ community. In-lined functions, consts and templates are usually a safer and superior alternative to a <code>#define</code>.</p>
<p>The following macro: </p>
<pre><code>#define SUCCEEDED(hr) ((HRESULT)(hr) >= 0)
</code></pre>
<p>is in no way superior to the type safe:</p>
<pre><code>inline bool succeeded(int hr) { return hr >= 0; }
</code></pre>
<p>But macros do have their place, please list the uses you find for macros that you <em>can't</em> do without the preprocessor. </p>
<p>Please put each use-cases in a seperate answer so it can be voted up and if you know of how to achieve one of the answers without the preprosessor point out how in that answer's comments.</p>
|
[
{
"answer_id": 96230,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 5,
"selected": false,
"text": "return break continue #define ASSERT_RETURN(condition, ret_val) \\\nif (!(condition)) { \\\n assert(false && #condition); \\\n return ret_val; }\n\n// should really be in a do { } while(false) but that's another discussion.\n"
},
{
"answer_id": 96238,
"author": "Loren Segal",
"author_id": 6436,
"author_profile": "https://Stackoverflow.com/users/6436",
"pm_score": 0,
"selected": false,
"text": "int SomeAPICallbackMethod(long a, long b, SomeCrazyClass c, long d, string e, string f, long double yx) { ... }\nint AnotherCallback(long a, long b, SomeCrazyClass c, long d, string e, string f, long double yx) { ... }\nint YetAnotherCallback(long a, long b, SomeCrazyClass c, long d, string e, string f, long double yx) { ... }\n #define APIARGS long a, long b, SomeCrazyClass c, long d, string e, string f, long double yx\nint SomeAPICallbackMethod(APIARGS) { ... } \n"
},
{
"answer_id": 96239,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 4,
"selected": false,
"text": "#define andm(a, b) (a) && (b)\n\nbool andf(bool a, bool b) { return a && b; }\n\nandm(x, y) // short circuits the operator so if x is false, y would not be evaluated\nandf(x, y) // y will always be evaluated\n"
},
{
"answer_id": 96241,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 3,
"selected": false,
"text": "void lock()\n{\n #ifdef WIN32\n EnterCriticalSection(...)\n #endif\n #ifdef POSIX\n pthread_mutex_lock(...)\n #endif\n}\n"
},
{
"answer_id": 96244,
"author": "Kena",
"author_id": 8027,
"author_profile": "https://Stackoverflow.com/users/8027",
"pm_score": 4,
"selected": false,
"text": "#ifndef MYHEADER_H\n#define MYHEADER_H\n\n...\n\n#endif\n"
},
{
"answer_id": 96248,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 5,
"selected": false,
"text": "assert #x x #define ASSERT_THROW(condition) \\\nif (!(condition)) \\\n throw std::exception(#condition \" is false\");\n"
},
{
"answer_id": 96251,
"author": "jdmichal",
"author_id": 12275,
"author_profile": "https://Stackoverflow.com/users/12275",
"pm_score": 7,
"selected": false,
"text": "#define foreach(list, index) for(index = 0; index < list.size(); index++)\n foreach(cookies, i)\n printf(\"Cookie: %s\", cookies[i]);\n"
},
{
"answer_id": 96259,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "#if defined(MY_OS1) && defined(MY_HARDWARE1)\n#define MY_ACTION(a,b,c) doSothing_OS1HW1(a,b,c);}\n#elif define(MY_OS1) && defined(MY_HARDWARE2)\n#define MY_ACTION(a,b,c) doSomthing_OS1HW2(a,b,c);}\n#elif define(MY_SUPER_OS)\n /* On this hardware it is a null operation */\n#define MY_ACTION(a,b,c)\n#else\n#error \"PLEASE DEFINE MY_ACTION() for this Compiler/OS/HArdware configuration\"\n#endif\n"
},
{
"answer_id": 96268,
"author": "Frank Szczerba",
"author_id": 8964,
"author_profile": "https://Stackoverflow.com/users/8964",
"pm_score": 8,
"selected": true,
"text": "__FILE__ __LINE__ #ifdef ( DEBUG )\n#define M_DebugLog( msg ) std::cout << __FILE__ << \":\" << __LINE__ << \": \" << msg\n#else\n#define M_DebugLog( msg )\n#endif\n std::source_location __LINE__ __FILE__"
},
{
"answer_id": 96300,
"author": "Andrew Stein",
"author_id": 13029,
"author_profile": "https://Stackoverflow.com/users/13029",
"pm_score": 6,
"selected": false,
"text": "#ifdef WE_ARE_ON_WIN32\n#define close(parm1) _close (parm1)\n#define rmdir(parm1) _rmdir (parm1)\n#define mkdir(parm1, parm2) _mkdir (parm1)\n#define access(parm1, parm2) _access(parm1, parm2)\n#define create(parm1, parm2) _creat (parm1, parm2)\n#define unlink(parm1) _unlink(parm1)\n#endif\n"
},
{
"answer_id": 96316,
"author": "Kevin",
"author_id": 6386,
"author_profile": "https://Stackoverflow.com/users/6386",
"pm_score": 6,
"selected": false,
"text": "#define HANDLE_EXCEPTIONS \\\ncatch (::mylib::exception& e) { \\\n throw gcnew MyDotNetLib::Exception(e); \\\n} \\\ncatch (::std::exception& e) { \\\n throw gcnew MyDotNetLib::Exception(e, __LINE__, __FILE__); \\\n} \\\ncatch (...) { \\\n throw gcnew MyDotNetLib::UnknownException(__LINE__, __FILE__); \\\n}\n void Foo()\n{\n try {\n ::mylib::Foo()\n }\n HANDLE_EXCEPTIONS\n}\n __FILE__ __LINE__"
},
{
"answer_id": 96331,
"author": "Keshi",
"author_id": 2430,
"author_profile": "https://Stackoverflow.com/users/2430",
"pm_score": 3,
"selected": false,
"text": "void debugAssert(bool val, const char* file, int lineNumber);\n#define assert(x) debugAssert(x,__FILE__,__LINE__);\n assert(n == true);\n void assert(bool val);\n"
},
{
"answer_id": 96354,
"author": "Johann Gerell",
"author_id": 6345,
"author_profile": "https://Stackoverflow.com/users/6345",
"pm_score": 3,
"selected": false,
"text": "__FILE__ __LINE__ OUR_OWN_THROW OUR_OWN_THROW(InvalidOperationException, (L\"Uninitialized foo!\"));\n InvalidOperationException"
},
{
"answer_id": 96361,
"author": "Mathieu Pagé",
"author_id": 5861,
"author_profile": "https://Stackoverflow.com/users/5861",
"pm_score": 0,
"selected": false,
"text": "#define COMMENT COMMENT_SLASH(/)\n#define COMMENT_SLASH(s) /##s\n\n#if defined _DEBUG\n#define DEBUG_ONLY\n#else\n#define DEBUG_ONLY COMMENT\n#endif\n cout <<\"Hello, World!\" <<endl;\nDEBUG_ONLY cout <<\"This is outputed only in debug mode\" <<endl;\n"
},
{
"answer_id": 96419,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 4,
"selected": false,
"text": "#define RAISE_ERROR_STL(p_strMessage) \\\ndo \\\n{ \\\n try \\\n { \\\n std::tstringstream strBuffer ; \\\n strBuffer << p_strMessage ; \\\n strMessage = strBuffer.str() ; \\\n raiseSomeAlert(__FILE__, __FUNCSIG__, __LINE__, strBuffer.str().c_str()) \\\n } \\\n catch(...){} \\\n { \\\n } \\\n} \\\nwhile(false)\n RAISE_ERROR_STL(\"Hello... The following values \" << i << \" and \" << j << \" are wrong\") ;\n Error Raised:\n====================================\nFile : MyFile.cpp, line 225\nFunction : MyFunction(int, double)\nMessage : \"Hello... The following values 23 and 12 are wrong\"\n #define WRNG_PRIVATE_STR2(z) #z\n#define WRNG_PRIVATE_STR1(x) WRNG_PRIVATE_STR2(x)\n#define WRNG __FILE__ \"(\"WRNG_PRIVATE_STR1(__LINE__)\") : ------------ : \"\n #pragma message(WRNG \"Hello World\")\n C:\\my_project\\my_cpp_file.cpp (225) : ------------ Hello World\n #define MY_TRY try{\n#define MY_CATCH } catch(...) {\n#define MY_END_TRY }\n MY_TRY\n doSomethingDangerous() ;\nMY_CATCH\n tryToRecoverEvenWithoutMeaningfullInfo() ;\n damnThoseMacros() ;\nMY_END_TRY\n boost::foreach #include <string>\n#include <iostream>\n#include <boost/foreach.hpp>\n\nint main()\n{\n std::string hello( \"Hello, world!\" );\n\n BOOST_FOREACH( char ch, hello )\n {\n std::cout << ch;\n }\n\n return 0;\n}\n std::for_each"
},
{
"answer_id": 96803,
"author": "Andrew Johnson",
"author_id": 5109,
"author_profile": "https://Stackoverflow.com/users/5109",
"pm_score": 3,
"selected": false,
"text": "/*\n * List of fields, names and values.\n */\nFIELD(EXAMPLE1, \"first example\", 10)\nFIELD(EXAMPLE2, \"second example\", 96)\nFIELD(ANOTHER, \"more stuff\", 32)\n...\n#undef FIELD\n #define FIELD(name, desc, value) FIELD_ ## name,\n\ntypedef field_ {\n\n#include \"field_list.h\"\n\n FIELD_MAX\n\n} field_en;\n #define FIELD(name, desc, value) \\\n table[FIELD_ ## name].desc = desc; \\\n table[FIELD_ ## name].value = value;\n\n#include \"field_list.h\"\n"
},
{
"answer_id": 96942,
"author": "Andrew Johnson",
"author_id": 5109,
"author_profile": "https://Stackoverflow.com/users/5109",
"pm_score": 2,
"selected": false,
"text": "#define malloc memlog_malloc\n#define calloc memlog calloc\n#define free memlog_free\n gcc -Imemlog_preinclude.h ...\n"
},
{
"answer_id": 97292,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 2,
"selected": false,
"text": "#define ARRAY_SIZE(arr) (sizeof arr / sizeof arr[0])\n char src[23];\nint dest[ARRAY_SIZE(src)];\n"
},
{
"answer_id": 98993,
"author": "mbac32768",
"author_id": 18446,
"author_profile": "https://Stackoverflow.com/users/18446",
"pm_score": 0,
"selected": false,
"text": "#define my_free(x) do { free(x); x = NULL; } while (0)\n"
},
{
"answer_id": 99380,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 2,
"selected": false,
"text": "#define -D /D"
},
{
"answer_id": 99437,
"author": "LarryF",
"author_id": 18518,
"author_profile": "https://Stackoverflow.com/users/18518",
"pm_score": 2,
"selected": false,
"text": "#define dbgmsg(_FORMAT, ...) if((debugmsg_flag & 0x00000001) || (debugmsg_flag & 0x80000000)) { log_dbgmsg(_FORMAT, __VA_ARGS__); }\n #define SECURITY_CHECK(lRequiredSecRoles) if(!DoSecurityCheck(lRequiredSecRoles, #lRequiredSecRoles, true)) return\n#define SECURITY_CHECK_QUIET(lRequiredSecRoles) (DoSecurityCheck(lRequiredSecRoles, #lRequiredSecRoles, false))\n SECURITY_CHECK(ROLE_BUSINESS_INFORMATION_STEWARD | ROLE_WORKER_ADMINISTRATOR);\n\nLRESULT CAddPerson1::OnWizardNext() \n{\n if(m_Role.GetItemData(m_Role.GetCurSel()) == parent->ROLE_EMPLOYEE) {\n SECURITY_CHECK(ROLE_WORKER_ADMINISTRATOR | ROLE_BUSINESS_INFORMATION_STEWARD ) -1;\n } else if(m_Role.GetItemData(m_Role.GetCurSel()) == parent->ROLE_CONTINGENT) {\n SECURITY_CHECK(ROLE_CONTINGENT_WORKER_ADMINISTRATOR | ROLE_BUSINESS_INFORMATION_STEWARD | ROLE_WORKER_ADMINISTRATOR) -1;\n }\n...\n"
},
{
"answer_id": 165410,
"author": "Eric",
"author_id": 4540,
"author_profile": "https://Stackoverflow.com/users/4540",
"pm_score": 1,
"selected": false,
"text": "// file foo.h, defines class Foo and various members on it without ever repeating the\n// list of fields.\n\n#if defined( FIELD_LIST )\n // here's the actual list of fields in the class. If FIELD_LIST is defined, we're at\n // the 3rd level of inclusion and somebody wants to actually use the field list. In order\n // to do so, they will have defined the macros STRING and INT before including us.\n STRING( fooString )\n INT( barInt ) \n#else // defined( FIELD_LIST )\n\n#if !defined(FOO_H)\n#define FOO_H\n\n#define DEFINE_STRUCT\n// recursively include this same file to define class Foo\n#include \"foo.h\"\n#undef DEFINE_STRUCT\n\n#define DEFINE_CLEAR\n// recursively include this same file to define method Foo::clear\n#include \"foo.h\"\n#undef DEFINE_CLEAR\n\n// etc ... many more interesting examples like serialization\n\n#else // defined(FOO_H)\n// from here on, we know that FOO_H was defined, in other words we're at the second level of\n// recursive inclusion, and the file is being used to make some particular\n// use of the field list, for example defining the class or a single method of it\n\n#if defined( DEFINE_STRUCT )\n#define STRING(a) std::string a;\n#define INT(a) long a;\n class Foo\n {\n public:\n#define FIELD_LIST\n// recursively include the same file (for the third time!) to get fields\n// This is going to translate into:\n// std::string fooString;\n// int barInt;\n#include \"foo.h\"\n#endif\n\n void clear();\n };\n#undef STRING\n#undef INT\n#endif // defined(DEFINE_STRUCT)\n\n\n#if defined( DEFINE_ZERO )\n#define STRING(a) a = \"\";\n#define INT(a) a = 0;\n#define FIELD_LIST\n void Foo::clear()\n {\n// recursively include the same file (for the third time!) to get fields.\n// This is going to translate into:\n// fooString=\"\";\n// barInt=0;\n#include \"foo.h\"\n#undef STRING\n#undef int\n }\n#endif // defined( DEFINE_ZERO )\n\n// etc...\n\n\n#endif // end else clause for defined( FOO_H )\n\n#endif // end else clause for defined( FIELD_LIST )\n"
},
{
"answer_id": 212773,
"author": "David Thornley",
"author_id": 14148,
"author_profile": "https://Stackoverflow.com/users/14148",
"pm_score": 6,
"selected": false,
"text": "__LINE__ __FILE__"
},
{
"answer_id": 212792,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 0,
"selected": false,
"text": "void Log::trace(const char *pszMsg) {\n if (!bDebugBuild) {\n return;\n }\n // Do the logging\n}\n\n...\n\nlog.trace(\"Inside MyFunction\");\n #ifdef _DEBUG\n#define LOG_TRACE log.trace\n#else\n#define LOG_TRACE void\n#endif\n\n...\n\nLOG_TRACE(\"Inside MyFunction\");\n"
},
{
"answer_id": 227412,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 5,
"selected": false,
"text": "const char * #define BASE_HKEY \"Software\\\\Microsoft\\\\Internet Explorer\\\\\"\n// Now we can concat with other literals\nRegOpenKey(HKEY_CURRENT_USER, BASE_HKEY \"Settings\", &settings);\nRegOpenKey(HKEY_CURRENT_USER, BASE_HKEY \"TypedURLs\", &URLs);\n const char * const char* BaseHkey = \"Software\\\\Microsoft\\\\Internet Explorer\\\\\";\nRegOpenKey(HKEY_CURRENT_USER, (string(BaseHkey) + \"Settings\").c_str(), &settings);\nRegOpenKey(HKEY_CURRENT_USER, (string(BaseHkey) + \"TypedURLs\").c_str(), &URLs);\n"
},
{
"answer_id": 1297177,
"author": "dwj",
"author_id": 346,
"author_profile": "https://Stackoverflow.com/users/346",
"pm_score": 1,
"selected": false,
"text": "// TICKS_PER_UNIT is defined in floating point to allow the conversions to compute during compile-time.\n#define TICKS_PER_UNIT 1024.0\n\n\n// NOTE: The TICKS_PER_x_MS will produce constants in the preprocessor. The (long) cast will\n// guarantee there are no floating point values in the embedded code and will produce a warning\n// if the constant is larger than the data type being stored to.\n// Adding 0.5 sec to the calculation forces rounding instead of truncation.\n#define TICKS_PER_1_MS( ms ) (long)( ( ( ms * TICKS_PER_UNIT ) / 1000 ) + 0.5 )\n"
},
{
"answer_id": 2199256,
"author": "Notinlist",
"author_id": 163454,
"author_profile": "https://Stackoverflow.com/users/163454",
"pm_score": 1,
"selected": false,
"text": "#define foreach(T, c, i) for(T::iterator i=(c).begin(); i!=(c).end(); ++i)\n#define foreach_const(T, c, i) for(T::const_iterator i=(c).begin(); i!=(c).end(); ++i)\n void MultiplyEveryElementInList(std::list<int>& ints, int mul)\n{\n foreach(std::list<int>, ints, i)\n (*i) *= mul;\n}\n\nint GetSumOfList(const std::list<int>& ints)\n{\n int ret = 0;\n foreach_const(std::list<int>, ints, i)\n ret += *i;\n return ret;\n}\n"
},
{
"answer_id": 2662237,
"author": "rkellerm",
"author_id": 213615,
"author_profile": "https://Stackoverflow.com/users/213615",
"pm_score": 1,
"selected": false,
"text": "typedef ...some struct\n typedef ...some another struct\n #ifdef WIN32\n#define TYPES_H \"WINTYPES.H\"\n#else \n#define TYPES_H \"POSIX_TYPES.H\"\n#endif\n\n#include TYPES_H\n"
},
{
"answer_id": 5925535,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": -1,
"selected": false,
"text": "#define COLUMNS(A,B) [(B) - (A) + 1]\n\nstruct \n{\n char firstName COLUMNS( 1, 30);\n char lastName COLUMNS( 31, 60);\n char address1 COLUMNS( 61, 90);\n char address2 COLUMNS( 91, 120);\n char city COLUMNS(121, 150);\n};\n"
},
{
"answer_id": 6364467,
"author": "MrBeast",
"author_id": 800422,
"author_profile": "https://Stackoverflow.com/users/800422",
"pm_score": 2,
"selected": false,
"text": "DEF_EXCEPTION(RessourceNotFound, \"Ressource not found\")\n #define DEF_EXCEPTION(A, B) class A : public exception\\\n {\\\n public:\\\n virtual const char* what() const throw()\\\n {\\\n return B;\\\n };\\\n }\\\n"
},
{
"answer_id": 7077922,
"author": "Martin Ba",
"author_id": 321013,
"author_profile": "https://Stackoverflow.com/users/321013",
"pm_score": 1,
"selected": false,
"text": "#define CALL_RETURN_WRAPPER(FnType, FName, ...) \\\n if( FnType theFunction = get_op_from_name(FName) ) { \\\n return theFunction(__VA_ARGS__); \\\n } else { \\\n throw invalid_function_name(FName); \\\n } \\\n/**/\n get_op_from_name"
},
{
"answer_id": 51674754,
"author": "einpoklum",
"author_id": 1593077,
"author_profile": "https://Stackoverflow.com/users/1593077",
"pm_score": -1,
"selected": false,
"text": "switch(x) {\ncase val1: do_stuff(); break;\ncase val2: do_other_stuff();\ncase val3: yet_more_stuff();\ndefault: something_else();\n}\n SWITCH(x)\nCASE val1 do_stuff(); break;\nCASE val2 do_other_stuff();\nCASE val3 yet_more_stuff();\nDEFAULT something_else();\nEND\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] |
96,211
|
<p>When writing manual SQL its pretty easy to estimate the size and shape of data returned by a query. I'm increasingly finding it hard to do this with LINQ to SQL queries. Sometimes I find WAY more data than I was expecting - which can really slow down a remote client that is accessing a database directly.</p>
<p>I'd like to be able to run a query and then tell exactly how much data has been returned across the wire, and use this to help me optimize. </p>
<p>I have already hooked up a log using the DataContext.Log method, but that only gives me an indication of the SQL sent, not the data received.</p>
<p>Any tips?</p>
|
[
{
"answer_id": 585641,
"author": "Martin Meixger",
"author_id": 64466,
"author_profile": "https://Stackoverflow.com/users/64466",
"pm_score": 0,
"selected": false,
"text": "SqlConnection sqlConnection = new SqlConnection(\"your_connection_string\");\n// enable statistics\ncn.StatisticsEnabled = true;\n\n// create your DataContext with the SqlConnection\nNorthWindDataContext nwContext = new NorthWindDataContext(sqlConnection);\n\nvar products = from product in nwContext\n where product.Category.CategoryName = \"Beverages\"\n select product;\nforeach (var product in products)\n{\n //do something with product\n}\n\n// retrieve statistics - for keys see http://msdn.microsoft.com/en-us/library/7h2ahss8(VS.80).aspx\nstring bytesSent = sqlConnection.RetrieveStatistics()[\"BytesSent\"].ToString();\nstring bytesReceived = sqlConnection.RetrieveStatistics()[\"BytesReceived\"].ToString();\n"
},
{
"answer_id": 587340,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 1,
"selected": false,
"text": " ((SqlConnection)dc.Connection).StatisticsEnabled = true;\n ((SqlConnection)dc.Connection).RetrieveStatistics()\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16940/"
] |
96,247
|
<p>I create a web application (WAR) and deploy it on Tomcat. In the <em>webapp</em> there is a page with a form where an administrator can enter some configuration data. I don't want to store this data in an DBMS, but just in an XML file on the file system. Where to put it?</p>
<p>I would like to put the file somewhere in the directory tree where the application itself is deployed. Should my configuration file be in the <em>WEB-INF</em> directory? Or put it somewhere else? </p>
<p>And what is the Java code to use in a servlet to find the absolute path of the directory? Or can it be accessed with a relative path?</p>
|
[
{
"answer_id": 96469,
"author": "Jataro",
"author_id": 9292,
"author_profile": "https://Stackoverflow.com/users/9292",
"pm_score": 4,
"selected": false,
"text": "public void init(ServletConfig servletConfig) throws ServletException{\n super.init(servletConfig);\n String path = servletConfig.getServletContext().getRealPath(\"/WEB-INF\")\n"
},
{
"answer_id": 96568,
"author": "Michael",
"author_id": 13379,
"author_profile": "https://Stackoverflow.com/users/13379",
"pm_score": 3,
"selected": false,
"text": "WEB-INF WEB-INF"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17746/"
] |
96,249
|
<p>Adding an element to the head of an alist (Associative list) is simple enough:</p>
<pre><code>> (cons '(ding . 53) '((foo . 42) (bar . 27)))
((ding . 53) (foo . 42) (bar . 27))
</code></pre>
<p>Appending to the tail of an alist is a bit trickier though. After some experimenting, I produced this:</p>
<pre><code>> (define (alist-append alist pair) `(,@alist ,pair))
> (alist-append '((foo . 42) (bar . 27)) '(ding . 53))
'((foo . 42) (bar . 27) (ding . 53))
</code></pre>
<p>However, it seems to me, that this isn't the idiomatic solution. So how is this usually done in scheme? Or is this in fact the way?</p>
|
[
{
"answer_id": 96754,
"author": "Matthias Benkard",
"author_id": 15517,
"author_profile": "https://Stackoverflow.com/users/15517",
"pm_score": 3,
"selected": false,
"text": "(acons key value alist)\n (cons (cons key value) alist)\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18180/"
] |
96,250
|
<p>My project has both client and server components in the same solution file. I usually have the debugger set to start them together when debugging, but it's often the case where I start the server up outside of the debugger so I can start and stop the client as needed when working on client-side only stuff. (this is much faster). </p>
<p>I'm trying to save myself the hassle of poking around in Solution Explorer to start individual projects and would rather just stick a button on the toolbar that calls a macro that starts the debugger for individual projects (while leaving "F5" type debugging alone to start up both processess). </p>
<p>I tried recording, but that didn't really result in anything useful. </p>
<p>So far all I've managed to do is to locate the project item in the solution explorer: </p>
<pre><code> Dim projItem As UIHierarchyItem
projItem = DTE.ToolWindows.SolutionExplorer.GetItem("SolutionName\ProjectFolder\ProjectName").Select(vsUISelectionType.vsUISelectionTypeSelect)
</code></pre>
<p>(This is based loosely on how the macro recorder tried to do it. I'm not sure if navigating the UI object model is the correct approach, or if I should be looking at going through the Solution/Project object model instead). </p>
|
[
{
"answer_id": 96478,
"author": "Jason Diller",
"author_id": 2187,
"author_profile": "https://Stackoverflow.com/users/2187",
"pm_score": 4,
"selected": true,
"text": " Sub DebugTheServer()\n DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate()\n DTE.ActiveWindow.Object.GetItem(\"Solution\\ServerFolder\\ServerProject\").Select(vsUISelectionType.vsUISelectionTypeSelect)\n DTE.Windows.Item(Constants.vsWindowKindOutput).Activate()\n DTE.ExecuteCommand(\"ClassViewContextMenus.ClassViewProject.Debug.Startnewinstance\")\n End Sub\n"
},
{
"answer_id": 32282888,
"author": "Erwin Mayer",
"author_id": 541420,
"author_profile": "https://Stackoverflow.com/users/541420",
"pm_score": 0,
"selected": false,
"text": "Dte.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate();\nDte.ToolWindows.SolutionExplorer.GetItem(\"SolutionName\\\\SolutionFolderName\\\\ProjectName\").Select(vsUISelectionType.vsUISelectionTypeSelect);\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2187/"
] |
96,264
|
<p>I have two code bases of an application. I need to copy all the files in all the directories with .java from the newer code base, to the older (so I can commit it to svn).</p>
<p>How can I write a batch files to do this?</p>
|
[
{
"answer_id": 96270,
"author": "Danimal",
"author_id": 2757,
"author_profile": "https://Stackoverflow.com/users/2757",
"pm_score": 4,
"selected": true,
"text": "xcopy c:\\olddir\\*.java c:\\newdir /D /E /Q /Y\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5653/"
] |
96,265
|
<p>I am programming a game on the iPhone. I am currently using NSTimer to trigger my game update/render. The problem with this is that (after profiling) I appear to lose a lot of time between updates/renders and this seems to be mostly to do with the time interval that I plug into NSTimer. </p>
<p>So my question is what is the best alternative to using NSTimer?</p>
<p>One alternative per answer please.</p>
|
[
{
"answer_id": 224891,
"author": "zoul",
"author_id": 17279,
"author_profile": "https://Stackoverflow.com/users/17279",
"pm_score": 4,
"selected": false,
"text": "- (void) gameLoop\n{\n while (running)\n {\n NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];\n [self renderFrame];\n [pool release];\n }\n}\n\n- (void) startLoop\n{\n running = YES;\n#ifdef THREADED_ANIMATION\n [NSThread detachNewThreadSelector:@selector(gameLoop)\n toTarget:self withObject:nil];\n#else\n timer = [NSTimer scheduledTimerWithTimeInterval:1.0f/60\n target:self selector:@selector(renderFrame) userInfo:nil repeats:YES];\n#endif\n}\n\n- (void) stopLoop\n{\n [timer invalidate];\n running = NO;\n}\n renderFrame"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25868/"
] |
96,285
|
<p>I'm fresh out of college and have been working in C++ for some time now. I understand all the basics of C++ and use them, but I'm having a hard time grasping more advanced topics like pointers and classes. I've read some books and tutorials and I understand the examples in them, but then when I look at some advanced real life examples I cannot figure them out. This is killing me because I feel like its keeping me from bring my C++ programming to the next level. Did anybody else have this problem? If so, how did you break through it?
Does anyone know of any books or tutorials that really describe pointers and class concepts well?
or maybe some example code with good descriptive comments using advanced pointers and class techniques?
any help would be greatly appreciated.</p>
|
[
{
"answer_id": 96310,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 0,
"selected": false,
"text": "x = 500; // memory address for hello;\nMEMORY[x] = \"hello\"; \nprint MEMORY[x]; \n #define MEMORY 0; \n#define MEMORYADDRESS( a ) *a;\n"
},
{
"answer_id": 96355,
"author": "nsanders",
"author_id": 1244,
"author_profile": "https://Stackoverflow.com/users/1244",
"pm_score": 4,
"selected": false,
"text": "int foo = 3; // integer\nint* bar = &foo; // assigns the address of foo to my pointer bar\n *bar = 5; // asterix means \"dereference\" (follow the arrow), foo is now 5\nbar = 0; // I just changed the address that bar points to\n"
},
{
"answer_id": 96891,
"author": "PiNoYBoY82",
"author_id": 13646,
"author_profile": "https://Stackoverflow.com/users/13646",
"pm_score": 1,
"selected": false,
"text": "HeartCard card = 4; // 4 of hearts!\n HeartCard card = 4; // 4 of hearts!\nprint &card // the address is BEGINNING!\n HeartCard *pointerToCard = MakeMyCard( \"10 of hearts\" );\nprint pointerToCard // the value of this is BEGINNING!\nprint *pointerToCard // this will be 10 of hearts!\n HeartCard *pointerToCard = MakeMyCard( \"10 of hearts\" );\nHeartCard card = 4; // 4 of hearts!\nprint *pointerToCard; // prints 10 of hearts\nprint pointerToCard; // prints BEGINNING\nprint card; // prints 4 of hearts\nprint &card; // prints END - the 4 of hearts used to be on top but we flipped over the deck!\n"
},
{
"answer_id": 98525,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 4,
"selected": false,
"text": "int x = 10;\n Expression Value\n----------------------------------\nx 10\n&x 1001\n int* xptr = &x;\n Variable lvalue rvalue\n--------------------------------------------\nx 1001 10 \nxptr 1002 1001\n int y = *xptr;\n Expression Value\n--------------------------------------------\nx 10\n&x 1001\nxptr 1001\n&xptr 1002\n*xptr 10\n int x = 10;\nint *xptr = &x;\n\nprintf(\"x = %d\\n\", x);\nprintf(\"&x = %d\\n\", &x); \nprintf(\"xptr = %d\\n\", xptr);\nprintf(\"*xptr = %d\\n\", *xptr);\n\n*xptr = 20;\n\nprintf(\"x = %d\\n\", x);\nprintf(\"*xptr = %d\\n\", *xptr);\n x = 10\n&x = 3537176\nxptr = 3537176\n*xptr = 10\nx = 20\n*xptr = 20\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117494/"
] |
96,297
|
<h2>General</h2>
<ul>
<li>Follow the same standards for all tests.</li>
<li>Be clear about what each test state is.</li>
<li>Be specific about the expected behavior.</li>
</ul>
<h2>Examples</h2>
<p>1) MethodName_StateUnderTest_ExpectedBehavior</p>
<pre><code>Public void Sum_NegativeNumberAs1stParam_ExceptionThrown()
Public void Sum_NegativeNumberAs2ndParam_ExceptionThrown ()
Public void Sum_simpleValues_Calculated ()
</code></pre>
<p>Source: <a href="http://osherove.com/blog/2005/4/3/naming-standards-for-unit-tests.html" rel="noreferrer">Naming standards for Unit Tests</a></p>
<p>2) Separating Each Word By Underscore</p>
<pre><code>Public void Sum_Negative_Number_As_1st_Param_Exception_Thrown()
Public void Sum_Negative_Number_As_2nd_Param_Exception_Thrown ()
Public void Sum_Simple_Values_Calculated ()
</code></pre>
<h2>Other</h2>
<ul>
<li>End method names with <em>Test</em></li>
<li>Start method names with class name</li>
</ul>
|
[
{
"answer_id": 1292173,
"author": "Jehof",
"author_id": 83039,
"author_profile": "https://Stackoverflow.com/users/83039",
"pm_score": 5,
"selected": false,
"text": "[TestMethod]\npublic void CanCountAllItems() {\n // Test the total count of items in collection.\n}\n [TestClass]\npublic class SuperCollectionTests(){\n // Any test methods that test the class SuperCollection\n}\n [TestMethod]\n[ExpectedException(typeOf(ArgumentException))]\npublic void CannotAddSameObjectAgain() {\n // Cannot add the same object again to the collection.\n}\n"
},
{
"answer_id": 4622383,
"author": "user566399",
"author_id": 566399,
"author_profile": "https://Stackoverflow.com/users/566399",
"pm_score": -1,
"selected": false,
"text": "AProj\n Objects\n AnObj\n AProp\n Misc\n Functions\n AFunc\n Tests\n TObjects\n TAnObj\n TAnObjsAreEqualUnderCondition\n TMisc\n TFunctions\n TFuncBehavesUnderCondition\n"
},
{
"answer_id": 8955564,
"author": "Robs",
"author_id": 78077,
"author_profile": "https://Stackoverflow.com/users/78077",
"pm_score": 5,
"selected": false,
"text": "using Xunit;\n\npublic class TitleizerFacts\n{\n public class TheTitleizerMethod\n {\n [Fact]\n public void NullName_ReturnsDefaultTitle()\n {\n // Test code\n }\n\n [Fact]\n public void Name_AppendsTitle()\n {\n // Test code\n }\n }\n\n public class TheKnightifyMethod\n {\n [Fact]\n public void NullName_ReturnsDefaultTitle()\n {\n // Test code\n }\n\n [Fact]\n public void MaleNames_AppendsSir()\n {\n // Test code\n }\n\n [Fact]\n public void FemaleNames_AppendsDame()\n {\n // Test code\n }\n }\n}\n"
},
{
"answer_id": 9298985,
"author": "CodingWithSpike",
"author_id": 28278,
"author_profile": "https://Stackoverflow.com/users/28278",
"pm_score": 5,
"selected": false,
"text": "MethodName_DoesWhat_WhenTheseConditions Sum_ThrowsException_WhenNegativeNumberAs1stParam\n UnderTheseTestConditions_WhenIDoThis_ThenIGetThis WhenNegativeNumberAs1stParam_Sum_ThrowsAnException\n Sum_ThrowsException_WhenNegativeNumberAs1stParam Sum_Throws_Exception_When_Negative_Number_As_1st_Param"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18170/"
] |
96,313
|
<p>I've got a couple large checkouts where the .svn folder has become damaged so I'm getting and error, "Cleanup failed to process the following path.." And I can no longer commit or update files in that directory.</p>
<p>I'd just delete and do the checkout again but the whole directory is over a gig.</p>
<p>Is there a tool that will restore the .svn folders for specific folders without having to download everything?</p>
<p>I understand that it's going to have to download all the files in that one folder so that it can determine if they've been changed..but subdirectories with valid .svn folders should be fine.</p>
<p>Oh.. I'm a big fan of TortoiseSVN or the command line for linux.</p>
<p>Thoughts?</p>
|
[
{
"answer_id": 96415,
"author": "Sander Rijken",
"author_id": 5555,
"author_profile": "https://Stackoverflow.com/users/5555",
"pm_score": 6,
"selected": true,
"text": "svn checkout --depth files --force REPOS WC\n svn update --depth files --force WC\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1430/"
] |
96,317
|
<p>Given an instance of <code>System.Reflection.Assembly</code>.</p>
|
[
{
"answer_id": 6260206,
"author": "Lisa",
"author_id": 314283,
"author_profile": "https://Stackoverflow.com/users/314283",
"pm_score": 6,
"selected": false,
"text": "XmlSchema mySchema;\nstring resourceName = \"MyEmbeddedSchema.xsd\";\nstring resourcesFolderName = \"Serialisation\";\nstring manifestResourceName = string.Format(\"{0}.{1}.{2}\",\n this.GetType().Namespace, resourcesFolderName, resourceName);\nusing (Stream schemaStream = currentAssembly.GetManifestResourceStream(manifestResourceName))\n mySchema = XmlSchema.Read(schemaStream, errorHandler);\n"
},
{
"answer_id": 24514107,
"author": "Tarek Haydar",
"author_id": 3729799,
"author_profile": "https://Stackoverflow.com/users/3729799",
"pm_score": 2,
"selected": false,
"text": "GetType(frm).Namespace\n frm"
},
{
"answer_id": 33651494,
"author": "Andy",
"author_id": 941676,
"author_profile": "https://Stackoverflow.com/users/941676",
"pm_score": 3,
"selected": false,
"text": "typeof(Root).Namespace;\n"
},
{
"answer_id": 36288455,
"author": "Mr.B",
"author_id": 1002613,
"author_profile": "https://Stackoverflow.com/users/1002613",
"pm_score": 2,
"selected": false,
"text": "typeof(App).Namespace"
},
{
"answer_id": 37108551,
"author": "Chris Moschini",
"author_id": 176877,
"author_profile": "https://Stackoverflow.com/users/176877",
"pm_score": 0,
"selected": false,
"text": " public static string GetRootNamespace()\n {\n StackTrace stackTrace = new StackTrace();\n StackFrame[] stackFrames = stackTrace.GetFrames();\n string ns = null;\n foreach(var frame in stackFrames)\n {\n string _ns = frame.GetMethod().DeclaringType.Namespace;\n int indexPeriod = _ns.IndexOf('.');\n string rootNs = _ns;\n if (indexPeriod > 0)\n rootNs = _ns.Substring(0, indexPeriod);\n\n if (rootNs == \"System\")\n break;\n ns = _ns;\n }\n\n return ns;\n }\n"
},
{
"answer_id": 42400492,
"author": "jhyry-gcpud",
"author_id": 6010052,
"author_profile": "https://Stackoverflow.com/users/6010052",
"pm_score": 0,
"selected": false,
"text": "Dim baseNamespace = String.Join(\".\"c,\n Me.GetType().Assembly.ManifestModule.GetTypes().\n Select(Function(type As Type)\n Return type.Namespace.Split(\".\"c)\n End Function\n ).\n Aggregate(Function(seed As String(), splitNamespace As String())\n Return seed.Intersect(splitNamespace).ToArray()\n End Function\n )\n)\n"
},
{
"answer_id": 44445070,
"author": "Howard",
"author_id": 459778,
"author_profile": "https://Stackoverflow.com/users/459778",
"pm_score": 0,
"selected": false,
"text": "''' <summary>\n''' Returns the namespace of the currently running website\n''' </summary>\nPublic Function GetWebsiteRootNamespace() As String\n For Each Asm In AppDomain.CurrentDomain.GetAssemblies()\n If Asm Is Nothing OrElse Asm.IsDynamic Then Continue For\n\n For Each Typ In Asm.GetTypes\n If Typ Is Nothing OrElse Typ.Name Is Nothing Then Continue For\n If Typ.Name = \"MyProject\" Then Return Typ.Namespace.Split(\".\"c)(0)\n Next\n Next\n\n Return Nothing\nEnd Function\n"
},
{
"answer_id": 70205992,
"author": "CBFT",
"author_id": 11820068,
"author_profile": "https://Stackoverflow.com/users/11820068",
"pm_score": 0,
"selected": false,
"text": "var assembly = System.Reflection.Assembly.GetExecutingAssembly();\nstring[] resourceNames = assembly.GetManifestResourceNames();\n\nstring resourceNameNoNamespace = $\"Languages.{languageSupport.IsoCode}.Languages.xml\";\nvar match = resourceNames.SingleOrDefault(rn => rn.EndsWith(resourceNameNoNamespace));\n"
},
{
"answer_id": 72977752,
"author": "Ondřej",
"author_id": 1796973,
"author_profile": "https://Stackoverflow.com/users/1796973",
"pm_score": 0,
"selected": false,
"text": "Dim applicationNamespace = TextBeforeFirst(Assembly.GetCallingAssembly().EntryPoint.DeclaringType.Namespace, \".\")\n\nPublic Function TextBeforeFirst(value As String, expression As String) As String\n If String.IsNullOrEmpty(value) Or String.IsNullOrEmpty(expression) Then Return Nothing\n Dim index = value.IndexOf(expression)\n If index = -1 Then Return Nothing\n Dim length = index\n Return value.Substring(0, length)\nEnd Function\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4094/"
] |
96,326
|
<p>I need to attach a file with mailx but at the moment I am not having success.</p>
<p><strong>Here's my code:</strong></p>
<pre><code>subject="Something happened"
to="somebody@somewhere.com"
body="Attachment Test"
attachment=/path/to/somefile.csv
uuencode $attachment | mailx -s "$subject" "$to" << EOF
The message is ready to be sent with the following file or link attachments:
somefile.csv
Note: To protect against computer viruses, e-mail programs may prevent
sending or receiving certain types of file attachments. Check your
e-mail security settings to determine how attachments are handled.
EOF
</code></pre>
<p>Any feedback would be highly appreciated.</p>
<hr>
<p><strong>Update</strong>
I have added the attachment var to avoid having to use the path every time.</p>
|
[
{
"answer_id": 96616,
"author": "Thomas Kammeyer",
"author_id": 4410,
"author_profile": "https://Stackoverflow.com/users/4410",
"pm_score": 1,
"selected": false,
"text": "cat <<EOF | ( cat -; uuencode -m /path/to/somefile.csv /path/to/somefile.csv; ) | mailx -s \"$subject\" \"$to\" \nplace your message from the here block in your example here\nEOF\n"
},
{
"answer_id": 96636,
"author": "Palmin",
"author_id": 5949,
"author_profile": "https://Stackoverflow.com/users/5949",
"pm_score": 3,
"selected": true,
"text": "$ subject=\"Something happened\"\n$ to=\"somebody@somewhere.com\"\n$ body=\"Attachment Test\"\n$ attachment=/path/to/somefile.csv\n$\n$ cat >msg.txt <<EOF\n> The message is ready to be sent with the following file or link attachments:\n>\n> somefile.csv\n>\n> Note: To protect against computer viruses, e-mail programs may prevent\n> sending or receiving certain types of file attachments. Check your\n> e-mail security settings to determine how attachments are handled.\n>\n> EOF\n$ ( cat msg.txt ; uuencode $attachment somefile.csv) | mailx -s \"$subject\" \"$to\"\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6992/"
] |
96,340
|
<p>We have a suite of interlinked .Net 3.5 applications. Some are web sites, some are web services, and some are windows applications. Each app currently has its own configuration file (app.config or web.config), and currently there are some duplicate keys across the config files (which at the moment are kept in sync manually) as multiple apps require the same config value. Also, this suite of applications is deployed across various envrionemnts (dev, test, live etc)</p>
<p>What is the best approach to managing the configuration of these multiple apps from a single configuration source, so configuration values can be shared between multiple apps if required? We would also like to have separate configs for each environment (so when deploying you don't have to manually change certain config values that are environment specific such as conenction strings), but at the same time don't want to maintain multiple large config files (one for each environment) as keeping this in sync when adding new config keys will prove troublesome.</p>
|
[
{
"answer_id": 96454,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 2,
"selected": false,
"text": "<SomeConfigSection>\n <SettingA/>\n <SettingB/>\n</SomeConfigSection>\n<OtherSection>\n <SettingX/>\n</OtherSection>\n <SomeConfigSection file=\"SomeSetting.xml\" />\n<OtherSection file=\"Other.xml\" />\n if debug copy SomeSettingDebug.xml deploydir/SomeSetting.xml\nif MySql copy OtherSectionMySql.xml deploydir/OtherSetting.xml\n"
},
{
"answer_id": 96466,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 2,
"selected": true,
"text": "<MyAppConfig>\n <DbConnString>${DbConnString}</DbConnString>\n <WebServiceUri uri=\"${WebServiceUri}\" />\n</MyAppConfig>\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17765/"
] |
96,360
|
<p>I am trying to write a servlet that will send a XML file (xml formatted string) to another servlet via a POST.
(Non essential xml generating code replaced with "Hello there")</p>
<pre><code> StringBuilder sb= new StringBuilder();
sb.append("Hello there");
URL url = new URL("theservlet's URL");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Length", "" + sb.length());
OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream());
outputWriter.write(sb.toString());
outputWriter.flush();
outputWriter.close();
</code></pre>
<p>This is causing a server error, and the second servlet is never invoked.</p>
|
[
{
"answer_id": 96393,
"author": "Craig B.",
"author_id": 10780,
"author_profile": "https://Stackoverflow.com/users/10780",
"pm_score": 2,
"selected": false,
"text": "connection.setDoOutput( true)\n"
},
{
"answer_id": 96410,
"author": "Sietse",
"author_id": 6400,
"author_profile": "https://Stackoverflow.com/users/6400",
"pm_score": 3,
"selected": false,
"text": "connection.setDoOutput(true); StringBuilder sb= new StringBuilder();\nsb.append(\"Hello there\");\n\nURL url = new URL(\"theservlet's URL\");\nHttpURLConnection connection = (HttpURLConnection)url.openConnection(); \nconnection.setDoOutput(true);\nconnection.setRequestMethod(\"POST\");\nconnection.setRequestProperty(\"Content-Length\", \"\" + sb.length());\n\nOutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream());\noutputWriter.write(sb.toString());\noutputWriter.flush();\noutputWriter.close();\n"
},
{
"answer_id": 96422,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 5,
"selected": true,
"text": "PostMethod post = new PostMethod(url);\nRequestEntity entity = new FileRequestEntity(inputFile, \"text/xml; charset=ISO-8859-1\");\npost.setRequestEntity(entity);\nHttpClient httpclient = new HttpClient();\nint result = httpclient.executeMethod(post);\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27/"
] |
96,377
|
<p>I am trying to use Validation in WPF. I created a NotNullOrEmptyValidationRule as shown below: </p>
<pre><code>public class NotNullOrEmptyValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (String.IsNullOrEmpty(value as String))
return new ValidationResult(false, "Value cannot be null or empty");
return new ValidationResult(true, null);
}
}
</code></pre>
<p>Now, I need to use it in my application. In my App.xaml file I declared the Style for the TextBox. Here is the declaration. </p>
<pre><code> <Style x:Key="textBoxStyle" TargetType="{x:Type TextBox}">
<Setter Property="Background" Value="Green"/>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="Background" Value="Red"/>
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
</code></pre>
<p>Now, I want to use it on my TextBox so I am using the following code: </p>
<pre><code> <TextBox Style="{StaticResource textBoxStyle}">
<TextBox.Text>
<Binding>
<Binding.ValidationRules>
<NotNullOrEmptyValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</code></pre>
<p>The error comes on the Tag NotNullOrEmptyValidationRule. The XAML syntax checker is not able to resolve the NotNullOrEmptyValidationRule. I have even tried putting the namespace but it does not seem to work. </p>
|
[
{
"answer_id": 96497,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": 3,
"selected": false,
"text": "<Window ...\n xmlns:local=\"clr-namespace:MyNamespaceName\">\n <Binding Path=\".\">\n <Binding.ValidationRules>\n <local:NotNullOrEmptyValidationRule />\n </Binding.ValidationRules>\n</Binding>\n"
},
{
"answer_id": 3633539,
"author": "lmheah",
"author_id": 438683,
"author_profile": "https://Stackoverflow.com/users/438683",
"pm_score": 1,
"selected": false,
"text": "Public Sub New()\n\n ' This call is required by the Windows Form Designer.\n InitializeComponent()\n\n Me.**NameOfTextBox**.DataContext = Me\nEnd Sub\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3797/"
] |
96,390
|
<p>I have a SQL statement that looks like:</p>
<pre><code>SELECT [Phone]
FROM [Table]
WHERE
(
[Phone] LIKE '[A-Z][a-z]'
OR [Phone] = 'N/A'
OR [Phone] LIKE '[0]'
)
</code></pre>
<p>The part I'm having trouble with is the where statement with the "LIKEs". I've seen SQL statements where authors used <code>like</code> statements in the way I'm using them above. At first, I thought this might be a version of Regular Expressions but I've since learned. </p>
<p>Is anyone familiar with using like statements in such a way. Note: the "N/A" is working fine. </p>
<p>What I need to match is phone numbers that have characters. Or phone numbers which contain nothing but zero.</p>
|
[
{
"answer_id": 96445,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 4,
"selected": true,
"text": "SELECT [Phone]\nFROM [Table]\nWHERE\n(\n [Phone] LIKE '%[A-Z]%'\n OR [Phone] LIKE '%[a-z]%'\n OR [Phone] = 'N/A'\n OR [Phone] LIKE '0'\n)\n"
},
{
"answer_id": 96451,
"author": "therealhoff",
"author_id": 18175,
"author_profile": "https://Stackoverflow.com/users/18175",
"pm_score": 2,
"selected": false,
"text": "t-sql ISNUMERIC TRIM REPLACE ISNUMERIC LEN"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18196/"
] |
96,405
|
<p>I have to deploy my php/html/css/etc code to multiple servers and i am looking at my options for software that allows easy and secure deployment to multiple servers.</p>
<p>Also helps if it could be tied into my SVN.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 98084,
"author": "reefnet_alex",
"author_id": 2745,
"author_profile": "https://Stackoverflow.com/users/2745",
"pm_score": 2,
"selected": false,
"text": "cap -f deploy.rb live deploy\n cap -f deploy.rb dev deploy\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14433/"
] |
96,414
|
<p>I'm experimenting with adding icons to a shell extension. I have this code (sanitized for easy reading), which works:</p>
<pre><code>InsertMenu(hmenu, index, MF_POPUP|MF_BYPOSITION, (UINT)hParentMenu, namestring);
</code></pre>
<p>The next step is this code:</p>
<pre><code>HICON hIconLarge, hIconSmall;
ICONINFO oIconInfo;
ExtractIconEx("c:\\progra~1\\winzip\\winzip32.exe", 0, &hIconLarge, &hIconSmall, 1);
GetIconInfo(hIconSmall, &oIconInfo);
//???????
SetMenuItemBitmaps(hParentMenu, indexMenu-1, MF_BITMAP | MF_BYPOSITION, hbmp, hbmp);
</code></pre>
<p>What do I put in to replace the ?'s. Attempts to Google this knowledge have found many tips that I failed to get working. Any advice on getting this to work, especially on older machines (e.g. no .net framework, no vista) is appreciated.</p>
|
[
{
"answer_id": 98084,
"author": "reefnet_alex",
"author_id": 2745,
"author_profile": "https://Stackoverflow.com/users/2745",
"pm_score": 2,
"selected": false,
"text": "cap -f deploy.rb live deploy\n cap -f deploy.rb dev deploy\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18192/"
] |
96,428
|
<p>I have this string</p>
<pre><code>'john smith~123 Street~Apt 4~New York~NY~12345'
</code></pre>
<p>Using JavaScript, what is the fastest way to parse this into</p>
<pre><code>var name = "john smith";
var street= "123 Street";
//etc...
</code></pre>
|
[
{
"answer_id": 96452,
"author": "Zach",
"author_id": 9128,
"author_profile": "https://Stackoverflow.com/users/9128",
"pm_score": 11,
"selected": true,
"text": "String.prototype.split var input = 'john smith~123 Street~Apt 4~New York~NY~12345';\n\nvar fields = input.split('~');\n\nvar name = fields[0];\nvar street = fields[1];\n// etc.\n"
},
{
"answer_id": 96467,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 6,
"selected": false,
"text": "var s = 'john smith~123 Street~Apt 4~New York~NY~12345';\nvar fields = s.split(/~/);\nvar name = fields[0];\nvar street = fields[1];\n\nconsole.log(name);\nconsole.log(street);"
},
{
"answer_id": 96471,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 3,
"selected": false,
"text": "var address = theEncodedString.split(/~/)\nvar name = address[0], street = address[1]\n"
},
{
"answer_id": 96479,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 2,
"selected": false,
"text": "var divided = str.split(\"/~/\");\nvar name=divided[0];\nvar street = divided[1];\n"
},
{
"answer_id": 11951118,
"author": "Torsten Walter",
"author_id": 1393908,
"author_profile": "https://Stackoverflow.com/users/1393908",
"pm_score": 4,
"selected": false,
"text": "var addressString = \"~john smith~123 Street~Apt 4~New York~NY~12345~\",\n keys = \"name address1 address2 city state zipcode\".split(\" \"),\n address = {};\n\n// clean up the string with the first replace\n// \"abuse\" the second replace to map the keys to the matches\naddressString.replace(/^~|~$/g).replace(/[^~]+/g, function(match){\n address[ keys.unshift() ] = match;\n});\n\n// address will contain the mapped result\naddress = {\n address1: \"123 Street\"\n address2: \"Apt 4\"\n city: \"New York\"\n name: \"john smith\"\n state: \"NY\"\n zipcode: \"12345\"\n}\n const [address1, address2, city, name, state, zipcode] = addressString.match(/[^~]+/g);\n\n// The variables defined above now contain the appropriate information:\n\nconsole.log(address1, address2, city, name, state, zipcode);\n// -> john smith 123 Street Apt 4 New York NY 12345\n"
},
{
"answer_id": 13622899,
"author": "BJ Patel",
"author_id": 2683759,
"author_profile": "https://Stackoverflow.com/users/2683759",
"pm_score": 3,
"selected": false,
"text": "function SplitTheString(ResultStr) {\n if (ResultStr != null) {\n var SplitChars = '~';\n if (ResultStr.indexOf(SplitChars) >= 0) {\n var DtlStr = ResultStr.split(SplitChars);\n var name = DtlStr[0];\n var street = DtlStr[1];\n }\n }\n}\n"
},
{
"answer_id": 19610068,
"author": "Billy Hallman",
"author_id": 2010101,
"author_profile": "https://Stackoverflow.com/users/2010101",
"pm_score": 2,
"selected": false,
"text": "// array[0][0] will produce brian\n// array[0][1] will produce james\n\n// array[1][0] will produce kevin\n// array[1][1] will produce haley\n\nvar array = [];\n array[0] = \"brian,james,doug\".split(\",\");\n array[1] = \"kevin,haley,steph\".split(\",\");\n"
},
{
"answer_id": 32921252,
"author": "Tushar",
"author_id": 2025923,
"author_profile": "https://Stackoverflow.com/users/2025923",
"pm_score": 3,
"selected": false,
"text": "split match var str = 'john smith~123 Street~Apt 4~New York~NY~12345';\nmatches = str.match(/[^~]+/g);\n\nconsole.log(matches);\ndocument.write(matches); [^~]+ ~"
},
{
"answer_id": 42185907,
"author": "Vahid Hallaji",
"author_id": 1121982,
"author_profile": "https://Stackoverflow.com/users/1121982",
"pm_score": 6,
"selected": false,
"text": "ES6 const input = 'john smith~123 Street~Apt 4~New York~NY~12345';\n\nconst [name, street, unit, city, state, zip] = input.split('~');\n\nconsole.log(name); // john smith\nconsole.log(street); // 123 Street\nconsole.log(unit); // Apt 4\nconsole.log(city); // New York\nconsole.log(state); // NY\nconsole.log(zip); // 12345 const input = 'john smith~123 Street~Apt 4~New York~NY~12345';\n\nconst [name, street, ...others] = input.split('~');\n\nconsole.log(name); // john smith\nconsole.log(street); // 123 Street\nconsole.log(others); // [\"Apt 4\", \"New York\", \"NY\", \"12345\"] const"
},
{
"answer_id": 49048718,
"author": "Bal mukund kumar",
"author_id": 7393281,
"author_profile": "https://Stackoverflow.com/users/7393281",
"pm_score": -1,
"selected": false,
"text": "function myFunction() {\nvar str = \"How are you doing today?\";\nvar res = str.split(\"/\");\n\n}\n"
},
{
"answer_id": 54228055,
"author": "imtk",
"author_id": 3159162,
"author_profile": "https://Stackoverflow.com/users/3159162",
"pm_score": 2,
"selected": false,
"text": "string.split(\"~\")[0]; \"john smith~123 Street~Apt 4~New York~NY~12345\" [\"john smith\", \"123 Street\", \"Apt 4\", \"New York\", \"NY\", \"12345\"] const split = (separator) => (text) => text.split(separator);\nconst splitByTilde = split('~');\n splitByTilde splitByTilde(\"john smith~123 Street~Apt 4~New York~NY~12345\") // [\"john smith\", \"123 Street\", \"Apt 4\", \"New York\", \"NY\", \"12345\"]\n list[0] first const first = (list) => list[0];\n getName compose reduce const compose = (...fns) => (value) => fns.reduceRight((acc, fn) => fn(acc), value);\n splitByTilde first const getName = compose(first, splitByTilde);\n\nlet string = 'john smith~123 Street~Apt 4~New York~NY~12345';\ngetName(string); // \"john smith\"\n"
},
{
"answer_id": 55399440,
"author": "Chris Bartholomew",
"author_id": 10234183,
"author_profile": "https://Stackoverflow.com/users/10234183",
"pm_score": 1,
"selected": false,
"text": "replace split var items = string.replace(/,\\s+/, \",\").split(',')\n"
},
{
"answer_id": 55589395,
"author": "Hari Lakkakula",
"author_id": 6601939,
"author_profile": "https://Stackoverflow.com/users/6601939",
"pm_score": 2,
"selected": false,
"text": " //basic url=http://localhost:58227/ExternalApproval.html?Status=1\n\n var ar= [url,statu] = window.location.href.split(\"=\");\n"
},
{
"answer_id": 57693059,
"author": "Developer",
"author_id": 10755206,
"author_profile": "https://Stackoverflow.com/users/10755206",
"pm_score": 2,
"selected": false,
"text": " var str = \"This-javascript-tutorial-string-split-method-examples-tutsmake.\"\n \n var result = str.split('-'); \n \n console.log(result);\n \n document.getElementById(\"show\").innerHTML = result; <html>\n<head>\n<title>How do you split a string, breaking at a particular character in javascript?</title>\n</head>\n<body>\n \n<p id=\"show\"></p> \n \n</body>\n</html>"
},
{
"answer_id": 63754660,
"author": "Ankit21ks",
"author_id": 5143638,
"author_profile": "https://Stackoverflow.com/users/5143638",
"pm_score": 3,
"selected": false,
"text": "split() var arr = input.split('~');\n arr[0] arr[1]"
},
{
"answer_id": 64845911,
"author": "PHP Guru",
"author_id": 10587413,
"author_profile": "https://Stackoverflow.com/users/10587413",
"pm_score": 0,
"selected": false,
"text": "function Record(s) {\n var keys = [\"name\", \"address\", \"address2\", \"city\", \"state\", \"zip\"], values = s.split(\"~\"), i\n for (i = 0; i<keys.length; i++) {\n this[keys[i]] = values[i]\n }\n}\n\nvar record = new Record('john smith~123 Street~Apt 4~New York~NY~12345')\n\nrecord.name // contains john smith\nrecord.address // contains 123 Street\nrecord.address2 // contains Apt 4\nrecord.city // contains New York\nrecord.state // contains NY\nrecord.zip // contains zip\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6161/"
] |
96,431
|
<p>I'm seeing some errors that would indicate a "connection leak". That is, connections that were not closed properly and the pool is running out. So, how do I go about instrumenting this to see exactly how many are open at a given time?</p>
|
[
{
"answer_id": 122162,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 0,
"selected": false,
"text": "using(SqlConnection connection = new SqlConnection())\n{\n...\n} // connection is always disposed (i.e. closed) here, even if an exception is thrown\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
] |
96,440
|
<p>I have a Flex application, which loads a SWF from CS3. The loaded SWF contains a text input called "myText". I can see this in the SWFLoader.content with no problems, but I don't know what type I should be treating it as in my Flex App. I thought the flex docs covered this but I can only find how to interact with another Flex SWF.</p>
<p>The Flex debugger tells me it is of type fl.controls.TextInput, which makes sense. But FlexBuilder doesn't seem to know this class. While Flash and Flex both use AS3, Flex has a whole new library of GUI classes. I thought it also had all the Flash classes, but I can't get it to know of ANY fl.*** packages.</p>
|
[
{
"answer_id": 103094,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 2,
"selected": false,
"text": "fl.* var textInput : * = getTheTextInput(); // insert your own method here\n\ntextInput.text = \"Lorem ipsum dolor sit amet\";\n\ntextInput.setSelection(4, 15);\n Adobe Flash CS3/Configuration/Component Source/ActionScript 3.0/User Interface/fl/controls/TextInput.as\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13220/"
] |
96,448
|
<p>I need to import a large CSV file into an SQL server. I'm using this :</p>
<pre><code>BULK
INSERT CSVTest
FROM 'c:\csvfile.txt'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO
</code></pre>
<p>problem is all my fields are surrounded by quotes (" ") so a row actually looks like :</p>
<pre><code>"1","","2","","sometimes with comma , inside", ""
</code></pre>
<p>Can I somehow bulk import them and tell SQL to use the quotes as field delimiters?</p>
<p><strong>Edit</strong>: The problem with using '","' as delimiter, as in the examples suggested is that :
What most examples do, is they import the data including the first " in the first column and the last " in the last, then they go ahead and strip that out. Alas my first (and last) column are datetime and will not allow a "20080902 to be imported as datetime.</p>
<p>From what I've been reading arround I think FORMATFILE is the way to go, but documentation (including MSDN) is terribly unhelpfull.</p>
|
[
{
"answer_id": 96474,
"author": "K Richard",
"author_id": 16771,
"author_profile": "https://Stackoverflow.com/users/16771",
"pm_score": 4,
"selected": false,
"text": "FIELDTERMINATOR='\",\"'"
},
{
"answer_id": 96489,
"author": "Epaga",
"author_id": 6583,
"author_profile": "https://Stackoverflow.com/users/6583",
"pm_score": 0,
"selected": false,
"text": "FIELDTERMINATOR = '\",\"'"
},
{
"answer_id": 151662,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Bulk insert test1\nfrom 'c:\\1.txt' with ( \n fieldterminator ='\",\"'\n ,rowterminator='\\n')\n\nupdate test1<br>\nset name =Substring (name , 2,len(name))\nwhere name like **' \"% '**\n\nupdate test1\nset email=substring(email, 1,len(email)-1)\nwhere email like **' %\" '**\n"
},
{
"answer_id": 151678,
"author": "cbp",
"author_id": 21966,
"author_profile": "https://Stackoverflow.com/users/21966",
"pm_score": 3,
"selected": false,
"text": "=concatenate(\"insert into myTable (columnA,columnB) values ('\",a1,\"','\",b1,\"'\")\")\n"
},
{
"answer_id": 18928719,
"author": "Kevin M",
"author_id": 1838481,
"author_profile": "https://Stackoverflow.com/users/1838481",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Data;\nusing System.Data.SqlClient;\n\nnamespace SqlBulkInsertExample\n{\n class Program\n {\n static void Main(string[] args)\n {\n DataTable prodSalesData = new DataTable(\"ProductSalesData\");\n\n // Create Column 1: SaleDate\n DataColumn dateColumn = new DataColumn();\n dateColumn.DataType = Type.GetType(\"System.DateTime\");\n dateColumn.ColumnName = \"SaleDate\";\n\n // Create Column 2: ProductName\n DataColumn productNameColumn = new DataColumn();\n productNameColumn.ColumnName = \"ProductName\";\n\n // Create Column 3: TotalSales\n DataColumn totalSalesColumn = new DataColumn();\n totalSalesColumn.DataType = Type.GetType(\"System.Int32\");\n totalSalesColumn.ColumnName = \"TotalSales\";\n\n // Add the columns to the ProductSalesData DataTable\n prodSalesData.Columns.Add(dateColumn);\n prodSalesData.Columns.Add(productNameColumn);\n prodSalesData.Columns.Add(totalSalesColumn);\n\n // Let's populate the datatable with our stats.\n // You can add as many rows as you want here!\n\n // Create a new row\n DataRow dailyProductSalesRow = prodSalesData.NewRow();\n dailyProductSalesRow[\"SaleDate\"] = DateTime.Now.Date;\n dailyProductSalesRow[\"ProductName\"] = \"Nike\";\n dailyProductSalesRow[\"TotalSales\"] = 10;\n\n // Add the row to the ProductSalesData DataTable\n prodSalesData.Rows.Add(dailyProductSalesRow);\n\n // Copy the DataTable to SQL Server using SqlBulkCopy\n using (SqlConnection dbConnection = new SqlConnection(\"Data Source=ProductHost;Initial Catalog=dbProduct;Integrated Security=SSPI;Connection Timeout=60;Min Pool Size=2;Max Pool Size=20;\"))\n {\n dbConnection.Open();\n using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))\n {\n s.DestinationTableName = prodSalesData.TableName;\n\n foreach (var column in prodSalesData.Columns)\n s.ColumnMappings.Add(column.ToString(), column.ToString());\n\n s.WriteToServer(prodSalesData);\n }\n }\n }\n }\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3263/"
] |
96,460
|
<p>Sessions in PHP seemed to have changed since the last time I used them, so I'm looking for a simple way of using sessions but at the same time for it to be relatively secure and a good common practice.</p>
|
[
{
"answer_id": 96544,
"author": "Laith",
"author_id": 5961,
"author_profile": "https://Stackoverflow.com/users/5961",
"pm_score": -1,
"selected": false,
"text": "session_start();\n$old_sessionid = session_id();\nsession_regenerate_id();\n$new_sessionid = session_id();\n"
},
{
"answer_id": 96592,
"author": "dittonamed",
"author_id": 16435,
"author_profile": "https://Stackoverflow.com/users/16435",
"pm_score": 2,
"selected": false,
"text": "# Start the session manager\nsession_start(); \n\n# Set a var\n$_SESSION['foo'] = 'whatever';\n\n# Access the var\nprint $_SESSION['foo'];\n"
},
{
"answer_id": 96709,
"author": "Christian P.",
"author_id": 9479,
"author_profile": "https://Stackoverflow.com/users/9479",
"pm_score": 1,
"selected": false,
"text": "$_SESSION['yourvar'] = 'somevalue';\n"
},
{
"answer_id": 46155253,
"author": "Grant Gubatan",
"author_id": 6467184,
"author_profile": "https://Stackoverflow.com/users/6467184",
"pm_score": 0,
"selected": false,
"text": "session_start();\nif( isset($_POST['username']) && isset($_POST['password']) )\n{\n if( auth($_POST['username'], $_POST['password']) )\n {\n //Authentication passed\n $_SESSION['user'] = $_POST['username'];\n // redirect to required page\n header( \"Location: index.php\" );\n } \n else \n {\n //Authentication failed redirect to login\n header( \"Location: loginform.html\" );\n }\n} \nelse \n{\n //Username and Password are required\n header( \"Location: loginform.html\" );\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10708/"
] |
96,463
|
<p>How do you access the response from the Request
object in MooTools? I've been looking at the documentation and the MooTorial, but
I can't seem to make any headway. Other Ajax stuff I've done with
MooTools I haven't had to manipulate the response at all, so I've just
been able to inject it straight into the document, but now I need to
make some changes to it first. I don't want to alert the response, I'd like to access it so I can make further changes to it. Any help would be greatly appreciated.
Thanks.</p>
<p>Edit:</p>
<p>I'd like to be able to access
the response after the request has already been made, preferably
outside of the Request object. It's for an RSS reader, so I need to do
some parsing and Request is just being used to get the feed from a
server file. This function is a method in a class, which should return
the response in a string, but it isn't returning anything but
undefined:</p>
<pre><code> fetch: function(site){
var feed;
var req = new Request({
method: this.options.method,
url: this.options.rssFetchPath,
data: { 'url' : site },
onRequest: function() {
if (this.options.targetId) { $
(this.options.targetId).setProperty('html',
this.options.onRequestMessage); }
}.bind(this),
onSuccess: function(responseText) {
feed = responseText;
}
});
req.send();
return feed;
}
</code></pre>
|
[
{
"answer_id": 96573,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 2,
"selected": false,
"text": "var req = new Request({\n method: 'get',\n url: ...,\n data: ...,\n onRequest: function() { alert('Request made. Please wait...'); },\n\n // the response is passed to the callback as the first parameter\n onComplete: function(response) { alert('Response: ' + response); }\n\n}).send(); \n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13281/"
] |
96,500
|
<p>Suppose I have the following code:</p>
<pre><code>class some_class{};
some_class some_function()
{
return some_class();
}
</code></pre>
<p>This seems to work pretty well and saves me the trouble of having to declare a variable just to make a return value. But I don't think I've ever seen this in any kind of tutorial or reference. Is this a compiler-specific thing (visual C++)? Or is this doing something wrong?</p>
|
[
{
"answer_id": 96665,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "A a;\na = fn();\n A a = fn();\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
96,525
|
<p>Is it possible to change the font size used in a ContextMenu using the .NET Framework 3.5 and C# for a desktop application? It seems it's a system-wide setting, but I would like to change it only within my application.</p>
|
[
{
"answer_id": 96682,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 4,
"selected": true,
"text": "ContextMenuStrip ContextMenu TextBox ContextMenuStrip TextBox"
},
{
"answer_id": 96688,
"author": "Isak Savo",
"author_id": 8521,
"author_profile": "https://Stackoverflow.com/users/8521",
"pm_score": 0,
"selected": false,
"text": "<Whatever.ContextMenu TextBlock.FontSize=\"12\">\n <MenuItem ... /> <!-- Will get the font size from parent -->\n</Whatever.ContextMenu>\n <Style TargetType=\"MenuItem\">\n <Setter Property=\"TextBlock.FontSize\" Value=\"12\" />\n</Style>\n"
},
{
"answer_id": 96809,
"author": "Ben Straub",
"author_id": 1319,
"author_profile": "https://Stackoverflow.com/users/1319",
"pm_score": 2,
"selected": false,
"text": "<Window.ContextMenu FontSize=\"36\">\n <!-- ... -->\n</Window.ContextMenu\n contextMenuStrip1.Font = new System.Drawing.Font(\"Segoe UI\", 24F);\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28952/"
] |
96,538
|
<p>We have multiple MFC apps, which use CMutex( false, "blah" ), where "blah" allows the mutex to work across process boundaries.</p>
<p>One of these apps was re-written without MFC (using Qt instead). How can I simulate the CMutex using Win32 calls? (Qt's QMutex is not inter-process.) I prefer not to modify the MFC apps.</p>
|
[
{
"answer_id": 96559,
"author": "RichS",
"author_id": 6247,
"author_profile": "https://Stackoverflow.com/users/6247",
"pm_score": 1,
"selected": false,
"text": "CreateMutex(...)\nWaitForSingleObject(...)\nReleaseMutex(...)\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18214/"
] |
96,541
|
<p>This isn't legal:</p>
<pre><code>public class MyBaseClass
{
public MyBaseClass() {}
public MyBaseClass(object arg) {}
}
public void ThisIsANoNo<T>() where T : MyBaseClass
{
T foo = new T("whoops!");
}
</code></pre>
<p>In order to do this, you have to do some reflection on the type object for T or you have to use Activator.CreateInstance. Both are pretty nasty. Is there a better way?</p>
|
[
{
"answer_id": 96557,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "where T : MyBaseClass, new()\n"
},
{
"answer_id": 96581,
"author": "chrissie1",
"author_id": 2936,
"author_profile": "https://Stackoverflow.com/users/2936",
"pm_score": -1,
"selected": false,
"text": "public void ThisIsANoNo<T>() where T : MyBaseClass\n{\n MyBaseClass foo = new MyBaseClass(\"whoops!\");\n}\n using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n ThisIsANoNo<MyClass>();\n ThisIsANoNo<MyBaseClass>();\n }\n\n public class MyBaseClass\n {\n public MyBaseClass() { }\n public MyBaseClass(object arg) { }\n }\n\n public class MyClass :MyBaseClass\n {\n public MyClass() { }\n public MyClass(object arg, Object arg2) { }\n }\n\n public static void ThisIsANoNo<T>() where T : MyBaseClass\n {\n MyBaseClass foo = new MyBaseClass(\"whoops!\");\n }\n }\n}\n"
},
{
"answer_id": 96752,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 2,
"selected": true,
"text": "public abstract class MyBaseClass\n{\n protected MyBaseClass() {}\n protected abstract MyBaseClass CreateFromObject(object arg);\n}\n\npublic void ThisWorksButIsntGreat<T>() where T : MyBaseClass, new()\n{\n T foo = new T().CreateFromObject(\"whoopee!\") as T;\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
96,553
|
<p>Is it particularly bad to have a very, very large SQL query with lots of (potentially redundant) WHERE clauses?</p>
<p>For example, here's a query I've generated from my web application with everything turned off, which should be the largest possible query for this program to generate:</p>
<pre><code>SELECT *
FROM 4e_magic_items
INNER JOIN 4e_magic_item_levels
ON 4e_magic_items.id = 4e_magic_item_levels.itemid
INNER JOIN 4e_monster_sources
ON 4e_magic_items.source = 4e_monster_sources.id
WHERE (itemlevel BETWEEN 1 AND 30)
AND source!=16 AND source!=2 AND source!=5
AND source!=13 AND source!=15 AND source!=3
AND source!=4 AND source!=12 AND source!=7
AND source!=14 AND source!=11 AND source!=10
AND source!=8 AND source!=1 AND source!=6
AND source!=9 AND type!='Arms' AND type!='Feet'
AND type!='Hands' AND type!='Head'
AND type!='Neck' AND type!='Orb'
AND type!='Potion' AND type!='Ring'
AND type!='Rod' AND type!='Staff'
AND type!='Symbol' AND type!='Waist'
AND type!='Wand' AND type!='Wondrous Item'
AND type!='Alchemical Item' AND type!='Elixir'
AND type!='Reagent' AND type!='Whetstone'
AND type!='Other Consumable' AND type!='Companion'
AND type!='Mount' AND (type!='Armor' OR (false ))
AND (type!='Weapon' OR (false ))
ORDER BY type ASC, itemlevel ASC, name ASC
</code></pre>
<p>It seems to work well enough, but it's also not particularly high traffic (a few hundred hits a day or so), and I wonder if it would be worth the effort to try and optimize the queries to remove redundancies and such.</p>
|
[
{
"answer_id": 96598,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 5,
"selected": true,
"text": "select * \nfrom\n 4e_magic_items mi\n ,4e_magic_item_levels mil\n ,4e_monster_sources ms\nwhere mi.id = mil.itemid\n and mi.source = ms.id\n and itemlevel between 1 and 30\n and source not in(16,2,5,13,15,3,4,12,7,14,11,10,8,1,6,9) \n and type not in(\n 'Arms' ,'Feet' ,'Hands' ,'Head' ,'Neck' ,'Orb' ,\n 'Potion' ,'Ring' ,'Rod' ,'Staff' ,'Symbol' ,'Waist' ,\n 'Wand' ,'Wondrous Item' ,'Alchemical Item' ,'Elixir' ,\n 'Reagent' ,'Whetstone' ,'Other Consumable' ,'Companion' ,\n 'Mount'\n )\n and ((type != 'Armor') or (false))\n and ((type != 'Weapon') or (false))\norder by\n type asc\n ,itemlevel asc\n ,name asc\n\n/*\nSome thoughts:\n==============\n0 - Formatting really matters, in SQL even more than most languages.\n1 - consider selecting only the columns you need, not \"*\"\n2 - use of table aliases makes it short & clear (\"MI\", \"MIL\" in my example)\n3 - joins in the WHERE clause will un-clutter your FROM clause\n4 - use NOT IN for long lists\n5 - logically, the last two lines can be added to the \"type not in\" section.\n I'm not sure why you have the \"or false\", but I'll assume some good reason\n and leave them here.\n*/\n"
},
{
"answer_id": 96689,
"author": "Kate Bertelsen",
"author_id": 16633,
"author_profile": "https://Stackoverflow.com/users/16633",
"pm_score": 1,
"selected": false,
"text": "SELECT x, y, z\nFROM a, b\nWHERE fiz = 1\nAND foo = 2\nAND a.x = b.y\nAND b.z IN (SELECT q, r, s, t\n FROM c, d, e\n WHERE c.q = d.r\n AND d.s = e.t\n AND c.gar IS NOT NULL)\nORDER BY b.gonk\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18210/"
] |
96,579
|
<p>I'm writing an inner loop that needs to place <code>struct</code>s in contiguous storage. I don't know how many of these <code>struct</code>s there will be ahead of time. My problem is that STL's <code>vector</code> initializes its values to 0, so no matter what I do, I incur the cost of the initialization plus the cost of setting the <code>struct</code>'s members to their values.</p>
<p>Is there any way to prevent the initialization, or is there an STL-like container out there with resizeable contiguous storage and uninitialized elements?</p>
<p>(I'm certain that this part of the code needs to be optimized, and I'm certain that the initialization is a significant cost.)</p>
<p>Also, see my comments below for a clarification about when the initialization occurs.</p>
<p>SOME CODE:</p>
<pre><code>void GetsCalledALot(int* data1, int* data2, int count) {
int mvSize = memberVector.size()
memberVector.resize(mvSize + count); // causes 0-initialization
for (int i = 0; i < count; ++i) {
memberVector[mvSize + i].d1 = data1[i];
memberVector[mvSize + i].d2 = data2[i];
}
}
</code></pre>
|
[
{
"answer_id": 96630,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 2,
"selected": false,
"text": "std::vector<T>::reserve(x)\n #include <iostream>\n#include <vector>\n\nstruct MyStruct\n{\n int m_iValue00 ;\n int m_iValue01 ;\n} ;\n\nint main()\n{\n MyStruct aaa, bbb, ccc ;\n\n std::vector<MyStruct> aMyStruct ;\n\n aMyStruct.push_back(aaa) ;\n aMyStruct.push_back(bbb) ;\n aMyStruct.push_back(ccc) ;\n\n aMyStruct.resize(6) ; // [EDIT] double the size\n\n for(std::vector<MyStruct>::size_type i = 0, iMax = aMyStruct.size(); i < iMax; ++i)\n {\n std::cout << \"[\" << i << \"] : \" << aMyStruct[i].m_iValue00 << \", \" << aMyStruct[0].m_iValue01 << \"\\n\" ;\n }\n\n return 0 ;\n}\n [0] : 134515780, -16121856\n[1] : 134554052, -16121856\n[2] : 134544501, -16121856\n[3] : 0, -16121856\n[4] : 0, -16121856\n[5] : 0, -16121856\n aMyStruct.push_back(MyStruct()) ;\naMyStruct.push_back(MyStruct()) ;\naMyStruct.push_back(MyStruct()) ;\n struct MyStruct\n{\n MyStruct(int p_d1, int p_d2) : d1(p_d1), d2(p_d2) {}\n int d1, d2 ;\n} ;\n"
},
{
"answer_id": 96836,
"author": "mbyrne215",
"author_id": 5241,
"author_profile": "https://Stackoverflow.com/users/5241",
"pm_score": 0,
"selected": false,
"text": "int *memberArray;\nint arrayCount;\nvoid GetsCalledALot(int* data1, int* data2, int count) {\n memberArray = realloc(memberArray, sizeof(int) * (arrayCount + count);\n for (int i = 0; i < count; ++i) {\n memberArray[arrayCount + i].d1 = data1[i];\n memberArray[arrayCount + i].d2 = data2[i];\n }\n arrayCount += count;\n}\n"
},
{
"answer_id": 96864,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "vect.push_back(MyStruct(fieldValue1, fieldValue2))\n"
},
{
"answer_id": 97061,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 1,
"selected": false,
"text": "copy(data1, data1 + count, back_inserter(v1));\ncopy(data2, data2 + count, back_inserter(v2));\n"
},
{
"answer_id": 97434,
"author": "Andreas Magnusson",
"author_id": 5811,
"author_profile": "https://Stackoverflow.com/users/5811",
"pm_score": 0,
"selected": false,
"text": "void GetsCalledALot(int* data1, int* data2, int count)\n{\n const size_t mvSize = memberVector.size();\n memberVector.reserve(mvSize + count);\n\n for (int i = 0; i < count; ++i) {\n memberVector.push_back(MyType(data1[i], data2[i]));\n }\n}\n"
},
{
"answer_id": 97536,
"author": "Lloyd",
"author_id": 9952,
"author_profile": "https://Stackoverflow.com/users/9952",
"pm_score": 6,
"selected": true,
"text": "std::vector vector reserve() push_back() struct YourData {\n int d1;\n int d2;\n YourData(int v1, int v2) : d1(v1), d2(v2) {}\n};\n\nstd::vector<YourData> memberVector;\n\nvoid GetsCalledALot(int* data1, int* data2, int count) {\n int mvSize = memberVector.size();\n\n // Does not initialize the extra elements\n memberVector.reserve(mvSize + count);\n\n // Note: consider using std::generate_n or std::copy instead of this loop.\n for (int i = 0; i < count; ++i) {\n // Copy construct using a temporary.\n memberVector.push_back(YourData(data1[i], data2[i]));\n }\n}\n reserve() resize() reserve() T&& std::vector template <typename T>\nclass my_vector_replacement {\n\n // ...\n\n template <typename F>\n my_vector::push_back_using_factory(F factory) {\n // ... check size of array, and resize if needed.\n\n // Copy construct using placement new,\n new(arrayData+end) T(factory())\n end += sizeof(T);\n }\n\n char* arrayData;\n size_t end; // Of initialized data in arrayData\n};\n\n// One of many possible implementations\nstruct MyFactory {\n MyFactory(int* p1, int* p2) : d1(p1), d2(p2) {}\n YourData operator()() const {\n return YourData(*d1,*d2);\n }\n int* d1;\n int* d2;\n};\n\nvoid GetsCalledALot(int* data1, int* data2, int count) {\n // ... Still will need the same call to a reserve() type function.\n\n // Note: consider using std::generate_n or std::copy instead of this loop.\n for (int i = 0; i < count; ++i) {\n // Copy construct using a factory\n memberVector.push_back_using_factory(MyFactory(data1+i, data2+i));\n }\n}\n"
},
{
"answer_id": 2798740,
"author": "fredoverflow",
"author_id": 252000,
"author_profile": "https://Stackoverflow.com/users/252000",
"pm_score": 4,
"selected": false,
"text": "emplace_back vector memberVector.emplace_back(data1[i], data2[i]);\n"
},
{
"answer_id": 18468610,
"author": "goertzenator",
"author_id": 398021,
"author_profile": "https://Stackoverflow.com/users/398021",
"pm_score": 4,
"selected": false,
"text": "unique_ptr auto my_uninit_array = std::unique_ptr<mystruct[]>(new mystruct[count]);\n"
},
{
"answer_id": 42510583,
"author": "deonb",
"author_id": 7508986,
"author_profile": "https://Stackoverflow.com/users/7508986",
"pm_score": 2,
"selected": false,
"text": "template <typename T>\nstruct no_init\n{\n T value;\n\n no_init() { static_assert(std::is_standard_layout<no_init<T>>::value && sizeof(T) == sizeof(no_init<T>), \"T does not have standard layout\"); }\n\n no_init(T& v) { value = v; }\n T& operator=(T& v) { value = v; return value; }\n\n no_init(no_init<T>& n) { value = n.value; }\n no_init(no_init<T>&& n) { value = std::move(n.value); }\n T& operator=(no_init<T>& n) { value = n.value; return this; }\n T& operator=(no_init<T>&& n) { value = std::move(n.value); return this; }\n\n T* operator&() { return &value; } // So you can use &(vec[0]) etc.\n};\n std::vector<no_init<char>> vec;\nvec.resize(2ul * 1024ul * 1024ul * 1024ul);\n"
},
{
"answer_id": 61641730,
"author": "Maxim Egorushkin",
"author_id": 412080,
"author_profile": "https://Stackoverflow.com/users/412080",
"pm_score": 3,
"selected": false,
"text": "boost::noinit_adaptor std::vector<T, boost::noinit_adaptor<std::allocator<T>> memberVector;\n resize"
},
{
"answer_id": 64211027,
"author": "SunlayGGX",
"author_id": 14395275,
"author_profile": "https://Stackoverflow.com/users/14395275",
"pm_score": 0,
"selected": false,
"text": "// This macro is to be defined before including VectorHijacker.h. Then you will be able to reuse the VectorHijacker.h with different objects.\n#define HIJACKED_TYPE SomeStruct\n\n// VectorHijacker.h\n#ifndef VECTOR_HIJACKER_STRUCT\n#define VECTOR_HIJACKER_STRUCT\n\nstruct VectorHijacker\n{\n std::size_t _newSize;\n};\n\n#endif\n\n\ntemplate<>\ntemplate<>\ninline decltype(auto) std::vector<HIJACKED_TYPE, std::allocator<HIJACKED_TYPE>>::emplace_back<const VectorHijacker &>(const VectorHijacker &hijacker)\n{\n // We're modifying directly the size of the vector without passing by the extra initialization. This is the part that relies on how the STL was implemented.\n _Mypair._Myval2._Mylast = _Mypair._Myval2._Myfirst + hijacker._newSize;\n}\n\ninline void setNumUninitialized_hijack(std::vector<HIJACKED_TYPE> &hijackedVector, const VectorHijacker &hijacker)\n{\n hijackedVector.reserve(hijacker._newSize);\n hijackedVector.emplace_back<const VectorHijacker &>(hijacker);\n}\n"
},
{
"answer_id": 72015151,
"author": "Henryk",
"author_id": 10503465,
"author_profile": "https://Stackoverflow.com/users/10503465",
"pm_score": 1,
"selected": false,
"text": "g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0\n g++ --std=c++17 -O3\n #include <vector>\n\nint main(){\n constexpr size_t size = 1024lu*1024lu*1024lu*25lu;//25B elements = 200GB\n std::vector<size_t> vec(size);\n}\nreal 0m36.246s\nuser 0m4.549s\nsys 0m31.604s\n #include <vector>\n#include <boost/core/noinit_adaptor.hpp>\n\nint main(){\n constexpr size_t size = 1024lu*1024lu*1024lu*25lu;//25B elements = 200GB\n std::vector<size_t,boost::noinit_adaptor<std::allocator<size_t>>> vec(size);\n}\n\nreal 0m0.002s\nuser 0m0.001s\nsys 0m0.000s\n #include <memory>\n\nint main(){\n constexpr size_t size = 1024lu*1024lu*1024lu*25lu;//25B elements = 200GB\n auto data = std::unique_ptr<size_t[]>(new size_t[size]);\n}\n\nreal 0m0.002s\nuser 0m0.002s\nsys 0m0.000s\n g++ --std=c++17-fopenmp -O3\n #include <vector>\n#include <random>\n\nint main(){\n constexpr size_t size = 1024lu*1024lu*1024lu*25lu;//25B elements = 200GB\n std::vector<size_t> vec(size);\n #pragma omp parallel\n {\n std::minstd_rand0 gen(42);\n #pragma omp for schedule(static)\n for (size_t i = 0; i < size; ++i) vec[i] = gen();\n }\n}\nreal 0m41.958s\nuser 4m37.495s\nsys 0m31.348s\n #include <vector>\n#include <random>\n#include <boost/core/noinit_adaptor.hpp>\n\nint main(){\n constexpr size_t size = 1024lu*1024lu*1024lu*25lu;//25B elements = 200GB\n std::vector<size_t,boost::noinit_adaptor<std::allocator<size_t>>> vec(size);\n #pragma omp parallel\n {\n std::minstd_rand0 gen(42);\n #pragma omp for schedule(static)\n for (size_t i = 0; i < size; ++i) vec[i] = gen();\n }\n}\nreal 0m10.508s\nuser 1m37.665s\nsys 3m14.951s\n std::vector"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6160/"
] |
96,597
|
<p>My development server (CentOS 5) is running Subversion 1.4.2, and I wish to upgrade it to 1.5. I have read in various blogs and documents scattered around the web that this may be done by using RPMForge. I have followed the instructions found on <a href="http://wiki.centos.org/AdditionalResources/Repositories/RPMForge?action=show&redirect=Repositories%2FRPMForge" rel="nofollow noreferrer">CentOS Wiki</a>, including installing yum-priorities and setting my priorities as indicated (1 and 2 for core repo sources, and 20 for RPMForge).</p>
<p>However, when I attempt to run:</p>
<pre><code>$ yum info subversion
</code></pre>
<p>the version number given to me is still 1.4.2, with a status of Installed. My other option at this point is compiling from source, but I would like to find a package-managed solution for ease of future upgrades.</p>
<p>Any thoughts?</p>
|
[
{
"answer_id": 96662,
"author": "Peter Stone",
"author_id": 1806,
"author_profile": "https://Stackoverflow.com/users/1806",
"pm_score": 1,
"selected": false,
"text": "repomd http://apt.sw.be redhat/el$(VERSION)/en/$(ARCH)/dag\n yum check-update subversion.i386 1.5.2-0.1.el5.rf rpmforge\nsubversion-perl.i386 1.5.2-0.1.el5.rf rpmforge\n"
},
{
"answer_id": 97105,
"author": "Peter Stone",
"author_id": 1806,
"author_profile": "https://Stackoverflow.com/users/1806",
"pm_score": 1,
"selected": false,
"text": "rpmforge enabled=1 enabled=0 /etc/yum/pluginconf.d/priorities.conf"
},
{
"answer_id": 97106,
"author": "8jean",
"author_id": 10011,
"author_profile": "https://Stackoverflow.com/users/10011",
"pm_score": 7,
"selected": true,
"text": "yum yum update enabled = 0 /etc/yum.repos.d/rpmforge.repo yum --enablerepo=rpmforge install subversion\n yum --enablerepo=rpmforge update subversion\n exclude=subversion [base] [update] /etc/yum.repos.d/CentOS-Base.repo yum update"
},
{
"answer_id": 2156067,
"author": "intoxicadocoder",
"author_id": 261154,
"author_profile": "https://Stackoverflow.com/users/261154",
"pm_score": 2,
"selected": false,
"text": "/etc/yum/pluginconf.d/priorities.conf $ rpm -qa|grep subversion\n subversion-1.4.2-4.el5_3.1\n subversion-1.4.2-4.el5_3.1 \n $ yum --enablerepo=rpmforge check-update subversion\nsubversion.x86_64 1.6.6-0.1.el5.rf rpmforge\n $ yum shell\n>erase mod_dav_svn-1.4.2-4.el5_3.1\n>erase subversion-1.4.2-4.el5_3.1\n>install mod_dav_svn-1.6.6-0.1.el5.rf\n>install subversion-1.6.6-0.1.el5.rf.x86_64\n>run\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5570/"
] |
96,615
|
<p>So if I'm using branches that are remote (tracked) branches, and I want to get the lastest, I'm still unclear if I should be doing <code>git pull</code> or <code>git rebase</code>. I thought I had read that doing <code>git rebase</code> when working on a branch with other users, it can screw them up when they pull or rebase. Is that true? Should we all be using <code>git pull</code>?</p>
|
[
{
"answer_id": 96666,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "git pull git rebase git rebase"
},
{
"answer_id": 96924,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 7,
"selected": true,
"text": "git rebase master\n git rebase mybranch\n"
},
{
"answer_id": 98077,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 3,
"selected": false,
"text": "rebase"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14873/"
] |
96,624
|
<p>I have an assembly which should <strong>not</strong> be used by any application other than the designated executable. Please give me some instructions to do so.</p>
|
[
{
"answer_id": 96681,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 1,
"selected": false,
"text": "int MySecretPrimeDetectionAlgorithm(int lastPrimeNumber);\n int Asdfasdfasdfasdfasdfasdfasdf(int qwerqwerqwerqwerqwerqwer);\n"
},
{
"answer_id": 96796,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 5,
"selected": true,
"text": "public class NotForAnyoneElse {\n public NotForAnyoneElse() {\n if (typeof(NotForAnyoneElse).Assembly.GetName().GetPublicKeyToken() != Assembly.GetEntryAssembly().GetName().GetPublicKeyToken()) {\n throw new SomeException(...);\n }\n }\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18198/"
] |
96,661
|
<p>I have a query that I would like to filter in different ways at different times. The way I have done this right now by placing parameters in the criteria field of the relevant query fields, however there are many cases in which I do not want to filter on a given field but only on the other fields. Is there any way in which a wildcard of some sort can be passed to the criteria parameter so that I can bypass the filtering for that particular call of the query?</p>
|
[
{
"answer_id": 96950,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 0,
"selected": false,
"text": "like [paramName] like [paramName] or Is Null"
},
{
"answer_id": 96978,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 4,
"selected": false,
"text": "PARAMETERS ParamA Text ( 255 );\nSELECT t.id, t.topic_id\nFROM SomeTable t\nWHERE t.id Like IIf(IsNull([ParamA]),\"*\",[ParamA])\n"
},
{
"answer_id": 100078,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 1,
"selected": false,
"text": "qr = \"Select Tbl_Country.* From Tbl_Country WHERE id_Country = [fid_country]\"\n qr = replace(qr,\"[fid_country]\",\"\"\"*\"\"\")\n qr = \"Select Tbl_Country.* From Tbl_Country _\n WHERE id_Country LIKE [fid_country]\"\n qr = replace(qr,\"[fid_country]\",\"G*\")\n set rs = currentDb.openRecordset(qr)\n"
},
{
"answer_id": 148614,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 2,
"selected": false,
"text": "* LIKE NOT LIKE \"*[!0-9]*\"\n NOT LIKE \"*[!0-9]*\" AND NOT LIKE \"%[!0-9]%\"\n NOT ALIKE \"%[!0-9]%\"\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16562/"
] |
96,671
|
<p>I have a flash app (SWF) running Flash 8 embedded in an HTML page. How do I get flash to reload the parent HTML page it is embedded in? I've tried using ExternalInterface to call a JavaScript function to reload the page but that doesn't seem to work.
</p>
|
[
{
"answer_id": 96717,
"author": "Alex Fort",
"author_id": 12624,
"author_profile": "https://Stackoverflow.com/users/12624",
"pm_score": 2,
"selected": false,
"text": "getURL(\"javascript:location.reload(true)\");"
},
{
"answer_id": 211359,
"author": "Yaba",
"author_id": 7524,
"author_profile": "https://Stackoverflow.com/users/7524",
"pm_score": 4,
"selected": false,
"text": " if (ExternalInterface.available)\n {\n var result = ExternalInterface.call(\"reload\");\n }\n function reload()\n {\n document.location.reload(true);\n return true;\n }\n"
},
{
"answer_id": 2595348,
"author": "stach",
"author_id": 64653,
"author_profile": "https://Stackoverflow.com/users/64653",
"pm_score": 1,
"selected": false,
"text": "navigateToURL(new URLRequest(\"path_to_page\"), \"_self\");\n"
},
{
"answer_id": 3563569,
"author": "Eliram",
"author_id": 18790,
"author_profile": "https://Stackoverflow.com/users/18790",
"pm_score": 2,
"selected": false,
"text": "import flash.external.ExternalInterface;\n\nExternalInterface.call(\"history.go\", 0);\n"
},
{
"answer_id": 15966881,
"author": "xLite",
"author_id": 745888,
"author_profile": "https://Stackoverflow.com/users/745888",
"pm_score": 2,
"selected": false,
"text": "ExternalInterface.call(\"document.location.reload\", true);\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
96,732
|
<p>I've got a situation where I have a DLL I'm creating that uses another third party DLL, but I would prefer to be able to build the third party DLL into my DLL instead of having to keep them both together if possible.</p>
<p>This with is C# and .NET 3.5.</p>
<p>The way I would like to do this is by storing the third party DLL as an embedded resource which I then place in the appropriate place during execution of the first DLL.</p>
<p>The way I originally planned to do this is by writing code to put the third party DLL in the location specified by <code>System.Reflection.Assembly.GetExecutingAssembly().Location.ToString()</code>
minus the last <code>/nameOfMyAssembly.dll</code>. I can successfully save the third party <code>.DLL</code> in this location (which ends up being </p>
<blockquote>
<p>C:\Documents and Settings\myUserName\Local Settings\Application
Data\assembly\dl3\KXPPAX6Y.ZCY\A1MZ1499.1TR\e0115d44\91bb86eb_fe18c901 </p>
</blockquote>
<p>), but when I get to the part of my code requiring this DLL, it can't find it.</p>
<p>Does anybody have any idea as to what I need to be doing differently?</p>
|
[
{
"answer_id": 97080,
"author": "dgvid",
"author_id": 9897,
"author_profile": "https://Stackoverflow.com/users/9897",
"pm_score": 3,
"selected": false,
"text": " Assembly resAssembly = Assembly.LoadFile(assemblyPathName);\n\n byte[] assemblyData;\n using (Stream stream = resAssembly.GetManifestResourceStream(resourceName))\n {\n assemblyData = ReadBytesFromStream(stream);\n stream.Close();\n }\n"
},
{
"answer_id": 97290,
"author": "Atif Aziz",
"author_id": 6682,
"author_profile": "https://Stackoverflow.com/users/6682",
"pm_score": 6,
"selected": true,
"text": "AppDomain.AssemblyResolve AppDomain.AssemblyResolve Assembly.GetManifestResourceStream Assembly.Load AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>\n{\n var resName = args.Name + \".dll\"; \n var thisAssembly = Assembly.GetExecutingAssembly(); \n using (var input = thisAssembly.GetManifestResourceStream(resName))\n {\n return input != null \n ? Assembly.Load(StreamToBytes(input))\n : null;\n }\n};\n StreamToBytes static byte[] StreamToBytes(Stream input) \n{\n var capacity = input.CanSeek ? (int) input.Length : 0;\n using (var output = new MemoryStream(capacity))\n {\n int readLength;\n var buffer = new byte[4096];\n\n do\n {\n readLength = input.Read(buffer, 0, buffer.Length);\n output.Write(buffer, 0, readLength);\n }\n while (readLength != 0);\n\n return output.ToArray();\n }\n}\n"
},
{
"answer_id": 103773,
"author": "Redwood",
"author_id": 1512,
"author_profile": "https://Stackoverflow.com/users/1512",
"pm_score": 4,
"selected": false,
"text": " public static void EnableDynamicLoadingForDlls(Assembly assemblyToLoadFrom, string embeddedResourcePrefix) {\n AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { // had to add =>\n try {\n string resName = embeddedResourcePrefix + \".\" + args.Name.Split(',')[0] + \".dll.resource\";\n using (Stream input = assemblyToLoadFrom.GetManifestResourceStream(resName)) {\n return input != null\n ? Assembly.Load(StreamToBytes(input))\n : null;\n }\n } catch (Exception ex) {\n _log.Error(\"Error dynamically loading dll: \" + args.Name, ex);\n return null;\n }\n }; // Had to add colon\n }\n\n private static byte[] StreamToBytes(Stream input) {\n int capacity = input.CanSeek ? (int)input.Length : 0;\n using (MemoryStream output = new MemoryStream(capacity)) {\n int readLength;\n byte[] buffer = new byte[4096];\n\n do {\n readLength = input.Read(buffer, 0, buffer.Length); // had to change to buffer.Length\n output.Write(buffer, 0, readLength);\n }\n while (readLength != 0);\n\n return output.ToArray();\n }\n }\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
] |
96,748
|
<p>I'm building a widget, and I've been using iframes to present content within it. At some point, I might start serving third party HTML and JS, so I thought iframes would be a good idea. </p>
<p>It does make the widget javascript a little more complicated, and I'm concerned that this might not be the best implementation.</p>
<p>Do you have any advice? It would be a huge help to hear what other people think about iframes.</p>
|
[
{
"answer_id": 96787,
"author": "Brian MacKay",
"author_id": 16082,
"author_profile": "https://Stackoverflow.com/users/16082",
"pm_score": 3,
"selected": false,
"text": "HttpContext.Current.Response.AddHeader(\"p3p\", \"CP=\\\"\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"\"\")\n"
},
{
"answer_id": 98396,
"author": "Evgeny",
"author_id": 18327,
"author_profile": "https://Stackoverflow.com/users/18327",
"pm_score": 4,
"selected": false,
"text": "document.domain = 'somedomain.com';\n"
},
{
"answer_id": 2486650,
"author": "Petri Pennanen",
"author_id": 253246,
"author_profile": "https://Stackoverflow.com/users/253246",
"pm_score": 0,
"selected": false,
"text": "<iframe src=\"content.html\">\n <p>\n This content will only be displayed by browsers that do not support\n iframes. You should provide a link to the content, or in your \n case an alternative way to use your widget.\n </p>\n</iframe>\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9106/"
] |
96,759
|
<p>I have CSV data loaded into a multidimensional array. In this way each "row" is a record and each "column" contains the same type of data. I am using the function below to load my CSV file.</p>
<pre><code>function f_parse_csv($file, $longest, $delimiter)
{
$mdarray = array();
$file = fopen($file, "r");
while ($line = fgetcsv($file, $longest, $delimiter))
{
array_push($mdarray, $line);
}
fclose($file);
return $mdarray;
}
</code></pre>
<p>I need to be able to specify a column to sort so that it rearranges the rows. One of the columns contains date information in the format of <code>Y-m-d H:i:s</code> and I would like to be able to sort with the most recent date being the first row.</p>
|
[
{
"answer_id": 96832,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 5,
"selected": false,
"text": "class TableSorter {\n protected $column;\n function __construct($column) {\n $this->column = $column;\n }\n function sort($table) {\n usort($table, array($this, 'compare'));\n return $table;\n }\n function compare($a, $b) {\n if ($a[$this->column] == $b[$this->column]) {\n return 0;\n }\n return ($a[$this->column] < $b[$this->column]) ? -1 : 1;\n }\n}\n $sorter = new TableSorter(0); // sort by first column\n$mdarray = $sorter->sort($mdarray);\n"
},
{
"answer_id": 96870,
"author": "Shinhan",
"author_id": 18219,
"author_profile": "https://Stackoverflow.com/users/18219",
"pm_score": 9,
"selected": true,
"text": "foreach ($mdarray as $key => $row) {\n // replace 0 with the field's index/key\n $dates[$key] = $row[0];\n}\n\narray_multisort($dates, SORT_DESC, $mdarray);\n array_multisort(array_column($mdarray, 0), SORT_DESC, $mdarray);\n"
},
{
"answer_id": 97572,
"author": "Devon",
"author_id": 13850,
"author_profile": "https://Stackoverflow.com/users/13850",
"pm_score": 2,
"selected": false,
"text": "// a sorter class\n// php4 and php5 compatible\nclass Sorter {\n\n var $sort_fields;\n var $backwards = false;\n var $numeric = false;\n\n function sort() {\n $args = func_get_args();\n $array = $args[0];\n if (!$array) return array();\n $this->sort_fields = array_slice($args, 1);\n if (!$this->sort_fields) return $array();\n\n if ($this->numeric) {\n usort($array, array($this, 'numericCompare'));\n } else {\n usort($array, array($this, 'stringCompare'));\n }\n return $array;\n }\n\n function numericCompare($a, $b) {\n foreach($this->sort_fields as $sort_field) {\n if ($a[$sort_field] == $b[$sort_field]) {\n continue;\n }\n return ($a[$sort_field] < $b[$sort_field]) ? ($this->backwards ? 1 : -1) : ($this->backwards ? -1 : 1);\n }\n return 0;\n }\n\n function stringCompare($a, $b) {\n foreach($this->sort_fields as $sort_field) {\n $cmp_result = strcasecmp($a[$sort_field], $b[$sort_field]);\n if ($cmp_result == 0) continue;\n\n return ($this->backwards ? -$cmp_result : $cmp_result);\n }\n return 0;\n }\n}\n\n/////////////////////\n// usage examples\n\n// some starting data\n$start_data = array(\n array('first_name' => 'John', 'last_name' => 'Smith', 'age' => 10),\n array('first_name' => 'Joe', 'last_name' => 'Smith', 'age' => 11),\n array('first_name' => 'Jake', 'last_name' => 'Xample', 'age' => 9),\n);\n\n// sort by last_name, then first_name\n$sorter = new Sorter();\nprint_r($sorter->sort($start_data, 'last_name', 'first_name'));\n\n// sort by first_name, then last_name\n$sorter = new Sorter();\nprint_r($sorter->sort($start_data, 'first_name', 'last_name'));\n\n// sort by last_name, then first_name (backwards)\n$sorter = new Sorter();\n$sorter->backwards = true;\nprint_r($sorter->sort($start_data, 'last_name', 'first_name'));\n\n// sort numerically by age\n$sorter = new Sorter();\n$sorter->numeric = true;\nprint_r($sorter->sort($start_data, 'age'));\n"
},
{
"answer_id": 98058,
"author": "Melikoth",
"author_id": 1536217,
"author_profile": "https://Stackoverflow.com/users/1536217",
"pm_score": 0,
"selected": false,
"text": "function sort2d_bycolumn($array, $column, $method, $has_header)\n {\n if ($has_header) $header = array_shift($array);\n foreach ($array as $key => $row) {\n $narray[$key] = $row[$column]; \n }\n array_multisort($narray, $method, $array);\n if ($has_header) array_unshift($array, $header);\n return $array;\n }"
},
{
"answer_id": 4230273,
"author": "Mike C",
"author_id": 474192,
"author_profile": "https://Stackoverflow.com/users/474192",
"pm_score": 3,
"selected": false,
"text": "function sort_multi_array ($array, $key)\n{\n $keys = array();\n for ($i=1;$i<func_num_args();$i++) {\n $keys[$i-1] = func_get_arg($i);\n }\n\n // create a custom search function to pass to usort\n $func = function ($a, $b) use ($keys) {\n for ($i=0;$i<count($keys);$i++) {\n if ($a[$keys[$i]] != $b[$keys[$i]]) {\n return ($a[$keys[$i]] < $b[$keys[$i]]) ? -1 : 1;\n }\n }\n return 0;\n };\n\n usort($array, $func);\n\n return $array;\n}\n"
},
{
"answer_id": 10142887,
"author": "feeela",
"author_id": 341201,
"author_profile": "https://Stackoverflow.com/users/341201",
"pm_score": 4,
"selected": false,
"text": "/**\n * Sorting array of associative arrays - multiple row sorting using a closure.\n * See also: http://the-art-of-web.com/php/sortarray/\n *\n * @param array $data input-array\n * @param string|array $fields array-keys\n * @license Public Domain\n * @return array\n */\nfunction sortArray( $data, $field ) {\n $field = (array) $field;\n uasort( $data, function($a, $b) use($field) {\n $retval = 0;\n foreach( $field as $fieldname ) {\n if( $retval == 0 ) $retval = strnatcmp( $a[$fieldname], $b[$fieldname] );\n }\n return $retval;\n } );\n return $data;\n}\n\n/* example */\n$data = array(\n array( \"firstname\" => \"Mary\", \"lastname\" => \"Johnson\", \"age\" => 25 ),\n array( \"firstname\" => \"Amanda\", \"lastname\" => \"Miller\", \"age\" => 18 ),\n array( \"firstname\" => \"James\", \"lastname\" => \"Brown\", \"age\" => 31 ),\n array( \"firstname\" => \"Patricia\", \"lastname\" => \"Williams\", \"age\" => 7 ),\n array( \"firstname\" => \"Michael\", \"lastname\" => \"Davis\", \"age\" => 43 ),\n array( \"firstname\" => \"Sarah\", \"lastname\" => \"Miller\", \"age\" => 24 ),\n array( \"firstname\" => \"Patrick\", \"lastname\" => \"Miller\", \"age\" => 27 )\n);\n\n$data = sortArray( $data, 'age' );\n$data = sortArray( $data, array( 'lastname', 'firstname' ) );\n"
},
{
"answer_id": 16788610,
"author": "Jon",
"author_id": 50079,
"author_profile": "https://Stackoverflow.com/users/50079",
"pm_score": 8,
"selected": false,
"text": "DateTime usort uasort array_multisort array_multisort function make_comparer() {\n // Normalize criteria up front so that the comparer finds everything tidy\n $criteria = func_get_args();\n foreach ($criteria as $index => $criterion) {\n $criteria[$index] = is_array($criterion)\n ? array_pad($criterion, 3, null)\n : array($criterion, SORT_ASC, null);\n }\n\n return function($first, $second) use (&$criteria) {\n foreach ($criteria as $criterion) {\n // How will we compare this round?\n list($column, $sortOrder, $projection) = $criterion;\n $sortOrder = $sortOrder === SORT_DESC ? -1 : 1;\n\n // If a projection was defined project the values now\n if ($projection) {\n $lhs = call_user_func($projection, $first[$column]);\n $rhs = call_user_func($projection, $second[$column]);\n }\n else {\n $lhs = $first[$column];\n $rhs = $second[$column];\n }\n\n // Do the actual comparison; do not return if equal\n if ($lhs < $rhs) {\n return -1 * $sortOrder;\n }\n else if ($lhs > $rhs) {\n return 1 * $sortOrder;\n }\n }\n\n return 0; // tiebreakers exhausted, so $first == $second\n };\n}\n $data = array(\n array('zz', 'name' => 'Jack', 'number' => 22, 'birthday' => '12/03/1980'),\n array('xx', 'name' => 'Adam', 'number' => 16, 'birthday' => '01/12/1979'),\n array('aa', 'name' => 'Paul', 'number' => 16, 'birthday' => '03/11/1987'),\n array('cc', 'name' => 'Helen', 'number' => 44, 'birthday' => '24/06/1967'),\n);\n make_comparer usort uasort $data name usort($data, make_comparer('name'));\n usort($data, make_comparer(0)); // 0 = first numerically indexed column\n make_comparer usort($data, make_comparer('number', 0));\n 0 => the column name to sort on (mandatory)\n1 => either SORT_ASC or SORT_DESC (optional)\n2 => a projection function (optional)\n usort($data, make_comparer(['name', SORT_DESC]));\n usort($data, make_comparer(['number', SORT_DESC], ['name', SORT_DESC]));\n usort make_comparer usort($data, make_comparer('birthday'));\n date_create usort($data, make_comparer(['birthday', SORT_ASC, 'date_create']));\n strtolower usort($data, make_comparer(\n ['number', SORT_DESC],\n ['birthday', SORT_ASC, 'date_create']\n));\n"
},
{
"answer_id": 17201125,
"author": "PJ Brunet",
"author_id": 722796,
"author_profile": "https://Stackoverflow.com/users/722796",
"pm_score": 0,
"selected": false,
"text": "// Sort by name, pull the other stuff along for the ride\nforeach ($names_stuff as $name_stuff) {\n // To sort by stuff1, that would be first in the contatenation\n $sorted_names[] = $name_stuff[0] .','. name_stuff[1] .','. $name_stuff[2];\n}\nsort($sorted_names, SORT_STRING);\n foreach ($sorted_names as $sorted_name) {\n $name_stuff = explode(',',$sorted_name);\n // use your $name_stuff[0] \n // use your $name_stuff[1] \n // ... \n}\n"
},
{
"answer_id": 24486990,
"author": "Kamal",
"author_id": 1093184,
"author_profile": "https://Stackoverflow.com/users/1093184",
"pm_score": 3,
"selected": false,
"text": " $array = array(\n array('price'=>'1000.50','product'=>'product 1'),\n array('price'=>'8800.50','product'=>'product 2'),\n array('price'=>'200.0','product'=>'product 3')\n);\n\nfunction cmp($a, $b) {\n return $a['price'] > $b['price'];\n}\nusort($array, \"cmp\");\nprint_r($array);\n Array\n(\n [0] => Array\n (\n [price] => 134.50\n [product] => product 1\n )\n\n [1] => Array\n (\n [price] => 2033.0\n [product] => product 3\n )\n\n [2] => Array\n (\n [price] => 8340.50\n [product] => product 2\n )\n\n)\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1536217/"
] |
96,780
|
<p>Visual Studio randomly crashes when adding/removing references and projects.
Any thoughts why? Will installing Sp1 help?</p>
<p>EDIT: I do not work with any addons except SourceSafe. I do most of my development in connected mode.<br></p>
<p>Developing using:<br>
Visual Studio 2008 <br>
WinXp Terminal Service -> Win2k3 Sp2 (64bit)<br>
VSS 8.0, 32bit<br></p>
|
[
{
"answer_id": 314756,
"author": "Charles Anderson",
"author_id": 11677,
"author_profile": "https://Stackoverflow.com/users/11677",
"pm_score": 4,
"selected": false,
"text": "devenv /resetuserdata\n"
},
{
"answer_id": 14887575,
"author": "Catherine Hope",
"author_id": 1070615,
"author_profile": "https://Stackoverflow.com/users/1070615",
"pm_score": 2,
"selected": false,
"text": ".suo The Open from Source Control operation is still in progress but you can start working now. the rest of the projects will be retrieved asynchronously."
},
{
"answer_id": 34913397,
"author": "Yar",
"author_id": 2517730,
"author_profile": "https://Stackoverflow.com/users/2517730",
"pm_score": 0,
"selected": false,
"text": "default"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14484/"
] |
96,826
|
<p>Pretty basic question, I'm trying to write a regex in Vim to match any phrase starting with <code>"abc "</code> directly followed by anything other than <code>"defg"</code>. </p>
<p>I've used <code>"[^defg]"</code> to match any single character other than d, e, f or g.</p>
<p>My first instinct was to try <code>/abc [^\(defg\)]</code> or <code>/abc [^\<defg\>]</code> but neither one of those works.</p>
|
[
{
"answer_id": 96946,
"author": "Lee H",
"author_id": 18201,
"author_profile": "https://Stackoverflow.com/users/18201",
"pm_score": 1,
"selected": false,
"text": "/\\%(\\%(.\\{-}\\)\\@<=XXXXXX\\zs\\)*\n /abc \\%(\\%(.\\{-}\\)\\@<=defg\\zs\\)*\n"
},
{
"answer_id": 97008,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 7,
"selected": true,
"text": "/abc \\(defg\\)\\@!\n :help \\@!\n"
},
{
"answer_id": 99129,
"author": "rampion",
"author_id": 9859,
"author_profile": "https://Stackoverflow.com/users/9859",
"pm_score": 4,
"selected": false,
"text": "/\\%(defg\\)\\@<!abc /\n :help \\@<! .* /\\%(defg.*\\)\\@<!abc /\n /\\%(defg.*\\)\\@<!abc \\%(.*defg\\)\\@!/\n :v// :s// :%v/defg/s/abc /<whatever>/g\n :help :v"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5379/"
] |
96,842
|
<p>I have migrated a couple of project from Subversion to git. It work really well but when I clone my repository, it's really long because I have all the history of a lot of .jar file included in the transfer.</p>
<p>Is there a way to keep only the latest version of certain type of file in my main repository. I mainly want to delete old version on binary file.</p>
|
[
{
"answer_id": 96876,
"author": "Martin OConnor",
"author_id": 18233,
"author_profile": "https://Stackoverflow.com/users/18233",
"pm_score": 1,
"selected": false,
"text": "git gc git pack"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16309/"
] |
96,848
|
<p>Is there any way to use a constant as a hash key?</p>
<p>For example:</p>
<pre><code>use constant X => 1;
my %x = (X => 'X');
</code></pre>
<p>The above code will create a hash with "X" as key and not 1 as key. Whereas, I want to use the value of constant X as key.</p>
|
[
{
"answer_id": 96869,
"author": "nohat",
"author_id": 3101,
"author_profile": "https://Stackoverflow.com/users/3101",
"pm_score": 7,
"selected": true,
"text": "use constant use constant X => 1;\n\nmy %x = ( &X => 'X');\n use constant X => 1;\n\nmy %x = ( X() => 'X');\n"
},
{
"answer_id": 96877,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 4,
"selected": false,
"text": "my %x = (X, 'X');\n my %x = ( X() => 'X' );\nmy %x = ( &X => 'X' );\n"
},
{
"answer_id": 96885,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "my %x = ( X, 'X');\n"
},
{
"answer_id": 96888,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 2,
"selected": false,
"text": "my %x ( (X) => 1 );\n my %x ( X, 1 );\n"
},
{
"answer_id": 96902,
"author": "Chris",
"author_id": 15578,
"author_profile": "https://Stackoverflow.com/users/15578",
"pm_score": 3,
"selected": false,
"text": "$hash{CONSTANT()} $hash{+CONSTANT}"
},
{
"answer_id": 97019,
"author": "shelfoo",
"author_id": 3444,
"author_profile": "https://Stackoverflow.com/users/3444",
"pm_score": 4,
"selected": false,
"text": "\nuse Readonly;\n\nReadonly my $CONSTANT => 'Some value';\n\n$hash{$CONSTANT} = 1;\n"
},
{
"answer_id": 97070,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 3,
"selected": false,
"text": "use constant => use constant X => 1;\n%hash = (X() => 1);\n%hash = (+X => 1);\n$hash{X()} = 1;\n$hash{+X} = 1;\n %hash = (X, 1);\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406/"
] |
96,859
|
<p>What are some good package naming conventions for domain specific object models. For example, say you have a <strong>Person.java</strong> POJO, would you put it in a <strong>mydomain.model</strong> or <strong>mydomain.entity</strong> or <strong>mydomain.om</strong> (object model) package. The idea is to separate the MVC model objects from the domain object model. Our MVC based application has a <strong>model</strong> package that contains behavior but using that package to contain our domain object model seems inappropriate and potentially confusing. </p>
|
[
{
"answer_id": 3284536,
"author": "Martin",
"author_id": 1106301,
"author_profile": "https://Stackoverflow.com/users/1106301",
"pm_score": 2,
"selected": false,
"text": "com.foobar.accounting.model.*\ncom.foobar.accounting.view.*\n\ncom.foobar.invoicing.model.*\ncom.foobar.invoicing.view.*\n com.foobar.model.accounting.*\ncom.foobar.model.invoicing.*\n\ncom.foobar.view.accounting.*\ncom.foobar.view.invoicing.*\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3803/"
] |
96,871
|
<p>I'd like to make status icons for a C# WinForms TreeList control. The statuses are combinations of other statuses (eg. a user node might be inactive or banned or inactive and banned), and the status icon is comprised of non-overlapping, smaller glyphs. </p>
<p>I'd really like to avoid having to hand-generate all the possibly permutations of status icons if I can avoid it. </p>
<p>Is it possible to create an image list (or just a bunch of bitmap resources or something) that I can use to generate the ImageList programmatically?</p>
<p>I'm poking around the System.Drawing classes and nothing's jumping out at me. Also, I'm stuck with .Net 2.0.</p>
|
[
{
"answer_id": 96907,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 2,
"selected": true,
"text": "Bitmap image1 = ...\nBitmap image2 = ...\n\nBitmap combined = new Bitmap(image1.Width, image1.Height);\nusing (Graphics g = Graphics.FromImage(combined)) {\n g.DrawImage(image1, new Point(0, 0));\n g.DrawImage(image2, new Point(0, 0);\n}\n\nimageList.Add(combined);\n"
},
{
"answer_id": 97793,
"author": "Joel Lucsy",
"author_id": 645,
"author_profile": "https://Stackoverflow.com/users/645",
"pm_score": 0,
"selected": false,
"text": "\nImage img = Image.FromStream( /*get stream from resources*/ );\nImageList1.Images.Add( img );\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5062/"
] |
96,882
|
<p>I need to create a nice installer for a Mac application. I want it to be a disk image (DMG), with a predefined size, layout and background image.</p>
<p>I need to do this programmatically in a script, to be integrated in an existing build system (more of a pack system really, since it only create installers. The builds are done separately). </p>
<p>I already have the DMG creation done using "hdiutil", what I haven't found out yet is how to make an icon layout and specify a background bitmap.</p>
|
[
{
"answer_id": 97042,
"author": "Ludvig A. Norin",
"author_id": 16909,
"author_profile": "https://Stackoverflow.com/users/16909",
"pm_score": 5,
"selected": false,
"text": "hdiutil create XXX.dmg -volname \"YYY\" -fs HFS+ -srcfolder \"ZZZ\"\n XXX == disk image file name (duh!)\nYYY == window title displayed when DMG is opened\nZZZ == Path to a folder containing the files that will be copied into the DMG\n"
},
{
"answer_id": 1513578,
"author": "Ludvig A. Norin",
"author_id": 16909,
"author_profile": "https://Stackoverflow.com/users/16909",
"pm_score": 9,
"selected": true,
"text": "hdiutil create -srcfolder \"${source}\" -volname \"${title}\" -fs HFS+ \\\n -fsargs \"-c c=64,a=16,e=16\" -format UDRW -size ${size}k pack.temp.dmg\n device=$(hdiutil attach -readwrite -noverify -noautoopen \"pack.temp.dmg\" | \\\n egrep '^/dev/' | sed 1q | awk '{print $1}')\n echo '\n tell application \"Finder\"\n tell disk \"'${title}'\"\n open\n set current view of container window to icon view\n set toolbar visible of container window to false\n set statusbar visible of container window to false\n set the bounds of container window to {400, 100, 885, 430}\n set theViewOptions to the icon view options of container window\n set arrangement of theViewOptions to not arranged\n set icon size of theViewOptions to 72\n set background picture of theViewOptions to file \".background:'${backgroundPictureName}'\"\n make new alias file at container window to POSIX file \"/Applications\" with properties {name:\"Applications\"}\n set position of item \"'${applicationName}'\" of container window to {100, 100}\n set position of item \"Applications\" of container window to {375, 100}\n update without registering applications\n delay 5\n close\n end tell\n end tell\n' | osascript\n chmod -Rf go-w /Volumes/\"${title}\"\nsync\nsync\nhdiutil detach ${device}\nhdiutil convert \"/pack.temp.dmg\" -format UDZO -imagekey zlib-level=9 -o \"${finalDMGName}\"\nrm -f /pack.temp.dmg \n ..\nset position of item \"'${applicationName}'\" of container window to {100, 100}\nset position of item \"Applications\" of container window to {375, 100}\nclose\nopen\n"
},
{
"answer_id": 18443866,
"author": "Parag Bafna",
"author_id": 944634,
"author_profile": "https://Stackoverflow.com/users/944634",
"pm_score": 3,
"selected": false,
"text": "/*Add a drive icon*/\ncp \"/Volumes/customIcon.icns\" \"/Volumes/dmgName/.VolumeIcon.icns\" \n\n\n/*SetFile -c icnC will change the creator of the file to icnC*/\nSetFile -c icnC /<your path>/.VolumeIcon.icns\n /*to set custom icon attribute*/\nSetFile -a C /Volumes/dmgName\n"
},
{
"answer_id": 20879598,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "#!/bin/sh\n# create_dmg Frobulator Frobulator.dmg path/to/frobulator/dir [ 'Your Code Sign Identity' ]\nset -e\n\nVOLNAME=\"$1\"\nDMG=\"$2\"\nSRC_DIR=\"$3\"\nCODESIGN_IDENTITY=\"$4\"\n\nhdiutil create -srcfolder \"$SRC_DIR\" \\\n -volname \"$VOLNAME\" \\\n -fs HFS+ -fsargs \"-c c=64,a=16,e=16\" \\\n -format UDZO -imagekey zlib-level=9 \"$DMG\"\n\nif [ -n \"$CODESIGN_IDENTITY\" ]; then\n codesign -s \"$CODESIGN_IDENTITY\" -v \"$DMG\"\nfi\n #!/bin/sh\n# create_dmg_with_icon Frobulator Frobulator.dmg path/to/frobulator/dir path/to/someicon.icns [ 'Your Code Sign Identity' ]\nset -e\nVOLNAME=\"$1\"\nDMG=\"$2\"\nSRC_DIR=\"$3\"\nICON_FILE=\"$4\"\nCODESIGN_IDENTITY=\"$5\"\n\nTMP_DMG=\"$(mktemp -u -t XXXXXXX)\"\ntrap 'RESULT=$?; rm -f \"$TMP_DMG\"; exit $RESULT' INT QUIT TERM EXIT\nhdiutil create -srcfolder \"$SRC_DIR\" -volname \"$VOLNAME\" -fs HFS+ \\\n -fsargs \"-c c=64,a=16,e=16\" -format UDRW \"$TMP_DMG\"\nTMP_DMG=\"${TMP_DMG}.dmg\" # because OSX appends .dmg\nDEVICE=\"$(hdiutil attach -readwrite -noautoopen \"$TMP_DMG\" | awk 'NR==1{print$1}')\"\nVOLUME=\"$(mount | grep \"$DEVICE\" | sed 's/^[^ ]* on //;s/ ([^)]*)$//')\"\n# start of DMG changes\ncp \"$ICON_FILE\" \"$VOLUME/.VolumeIcon.icns\"\nSetFile -c icnC \"$VOLUME/.VolumeIcon.icns\"\nSetFile -a C \"$VOLUME\"\n# end of DMG changes\nhdiutil detach \"$DEVICE\"\nhdiutil convert \"$TMP_DMG\" -format UDZO -imagekey zlib-level=9 -o \"$DMG\"\nif [ -n \"$CODESIGN_IDENTITY\" ]; then\n codesign -s \"$CODESIGN_IDENTITY\" -v \"$DMG\"\nfi\n"
},
{
"answer_id": 28112853,
"author": "Linus Unnebäck",
"author_id": 148072,
"author_profile": "https://Stackoverflow.com/users/148072",
"pm_score": 5,
"selected": false,
"text": "appdmg npm install -g appdmg\n spec.json {\n \"title\": \"Test Title\",\n \"background\": \"background.png\",\n \"icon-size\": 80,\n \"contents\": [\n { \"x\": 192, \"y\": 344, \"type\": \"file\", \"path\": \"TestApp.app\" },\n { \"x\": 448, \"y\": 344, \"type\": \"link\", \"path\": \"/Applications\" }\n ]\n}\n appdmg spec.json test.dmg\n"
},
{
"answer_id": 31619515,
"author": "P.M.",
"author_id": 702391,
"author_profile": "https://Stackoverflow.com/users/702391",
"pm_score": 2,
"selected": false,
"text": "#!/bin/bash\n#Create a R/W DMG\n\ndir=\"$TEMP_FILES_DIR/disk\"\ndmg=\"$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.temp.dmg\"\n\nrm -rf \"$dir\"\nmkdir \"$dir\"\ncp -R \"$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.app\" \"$dir\"\nln -s \"/Applications\" \"$dir/Applications\"\nmkdir \"$dir/.background\"\ncp \"$PROJECT_DIR/$PROJECT_NAME/some_image.png\" \"$dir/.background\"\nrm -f \"$dmg\"\nhdiutil create \"$dmg\" -srcfolder \"$dir\" -volname \"$PRODUCT_NAME\" -format UDRW\n\n#Mount the disk image, and store the device name\nhdiutil attach \"$dmg\" -noverify -noautoopen -readwrite\n #!/usr/bin/osascript\n#get the dimensions of the main window using a bash script\n\nset {width, height, scale} to words of (do shell script \"system_profiler SPDisplaysDataType | awk '/Main Display: Yes/{found=1} /Resolution/{width=$2; height=$4} /Retina/{scale=($2 == \\\"Yes\\\" ? 2 : 1)} /^ {8}[^ ]+/{if(found) {exit}; scale=1} END{printf \\\"%d %d %d\\\\n\\\", width, height, scale}'\")\nset x to ((width / 2) / scale)\nset y to ((height / 2) / scale)\n\n#get the product name using a bash script\nset {product_name} to words of (do shell script \"printf \\\"%s\\\", $PRODUCT_NAME\")\nset background to alias (\"Volumes:\"&product_name&\":.background:some_image.png\")\n\ntell application \"Finder\"\n tell disk product_name\n open\n set current view of container window to icon view\n set toolbar visible of container window to false\n set statusbar visible of container window to false\n set the bounds of container window to {x, y, (x + 479), (y + 383)}\n set theViewOptions to the icon view options of container window\n set arrangement of theViewOptions to not arranged\n set icon size of theViewOptions to 128\n set background picture of theViewOptions to background\n set position of item (product_name & \".app\") of container window to {100, 225}\n set position of item \"Applications\" of container window to {375, 225}\n update without registering applications\n close\n end tell\nend tell\n #!/bin/bash\ndir=\"$TEMP_FILES_DIR/disk\"\ncp \"$PROJECT_DIR/$PROJECT_NAME/some_other_image.png\" \"$dir/\"\n\n#unmount the temp image file, then convert it to final image file\nsync\nsync\nhdiutil detach /Volumes/$PRODUCT_NAME\nrm -f \"$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.dmg\"\nhdiutil convert \"$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.temp.dmg\" -format UDZO -imagekey zlib-level=9 -o \"$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.dmg\"\nrm -f \"$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.temp.dmg\"\n\n#Change the icon of the image file\nsips -i \"$dir/some_other_image.png\"\nDeRez -only icns \"$dir/some_other_image.png\" > \"$dir/tmpicns.rsrc\"\nRez -append \"$dir/tmpicns.rsrc\" -o \"$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.dmg\"\nSetFile -a C \"$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.dmg\"\n\nrm -rf \"$dir\"\n"
},
{
"answer_id": 67092989,
"author": "mmerle",
"author_id": 10983525,
"author_profile": "https://Stackoverflow.com/users/10983525",
"pm_score": 2,
"selected": false,
"text": "pip3 install dmgbuild {\n \"title\": \"NAME\",\n \"background\": \"YOUR_BACKGROUND.png\",\n \"format\": \"UDZO\",\n \"compression-level\": 9,\n \"window\": { \"position\": { \"x\": 100, \"y\": 100 },\n \"size\": { \"width\": 640, \"height\": 300 } },\n \"contents\": [\n { \"x\": 140, \"y\": 165, \"type\": \"file\", \"path\": \"/Volumes/YOUR_VOLUME_NAME/YOUR_APP.app\" },\n { \"x\": 480, \"y\": 165, \"type\": \"link\", \"path\": \"/Applications\" }\n ]\n}\n dmgbuild -s settings.json \"YOUR_VOLUME_NAME\" output.dmg"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16909/"
] |
96,922
|
<p>The standard answer is that it's useful when you only need to write a few lines of code ...</p>
<p>I have both languages integrated inside of Eclipse. Because Eclipse handles the compiling, interpreting, running etc. both "run" exactly the same.</p>
<p>The Eclipse IDE for both is similar - instant "compilation", intellisense etc. Both allow the use of the Debug perspective.</p>
<p>If I want to test a few lines of Java, I don't have to create a whole new Java project - I just use the <a href="http://www.eclipsezone.com/eclipse/forums/t61137.html" rel="noreferrer">Scrapbook</a> feature inside Eclipse which which allows me to <em>"execute Java expressions without having to create a new Java program. This is a neat way to quickly test an existing class or evaluate a code snippet"</em>. </p>
<p>Jython allows the use of the Java libraries - but then so (by definition) does Java!</p>
<p>So what other benefits does Jython offer?</p>
|
[
{
"answer_id": 97540,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 5,
"selected": false,
"text": "import java.net.*;\nimport java.io.*;\n\npublic class JGet {\n public static void main (String[] args) throws IOException {\n try {\n URL url = new URL(\"http://www.google.com\");\n\n BufferedReader in = \n new BufferedReader(new InputStreamReader(url.openStream()));\n String str;\n\n while ((str = in.readLine()) != null) {\n System.out.println(str);\n }\n\n in.close();\n } \n catch (MalformedURLException e) {} \n catch (IOException e) {}\n }\n}\n import urllib\nprint urllib.urlopen('http://www.google.com').read()\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9922/"
] |
96,945
|
<p>I am using Oracle 9 and JDBC and would like to encyrpt a clob as it is inserted into the DB. Ideally I'd like to be able to just insert the plaintext and have it encrypted by a stored procedure:</p>
<pre><code>String SQL = "INSERT INTO table (ID, VALUE) values (?, encrypt(?))";
PreparedStatement ps = connection.prepareStatement(SQL);
ps.setInt(id);
ps.setString(plaintext);
ps.executeUpdate();
</code></pre>
<p>The plaintext is not expected to exceed 4000 characters but encrypting makes text longer. Our current approach to encryption uses dbms_obfuscation_toolkit.DESEncrypt() but we only process varchars. Will the following work?</p>
<pre><code>FUNCTION encrypt(p_clob IN CLOB) RETURN CLOB
IS
encrypted_string CLOB;
v_string CLOB;
BEGIN
dbms_lob.createtemporary(encrypted_string, TRUE);
v_string := p_clob;
dbms_obfuscation_toolkit.DESEncrypt(
input_string => v_string,
key_string => key_string,
encrypted_string => encrypted_string );
RETURN UTL_RAW.CAST_TO_RAW(encrypted_string);
END;
</code></pre>
<p>I'm confused about the temporary clob; do I need to close it? Or am I totally off-track?</p>
<p>Edit:
The purpose of the obfuscation is to prevent trivial access to the data. My other purpose is to obfuscate clobs in the same way that we are already obfuscating the varchar columns. The oracle sample code does not deal with clobs which is where my specific problem lies; encrypting varchars (smaller than 2000 chars) is straightforward.</p>
|
[
{
"answer_id": 97469,
"author": "borjab",
"author_id": 16206,
"author_profile": "https://Stackoverflow.com/users/16206",
"pm_score": 2,
"selected": false,
"text": "DECLARE\n input_string VARCHAR2(16) := 'tigertigertigert';\n raw_input RAW(128) := UTL_RAW.CAST_TO_RAW(input_string);\n key_string VARCHAR2(8) := 'scottsco';\n raw_key RAW(128) := UTL_RAW.CAST_TO_RAW(key_string);\n encrypted_raw RAW(2048);\n encrypted_string VARCHAR2(2048);\n decrypted_raw RAW(2048);\n decrypted_string VARCHAR2(2048); \n error_in_input_buffer_length EXCEPTION;\n PRAGMA EXCEPTION_INIT(error_in_input_buffer_length, -28232);\n INPUT_BUFFER_LENGTH_ERR_MSG VARCHAR2(100) :=\n '*** DES INPUT BUFFER NOT A MULTIPLE OF 8 BYTES - IGNORING \nEXCEPTION ***';\n double_encrypt_not_permitted EXCEPTION;\n PRAGMA EXCEPTION_INIT(double_encrypt_not_permitted, -28233);\n DOUBLE_ENCRYPTION_ERR_MSG VARCHAR2(100) :=\n '*** CANNOT DOUBLE ENCRYPT DATA - IGNORING EXCEPTION ***';\n\n -- 1. Begin testing raw data encryption and decryption\n BEGIN\n dbms_output.put_line('> ========= BEGIN TEST RAW DATA =========');\n dbms_output.put_line('> Raw input : ' || \n UTL_RAW.CAST_TO_VARCHAR2(raw_input));\n BEGIN \n dbms_obfuscation_toolkit.DESEncrypt(input => raw_input, \n key => raw_key, encrypted_data => encrypted_raw );\n dbms_output.put_line('> encrypted hex value : ' || \n rawtohex(encrypted_raw));\n dbms_obfuscation_toolkit.DESDecrypt(input => encrypted_raw, \n key => raw_key, decrypted_data => decrypted_raw);\n dbms_output.put_line('> Decrypted raw output : ' || \n UTL_RAW.CAST_TO_VARCHAR2(decrypted_raw));\n dbms_output.put_line('> '); \n if UTL_RAW.CAST_TO_VARCHAR2(raw_input) = \n UTL_RAW.CAST_TO_VARCHAR2(decrypted_raw) THEN\n dbms_output.put_line('> Raw DES Encyption and Decryption successful');\n END if;\n EXCEPTION\n WHEN error_in_input_buffer_length THEN\n dbms_output.put_line('> ' || INPUT_BUFFER_LENGTH_ERR_MSG);\n END;\n dbms_output.put_line('> ');\n"
},
{
"answer_id": 113291,
"author": "tardate",
"author_id": 6329,
"author_profile": "https://Stackoverflow.com/users/6329",
"pm_score": 1,
"selected": true,
"text": "DBMS_CRYPTO.ENCRYPT(\n dst IN OUT NOCOPY BLOB,\n src IN CLOB CHARACTER SET ANY_CS,\n typ IN PLS_INTEGER,\n key IN RAW,\n iv IN RAW DEFAULT NULL);\n\nDBMS_CRYPT.DECRYPT(\n dst IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,\n src IN BLOB,\n typ IN PLS_INTEGER,\n key IN RAW,\n iv IN RAW DEFAULT NULL);\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7867/"
] |
96,952
|
<p>What mysql functions are there (if any) to trim leading zeros from an alphanumeric text field? </p>
<p>Field with value "00345ABC" would need to return "345ABC".</p>
|
[
{
"answer_id": 96971,
"author": "Chris Bartow",
"author_id": 497,
"author_profile": "https://Stackoverflow.com/users/497",
"pm_score": 8,
"selected": true,
"text": "SELECT TRIM(LEADING '0' FROM myfield) FROM table\n"
},
{
"answer_id": 96992,
"author": "JustinD",
"author_id": 12063,
"author_profile": "https://Stackoverflow.com/users/12063",
"pm_score": 3,
"selected": false,
"text": "SELECT TRIM(LEADING '0' FROM myField)\n"
},
{
"answer_id": 1247202,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "SELECT TRIM(LEADING '0' FROM myfield) FROM table\n"
},
{
"answer_id": 10829460,
"author": "Hemali",
"author_id": 1427809,
"author_profile": "https://Stackoverflow.com/users/1427809",
"pm_score": 2,
"selected": false,
"text": "TRIM ( LEADING SELECT * FROM my_table WHERE TRIM(LEADING '0' FROM accountid ) = '00322994' \n"
},
{
"answer_id": 14157004,
"author": "lubosdz",
"author_id": 1485984,
"author_profile": "https://Stackoverflow.com/users/1485984",
"pm_score": 4,
"selected": false,
"text": "SELECT * FROM my_table WHERE accountid = '00322994' * 1\n SELECT * FROM my_table WHERE accountid = 322994\n"
},
{
"answer_id": 35144965,
"author": "theBuzzyCoder",
"author_id": 2147023,
"author_profile": "https://Stackoverflow.com/users/2147023",
"pm_score": 4,
"selected": false,
"text": "USE database_name;\nUPDATE `table_name` SET `field` = TRIM(LEADING '0' FROM `field`) WHERE `field` LIKE '0%';\n"
},
{
"answer_id": 40980354,
"author": "cacti5",
"author_id": 5839007,
"author_profile": "https://Stackoverflow.com/users/5839007",
"pm_score": 2,
"selected": false,
"text": "select trim(myfield) from (select ' test' myfield) t;\n>> 'test'\nselect trim('0' from myfield) from (select '000000123000' myfield) t;\n>> '123'\nselect trim(both '0' from myfield) from (select '000000123000' myfield) t;\n>> '123'\nselect trim(leading '0' from myfield) from (select '000000123000' myfield) t;\n>> '123000'\nselect trim(trailing '0' from myfield) from (select '000000123000' myfield) t;\n>> '000000123'\n"
},
{
"answer_id": 49064319,
"author": "sanduniYW",
"author_id": 9373268,
"author_profile": "https://Stackoverflow.com/users/9373268",
"pm_score": 3,
"selected": false,
"text": "SELECT TRIM(LEADING '0' FROM *columnName*) FROM *tableName* ;\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/96952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5446/"
] |
97,013
|
<p>Does anyone know is there a way to open a project in Eclipse in read-only mode? If there is a lot of similar projects open it is easy to make changes to a wrong one.</p>
|
[
{
"answer_id": 2304667,
"author": "s3m3n",
"author_id": 277937,
"author_profile": "https://Stackoverflow.com/users/277937",
"pm_score": 3,
"selected": false,
"text": "sudo chmod 444 -R /path/to/your/project\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20128/"
] |
97,050
|
<p>Assuming a map where you want to preserve existing entries. 20% of the time, the entry you are inserting is new data. Is there an advantage to doing std::map::find then std::map::insert using that returned iterator? Or is it quicker to attempt the insert and then act based on whether or not the iterator indicates the record was or was not inserted?</p>
|
[
{
"answer_id": 101129,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 4,
"selected": false,
"text": "typedef std::map <int, int> MapOfInts;\ntypedef std::pair <MapOfInts::iterator, bool> IResult;\n\nvoid foo (MapOfInts & m, int k, int v) {\n IResult ir = m.insert (std::make_pair (k, v));\n if (ir.second) {\n // insertion took place (ie. new entry)\n }\n else if ( replaceEntry ( ir.first->first ) ) {\n ir.first->second = v;\n }\n}\n class LargeDataType { /* ... */ };\ntypedef std::map <int, LargeDataType> MapOfLargeDataType;\ntypedef std::pair <MapOfLargeDataType::iterator, bool> IResult;\n\nvoid foo (MapOfLargeDataType & m, int k) {\n\n // This call is more expensive than a find through the map:\n LargeDataType const & v = VeryExpensiveCall ( /* ... */ );\n\n IResult ir = m.insert (std::make_pair (k, v));\n if (ir.second) {\n // insertion took place (ie. new entry)\n }\n else if ( replaceEntry ( ir.first->first ) ) {\n ir.first->second = v;\n }\n}\n"
},
{
"answer_id": 101980,
"author": "luke",
"author_id": 16434,
"author_profile": "https://Stackoverflow.com/users/16434",
"pm_score": 8,
"selected": true,
"text": "typedef map<int, int> MapType; // Your map type may vary, just change the typedef\n\nMapType mymap;\n// Add elements to map here\nint k = 4; // assume we're searching for keys equal to 4\nint v = 0; // assume we want the value 0 associated with the key of 4\n\nMapType::iterator lb = mymap.lower_bound(k);\n\nif(lb != mymap.end() && !(mymap.key_comp()(k, lb->first)))\n{\n // key already exists\n // update lb->second if you care to\n}\nelse\n{\n // the key does not exist in the map\n // add it to the map\n mymap.insert(lb, MapType::value_type(k, v)); // Use lb as a hint to insert,\n // so it can avoid another lookup\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16496/"
] |
97,063
|
<p>Business Objects Web Services returns error codes and I have yet to find a good resource where these are listed and what they mean. I am currently getting an "The resultset was empty. (Error: WBP 42019)". Any ideas on where these might be listed? I've called Business Objects support and the tech couldn't even tell me. Anyone?</p>
|
[
{
"answer_id": 66471990,
"author": "IncreMan",
"author_id": 2681411,
"author_profile": "https://Stackoverflow.com/users/2681411",
"pm_score": 0,
"selected": false,
"text": "#ifndef __SBOERR_H_\n#define __SBOERR_H_\n\ntypedef long SBOErr;\n\n#define dbdError -1\n#define noErr 0\n#define errNoMsg -10\n#define coreEndOfFile -39\n#define coreFileNotFound -43\n#define coreFileBusy -47\n#define coreFileNotOpened -50\n#define coreFileCorrupted -51\n#define coreDivisionByZero -99\n#define coreOutOfMemory -100\n#define corePrinterError -101\n#define corePrintCanceled -103\n#define coreMoneyOverflow -104\n#define coreInvalidPointer -111\n#define coreError -199\n#define coreBadDirectory -213\n#define coreFileExists -214\n#define coreInvalidFilePermission -216\n#define coreInvalidPath -217\n#define coreBadPassword -218\n#define coreBadUser -219\n#define coreUpgradePerformed -221\n#define coreNoCurrPeriodErr -222\n#define coreLanguageInitErr -8020\n\n/* DBM Errors */\n#define dbmFirstError -1000\n#define dbmBadColumnType -1001\n#define dbmNotSupported -1002\n#define dbmAliasNotFound -1003\n#define dbmValueNotFound -1004\n#define dbmBadDate -1005\n#define dbmNoDefaultColumn -1012\n#define dbmZeroOrBlankValue -1013\n#define dbmIntegerTooLarge -1015\n#define dbmBadValue -1016\n#define dbmOtherFileNotRelated -1022\n#define dbmOtherKeyNotInMainKey -1023\n#define dbmArrayRecordNotFound -1025\n#define dbmMustBePositive -1027\n#define dbmMustBeNegative -1028\n#define dbmColumnNotUpdatable -1029\n#define dbmBadNumValue -1030\n#define dbmBadTimeValue -1031\n#define dbmBadMoneyValue -1032\n#define dbmNotUserDataSource -1033\n\n#define dbmCannotAllocEnv -1100\n#define dbmBadConnection -1101\n#define dbmConnectionNotOpen -1102\n#define dbmDatabaseExists -1103\n#define dbmCannotCreateDatabase -1104\n\n#define dbmInternalError -1200\n\n#define dbmBadParameters -2001\n#define dbmTooManyTables -2003\n#define dbmTableNotFound -2004\n#define dbmBadDefinition -2006\n#define dbmBadDAG -2007\n#define dbmBadRecordOffset -2010\n#define dbmNoColumns -2013\n#define dbmBadColumnIndex -2014\n#define dbmBadIndexNumber -2015\n#define dbmBadAlias -2017\n#define dbmAliasAlreadyExists -2018\n#define dbmBadColumnSize -2020\n#define dbmBadColumLevel -2022\n#define dbmDAGsNoMatch -2024\n#define dbmNoKeys -2025\n#define dbmPartialDataFound -2027\n#define dbmNoDataFound -2028\n#define dbmColumnsNoMatch -2029\n#define dbmDuplicateKey -2035\n#define dbmRecordLocked -2038\n#define dbmDataWasChanged -2039\n#define dbmEndOfSort -2045\n#define dbmNotOpenForWrite -2049\n#define dbmNoMatchWithDAG -2056\n#define dbmBadContainerOffset -2062\n#define dbmLoadExtLibFailed -2100\n#define dbmRowSizeTooLong -2110 // the size of the table row is over the Sql limit 8K\n#define dbmLastError -2999\n\n//db2 specific errors\n#define dbmdb2AttachFailed -2101\n#define dbmdb2CreateDBFailed -2102\n#define dbmdb2DeAttachFailed -2103\n#define dbmdb2BackupFailed -2104\n\n//sybase specific errors\n#define dbmSybaseDeviceCreationFailed -2200\n\n// QRY errors\n#define qryNotDefined -1\n#define qryFirstError -3000\n#define qryColumnNotFound -3001\n#define qryBadVarNum -3003\n#define qryWrongToken -3004\n#define qryTokenAfterEnd -3005\n#define qryUnexpectedEnd -3006\n#define qryQueryTooLong -3008\n#define qryExtraRightPar -3009\n#define qryNoRightPar -3010\n#define qryNoOpcode -3012\n#define qryNoColInComp -3013\n#define qryBadCondition -3014\n#define qryBadSortList -3015\n#define qryNoString -3017\n#define qryTooManyColumns -3018\n#define qryTooManyIndices -3019\n#define qryTooManyTables -3020\n#define qryRefNotFound -3021\n#define qryBadRangeSet -3022\n#define qryBadParse -3023\n#define qryTwoArraysInQuery -3024\n#define qryVarMissing -3025\n#define qryBadInput -3026\n#define qryProgressAborted -3027\n#define qryBadTableIndex -3028\n#define qryBadQuery -3032\n#define qryEmptyRecord -3033\n#define qryNoImpYet -3034\n#define qryBadParameter -3036\n#define qryMissingTableInList -3037\n#define qryBadOperation -3040\n#define qryBadExpression -3041\n#define qryNameAlreadyExists -3042\n#define qryTimeExpired -3044\n#define qryBadCallbackNum -3045\n#define qryNoCallback -3046\n#define qryLastError -3046\n\n//FORM errors\n#define formNoWindow 3001\n#define formBadVarNum 3002\n#define formTooManyVars 3003\n#define formDuplicateUID 3004\n#define formInvalidItem 3006\n#define formTooManyForms 3007\n#define formTooManySavedPtrs 3009\n#define formInvalidForm 3012\n#define formCantGetMultilineEdit 3015\n#define formBadItemType 3016\n#define formBadParameters 3017\n#define formNoMessageProc 3023\n#define formItemNotSelectable 3029\n#define formBadValue 3031\n#define formItemNotFound 3033\n#define formAXCreateFailed 3034\n#define formNotUserItem 3035\n#define formItemNotEditable 3036\n#define formItemFocusFailedNotVisible 3037\n#define formItemFocusFailedNotEditable 3038\n#define fromCloseAllFormsFailed 3039\n\n// GRID errors\n#define gridInvalidGrid 4007\n#define gridBadSize 4008\n#define gridNoData 4009\n#define gridInvalidParams 4011\n#define gridNoSuperTitle 4013\n#define gridSuperTitle2Exits 4014\n#define gridBadItemNum 4015\n#define gridBadData 4016\n#define gridAlreadyFolded 4017\n#define gridAlreadyExpanded 4018\n#define gridLineExists 4019\n#define gridNotEnoughData 4020\n#define gridSuperTitlesExists 4022\n#define gridRowNotCollapssible 4027\n#define gridRowHasNoCollapseLevel 4028\n#define gridInvalidRow 4029\n#define gridItemSelectNotSupported 4030\n#define gridInvalidColNum 4031\n#define gridFocusFailedNotEditable 4032\n#define gridFocusFailedNotVisible 4033\n#define gridColumnFocusFailedNotEditable 4034\n\n// SBAR\n#define sbarNoSuchInfo 8004\n#define sbarInfoOcccupied 8005\n#define sbarProgressStopped 8007\n#define sbarTooManyProgresses 8008\n#define sbarNoMessageBar 8006\n\n// GRAPH\n#define graphInvalidGraph 5001\n#define graphBadItemNum 5002\n#define graphBadParameters 5005\n\n// IBAR\n#define ibarError 9000\n\n// SCRIPT\n#define scFirstError -9000\n#define scInvalidType -9000\n#define scLineTooLarge -9002\n#define scInvalidTokType -9003\n#define scInvalidLine -9004\n#define scInvalidFormType -9005\n#define scInvalidOperator -9006\n#define scInvalidScriptCall -9007\n#define scItemNotValid -9008\n#define scNotGird -9009\n#define scUndefinedVar -9010\n#define scRedefinedVar -9011\n#define scNotVarOperation -9012\n#define scIncompatVarType -9013\n#define scStringTooLong -9014\n#define scDivByZero -9015\n#define scFileNotChoosen -9016\n#define scFileNotOpen -9017\n#define scSomeDataRead -9018\n#define scIfNotClosed -9020\n#define scLoopNotClosed -9021\n#define scNotCompareThisType -9022\n#define scLastError -9022\n\n// Reports\n#define rptFirstError -6100\n#define rptNotValid -6100\n#define rptDuplicateItem -6101\n#define rptBadParameters -6200\n#define rptColNotFound -6250\n#define rptBadVarNum -6300\n#define rptVarNotSet -6305\n#define rptBadStandardIndex -6350\n#define rptBadItemNum -6370\n#define rptBadItemType -6373\n#define rptItemFromAnotherPart -6380\n#define rptPassedPageLimit -6390\n#define rptProgressAborted -6400\n#define rptTooManyPages -6450\n#define rptNotPageFooter -6500\n#define rptNoQuery -6550\n#define rptNotPicture -6600\n#define rptPrintCanceledByUser -6650\n#define rptMarginTooLarge -6651\n#define rptLoadExtLibFailed -6652\n#define rptLoadExtProcFailed -6653\n#define rptReportTooLongForExport -6700\n#define rptInvalidFieldIDFormat -6710\n#define rptFieldIDAlreadyExist -6711\n#define rptRecursiveDependency -6712\n#define rptFormulaGrammarError -6713\n#define rptSumItemCanOnlyBeInRepArea -6714\n#define rptNoSums -6715\n#define rptDataTypeNoSuchMethod -6716\n#define rptFieldDoesnotExist -6717\n#define rptFieldNotEvaluatedYet -6718\n#define rptInvalidParameter -6719\n#define rptMethodNotSupported -6720\n#define rptTotalPageLiveAlone -6721\n#define rptRecursiveRelation -6722\n#define rptLastError -6799\n\n// Prog\n#define progBadProgress 9001\n#define progProgressIsModal 9002\n#define progProgressStopped 9003\n#define progBadParams 9004\n#define progOnlyOneDim 9005\n#define progModalProgressAlreadyOn 9006\n\n\n//Menus\n#define menuNotOwnerDrawn -11001\n#define menuNotSupportedImageType -11002\n#define menuCannotLoadImageFile -11003\n\n//UI errors\n#define uiDuplicateUniqueID -7502\n#define uiInvalidObject -7503\n#define uiFunctionNotSupported -7002\n#define uiCannotSetFocusOnItem -7653\n#define uiSecuritySetFocusFailed -7654\n#define uiFailedLoadXml -7040\n#define uiInvalidFieldValue -7018\n\n#define dataTableSourceDTEqualToTargetDT -7751\n#define dataTableDuplicateColumnUID -7752 //4500\n#define dataTableInvalidColumnIndex -7753 //4501\n#define dataTableInvalidColumnUid -7754 //4502\n#define dataTableInvalidDAG -7755 //4503\n#define dataTableDuplicateUid -7756 //4504\n#define dataTableInvalidUid -7757 //4505\n#define dataTableInvalidIndex -7758 //4506\n#define dataTableInvalidVaribleNumber -7759 //4507\n#define dataTableInvalidRowIndex -7760 //4508\n#define dataTableInvalidAlias -7761 //4509\n#define dataTableLineExists -7762 //4510\n#define dataTableInvalidItemType -7763 //4511\n#define dataTableNotWritable -7764 //4512\n#define dataTableAlreadyConnectedToGrid -7765 //4513\n#define dataTableAlreadyConnectedToFormItem -7766 //4514\n#define dataTableColumnDataExceedsSize -7767 //4515\n#define dataTableInvalidValueType -7768\n\n#endif\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17891/"
] |
97,081
|
<p>Someone told me about a C++ style difference in their team. I have my own viewpoint on the subject, but I would be interested by <em>pros</em> and <em>cons</em> coming from everyone.</p>
<p>So, in case you have a class property you want to expose via two getters, one read/write, and the other, readonly (i.e. there is no set method). There are at least two ways of doing it:</p>
<pre><code>class T ;
class MethodA
{
public :
const T & get() const ;
T & get() ;
// etc.
} ;
class MethodB
{
public :
const T & getAsConst() const ;
T & get() ;
// etc.
} ;
</code></pre>
<p>What would be the pros and the cons of each method?</p>
<p>I am interested more by C++ technical/semantic reasons, but style reasons are welcome, too.</p>
<p>Note that <code>MethodB</code> has one major technical drawback (hint: in generic code).</p>
|
[
{
"answer_id": 97170,
"author": "jdmichal",
"author_id": 12275,
"author_profile": "https://Stackoverflow.com/users/12275",
"pm_score": 0,
"selected": false,
"text": "const"
},
{
"answer_id": 103534,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 0,
"selected": false,
"text": "template <typename T>\nT & getMax(T & p_oLeft, T & p_oRight)\n{\n if(p_oLeft.get() > p_oRight.get())\n {\n return p_oLeft ;\n }\n else\n {\n return p_oRight ;\n }\n}\n // Ok\nconst MethodA oA_C0(), oA_C1() ;\nconst MethodA & oA_CResult = getMax(oA_C0, oA_C1) ;\n\n// Ok again\nMethodA oA_0(), oA_1() ;\nMethodA & oA_Result = getMax(oA_0, oA_1) ;\n // NOT Ok\nconst MethodB oB_C0(), oB_C1() ;\nconst MethodB & oB_CResult = getMax(oB_C0, oB_C1) ; // Won't compile\n\n// Ok\nMethodA oB_0(), oB_1() ;\nMethodA & oB_Result = getMax(oB_0, oB_1) ;\n template <typename T>\nconst T & getMax(const T & p_oLeft, const T & p_oRight)\n{\n if(p_oLeft.getAsConst() > p_oRight.getAsConst())\n {\n return p_oLeft ;\n }\n else\n {\n return p_oRight ;\n }\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14089/"
] |
97,092
|
<p>What I am trying to achieve is a form that has a button on it that causes the Form to 'drop-down' and become larger, displaying more information. My current attempt is this:</p>
<pre><code>private void btnExpand_Click(object sender, EventArgs e)
{
if (btnExpand.Text == ">")
{
btnExpand.Text = "<";
_expanded = true;
this.MinimumSize = new Size(1, 300);
this.MaximumSize = new Size(int.MaxValue, 300);
}
else
{
btnExpand.Text = ">";
_expanded = false;
this.MinimumSize = new Size(1, 104);
this.MaximumSize = new Size(int.MaxValue, 104);
}
}
</code></pre>
<p>Which works great! Except for one small detail... Note that the width values are supposed to be able to go from 1 to int.MaxValue? Well, in practice, they go from this.Width to int.MaxValue, ie. you can make the form larger, but never smaller again. I'm at a loss for why this would occur. Anyone have any ideas?</p>
<p>For the record: I've also tried a Form.Resize handler that set the Height of the form to the same value depending on whatever the boolean _expanded was set to, but I ended up with the same side effect.</p>
<p>PS: I'm using .NET 3.5 in Visual Studio 2008. Other solutions are welcome, but this was my thoughts on how it "should" be done and how I attempted to do it.</p>
<p>Edit: Seems the code works, as per the accepted answers response. If anyone else has troubles with this particular problem, check the AutoSize property of your form, it should be FALSE, not TRUE. (This is the default, but I'd switched it on as I was using the form and a label with autosize also on for displaying debugging info earlier)</p>
|
[
{
"answer_id": 97870,
"author": "Tim Jarvis",
"author_id": 10387,
"author_profile": "https://Stackoverflow.com/users/10387",
"pm_score": 0,
"selected": false,
"text": "MinimumSize MaximumSize"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
] |
97,097
|
<p>What is the C# version of VB.net's InputBox?</p>
|
[
{
"answer_id": 97156,
"author": "Ozgur Ozcitak",
"author_id": 976,
"author_profile": "https://Stackoverflow.com/users/976",
"pm_score": 9,
"selected": true,
"text": "Microsoft.VisualBasic InputBox Microsoft.VisualBasic.Interaction using Microsoft.VisualBasic;\nstring input = Interaction.InputBox(\"Prompt\", \"Title\", \"Default\", x_coordinate, y_coordinate);\n prompt"
},
{
"answer_id": 97190,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 2,
"selected": false,
"text": "Microsoft.VisualBasic string response = Microsoft.VisualBasic.Interaction.InputBox(\"What's 1+1?\", \"Title\", \"2\", 0, 0);\n"
},
{
"answer_id": 97467,
"author": "Tomas Sedovic",
"author_id": 2239,
"author_profile": "https://Stackoverflow.com/users/2239",
"pm_score": 7,
"selected": false,
"text": "string input = Microsoft.VisualBasic.Interaction.InputBox(\"Prompt\", \"Title\", \"Default\", 0, 0);\n"
},
{
"answer_id": 15013055,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 3,
"selected": false,
"text": " public static String InputBox(String caption, String prompt, String defaultText)\n {\n String localInputText = defaultText;\n if (InputQuery(caption, prompt, ref localInputText))\n {\n return localInputText;\n }\n else\n {\n return \"\";\n }\n }\n String true false public static Boolean InputQuery(String caption, String prompt, ref String value)\n {\n Form form;\n form = new Form();\n form.AutoScaleMode = AutoScaleMode.Font;\n form.Font = SystemFonts.IconTitleFont;\n\n SizeF dialogUnits;\n dialogUnits = form.AutoScaleDimensions;\n\n form.FormBorderStyle = FormBorderStyle.FixedDialog;\n form.MinimizeBox = false;\n form.MaximizeBox = false;\n form.Text = caption;\n\n form.ClientSize = new Size(\n Toolkit.MulDiv(180, dialogUnits.Width, 4),\n Toolkit.MulDiv(63, dialogUnits.Height, 8));\n\n form.StartPosition = FormStartPosition.CenterScreen;\n\n System.Windows.Forms.Label lblPrompt;\n lblPrompt = new System.Windows.Forms.Label();\n lblPrompt.Parent = form;\n lblPrompt.AutoSize = true;\n lblPrompt.Left = Toolkit.MulDiv(8, dialogUnits.Width, 4);\n lblPrompt.Top = Toolkit.MulDiv(8, dialogUnits.Height, 8);\n lblPrompt.Text = prompt;\n\n System.Windows.Forms.TextBox edInput;\n edInput = new System.Windows.Forms.TextBox();\n edInput.Parent = form;\n edInput.Left = lblPrompt.Left;\n edInput.Top = Toolkit.MulDiv(19, dialogUnits.Height, 8);\n edInput.Width = Toolkit.MulDiv(164, dialogUnits.Width, 4);\n edInput.Text = value;\n edInput.SelectAll();\n\n\n int buttonTop = Toolkit.MulDiv(41, dialogUnits.Height, 8);\n //Command buttons should be 50x14 dlus\n Size buttonSize = Toolkit.ScaleSize(new Size(50, 14), dialogUnits.Width / 4, dialogUnits.Height / 8);\n\n System.Windows.Forms.Button bbOk = new System.Windows.Forms.Button();\n bbOk.Parent = form;\n bbOk.Text = \"OK\";\n bbOk.DialogResult = DialogResult.OK;\n form.AcceptButton = bbOk;\n bbOk.Location = new Point(Toolkit.MulDiv(38, dialogUnits.Width, 4), buttonTop);\n bbOk.Size = buttonSize;\n\n System.Windows.Forms.Button bbCancel = new System.Windows.Forms.Button();\n bbCancel.Parent = form;\n bbCancel.Text = \"Cancel\";\n bbCancel.DialogResult = DialogResult.Cancel;\n form.CancelButton = bbCancel;\n bbCancel.Location = new Point(Toolkit.MulDiv(92, dialogUnits.Width, 4), buttonTop);\n bbCancel.Size = buttonSize;\n\n if (form.ShowDialog() == DialogResult.OK)\n {\n value = edInput.Text;\n return true;\n }\n else\n {\n return false;\n }\n }\n\n /// <summary>\n /// Multiplies two 32-bit values and then divides the 64-bit result by a \n /// third 32-bit value. The final result is rounded to the nearest integer.\n /// </summary>\n public static int MulDiv(int nNumber, int nNumerator, int nDenominator)\n {\n return (int)Math.Round((float)nNumber * nNumerator / nDenominator);\n }\n"
},
{
"answer_id": 17546909,
"author": "Gorkem",
"author_id": 2138992,
"author_profile": "https://Stackoverflow.com/users/2138992",
"pm_score": 7,
"selected": false,
"text": "private static DialogResult ShowInputDialog(ref string input)\n {\n System.Drawing.Size size = new System.Drawing.Size(200, 70);\n Form inputBox = new Form();\n\n inputBox.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;\n inputBox.ClientSize = size;\n inputBox.Text = \"Name\";\n\n System.Windows.Forms.TextBox textBox = new TextBox();\n textBox.Size = new System.Drawing.Size(size.Width - 10, 23);\n textBox.Location = new System.Drawing.Point(5, 5);\n textBox.Text = input;\n inputBox.Controls.Add(textBox);\n\n Button okButton = new Button();\n okButton.DialogResult = System.Windows.Forms.DialogResult.OK;\n okButton.Name = \"okButton\";\n okButton.Size = new System.Drawing.Size(75, 23);\n okButton.Text = \"&OK\";\n okButton.Location = new System.Drawing.Point(size.Width - 80 - 80, 39);\n inputBox.Controls.Add(okButton);\n\n Button cancelButton = new Button();\n cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;\n cancelButton.Name = \"cancelButton\";\n cancelButton.Size = new System.Drawing.Size(75, 23);\n cancelButton.Text = \"&Cancel\";\n cancelButton.Location = new System.Drawing.Point(size.Width - 80, 39);\n inputBox.Controls.Add(cancelButton);\n\n inputBox.AcceptButton = okButton;\n inputBox.CancelButton = cancelButton; \n\n DialogResult result = inputBox.ShowDialog();\n input = textBox.Text;\n return result;\n }\n string input=\"hede\";\nShowInputDialog(ref input);\n"
},
{
"answer_id": 25912587,
"author": "Stefan Steiger",
"author_id": 155077,
"author_profile": "https://Stackoverflow.com/users/155077",
"pm_score": 2,
"selected": false,
"text": "// \"dynamic\" requires reference to Microsoft.CSharp\nType tScriptControl = Type.GetTypeFromProgID(\"ScriptControl\");\ndynamic oSC = Activator.CreateInstance(tScriptControl);\n\noSC.Language = \"VBScript\";\nstring sFunc = @\"Function InBox(prompt, title, default) \nInBox = InputBox(prompt, title, default) \nEnd Function\n\";\noSC.AddCode(sFunc);\ndynamic Ret = oSC.Run(\"InBox\", \"メッセージ\", \"タイトル\", \"初期値\");\n string sFunc = @\"Function InBox(prompt, title, default) \nInBox = InputBox(prompt, title, default) \nEnd Function\n\";\n\nType tScriptControl = Type.GetTypeFromProgID(\"ScriptControl\");\nobject oSC = Activator.CreateInstance(tScriptControl);\n\n// https://github.com/mono/mono/blob/master/mcs/class/corlib/System/MonoType.cs\n// System.Reflection.PropertyInfo pi = tScriptControl.GetProperty(\"Language\", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.CreateInstance| System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.IgnoreCase);\n// pi.SetValue(oSC, \"VBScript\", null);\n\ntScriptControl.InvokeMember(\"Language\", System.Reflection.BindingFlags.SetProperty, null, oSC, new object[] { \"VBScript\" });\ntScriptControl.InvokeMember(\"AddCode\", System.Reflection.BindingFlags.InvokeMethod, null, oSC, new object[] { sFunc });\nobject ret = tScriptControl.InvokeMember(\"Run\", System.Reflection.BindingFlags.InvokeMethod, null, oSC, new object[] { \"InBox\", \"メッセージ\", \"タイトル\", \"初期値\" });\nConsole.WriteLine(ret);\n"
},
{
"answer_id": 32616012,
"author": "David Carrigan",
"author_id": 2305236,
"author_profile": "https://Stackoverflow.com/users/2305236",
"pm_score": 2,
"selected": false,
"text": "public partial class InputBox \n : Form\n{\n\n public String Input\n {\n get { return textInput.Text; }\n }\n\n public InputBox()\n {\n InitializeComponent();\n }\n\n private void button2_Click(object sender, EventArgs e)\n {\n DialogResult = System.Windows.Forms.DialogResult.OK;\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n DialogResult = System.Windows.Forms.DialogResult.Cancel;\n }\n\n private void InputBox_Load(object sender, EventArgs e)\n {\n this.ActiveControl = textInput;\n }\n\n public static DialogResult Show(String title, String message, String inputTitle, out String inputValue)\n {\n InputBox inputBox = null;\n DialogResult results = DialogResult.None;\n\n using (inputBox = new InputBox() { Text = title })\n {\n inputBox.labelMessage.Text = message;\n inputBox.splitContainer2.SplitterDistance = inputBox.labelMessage.Width;\n inputBox.labelInput.Text = inputTitle;\n inputBox.splitContainer1.SplitterDistance = inputBox.labelInput.Width;\n inputBox.Size = new Size(\n inputBox.Width,\n 8 + inputBox.labelMessage.Height + inputBox.splitContainer2.SplitterWidth + inputBox.splitContainer1.Height + 8 + inputBox.button2.Height + 12 + (50));\n results = inputBox.ShowDialog();\n inputValue = inputBox.Input;\n }\n\n return results;\n }\n\n void labelInput_TextChanged(object sender, System.EventArgs e)\n {\n }\n\n}\n\npartial class InputBox\n{\n /// <summary>\n /// Required designer variable.\n /// </summary>\n private System.ComponentModel.IContainer components = null;\n\n /// <summary>\n /// Clean up any resources being used.\n /// </summary>\n /// <param name=\"disposing\">true if managed resources should be disposed; otherwise, false.</param>\n protected override void Dispose(bool disposing)\n {\n if (disposing && (components != null))\n {\n components.Dispose();\n }\n base.Dispose(disposing);\n }\n\n #region Windows Form Designer generated code\n\n /// <summary>\n /// Required method for Designer support - do not modify\n /// the contents of this method with the code editor.\n /// </summary>\n private void InitializeComponent()\n {\n this.labelMessage = new System.Windows.Forms.Label();\n this.button1 = new System.Windows.Forms.Button();\n this.button2 = new System.Windows.Forms.Button();\n this.labelInput = new System.Windows.Forms.Label();\n this.textInput = new System.Windows.Forms.TextBox();\n this.splitContainer1 = new System.Windows.Forms.SplitContainer();\n this.splitContainer2 = new System.Windows.Forms.SplitContainer();\n ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();\n this.splitContainer1.Panel1.SuspendLayout();\n this.splitContainer1.Panel2.SuspendLayout();\n this.splitContainer1.SuspendLayout();\n ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit();\n this.splitContainer2.Panel1.SuspendLayout();\n this.splitContainer2.Panel2.SuspendLayout();\n this.splitContainer2.SuspendLayout();\n this.SuspendLayout();\n // \n // labelMessage\n // \n this.labelMessage.AutoSize = true;\n this.labelMessage.Location = new System.Drawing.Point(3, 0);\n this.labelMessage.MaximumSize = new System.Drawing.Size(379, 0);\n this.labelMessage.Name = \"labelMessage\";\n this.labelMessage.Size = new System.Drawing.Size(50, 13);\n this.labelMessage.TabIndex = 99;\n this.labelMessage.Text = \"Message\";\n // \n // button1\n // \n this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));\n this.button1.Location = new System.Drawing.Point(316, 126);\n this.button1.Name = \"button1\";\n this.button1.Size = new System.Drawing.Size(75, 23);\n this.button1.TabIndex = 3;\n this.button1.Text = \"Cancel\";\n this.button1.UseVisualStyleBackColor = true;\n this.button1.Click += new System.EventHandler(this.button1_Click);\n // \n // button2\n // \n this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));\n this.button2.Location = new System.Drawing.Point(235, 126);\n this.button2.Name = \"button2\";\n this.button2.Size = new System.Drawing.Size(75, 23);\n this.button2.TabIndex = 2;\n this.button2.Text = \"OK\";\n this.button2.UseVisualStyleBackColor = true;\n this.button2.Click += new System.EventHandler(this.button2_Click);\n // \n // labelInput\n // \n this.labelInput.AutoSize = true;\n this.labelInput.Location = new System.Drawing.Point(3, 6);\n this.labelInput.Name = \"labelInput\";\n this.labelInput.Size = new System.Drawing.Size(31, 13);\n this.labelInput.TabIndex = 99;\n this.labelInput.Text = \"Input\";\n this.labelInput.TextChanged += new System.EventHandler(this.labelInput_TextChanged);\n // \n // textInput\n // \n this.textInput.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) \n | System.Windows.Forms.AnchorStyles.Right)));\n this.textInput.Location = new System.Drawing.Point(3, 3);\n this.textInput.Name = \"textInput\";\n this.textInput.Size = new System.Drawing.Size(243, 20);\n this.textInput.TabIndex = 1;\n // \n // splitContainer1\n // \n this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;\n this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel2;\n this.splitContainer1.IsSplitterFixed = true;\n this.splitContainer1.Location = new System.Drawing.Point(0, 0);\n this.splitContainer1.Name = \"splitContainer1\";\n // \n // splitContainer1.Panel1\n // \n this.splitContainer1.Panel1.Controls.Add(this.labelInput);\n // \n // splitContainer1.Panel2\n // \n this.splitContainer1.Panel2.Controls.Add(this.textInput);\n this.splitContainer1.Size = new System.Drawing.Size(379, 50);\n this.splitContainer1.SplitterDistance = 126;\n this.splitContainer1.TabIndex = 99;\n // \n // splitContainer2\n // \n this.splitContainer2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) \n | System.Windows.Forms.AnchorStyles.Left) \n | System.Windows.Forms.AnchorStyles.Right)));\n this.splitContainer2.IsSplitterFixed = true;\n this.splitContainer2.Location = new System.Drawing.Point(12, 12);\n this.splitContainer2.Name = \"splitContainer2\";\n this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal;\n // \n // splitContainer2.Panel1\n // \n this.splitContainer2.Panel1.Controls.Add(this.labelMessage);\n // \n // splitContainer2.Panel2\n // \n this.splitContainer2.Panel2.Controls.Add(this.splitContainer1);\n this.splitContainer2.Size = new System.Drawing.Size(379, 108);\n this.splitContainer2.SplitterDistance = 54;\n this.splitContainer2.TabIndex = 99;\n // \n // InputBox\n // \n this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);\n this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;\n this.ClientSize = new System.Drawing.Size(403, 161);\n this.Controls.Add(this.splitContainer2);\n this.Controls.Add(this.button2);\n this.Controls.Add(this.button1);\n this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;\n this.MaximizeBox = false;\n this.MinimizeBox = false;\n this.Name = \"InputBox\";\n this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;\n this.Text = \"Title\";\n this.TopMost = true;\n this.Load += new System.EventHandler(this.InputBox_Load);\n this.splitContainer1.Panel1.ResumeLayout(false);\n this.splitContainer1.Panel1.PerformLayout();\n this.splitContainer1.Panel2.ResumeLayout(false);\n this.splitContainer1.Panel2.PerformLayout();\n ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();\n this.splitContainer1.ResumeLayout(false);\n this.splitContainer2.Panel1.ResumeLayout(false);\n this.splitContainer2.Panel1.PerformLayout();\n this.splitContainer2.Panel2.ResumeLayout(false);\n ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit();\n this.splitContainer2.ResumeLayout(false);\n this.ResumeLayout(false);\n\n }\n\n #endregion\n\n private System.Windows.Forms.Label labelMessage;\n private System.Windows.Forms.Button button1;\n private System.Windows.Forms.Button button2;\n private System.Windows.Forms.Label labelInput;\n private System.Windows.Forms.TextBox textInput;\n private System.Windows.Forms.SplitContainer splitContainer1;\n private System.Windows.Forms.SplitContainer splitContainer2;\n}\n String output = \"\";\n\nresult = System.Windows.Forms.DialogResult.None;\n\nresult = InputBox.Show(\n \"Input Required\",\n \"Please enter the value (if available) below.\",\n \"Value\",\n out output);\n\nif (result != System.Windows.Forms.DialogResult.OK)\n{\n return;\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
] |
97,113
|
<p>I have the following string:</p>
<pre><code>cn=abcd,cn=groups,dc=domain,dc=com
</code></pre>
<p>Can a regular expression be used here to extract the string after the first <code>cn=</code> and before the first <code>,</code>? In the example above the answer should be <code>abcd</code>. </p>
|
[
{
"answer_id": 97125,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "cn=([^,]*),"
},
{
"answer_id": 97129,
"author": "shelfoo",
"author_id": 3444,
"author_profile": "https://Stackoverflow.com/users/3444",
"pm_score": 3,
"selected": false,
"text": "/^cn=([^,]+),/"
},
{
"answer_id": 97131,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 5,
"selected": true,
"text": " /cn=([^,]+),/ \n $x =~ s/^cn=//\n$x =~ s/,.*$//\n sed -n -r '/cn=/s/^cn=([^,]+),.*$/\\1/p' < logfile > dumpfile \n"
},
{
"answer_id": 11585720,
"author": "renoirb",
"author_id": 852395,
"author_profile": "https://Stackoverflow.com/users/852395",
"pm_score": 0,
"selected": false,
"text": "CN=username,OU=UNITNAME,OU=Region,OU=Country,DC=subdomain,DC=domain,DC=com\n array (\n [CN] => array( username )\n [OU] => array( UNITNAME, Region, Country )\n [DC] => array ( subdomain, domain, com )\n)\n /**\n * Read a LDAP DN, and return what is needed\n *\n * Takes care of the character escape and unescape\n *\n * Using:\n * CN=username,OU=UNITNAME,OU=Region,OU=Country,DC=subdomain,DC=domain,DC=com\n *\n * Would normally return:\n * Array (\n * [count] => 9\n * [0] => CN=username\n * [1] => OU=UNITNAME\n * [2] => OU=Region\n * [5] => OU=Country\n * [6] => DC=subdomain\n * [7] => DC=domain\n * [8] => DC=com\n * )\n *\n * Returns instead a manageable array:\n * array (\n * [CN] => array( username )\n * [OU] => array( UNITNAME, Region, Country )\n * [DC] => array ( subdomain, domain, com )\n * )\n *\n *\n * @author gabriel at hrz dot uni-marburg dot de 05-Aug-2003 02:27 (part of the character replacement)\n * @author Renoir Boulanger\n * \n * @param string $dn The DN\n * @return array\n */\nfunction parseLdapDn($dn)\n{\n $parsr=ldap_explode_dn($dn, 0);\n //$parsr[] = 'EE=Sôme Krazï string';\n //$parsr[] = 'AndBogusOne';\n $out = array();\n foreach($parsr as $key=>$value){\n if(FALSE !== strstr($value, '=')){\n list($prefix,$data) = explode(\"=\",$value);\n $data=preg_replace(\"/\\\\\\([0-9A-Fa-f]{2})/e\", \"''.chr(hexdec('\\\\1')).''\", $data);\n if(isset($current_prefix) && $prefix == $current_prefix){\n $out[$prefix][] = $data;\n } else {\n $current_prefix = $prefix;\n $out[$prefix][] = $data;\n }\n }\n }\n return $out;\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17273/"
] |
97,114
|
<p>In a recent question on stubbing, many answers suggested C# interfaces or delegates for implementing stubs, but <a href="https://stackoverflow.com/questions/43711/whats-a-good-way-to-overwrite-datetimenow-during-testing#43718">one answer</a> suggested using conditional compilation, retaining static binding in the production code. This answer was modded -2 at the time of reading, so at least 2 people really thought this was a <em>wrong</em> answer. Perhaps misuse of DEBUG was the reason, or perhaps use of fixed value instead of more extensive validation. But I can't help wondering:</p>
<p>Is the use of conditional compilation an inappropriate technique for implementing unit test stubs? Sometimes? Always?</p>
<p>Thanks.</p>
<p><strong>Edit-add:</strong> I'd like to add an example as a though experiment:</p>
<pre><code>class Foo {
public Foo() { .. }
private DateTime Now {
get {
#if UNITTEST_Foo
return Stub_DateTime.Now;
#else
return DateTime.Now;
#endif
}
}
// .. rest of Foo members
}
</code></pre>
<p>comparing to</p>
<pre><code>interface IDateTimeStrategy {
DateTime Now { get; }
}
class ProductionDateTimeStrategy : IDateTimeStrategy {
public DateTime Now { get { return DateTime.Now; } }
}
class Foo {
public Foo() : Foo(new ProductionDateTimeStrategy()) {}
public Foo(IDateTimeStrategy s) { datetimeStrategy = s; .. }
private IDateTime_Strategy datetimeStrategy;
private DateTime Now { get { return datetimeStrategy.Now; } }
}
</code></pre>
<p>Which allows the outgoing dependency on "DateTime.Now" to be stubbed through a C# interface. However, we've now added a dynamic dispatch call where static would suffice, the object is larger even in the production version, and we've added a new failure path for Foo's constructor (allocation can fail). </p>
<p>Am I worrying about nothing here? Thanks for the feedback so far!</p>
|
[
{
"answer_id": 97248,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "if (globals.isTest)\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14153/"
] |
97,137
|
<p>I know I once know how to do this but... how do you run a script (bash is OK) on login in unix?</p>
|
[
{
"answer_id": 97146,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 1,
"selected": false,
"text": "~/.bash_profile"
},
{
"answer_id": 97154,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 2,
"selected": false,
"text": "~/.bash_profile\n"
},
{
"answer_id": 97164,
"author": "Craig B.",
"author_id": 10780,
"author_profile": "https://Stackoverflow.com/users/10780",
"pm_score": 2,
"selected": false,
"text": "~/.profile"
},
{
"answer_id": 97224,
"author": "Michael Johnson",
"author_id": 17688,
"author_profile": "https://Stackoverflow.com/users/17688",
"pm_score": 3,
"selected": false,
"text": "~/.bash_profile ~/.bash_login ~/.profile ~/.profile ~/.bashrc .bashrc .bash_profile ssh-agent screen"
},
{
"answer_id": 97233,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": false,
"text": "echo \"/usr/bin/uptime\" >> /etc/shells\nvim /etc/passwd \n * username:x:uid:grp:message:homedir:/usr/bin/uptime\n"
},
{
"answer_id": 97320,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 2,
"selected": false,
"text": "/etc/profile .bash_profile"
},
{
"answer_id": 97521,
"author": "pjz",
"author_id": 8002,
"author_profile": "https://Stackoverflow.com/users/8002",
"pm_score": 5,
"selected": false,
"text": "echo $SHELL\n"
},
{
"answer_id": 98314,
"author": "jtimberman",
"author_id": 7672,
"author_profile": "https://Stackoverflow.com/users/7672",
"pm_score": 2,
"selected": false,
"text": "man bash\n/^INVOCATION\n ~/.bash_profile\n The personal initialization file, executed for login shells\n ~/.bashrc\n The individual per-interactive-shell startup file\n"
},
{
"answer_id": 102081,
"author": "Milhous",
"author_id": 17712,
"author_profile": "https://Stackoverflow.com/users/17712",
"pm_score": 2,
"selected": false,
"text": "Launchd ~/Library/LaunchAgents launchd launchctl load /Library/LaunchDaemons/com.bob.plist\n launchctl unload /Library/LaunchDaemons/com.bob.plist\n com.bob.plist <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n<key>Label</key>\n<string>com.bob</string>\n<key>RunAtLoad</key>\n<true/>\n<key>ProgramArguments</key>\n<array>\n<string>/usr/bin/java</string>\n<string>-jar</string>\n<string>/Users/user/program.jar</string>\n</array>\n</dict>\n</plist>\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11760/"
] |
97,142
|
<p>I am trying to do 'rake db:migrate' and getting the error message 'no such file to load -- openssl'. Both 'openssl' and 'openssl-devel' packages are installed. Others on Debian or Ubuntu seem to be able to get rid of this by installing 'libopenssl-ruby', which is not available for RedHat. Has anybody run into this and have a solution for it?</p>
|
[
{
"answer_id": 97214,
"author": "Otto",
"author_id": 9594,
"author_profile": "https://Stackoverflow.com/users/9594",
"pm_score": 0,
"selected": false,
"text": "--trace"
},
{
"answer_id": 97222,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 3,
"selected": false,
"text": "ruby extconf.rb\ncd ../..\nmake\nmake install\n"
},
{
"answer_id": 294075,
"author": "Joel",
"author_id": 31092,
"author_profile": "https://Stackoverflow.com/users/31092",
"pm_score": 4,
"selected": false,
"text": "\n sudo apt-get install libopenssl-ruby\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
97,173
|
<p>I'm using freemarker, SiteMesh and Spring framework.
For the pages I use ${requestContext.getMessage()} to get the message from message.properties. But for the decorators this doesn't work. How should I do to get the internationalization working for sitemesh?</p>
|
[
{
"answer_id": 105142,
"author": "mathd",
"author_id": 16309,
"author_profile": "https://Stackoverflow.com/users/16309",
"pm_score": 2,
"selected": false,
"text": "<%@ taglib prefix=\"decorator\" uri=\"http://www.opensymphony.com/sitemesh/decorator\"%>\n<%@ taglib prefix=\"page\" uri=\"http://www.opensymphony.com/sitemesh/page\"%>\n<%@ taglib prefix=\"c\" uri=\"http://java.sun.com/jstl/core\"%>\n<%@ taglib prefix=\"fmt\" uri=\"http://java.sun.com/jstl/fmt\"%>\n<fmt:setBundle basename=\"messages\" />\n <fmt:message key=\"key_of_message\" />\n"
},
{
"answer_id": 182046,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<#assign fmt=JspTaglibs[\"http://java.sun.com/jstl/fmt\"]>\n<@fmt.message key=\"webapp.name\" />\n web.xml <context-param>\n <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>\n <param-value>messages</param-value>\n</context-param>\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8041/"
] |
97,188
|
<p>I'd like to view historical data for guest cpu/memory/IO usage, rather than just current usage.</p>
|
[
{
"answer_id": 1526671,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "perl xenstat.pl -- generate cpu stats every 5 secs\nperl xenstat.pl 10 -- generate cpu stats every 10 secs\nperl xenstat.pl 5 2 -- generate cpu stats every 5 secs, 2 samples\n\nperl xenstat.pl d 3 -- generate disk stats every 3 secs\nperl xenstat.pl n 3 -- generate network stats every 3 secs\nperl xenstat.pl a 5 -- generate cpu avail (e.g. cpu idle) stats every 5 secs\n\nperl xenstat.pl 3 1 http://server/log.php -- gather 3 secs cpu stats and send to URL\nperl xenstat.pl d 4 1 http://server/log.php -- gather 4 secs disk stats and send to URL\nperl xenstat.pl n 5 1 http://server/log.php -- gather 5 secs network stats and send to URL\n [server~]# xenstat 5 \ncpus=2\n 40_falcon 2.67% 2.51 cpu hrs in 1.96 days ( 2 vcpu, 2048 M)\n 52_python 0.24% 747.57 cpu secs in 1.79 days ( 2 vcpu, 1500 M)\n 54_garuda_0 0.44% 2252.32 cpu secs in 2.96 days ( 2 vcpu, 750 M)\n Dom-0 2.24% 9.24 cpu hrs in 8.59 days ( 2 vcpu, 564 M)\n\n 40_falc 52_pyth 54_garu Dom-0 Idle\n2009-10-02 19:31:20 0.1 0.1 82.5 17.3 0.0 *****\n2009-10-02 19:31:25 0.1 0.1 64.0 9.3 26.5 ****\n2009-10-02 19:31:30 0.1 0.0 50.0 49.9 0.0 *****\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9594/"
] |
97,193
|
<p>Is there a way via System.Reflection, System.Diagnostics or other to get a reference to the actual instance that is calling a static method without passing it in to the method itself?</p>
<p>For example, something along these lines</p>
<pre><code>class A
{
public void DoSomething()
{
StaticClass.ExecuteMethod();
}
}
class B
{
public void DoSomething()
{
SomeOtherClass.ExecuteMethod();
}
}
public class SomeOtherClass
{
public static void ExecuteMethod()
{
// Returns an instance of A if called from class A
// or an instance of B if called from class B.
object caller = getCallingInstance();
}
}
</code></pre>
<p>I can get the type using <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.getframes.aspx" rel="noreferrer">System.Diagnostics.StackTrace.GetFrames</a>, but is there a way to get a reference to the actual instance?</p>
<p>I am aware of the issues with reflection and performance, as well as static to static calls, and that this is generally, perhaps even almost univerally, not the right way to approach this. Part of the reason of this question is I was curious if it was doable; we are currently passing the instance in.</p>
<pre><code>ExecuteMethod(instance)
</code></pre>
<p>And I just wondered if this was possible and still being able to access the instance.</p>
<pre><code>ExecuteMethod()
</code></pre>
<hr>
<p>@Steve Cooper:
I hadn't considered extension methods. Some variation of that might work.</p>
|
[
{
"answer_id": 97315,
"author": "Steve Cooper",
"author_id": 6722,
"author_profile": "https://Stackoverflow.com/users/6722",
"pm_score": 3,
"selected": false,
"text": "public static StaticExecute(this object instance)\n{\n // Reference to 'instance'\n}\n this.StaticExecute();\n static"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4299/"
] |
97,197
|
<p>The "N+1 selects problem" is generally stated as a problem in Object-Relational mapping (ORM) discussions, and I understand that it has something to do with having to make a lot of database queries for something that seems simple in the object world.</p>
<p>Does anybody have a more detailed explanation of the problem?</p>
|
[
{
"answer_id": 97223,
"author": "davetron5000",
"author_id": 3029,
"author_profile": "https://Stackoverflow.com/users/3029",
"pm_score": 5,
"selected": false,
"text": "select * from employees where company_id = XX"
},
{
"answer_id": 97253,
"author": "Matt Solnit",
"author_id": 6198,
"author_profile": "https://Stackoverflow.com/users/6198",
"pm_score": 11,
"selected": true,
"text": "Car Car Wheel Car Wheel SELECT * FROM Cars;\n Car SELECT * FROM Wheel WHERE CarId = ?\n SELECT * FROM Wheel;\n"
},
{
"answer_id": 97308,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 7,
"selected": false,
"text": "SELECT \ntable1.*\n, table2.*\nINNER JOIN table2 ON table2.SomeFkId = table1.SomeId\n SELECT table1.*\n\nSELECT table2.* WHERE SomeFkId = #\n class House\n{\n int Id { get; set; }\n string Address { get; set; }\n Person[] Inhabitants { get; set; }\n}\n\nclass Person\n{\n string Name { get; set; }\n int HouseId { get; set; }\n}\n Id Address Name HouseId\n1 22 Valley St Dave 1\n1 22 Valley St John 1\n1 22 Valley St Mike 1\n Id Address\n1 22 Valley St\n SELECT * FROM Person WHERE HouseId = 1\n Name HouseId\nDave 1\nJohn 1\nMike 1\n"
},
{
"answer_id": 1826225,
"author": "Summy",
"author_id": 210353,
"author_profile": "https://Stackoverflow.com/users/210353",
"pm_score": 6,
"selected": false,
"text": "***** Table: Supplier *****\n+-----+-------------------+\n| ID | NAME |\n+-----+-------------------+\n| 1 | Supplier Name 1 |\n| 2 | Supplier Name 2 |\n| 3 | Supplier Name 3 |\n| 4 | Supplier Name 4 |\n+-----+-------------------+\n\n***** Table: Product *****\n+-----+-----------+--------------------+-------+------------+\n| ID | NAME | DESCRIPTION | PRICE | SUPPLIERID |\n+-----+-----------+--------------------+-------+------------+\n|1 | Product 1 | Name for Product 1 | 2.0 | 1 |\n|2 | Product 2 | Name for Product 2 | 22.0 | 1 |\n|3 | Product 3 | Name for Product 3 | 30.0 | 2 |\n|4 | Product 4 | Name for Product 4 | 7.0 | 3 |\n+-----+-----------+--------------------+-------+------------+\n // It takes Select fetch mode as a default\nQuery query = session.createQuery( \"from Product p\");\nList list = query.list();\n// Supplier is being accessed\ndisplayProductsListWithSupplierName(results);\n\nselect ... various field names ... from PRODUCT\nselect ... various field names ... from SUPPLIER where SUPPLIER.id=?\nselect ... various field names ... from SUPPLIER where SUPPLIER.id=?\nselect ... various field names ... from SUPPLIER where SUPPLIER.id=?\n"
},
{
"answer_id": 6299416,
"author": "rorycl",
"author_id": 299031,
"author_profile": "https://Stackoverflow.com/users/299031",
"pm_score": 5,
"selected": false,
"text": "for p in person:\n print p.car.colour\n select * from people_car_colour; # this is a view or sql function\n p.id | p.name | p.telno | car.id | car.type | car.colour\n -----+--------+---------+--------+----------+-----------\n 2 | jones | 2145 | 77 | ford | red\n 2 | jones | 2145 | 1012 | toyota | blue\n 16 | ashby | 124 | 99 | bmw | yellow\n for p in people:\n print p.car.colour # no more car queries\n"
},
{
"answer_id": 12927312,
"author": "Adam Gent",
"author_id": 318174,
"author_profile": "https://Stackoverflow.com/users/318174",
"pm_score": 3,
"selected": false,
"text": "IN () OneToMany INSERT INTO temp_ids \n (product_id, batch_id)\n (SELECT p.product_id, ? \n FROM product p ORDER BY p.product_id\n LIMIT ? OFFSET ?);\n OneToMany SELECT INNER JOIN WHERE batch_id="
},
{
"answer_id": 26799148,
"author": "Redoman",
"author_id": 988591,
"author_profile": "https://Stackoverflow.com/users/988591",
"pm_score": 5,
"selected": false,
"text": "$cats = load_cats();\nforeach ($cats as $cat) {\n $cats_hats => load_hats_for_cat($cat);\n // ...\n}\n load_cats() SELECT * FROM cat WHERE ...\n load_hats_for_cat($cat) SELECT * FROM hat WHERE catID = ...\n SELECT * FROM cat WHERE ...\nSELECT * FROM hat WHERE catID = 1\nSELECT * FROM hat WHERE catID = 2\nSELECT * FROM hat WHERE catID = 3\nSELECT * FROM hat WHERE catID = 4\n...\n"
},
{
"answer_id": 29644570,
"author": "bedrin",
"author_id": 504452,
"author_profile": "https://Stackoverflow.com/users/504452",
"pm_score": 3,
"selected": false,
"text": "@Rule\npublic final QueryCounter queryCounter = new QueryCounter();\n\n@Expectation(atMost = 3)\n@Test\npublic void testInvokingDatabase() {\n // your JDBC or JPA code\n}\n"
},
{
"answer_id": 39696775,
"author": "Vlad Mihalcea",
"author_id": 1025118,
"author_profile": "https://Stackoverflow.com/users/1025118",
"pm_score": 8,
"selected": false,
"text": "post INSERT INTO post (title, id)\nVALUES ('High-Performance Java Persistence - Part 1', 1)\n \nINSERT INTO post (title, id)\nVALUES ('High-Performance Java Persistence - Part 2', 2)\n \nINSERT INTO post (title, id)\nVALUES ('High-Performance Java Persistence - Part 3', 3)\n \nINSERT INTO post (title, id)\nVALUES ('High-Performance Java Persistence - Part 4', 4)\n post_comment INSERT INTO post_comment (post_id, review, id)\nVALUES (1, 'Excellent book to understand Java Persistence', 1)\n \nINSERT INTO post_comment (post_id, review, id)\nVALUES (2, 'Must-read for Java developers', 2)\n \nINSERT INTO post_comment (post_id, review, id)\nVALUES (3, 'Five Stars', 3)\n \nINSERT INTO post_comment (post_id, review, id)\nVALUES (4, 'A great reference book', 4)\n post_comments List<Tuple> comments = entityManager.createNativeQuery(\"\"\"\n SELECT\n pc.id AS id,\n pc.review AS review,\n pc.post_id AS postId\n FROM post_comment pc\n \"\"\", Tuple.class)\n.getResultList();\n post title post_comment for (Tuple comment : comments) {\n String review = (String) comment.get(\"review\");\n Long postId = ((Number) comment.get(\"postId\")).longValue();\n \n String postTitle = (String) entityManager.createNativeQuery(\"\"\"\n SELECT\n p.title\n FROM post p\n WHERE p.id = :postId\n \"\"\")\n .setParameter(\"postId\", postId)\n .getSingleResult();\n \n LOGGER.info(\n \"The Post '{}' got this review '{}'\",\n postTitle,\n review\n );\n}\n SELECT\n pc.id AS id,\n pc.review AS review,\n pc.post_id AS postId\nFROM post_comment pc\n \nSELECT p.title FROM post p WHERE p.id = 1\n-- The Post 'High-Performance Java Persistence - Part 1' got this review\n-- 'Excellent book to understand Java Persistence'\n \nSELECT p.title FROM post p WHERE p.id = 2\n-- The Post 'High-Performance Java Persistence - Part 2' got this review\n-- 'Must-read for Java developers'\n \nSELECT p.title FROM post p WHERE p.id = 3\n-- The Post 'High-Performance Java Persistence - Part 3' got this review\n-- 'Five Stars'\n \nSELECT p.title FROM post p WHERE p.id = 4\n-- The Post 'High-Performance Java Persistence - Part 4' got this review\n-- 'A great reference book'\n List<Tuple> comments = entityManager.createNativeQuery(\"\"\"\n SELECT\n pc.id AS id,\n pc.review AS review,\n p.title AS postTitle\n FROM post_comment pc\n JOIN post p ON pc.post_id = p.id\n \"\"\", Tuple.class)\n.getResultList();\n \nfor (Tuple comment : comments) {\n String review = (String) comment.get(\"review\");\n String postTitle = (String) comment.get(\"postTitle\");\n \n LOGGER.info(\n \"The Post '{}' got this review '{}'\",\n postTitle,\n review\n );\n}\n post post_comments @Entity(name = \"Post\")\n@Table(name = \"post\")\npublic class Post {\n \n @Id\n private Long id;\n \n private String title;\n \n //Getters and setters omitted for brevity\n}\n \n@Entity(name = \"PostComment\")\n@Table(name = \"post_comment\")\npublic class PostComment {\n \n @Id\n private Long id;\n \n @ManyToOne\n private Post post;\n \n private String review;\n \n //Getters and setters omitted for brevity\n}\n FetchType.EAGER FetchType.EAGER FetchType.EAGER @ManyToOne @OneToOne FetchType.EAGER @ManyToOne\nprivate Post post;\n FetchType.EAGER JOIN FETCH PostComment List<PostComment> comments = entityManager\n.createQuery(\"\"\"\n select pc\n from PostComment pc\n \"\"\", PostComment.class)\n.getResultList();\n SELECT \n pc.id AS id1_1_, \n pc.post_id AS post_id3_1_, \n pc.review AS review2_1_ \nFROM \n post_comment pc\n\nSELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 1\nSELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 2\nSELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 3\nSELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 4\n post List PostComment find EntityManager post FetchType.EAGER FetchType.LAZY post JOIN FETCH List<PostComment> comments = entityManager.createQuery(\"\"\"\n select pc\n from PostComment pc\n join fetch pc.post p\n \"\"\", PostComment.class)\n.getResultList();\n\nfor(PostComment comment : comments) {\n LOGGER.info(\n \"The Post '{}' got this review '{}'\", \n comment.getPost().getTitle(), \n comment.getReview()\n );\n}\n SELECT \n pc.id as id1_1_0_, \n pc.post_id as post_id3_1_0_, \n pc.review as review2_1_0_, \n p.id as id1_0_1_, \n p.title as title2_0_1_ \nFROM \n post_comment pc \nINNER JOIN \n post p ON pc.post_id = p.id\n \n-- The Post 'High-Performance Java Persistence - Part 1' got this review \n-- 'Excellent book to understand Java Persistence'\n\n-- The Post 'High-Performance Java Persistence - Part 2' got this review \n-- 'Must-read for Java developers'\n\n-- The Post 'High-Performance Java Persistence - Part 3' got this review \n-- 'Five Stars'\n\n-- The Post 'High-Performance Java Persistence - Part 4' got this review \n-- 'A great reference book'\n FetchType.LAZY FetchType.LAZY post @ManyToOne(fetch = FetchType.LAZY)\nprivate Post post;\n PostComment List<PostComment> comments = entityManager\n.createQuery(\"\"\"\n select pc\n from PostComment pc\n \"\"\", PostComment.class)\n.getResultList();\n SELECT \n pc.id AS id1_1_, \n pc.post_id AS post_id3_1_, \n pc.review AS review2_1_ \nFROM \n post_comment pc\n post for(PostComment comment : comments) {\n LOGGER.info(\n \"The Post '{}' got this review '{}'\", \n comment.getPost().getTitle(), \n comment.getReview()\n );\n}\n SELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 1\n-- The Post 'High-Performance Java Persistence - Part 1' got this review \n-- 'Excellent book to understand Java Persistence'\n\nSELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 2\n-- The Post 'High-Performance Java Persistence - Part 2' got this review \n-- 'Must-read for Java developers'\n\nSELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 3\n-- The Post 'High-Performance Java Persistence - Part 3' got this review \n-- 'Five Stars'\n\nSELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 4\n-- The Post 'High-Performance Java Persistence - Part 4' got this review \n-- 'A great reference book'\n post JOIN FETCH List<PostComment> comments = entityManager.createQuery(\"\"\"\n select pc\n from PostComment pc\n join fetch pc.post p\n \"\"\", PostComment.class)\n.getResultList();\n\nfor(PostComment comment : comments) {\n LOGGER.info(\n \"The Post '{}' got this review '{}'\", \n comment.getPost().getTitle(), \n comment.getReview()\n );\n}\n FetchType.EAGER FetchType.LAZY @OneToOne db-util <dependency>\n <groupId>com.vladmihalcea</groupId>\n <artifactId>db-util</artifactId>\n <version>${db-util.version}</version>\n</dependency>\n SQLStatementCountValidator SQLStatementCountValidator.reset();\n\nList<PostComment> comments = entityManager.createQuery(\"\"\"\n select pc\n from PostComment pc\n \"\"\", PostComment.class)\n.getResultList();\n\nSQLStatementCountValidator.assertSelectCount(1);\n FetchType.EAGER SELECT \n pc.id as id1_1_, \n pc.post_id as post_id3_1_, \n pc.review as review2_1_ \nFROM \n post_comment pc\n\nSELECT p.id as id1_0_0_, p.title as title2_0_0_ FROM post p WHERE p.id = 1\n\nSELECT p.id as id1_0_0_, p.title as title2_0_0_ FROM post p WHERE p.id = 2\n\n\n-- SQLStatementCountMismatchException: Expected 1 statement(s) but recorded 3 instead!\n"
},
{
"answer_id": 64487275,
"author": "Adam Gaj",
"author_id": 14231619,
"author_profile": "https://Stackoverflow.com/users/14231619",
"pm_score": 0,
"selected": false,
"text": "@SpringBootTest\nclass LazyLoadingTest {\n\n @Autowired\n private JPlusOneAssertionContext assertionContext;\n\n @Autowired\n private SampleService sampleService;\n\n @Test\n public void shouldBusinessCheckOperationAgainstJPlusOneAssertionRule() {\n JPlusOneAssertionRule rule = JPlusOneAssertionRule\n .within().lastSession()\n .shouldBe().noImplicitOperations().exceptAnyOf(exclusions -> exclusions\n .loadingEntity(Author.class).times(atMost(2))\n .loadingCollection(Author.class, \"books\")\n );\n\n // trigger business operation which you wish to be asserted against the rule,\n // i.e. calling a service or sending request to your API controller\n sampleService.executeBusinessOperation();\n\n rule.check(assertionContext);\n }\n}\n"
},
{
"answer_id": 69531377,
"author": "Jimmy",
"author_id": 11527968,
"author_profile": "https://Stackoverflow.com/users/11527968",
"pm_score": 3,
"selected": false,
"text": "Entity Model\n@Entity\n@Table(name = \"DB_USER\")\npublic class User {\n\n @Id\n @GeneratedValue(strategy=GenerationType.AUTO)\n private Long id;\n private String name;\n\n @ManyToMany(fetch = FetchType.LAZY) \n private Set<Role> roles;\n //Getter and Setters \n }\n\n@Entity\n@Table(name = \"DB_ROLE\")\npublic class Role {\n\n @Id\n @GeneratedValue(strategy= GenerationType.AUTO)\n private Long id;\n\n private String name;\n //Getter and Setters\n }\n public interface UserRepository extends CrudRepository<User, Long> {\n\n List<User> findAllBy();\n}\n Select * from DB_USER;\n Select * from DB_USER_ROLE where userid = <userid>;\n select user0_.id, role2_.id, user0_.name, role2_.name, roles1_.user_id, roles1_.roles_id from db_user user0_ left outer join db_user_roles roles1_ on user0_.id=roles1_.user_id left outer join db_role role2_ on roles1_.roles_id=role2_.id\n public interface UserRepository extends CrudRepository<User, Long> {\n\n List<User> findAllBy(); \n\n @Query(\"SELECT p FROM User p LEFT JOIN FETCH p.roles\") \n List<User> findWithoutNPlusOne();\n\n @EntityGraph(attributePaths = {\"roles\"}) \n List<User> findAll();\n}\n from User u *join fetch* u.roles roles roles\n Criteria criteria = session.createCriteria(User.class);\ncriteria.setFetchMode(\"roles\", FetchMode.EAGER);\n"
},
{
"answer_id": 71123306,
"author": "Lukas Eder",
"author_id": 521799,
"author_profile": "https://Stackoverflow.com/users/521799",
"pm_score": 2,
"selected": false,
"text": "dbms_output.get_lines dbms_output.get_line -- This loop is executed once\nfor parent in (select * from parent) loop\n\n -- This loop is executed N times\n for child in (select * from child where parent_id = parent.id) loop\n ...\n end loop;\nend loop;\n for rec in (\n select *\n from parent p\n join child c on c.parent_id = p.id\n)\nloop\n ...\nend loop;\n O(N) O(N log N)"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6120/"
] |
97,206
|
<p>I am using the <strong>AjaxControlToolkit</strong> in VS2005, and it works fine. I do have some issues though, when I go to some pages I have, then click back, I get this JavaScript error:</p>
<blockquote>
<p>'AjaxControlToolkit' is undefined</p>
</blockquote>
<p>I have searched MSDN forums, and google, and tried many of the solutions, but none have worked. I have tried, <code>EnablePartialRendering="true",</code> and others. Short of rewriting everything and changing the workflow of my application, is there any way to find the root cause of this, or fix it?
</p>
|
[
{
"answer_id": 97327,
"author": "CodeRot",
"author_id": 14134,
"author_profile": "https://Stackoverflow.com/users/14134",
"pm_score": 1,
"selected": false,
"text": "<system.web.extensions>\n <scripting>\n <scriptResourceHandler enableCompression=\"false\" enableCaching=\"false\" />\n </scripting></system.web.extensions>\n"
},
{
"answer_id": 4599760,
"author": "jcpennypincher",
"author_id": 407379,
"author_profile": "https://Stackoverflow.com/users/407379",
"pm_score": 2,
"selected": false,
"text": "<myTagPrefix:ToolkitScriptManager ID=\"ScriptManager1\" runat=\"server\" EnablePageMethods=\"true\" EnablePartialRendering=\"true\" SupportsPartialRendering=\"true\" **CombineScripts=\"false\"**>\n <%@ Register assembly=\"AjaxControlToolkit\" namespace=\"AjaxControlToolkit\" tagprefix=\"myTagPrefix\" %>\n"
},
{
"answer_id": 9037895,
"author": "Danish",
"author_id": 159910,
"author_profile": "https://Stackoverflow.com/users/159910",
"pm_score": 3,
"selected": false,
"text": "Sys.Extended.UI.BehaviorBase AjaxControlToolkit.BehaviorBase registerClass"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12268/"
] |
97,220
|
<p>When dealing with mobile clients it is very common to have multisecond delays during the transmission of HTTP requests. If you are serving pages or services out of a prefork Apache the child processes will be tied up for seconds serving a single mobile client, even if your app server logic is done in 5ms. I am looking for a HTTP server, balancer or proxy server that supports the following:</p>
<ol>
<li><p>A request arrives to the proxy. The proxy starts buffering in RAM or in disk the request, including headers and POST/PUT bodies. The proxy DOES NOT open a connection to the backend server. This is probably the most important part.</p></li>
<li><p>The proxy server stops buffering the request when:</p>
<ul>
<li>A size limit has been reached (say, 4KB), or</li>
<li>The request has been received completely, headers and body</li>
</ul></li>
<li><p>Only now, with (part of) the request in memory, a connection is opened to the backend and the request is relayed.</p></li>
<li><p>The backend sends back the response. Again the proxy server starts buffering it immediately (up to a more generous size, say 64KB.) </p></li>
<li><p>Since the proxy has a big enough buffer the backend response is stored completely in the proxy server in a matter of miliseconds, and the backend process/thread is free to process more requests. The backend connection is immediately closed.</p></li>
<li><p>The proxy sends back the response to the mobile client, as fast or as slow as it is capable of, without having a connection to the backend tying up resources.</p></li>
</ol>
<p>I am fairly sure you can do 4-6 with Squid, and nginx appears to support 1-3 (and looks like fairly unique in this respect). My question is: is there any proxy server that empathizes these buffering and not-opening-connections-until-ready capabilities? Maybe there is just a bit of Apache config-fu that makes this buffering behaviour trivial? Any of them that it is not a dinosaur like Squid and that supports a lean single-process, asynchronous, event-based execution model?</p>
<p>(Siderant: I would be using nginx but it doesn't support chunked POST bodies, making it useless for serving stuff to mobile clients. Yes cheap 50$ handsets love chunked POSTs... sigh)</p>
|
[
{
"answer_id": 98062,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 2,
"selected": false,
"text": "Rules | Custom Rules... sleep()"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7027/"
] |
97,228
|
<p>Ok, here's the breakdown of my project: I have a web project with a "Scripts" subfolder. That folder contains a few javascript files and a copy of JSMin.exe along with a batch file that runs the JSMin.exe on a few of the files. I tried to set up a post build step of 'call "$(ProjectDir)Scripts\jsmin.bat"'. When I perform the build, the batch file is always "exited with code 1." This happens going through Visual Studio or through the msbuild command line. I can run the batch file manually from the Scripts folder and it seems to work as expected, so I'm not sure what the issue here is. The $(ProjectDir)Scripts\jsmin.bat call is in quotes because $(ProjectDir) could have spaces (and in fact does on my machine). I'm not sure what to do at this point. I've tried removing the contents of the batch file as the post build step but that doesn't seem to work either.</p>
<p>Ideally I would like to solve this problem through the post or pre-build steps so that the build manager won't have to go through an extra step when deploying code.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 97284,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 3,
"selected": true,
"text": "exit 0\n"
},
{
"answer_id": 167155,
"author": "Jonathan Webb",
"author_id": 1518,
"author_profile": "https://Stackoverflow.com/users/1518",
"pm_score": 1,
"selected": false,
"text": "echo \"test\" >>\"test.txt\"\n echo \"test\" >>\"C:\\Temp\\CompileTest\\test.txt\"\n call \"C:\\Temp\\CompileTest\\DoStuff.bat\"\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16149/"
] |
97,276
|
<p>If I've got a time_t value from <code>gettimeofday()</code> or compatible in a Unix environment (e.g., Linux, BSD), is there a compact algorithm available that would be able to tell me the corresponding week number within the month?</p>
<p>Ideally the return value would work in similar to the way <code>%W</code> behaves in <code>strftime()</code> , except giving the week within the month rather than the week within the year.</p>
<p>I think Java has a <code>W</code> formatting token that does something more or less like what I'm asking.</p>
<hr>
<p>[Everything below written after answers were posted by David Nehme, Branan, and Sparr.]</p>
<p>I realized that to return this result in a similar way to <code>%W</code>, we want to count the number of Mondays that have occurred in the month so far. If that number is zero, then 0 should be returned.</p>
<p>Thanks to David Nehme and Branan in particular for their solutions which started things on the right track. The bit of code returning [using Branan's variable names] <code>((ts->mday - 1) / 7)</code> tells the number of complete weeks that have occurred before the current day.</p>
<p>However, if we're counting the number of Mondays that have occurred so far, then we want to count the number of integral weeks, including today, then consider if the fractional week left over also contains any Mondays.</p>
<p>To figure out whether the fractional week left after taking out the whole weeks contains a Monday, we need to consider <code>ts->mday % 7</code> and compare it to the day of the week, <code>ts->wday</code>. This is easy to see if you write out the combinations, but if we insure the day is not Sunday (<code>wday > 0</code>), then anytime <code>ts->wday <= (ts->mday % 7)</code> we need to increment the count of Mondays by 1. This comes from considering the number of days since the start of the month, and whether, based on the current day of the week within the the first fractional week, the fractional week contains a Monday.</p>
<p>So I would rewrite Branan's return statement as follows:</p>
<p><code>return (ts->tm_mday / 7) + ((ts->tm_wday > 0) && (ts->tm_wday <= (ts->tm_mday % 7)));</code></p>
|
[
{
"answer_id": 97377,
"author": "Branan",
"author_id": 13894,
"author_profile": "https://Stackoverflow.com/users/13894",
"pm_score": 1,
"selected": false,
"text": "int getWeekOfMonth()\n{\n time_t my_time;\n struct tm *ts;\n\n my_time = time(NULL);\n ts = localtime(&my_time);\n\n return ((ts->tm_mday -1) / 7) + 1;\n}\n +1"
},
{
"answer_id": 97475,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 1,
"selected": false,
"text": "int week_of_month( const time_t *my_time)\n{\n struct tm *timeinfo;\n\n timeinfo =localtime(my_time);\n return 1 + (timeinfo->tm_mday-1) / 7;\n\n}\n"
},
{
"answer_id": 97493,
"author": "Sparr",
"author_id": 13675,
"author_profile": "https://Stackoverflow.com/users/13675",
"pm_score": 0,
"selected": false,
"text": "int week_num_in_month(time_t timestamp) {\n int first_weekday_of_month, day_of_month;\n day_of_month = strftime(timestamp,\"%d\");\n first_weekday_of_month = strftime(timefstr(strftime(timestamp,\"%d/%m/01\")),\"%w\");\n return (day_of_month + first_weekday_of_month - 1 ) / 7 + 1;\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
97,279
|
<p>Does anyone know a keyboard shortcut to close all tabs except for the current one in Visual Studio? And while we're at it, the shortcut for closing all tabs? Is there a Resharper option for this? I've looked in the past and have never been able to find it. </p>
|
[
{
"answer_id": 97358,
"author": "Micky McQuade",
"author_id": 12908,
"author_profile": "https://Stackoverflow.com/users/12908",
"pm_score": 2,
"selected": false,
"text": "File.CloseAllButThis"
},
{
"answer_id": 197213,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 6,
"selected": false,
"text": "File.CloseAllButThis File.CloseAllButThis Window.CloseAllDocuments"
},
{
"answer_id": 68953873,
"author": "Caleb Waldner",
"author_id": 10044909,
"author_profile": "https://Stackoverflow.com/users/10044909",
"pm_score": 3,
"selected": false,
"text": "workbench.action.closeOtherEditors"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9344/"
] |
97,283
|
<p>For example if the user is currently running VS2008 then I want the value VS2008.</p>
|
[
{
"answer_id": 97517,
"author": "Ozgur Ozcitak",
"author_id": 976,
"author_profile": "https://Stackoverflow.com/users/976",
"pm_score": 5,
"selected": true,
"text": "// The GetForegroundWindow function returns a handle to the foreground window\n// (the window with which the user is currently working).\n[System.Runtime.InteropServices.DllImport(\"user32.dll\")]\nprivate static extern IntPtr GetForegroundWindow();\n\n// The GetWindowThreadProcessId function retrieves the identifier of the thread\n// that created the specified window and, optionally, the identifier of the\n// process that created the window.\n[System.Runtime.InteropServices.DllImport(\"user32.dll\")]\nprivate static extern Int32 GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);\n\n// Returns the name of the process owning the foreground window.\nprivate string GetForegroundProcessName()\n{\n IntPtr hwnd = GetForegroundWindow();\n\n // The foreground window can be NULL in certain circumstances, \n // such as when a window is losing activation.\n if (hwnd == null)\n return \"Unknown\";\n\n uint pid;\n GetWindowThreadProcessId(hwnd, out pid);\n\n foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())\n {\n if (p.Id == pid)\n return p.ProcessName;\n }\n\n return \"Unknown\";\n}\n"
},
{
"answer_id": 19045382,
"author": "user2533527",
"author_id": 2533527,
"author_profile": "https://Stackoverflow.com/users/2533527",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Windows;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\nnamespace FGHook\n{\n class ForegroundTracker\n {\n // Delegate and imports from pinvoke.net:\n\n delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType,\n IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);\n\n [DllImport(\"user32.dll\")]\n static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr\n hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess,\n uint idThread, uint dwFlags);\n\n [DllImport(\"user32.dll\")]\n static extern IntPtr GetForegroundWindow();\n\n [DllImport(\"user32.dll\")]\n static extern Int32 GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);\n\n\n [DllImport(\"user32.dll\")]\n static extern bool UnhookWinEvent(IntPtr hWinEventHook);\n\n\n\n // Constants from winuser.h\n const uint EVENT_SYSTEM_FOREGROUND = 3;\n const uint WINEVENT_OUTOFCONTEXT = 0;\n\n // Need to ensure delegate is not collected while we're using it,\n // storing it in a class field is simplest way to do this.\n static WinEventDelegate procDelegate = new WinEventDelegate(WinEventProc);\n\n public static void Main()\n {\n // Listen for foreground changes across all processes/threads on current desktop...\n IntPtr hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero,\n procDelegate, 0, 0, WINEVENT_OUTOFCONTEXT);\n\n // MessageBox provides the necessary mesage loop that SetWinEventHook requires.\n MessageBox.Show(\"Tracking focus, close message box to exit.\");\n\n UnhookWinEvent(hhook);\n }\n\n static void WinEventProc(IntPtr hWinEventHook, uint eventType,\n IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)\n {\n Console.WriteLine(\"Foreground changed to {0:x8}\", hwnd.ToInt32());\n //Console.WriteLine(\"ObjectID changed to {0:x8}\", idObject);\n //Console.WriteLine(\"ChildID changed to {0:x8}\", idChild);\n GetForegroundProcessName();\n\n }\n static void GetForegroundProcessName()\n {\n IntPtr hwnd = GetForegroundWindow();\n\n // The foreground window can be NULL in certain circumstances, \n // such as when a window is losing activation.\n if (hwnd == null)\n return;\n\n uint pid;\n GetWindowThreadProcessId(hwnd, out pid);\n\n foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())\n {\n if (p.Id == pid)\n {\n Console.WriteLine(\"Pid is: {0}\",pid);\n Console.WriteLine(\"Process name is {0}\",p.ProcessName);\n return;\n }\n //return;\n }\n\n Console.WriteLine(\"Unknown\");\n }\n }\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44972/"
] |
97,312
|
<p>How do I find out what directory my console app is running in with C#?</p>
|
[
{
"answer_id": 97331,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 8,
"selected": true,
"text": "AppDomain.CurrentDomain.BaseDirectory\n Environment.CurrentDirectory\n"
},
{
"answer_id": 97343,
"author": "Travis Illig",
"author_id": 8116,
"author_profile": "https://Stackoverflow.com/users/8116",
"pm_score": 2,
"selected": false,
"text": "System.Environment.CurrentDirectory System.Reflection.Assembly.GetExecutingAssembly().Location"
},
{
"answer_id": 97491,
"author": "Atif Aziz",
"author_id": 6682,
"author_profile": "https://Stackoverflow.com/users/6682",
"pm_score": 4,
"selected": false,
"text": "Console.WriteLine( Assembly.GetEntryAssembly().Location );\nConsole.WriteLine( new Uri(Assembly.GetEntryAssembly().CodeBase).LocalPath );\nConsole.WriteLine( Environment.GetCommandLineArgs()[0] );\nConsole.WriteLine( Process.GetCurrentProcess().MainModule.FileName );\n"
},
{
"answer_id": 58547501,
"author": "R M Shahidul Islam Shahed",
"author_id": 3201212,
"author_profile": "https://Stackoverflow.com/users/3201212",
"pm_score": 2,
"selected": false,
"text": "Console.WriteLine(Environment.CurrentDirectory);\n Get Project .csproj file directory:\nstring ProjectDirPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @\"..\\..\\..\\\"));\nConsole.WriteLine(ProjectDirPath);\n"
},
{
"answer_id": 63185948,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 0,
"selected": false,
"text": "AppContext.BaseDirectory"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1786/"
] |
97,329
|
<p>Suppose I have a collection (be it an array, generic List, or whatever is the <strong>fastest</strong> solution to this problem) of a certain class, let's call it <code>ClassFoo</code>:</p>
<pre><code>class ClassFoo
{
public string word;
public float score;
//... etc ...
}
</code></pre>
<p>Assume there's going to be like 50.000 items in the collection, all in memory.
Now I want to obtain as fast as possible all the instances in the collection that obey a condition on its bar member, for example like this:</p>
<pre><code>List<ClassFoo> result = new List<ClassFoo>();
foreach (ClassFoo cf in collection)
{
if (cf.word.StartsWith(query) || cf.word.EndsWith(query))
result.Add(cf);
}
</code></pre>
<p>How do I get the results as fast as possible? Should I consider some advanced indexing techniques and datastructures?</p>
<p>The application domain for this problem is an autocompleter, that gets a query and gives a collection of suggestions as a result. Assume that the condition doesn't get any more complex than this. Assume also that there's going to be a lot of searches.</p>
|
[
{
"answer_id": 97449,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 0,
"selected": false,
"text": "Dictionary<char, List<ClassFoo>> indexByFirstLetter;\nforeach (var cf in collection) {\n indexByFirstLetter[cf.bar[0]] = indexByFirstLetter[cf.bar[0]] ?? new List<ClassFoo>();\n indexByFirstLetter[cf.bar[0]].Add(cf);\n indexByFirstLetter[cf.bar[cf.bar.length - 1]] = indexByFirstLetter[cf.bar[cf.bar.Length - 1]] ?? new List<ClassFoo>();\n indexByFirstLetter[cf.bar[cf.bar.Length - 1]].Add(cf);\n}\n foreach (ClasssFoo cf in indexByFirstLetter[query[0]]) {\n if (cf.bar.StartsWith(query) || cf.bar.EndsWith(query))\n result.Add(cf);\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6264/"
] |
97,338
|
<p>I'm using GCC to generate a dependency file, but my build rules put the output into a subdirectory. Is there a way to tell GCC to put my subdirectory prefix in the dependency file it generates for me?</p>
<pre><code>gcc $(INCLUDES) -E -MM $(CFLAGS) $(SRC) >>$(DEP)
</code></pre>
|
[
{
"answer_id": 97374,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 0,
"selected": false,
"text": "<blah>.o ${OBJDIR}/<blah>.o"
},
{
"answer_id": 97710,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "test.c test.h subdir/test.d subdir/test.o subdir/test.d subdir/test.o: test.c test.h\n test.o: test.c test.h\n .d gcc $(INCLUDES) -MMD $(CFLAGS) $(SRC) -o $(SUBDIR)/$(OBJ)\n SRC=test.c SUBDIR=subdir OBJ=test.o subdir/test.d"
},
{
"answer_id": 97893,
"author": "florin",
"author_id": 18308,
"author_profile": "https://Stackoverflow.com/users/18308",
"pm_score": 0,
"selected": false,
"text": "-o"
},
{
"answer_id": 99282,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 6,
"selected": true,
"text": "-MT -MT target .c -MT -MT -MT -MT '$(objpfx)foo.o' $(objpfx)foo.o: foo.c\n"
},
{
"answer_id": 2045668,
"author": "Don McCaughey",
"author_id": 65764,
"author_profile": "https://Stackoverflow.com/users/65764",
"pm_score": 5,
"selected": false,
"text": "SRCS = \\\n main.c \\\n foo.c \\\n stuff/bar.c\n\nDEPS = $(SRCS:.c=.d)\n include $(DEPS)\n # automatically generate dependency rules\n\n%.d : %.c\n $(CC) $(CCFLAGS) -MF\"$@\" -MG -MM -MP -MT\"$@\" -MT\"$(<:.c=.o)\" \"$<\"\n\n# -MF write the generated dependency rule to a file\n# -MG assume missing headers will be generated and don't stop with an error\n# -MM generate dependency rule for prerequisite, skipping system headers\n# -MP add phony target for each header to prevent errors when header is missing\n# -MT add a target to the generated dependency\n"
},
{
"answer_id": 16969086,
"author": "Steve Pitchers",
"author_id": 7255,
"author_profile": "https://Stackoverflow.com/users/7255",
"pm_score": 4,
"selected": false,
"text": "SRCS = \\\n main.c \\\n foo.c \\\n stuff/bar.c\n DEPS = $(SRCS:.c=.d) -include $(DEPS) - .d -MD -MMD .d %.o: %.c\n gcc $(INCLUDE) -MMD -c $< -o $@\n\n# -MD can be used to generate a dependency output file as a side-effect of the compilation process.\n"
},
{
"answer_id": 24129675,
"author": "rsp1984",
"author_id": 1232524,
"author_profile": "https://Stackoverflow.com/users/1232524",
"pm_score": 2,
"selected": false,
"text": ".depend: $(SOURCES)\n $(CC) $(CFLAGS) -MM $(SOURCES) | sed 's|[a-zA-Z0-9_-]*\\.o|$(OBJDIR)/&|' > ./.depend\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
] |
97,349
|
<p>We want to store our overridden build targets in an external file and include that targets file in the TFSBuild.proj. We have a core set steps that happens and would like to get those additional steps by simply adding the import line to the TFSBuild.proj created by the wizard. </p>
<pre><code><Import Project="$(SolutionRoot)/libs/my.team.build/my.team.build.targets"/>
</code></pre>
<p>We cannot have an import on any file in the <code>$(SolutionRoot)</code> because at the time the Import statement is validated, the source has not be fetched from the repository. It looks like TFS is pulling down the <code>TFSBuild.proj</code> first without any other files.</p>
<p>Even if we add a conditional import, the version in source control will not be imported if present. The previous version, already present on disk will be imported. </p>
<p>We can give up storing those build targets with our source, but it is the first dependency to move out of our source tree so we are reluctant to do it.</p>
<p>Is there a way to either:</p>
<ol>
<li>Tell Team Build to pull down a few more files so those <code>Import</code> statements evaluate correctly?</li>
<li>Override those Team Build targets like <code>AfterCompile</code> in a manner besides the <code>Import</code>?</li>
<li>Ultimately run build targets in Team Build that are kept under the source it's trying to build?</li>
</ol>
|
[
{
"answer_id": 97486,
"author": "Gregg",
"author_id": 18266,
"author_profile": "https://Stackoverflow.com/users/18266",
"pm_score": 1,
"selected": false,
"text": "<Import Project=\"$(MSBuildProjectDirectory)\\my.team.build.targets.proj\" />\n <Import Project=\"$(SolutionRoot)/libs/my.team.build/my.team.build.targets\" Condition=\"Exists('$(SolutionRoot)/libs/my.team.build/my.team.build.targets')\" />\n"
},
{
"answer_id": 99893,
"author": "Mr. Kraus",
"author_id": 5132,
"author_profile": "https://Stackoverflow.com/users/5132",
"pm_score": 0,
"selected": false,
"text": "<Import Project=\"$(MSBuildProjectDirectory)\\TeamBuildOverrides.targets\" />\n"
},
{
"answer_id": 100493,
"author": "Martin Woodward",
"author_id": 6438,
"author_profile": "https://Stackoverflow.com/users/6438",
"pm_score": 5,
"selected": true,
"text": "<Import Project=\"myTeamBuild.targets\"/>\n $/TeamProject/main/MySolution/TeamBuild\n <add key=\"ConfigurationFolderRecursionType\" value=\"Full\" />\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/97349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18264/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.