qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
264,278 |
<p>I am developing an Intranet Application in ASP.NET that uses Windows Authentication. I have created an AD class that gets information from the Active Directory Domain Controller. This is what I use to get things like User Groups that the currently logged user is in. The problem is in the ASP.NET Roles that the user is in. Seems funny, but the list of AD Groups that the user is in is totally different from the list of Roles that the user has.</p>
<p>Here is what I get:</p>
<p>List of AD Groups for a certian user</p>
<ol>
<li>Developers</li>
<li>Account Operators</li>
<li>Domain Admins</li>
<li>IS_IUSRS</li>
<li>Administrators</li>
</ol>
<p>List of the same user's Roles</p>
<ol>
<li>PUDDOM\Domain Users</li>
<li>Everyone</li>
<li>BUILTIN\Users</li>
<li>BUILTIN\Administrators</li>
<li>NT AUTHORITY\INTERACTIVE</li>
<li>NT AUTHORITY\Authenticated Users</li>
<li>NT AUTHORITY\This Organization</li>
<li>LOCAL</li>
<li>PUDDOM\Domain Admins</li>
<li>PUDDOM\Denied RODC Password Replication Group</li>
<li>PUDDOM\DnsAdmins</li>
</ol>
<p>OTHER INFORMATION:</p>
<ol>
<li>I have my website use Integrated Windows Authentication from IIS7.</li>
<li>A portion of my <code>web.config</code> looks like </li>
</ol>
<p>this:</p>
<pre><code><authentication mode="Windows" />
<authorization>
<deny users="?" />
</authorization>
<roleManager defaultProvider="AspNetWindowsTokenRoleProvider" enabled="true">
<providers>
<remove name="AspNetSqlRoleProvider" />
</providers>
</roleManager>
</code></pre>
<p>How do I reconcile the list?</p>
<p>I need to make my Roles list reflect the same data as my AD Groups list because I will use Role trimming in my site map and other stuff. </p>
|
[
{
"answer_id": 264435,
"author": "CPU_BUSY",
"author_id": 27688,
"author_profile": "https://Stackoverflow.com/users/27688",
"pm_score": 0,
"selected": false,
"text": "<p>You might need to assign the website permissions specifically to the groups you want to enumerate.</p>\n"
},
{
"answer_id": 264475,
"author": "Stephen M. Redd",
"author_id": 10115,
"author_profile": "https://Stackoverflow.com/users/10115",
"pm_score": 2,
"selected": false,
"text": "<p>Part of your result is because some of the groups the user belongs to are members of other groups. The full list of a user's groups will include all groups the user belongs to, both directly and via membership in other groups who are also members. </p>\n\n<p>The list will also include built-in groups that are normally hidden from the native admin tools by default.</p>\n\n<p>Your best bet is to have the application store a master list of the groups you want your application to see, or a list of groups you want your application to ignore (either an include list, or an exclude list). Then when you pull back a specific user's roles, just compare it to the configured exclude or include list and filter out the unwanted results. </p>\n\n<p>If you want an easier way, there is an open source <a href=\"http://www.codeproject.com/KB/aspnet/active_directory_roles.aspx\" rel=\"nofollow noreferrer\">AD role provider over at codeproject</a> that already has support for both exclude and include lists. It also has other nice features like optional caching that will REALLY speed up your application. The build-in AD role provider performs very poorly. </p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am developing an Intranet Application in ASP.NET that uses Windows Authentication. I have created an AD class that gets information from the Active Directory Domain Controller. This is what I use to get things like User Groups that the currently logged user is in. The problem is in the ASP.NET Roles that the user is in. Seems funny, but the list of AD Groups that the user is in is totally different from the list of Roles that the user has.
Here is what I get:
List of AD Groups for a certian user
1. Developers
2. Account Operators
3. Domain Admins
4. IS\_IUSRS
5. Administrators
List of the same user's Roles
1. PUDDOM\Domain Users
2. Everyone
3. BUILTIN\Users
4. BUILTIN\Administrators
5. NT AUTHORITY\INTERACTIVE
6. NT AUTHORITY\Authenticated Users
7. NT AUTHORITY\This Organization
8. LOCAL
9. PUDDOM\Domain Admins
10. PUDDOM\Denied RODC Password Replication Group
11. PUDDOM\DnsAdmins
OTHER INFORMATION:
1. I have my website use Integrated Windows Authentication from IIS7.
2. A portion of my `web.config` looks like
this:
```
<authentication mode="Windows" />
<authorization>
<deny users="?" />
</authorization>
<roleManager defaultProvider="AspNetWindowsTokenRoleProvider" enabled="true">
<providers>
<remove name="AspNetSqlRoleProvider" />
</providers>
</roleManager>
```
How do I reconcile the list?
I need to make my Roles list reflect the same data as my AD Groups list because I will use Role trimming in my site map and other stuff.
|
Part of your result is because some of the groups the user belongs to are members of other groups. The full list of a user's groups will include all groups the user belongs to, both directly and via membership in other groups who are also members.
The list will also include built-in groups that are normally hidden from the native admin tools by default.
Your best bet is to have the application store a master list of the groups you want your application to see, or a list of groups you want your application to ignore (either an include list, or an exclude list). Then when you pull back a specific user's roles, just compare it to the configured exclude or include list and filter out the unwanted results.
If you want an easier way, there is an open source [AD role provider over at codeproject](http://www.codeproject.com/KB/aspnet/active_directory_roles.aspx) that already has support for both exclude and include lists. It also has other nice features like optional caching that will REALLY speed up your application. The build-in AD role provider performs very poorly.
|
264,281 |
<p>Is there a way (in C#) to access the systray?
I am not talking about making a notify icon.
I want to iterate through the items in the tray (I would guess through the processes but I don't know how to determine what is actually in the tray and what is just a process) and also represent the items with their icons in my own ui.</p>
|
[
{
"answer_id": 264341,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 1,
"selected": false,
"text": "<p>Mathias Rauen's madCollection (for Delphi not c#) can list <a href=\"http://help.madshi.net/TrayIcons.htm\" rel=\"nofollow noreferrer\">Tray Icons</a>.</p>\n\n<p>And there is a commandline tool: <a href=\"http://exodusdev.com/products/windows-system-tray-scan-utility\" rel=\"nofollow noreferrer\">Windows System Tray Scan Utility</a></p>\n\n<p>I have also written (not released) my own program in Delphi (not Delphi.NET), not using madCollection, which shows tray icons, process names, tooltips and other info but it's not perfect. There are a few icons it can't display (even though it lists other info), and it can't display any icons under windows 9x. I haven't tested it at all under Vista.</p>\n"
},
{
"answer_id": 264595,
"author": "Rob",
"author_id": 34224,
"author_profile": "https://Stackoverflow.com/users/34224",
"pm_score": 4,
"selected": true,
"text": "<p>How do you feel about Win32 interop? I found <a href=\"http://skyscraper.fortunecity.com/gigo/311/winprog/shellico.txt\" rel=\"nofollow noreferrer\" title=\"this C/Win32 code\">C/Win32 code</a> that might do the trick for you. (Actually, it looks like an interesting problem so I might try to tackle it myself, just not now).</p>\n\n<p>The magic appears to be that he gets a handle to the system tray's window:</p>\n\n<pre><code>NotifyWnd = FindWindowEx(SysTray, 0, \"TrayNotifyWnd\", 0);</code></pre>\n\n<p>Then he sets a hook on its message pump:</p>\n\n<pre><code>hHook=SetWindowsHookEx(WH_CALLWNDPROC,HOOKPROC(MsgProc),\n hInstance,dwExplorerThreadId);</code></pre>\n\n<p>Then during the message pump hook callback, he gets a reference to some pointer data about the window:</p>\n\n<pre><code>TWDataT* twd=(TWDataT*)GetWindowLong(NotifyWnd,0);</code></pre>\n\n<p>The mystery is then his loop:</p>\n\n<pre><code> pTWIconDataT p=COMCTL32_332(twd->iconsInfo,i);</code></pre>\n\n<p>COMCTL32_332 is defined with GetProcAddress and points to ordinal 332 of Comctl32.dll - according to my checking with Dependency Viewer, that's <a href=\"http://msdn.microsoft.com/en-us/library/bb775617.aspx\" rel=\"nofollow noreferrer\" title=\"DPA_GetPtr\">DPA_GetPtr</a>, which gets data from a dynamic pointer array. I'm not familiar with what's going on behind the scenes there, but it doesn't seem entirely out of the question.</p>\n\n<p>I'm going to play with this a bit myself, but hopefully it's a good place to get you started. :)</p>\n"
},
{
"answer_id": 264733,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 1,
"selected": false,
"text": "<p>In Windows 2000, the system tray icons are in a plain toolbar control (window class \"ToolbarWindow32\") which is a child of the \"TrayNotifyWnd\" window, so you can send it toolbar messages such as <code>TB_BUTTONCOUNT</code> and <code>TB_GETBUTTON</code>.</p>\n\n<p>You need to be careful though: messages such as TB_GETBUTTON which require a pointer to a buffer in which to store the results need that buffer to <strong>be in the SysTray process itself</strong>. This requires that you have the right permissions, and that you use <code>VirtualAllocEx</code> to allocate the memory.</p>\n\n<p>I haven't tried it on XP or Vista. I expect things have changed.</p>\n"
},
{
"answer_id": 6242630,
"author": "michalczerwinski",
"author_id": 306146,
"author_profile": "https://Stackoverflow.com/users/306146",
"pm_score": 0,
"selected": false,
"text": "<p>It was perfectly possible to achieve it in Windows 2000/Xp.\nUnfortunately in Windows 7 it seems to be not feasible any more.</p>\n\n<p>Trick was simple: you have to find tray window handle:</p>\n\n<pre><code> static IntPtr GetSystemTrayHandle()\n {\n IntPtr hWndTray = FindWindow(\"Shell_TrayWnd\", null);\n if (hWndTray != IntPtr.Zero)\n {\n hWndTray = FindWindowEx(hWndTray, IntPtr.Zero, \"TrayNotifyWnd\", null);\n if (hWndTray != IntPtr.Zero)\n {\n hWndTray = FindWindowEx(hWndTray, IntPtr.Zero, \"SysPager\", null);\n if (hWndTray != IntPtr.Zero)\n {\n hWndTray = FindWindowEx(hWndTray, IntPtr.Zero, \"ToolbarWindow32\", null);\n return hWndTray;\n }\n }\n }\n\n return IntPtr.Zero;\n }\n</code></pre>\n\n<p>Since this window is ToolbarWindow32 then you have to enumerate throughout buttons using WinAPI. The only problem is that all structures used for this should be allocated in target process address space, so you have to use something like this:</p>\n\n<pre><code> private static unsafe bool GetTBButton(IntPtr hToolbar, int i, ref TBBUTTON tbButton, ref string text, ref IntPtr ipWindowHandle)\n {\n // One page\n const int BUFFER_SIZE = 0x1000;\n\n byte[] localBuffer = new byte[BUFFER_SIZE];\n\n UInt32 processId = 0;\n UInt32 threadId = User32.GetWindowThreadProcessId(hToolbar, out processId);\n\n IntPtr hProcess = Kernel32.OpenProcess(ProcessRights.ALL_ACCESS, false, processId);\n if (hProcess == IntPtr.Zero) { Debug.Assert(false); return false; }\n\n IntPtr ipRemoteBuffer = Kernel32.VirtualAllocEx(\n hProcess,\n IntPtr.Zero,\n new UIntPtr(BUFFER_SIZE),\n MemAllocationType.COMMIT,\n MemoryProtection.PAGE_READWRITE);\n\n if (ipRemoteBuffer == IntPtr.Zero) { Debug.Assert(false); return false; }\n\n // TBButton\n fixed (TBBUTTON* pTBButton = &tbButton)\n {\n IntPtr ipTBButton = new IntPtr(pTBButton);\n\n int b = (int)User32.SendMessage(hToolbar, TB.GETBUTTON, (IntPtr)i, ipRemoteBuffer);\n if (b == 0) { Debug.Assert(false); return false; }\n\n // this is fixed\n Int32 dwBytesRead = 0;\n IntPtr ipBytesRead = new IntPtr(&dwBytesRead);\n\n bool b2 = Kernel32.ReadProcessMemory(\n hProcess,\n ipRemoteBuffer,\n ipTBButton,\n new UIntPtr((uint)sizeof(TBBUTTON)),\n ipBytesRead);\n\n if (!b2) { Debug.Assert(false); return false; }\n }\n\n // button text\n fixed (byte* pLocalBuffer = localBuffer)\n {\n IntPtr ipLocalBuffer = new IntPtr(pLocalBuffer);\n\n int chars = (int)User32.SendMessage(hToolbar, TB.GETBUTTONTEXTW, (IntPtr)tbButton.idCommand, ipRemoteBuffer);\n if (chars == -1) { Debug.Assert(false); return false; }\n\n // this is fixed\n Int32 dwBytesRead = 0;\n IntPtr ipBytesRead = new IntPtr(&dwBytesRead);\n\n bool b4 = Kernel32.ReadProcessMemory(\n hProcess,\n ipRemoteBuffer,\n ipLocalBuffer,\n new UIntPtr(BUFFER_SIZE),\n ipBytesRead);\n\n if (!b4) { Debug.Assert(false); return false; }\n\n text = Marshal.PtrToStringUni(ipLocalBuffer, chars);\n\n if (text == \" \") text = String.Empty;\n }\n</code></pre>\n\n<p>Unfortunately in Windows 7 tbButton.dwData is equal 0, so you can't find any association between NotifyIcon and a target process</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34514/"
] |
Is there a way (in C#) to access the systray?
I am not talking about making a notify icon.
I want to iterate through the items in the tray (I would guess through the processes but I don't know how to determine what is actually in the tray and what is just a process) and also represent the items with their icons in my own ui.
|
How do you feel about Win32 interop? I found [C/Win32 code](http://skyscraper.fortunecity.com/gigo/311/winprog/shellico.txt "this C/Win32 code") that might do the trick for you. (Actually, it looks like an interesting problem so I might try to tackle it myself, just not now).
The magic appears to be that he gets a handle to the system tray's window:
```
NotifyWnd = FindWindowEx(SysTray, 0, "TrayNotifyWnd", 0);
```
Then he sets a hook on its message pump:
```
hHook=SetWindowsHookEx(WH_CALLWNDPROC,HOOKPROC(MsgProc),
hInstance,dwExplorerThreadId);
```
Then during the message pump hook callback, he gets a reference to some pointer data about the window:
```
TWDataT* twd=(TWDataT*)GetWindowLong(NotifyWnd,0);
```
The mystery is then his loop:
```
pTWIconDataT p=COMCTL32_332(twd->iconsInfo,i);
```
COMCTL32\_332 is defined with GetProcAddress and points to ordinal 332 of Comctl32.dll - according to my checking with Dependency Viewer, that's [DPA\_GetPtr](http://msdn.microsoft.com/en-us/library/bb775617.aspx "DPA_GetPtr"), which gets data from a dynamic pointer array. I'm not familiar with what's going on behind the scenes there, but it doesn't seem entirely out of the question.
I'm going to play with this a bit myself, but hopefully it's a good place to get you started. :)
|
264,309 |
<p>There is a similar question going around, but it just got the same old answers that people always give about Regex syntax, but that's not the point here, so please try to not knee jerk the same old answers about regex syntax. Try to be a little more original and personal about it this time.</p>
<p>Regex syntax is very VERY compact, almost too compact to be good. Its like code-golfing,
and everyone agrees code-golfing isn't a good thing in production code. However most people accept regex syntax, which seems... contradictory to say the least.</p>
<p>So now some common defenses one is likely to hear include :</p>
<ul>
<li><p><em>Answer</em>: It's compact</p></li>
<li><p><em>Counter</em>: Haven't we all agreed in this day and age that code should be literate and a variable like "client" is better than "c"?</p></li>
<li><p><em>Answer</em>: It's a "domain specific language"</p></li>
<li><p><em>Counter</em>: how about all the very easy to understand, non compact, non cryptic and dare I say pretty domain languages out there like SQL or LINQ?</p></li>
<li><p><em>Answer</em>: Its easy to understand once you know it.</p></li>
<li><p><em>Counter</em>: Most great languages are easy to understand even if you've never used them before. For example anyone could jump into Python very easily even if they had never seen it before. And why do people defend Regex when its such a hard language to look at, but then go on and complain about Lisps parenthesis?</p></li>
</ul>
<p>Ok now everyone try to be original and honest here, don't just pull out the same old rote answers programmers used 20 years ago to design regex. Unless you really believe they are valid propositions in this day and age.</p>
<hr>
<p><strong>Edit:</strong> For the record, I know Regex from years ago, use them frequently even today and might even grok them. However I suddenly had a feeling it was perhaps time to reconsider things I had taken as "truths" about regex, and look at them from a modern standpoint. Mostly because questioning principles is necessary for further development, and because so many newcomers complain vehemently about them, they can't just be flat out right, so I decided to try to step into the shoes of a newcomer and consider what are some good points against regex.</p>
<p>As for being <strong>subjective</strong>, I don't think this is less subjective OR less programmer related than <strong>Programmer Jokes</strong> of the days stuff. On the contrary it is very programmer related.</p>
<p>As for <strong>argumentative</strong>, thats the point of the question. To get good arguments pro and con regex outdated syntax, that can serve newcomers to actually understand more about why regex are what they are, and even better hopefully get some newcomer to come up with a better solution US old minded can't see because we are blinded by the "coolness" of regex.</p>
<hr>
<p><strong>Quote:</strong></p>
<blockquote>
<p>The Perl 5.10 documentation for
regexes has melted down into a heap of
unreadable drivel because so many zany
features have creeped into the syntax
that no-one can write sensible
documentation for it any more.</p>
</blockquote>
<p>You're trying to say regex have become unmaintainable? Well then as good programmers should we consider refactoring them? Maybe cleaning up and trying over as we've done with some many other technologies?</p>
|
[
{
"answer_id": 264314,
"author": "Frederic Morin",
"author_id": 4064,
"author_profile": "https://Stackoverflow.com/users/4064",
"pm_score": 3,
"selected": false,
"text": "<p>Another problem with regex is that there are many flavours of it. .Net regex vs php regex vs other regex, all look alike but don't give the same result (sometimes no result at all).</p>\n"
},
{
"answer_id": 264315,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 5,
"selected": false,
"text": "<p>Look at the other side of the question: how would you design a new syntax that embodies all the features, consistency, conciseness, and robustness as regex, but is more programmer-friendly?</p>\n"
},
{
"answer_id": 264324,
"author": "Aditya Mukherji",
"author_id": 25990,
"author_profile": "https://Stackoverflow.com/users/25990",
"pm_score": 3,
"selected": false,
"text": "<p>it works!!<br>\nif there is a easy-to-read language that has extensions in every major programming language and is well documented and tested and not as compressed as regex, but neither too verbose (verbose = irritating), i would love to know more about it</p>\n"
},
{
"answer_id": 264325,
"author": "Tony Arkles",
"author_id": 13868,
"author_profile": "https://Stackoverflow.com/users/13868",
"pm_score": 4,
"selected": false,
"text": "<p>I'd defend regex syntax because it (roughly) matches the notation that I learned when I took my Algorithms & Machines course. It's an easy way to generate a machine to ingest the specified regular language.</p>\n\n<p>The regex syntax is the way it is because it's really all that you need to fully describe the behaviour you're looking for. </p>\n"
},
{
"answer_id": 264326,
"author": "DGM",
"author_id": 14253,
"author_profile": "https://Stackoverflow.com/users/14253",
"pm_score": 2,
"selected": false,
"text": "<p>Like Adam said, is there anything better? I shudder to think of trying to do a bunch of strcmp operations instead of a good regex. Like any expressive language it is possible to abuse the regex and make very unreadable constructs, but often even a seemingly unreadable regex makes much more sense than the equivalent procedural code to achieve the same thing.</p>\n\n<p>Without the regex, you'd have to write your own routine to parse, backtrack, compare, store indexes, make substitutions, and manage all the results. Regex gives you all that in a very expressive form. I don't like to repeat code, but if I had to code my own parser every time I needed to look for a moderately complex pattern... I don't know what I'd do.</p>\n\n<p>Yes there are different flavors of regex, but most the most popular ones are very similar, and whatever language you are using them in usually has documentation to help you read it.</p>\n"
},
{
"answer_id": 264330,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "<p>You should be looking at regular expressions as high-end power tools (and I mean power tools in the construction industry sense).</p>\n\n<p>If you're building a little work table for your shed, you don't pull out the nail gun, chainsaw and industrial router. You use a saw, some nails and a hammer.</p>\n\n<p>Similarly, you don't build a 30-floor building without a crane in there somewhere.</p>\n\n<p>The idea is to use the right tool for the job <strong>AND</strong> the right tool for your skill level.</p>\n\n<p>If you have to cut down a tree, make sure you know all about kickback before you start up the chainsaw. If you don't, then use a hand saw instead and save yourself a trip to the hospital to re-attach your severed limb.</p>\n\n<p>I use regular expressions the way I use my chainsaw - very carefully. If you're uncomfortable with the tool, don't use it. Once you learn how to use it properly, you'll find it a lot easier to get things done faster.</p>\n"
},
{
"answer_id": 264344,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 4,
"selected": false,
"text": "<p>It's actually a conspiracy perpetuated by the American Association of Retired Programmers against today's young whippersnappers who cut their teeth on Python and Java. We need to maintain a sense of awe and respect for the mystics whose cleverness surmounted the challenges of tiny core memories and arcane languages with 3-character mnemonics ... and <em>liked</em> it. Uphill ... both ways ... in the snow. :-)</p>\n"
},
{
"answer_id": 264347,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 4,
"selected": false,
"text": "<p>Your counter-arguments are specious. Do you know regex syntax, or are you arguing from a point of ignorance? It's an important point to establish your bias.</p>\n\n<ul>\n<li><p>It's not at all like code golfing. I'm not sure of your connection there. Why not complain about pointers or something else using the same argument?</p></li>\n<li><p>Regular expression's compactness has nothing to do with poor variable names. A variable named c could be anything. The regex syntax is neither ambiguous nor vague. It exactly describes its pattern.</p></li>\n<li><p>It's a DSL. So what if it is? Have you ever tried to do complex things in SQL? It's a big mess too. Making the same thing require more typing and more syntax doesn't improve the situation. Most people I teach have problems with regexes because they are not used to thinking in and designing patterns, not because the syntax is exotic.</p></li>\n<li><p>It's easy to understand once you know it. Well, it is. Power tools are not optimized for newbies or for people unwilling to learn. I don't complain about Lisp parenthesis, but I do not mind the regex syntax.</p></li>\n</ul>\n\n<p>If you don't want to use regular expressions, then don't. Use the string manipulation functions or parsers. Use some other tool. While you're busy with that, I'll be ten problems ahead of you because I'm not swimming against the tide or blaming the tools for the work I can't get done.</p>\n\n<p>It's up to you how much work you want to get done. Find the tool that gets you there the fastest and learn it. If you don't like that, invent something better. Until then, stop complaining.</p>\n"
},
{
"answer_id": 264352,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 2,
"selected": false,
"text": "<p>It's the way it is... mostly for traditional reasons as you pointed out correctly. Now </p>\n\n<ul>\n<li><strong>Retraining and retooling</strong>: it has gained a huge following and the roots have grown too deep for an overhaul even if someone wants to. People have learned the arcane rules and have developed their bag of tricks, communities and tools (I plug Expresso). </li>\n<li><strong>Extensive Support</strong>: The current syntax is widely supported across platforms.. rewriting that level of support is a huge task <em>even if you discount the monumental task of writing your own engine and handling all the fringe cases</em> </li>\n<li><strong>Reg Exp are less likely to change</strong> Finally and most importantly RegExp cannot be equated to code w.r.t. readability. Personally I use a regexp sparingly and for quick incisions, where its advantages outweigh the benefits. (e.g. an internal tool to scrape the customer's Excel spreadsheet into an XML format devised by-for the developer cleanly.) Regexps should not need to be maintained and modified.. if it is very complex.. mask the odor with a comment (and it should only be once). If you find regexp being modified regularly (or if no one else at your workplace knows regexps), it probably was a bad choice and you should switch to regular code.</li>\n</ul>\n\n<p>Personally I find regexps (atleast the section required for routine tasks) easy to pick up.. a day or 2. The advanced stuff is hard (second half of the MasteringRegExp book) but then you don't need it that often either.</p>\n"
},
{
"answer_id": 264384,
"author": "he_the_great",
"author_id": 34435,
"author_profile": "https://Stackoverflow.com/users/34435",
"pm_score": 6,
"selected": true,
"text": "<p>Most of what I have to say were addressed by Adam and DGM, but I don't think they cover your second point very well.</p>\n\n<p>\"how about all the very easy to understand, non compact, non cryptic and dare I say pretty domain languages out there like SQL or LINQ?\"</p>\n\n<p>I think a good way to express an answer to this is to ask, how would you use English to explain a regular expression?</p>\n\n<pre><code><TAG\\b[^>]*>(.*?)</TAG>\n</code></pre>\n\n<p>Look for \"<TAG\" a word boundary zero or more of something that is not '>' followed by a '>' remember zero or more of something, stopping at the first \"</TAG>\"</p>\n\n<p>This is a fairly simple regex. Is the English form really easier to understand? Could you do better?</p>\n\n<p>Regular expressions are hard to read, but what you want from them can be just as hard to explain.</p>\n"
},
{
"answer_id": 264398,
"author": "user21714",
"author_id": 21714,
"author_profile": "https://Stackoverflow.com/users/21714",
"pm_score": 3,
"selected": false,
"text": "<p>Some of the problem with regexes isn't the language itself but what people try to use them for. They will write lines and lines of regexes when what they really want is a fairly simple parser. </p>\n\n<p>Regexes are great for simple to moderately complicated substring matching and data extraction. But at some point of complexity you have just got to whip out the compiler-compiler and write a real parser. I think a lot of people don't realize that regexes are primarily for matching, not for doing parsing.</p>\n"
},
{
"answer_id": 264416,
"author": "AmbroseChapel",
"author_id": 242241,
"author_profile": "https://Stackoverflow.com/users/242241",
"pm_score": 3,
"selected": false,
"text": "<p>I think an SQL-like regular expression language would be a fascinating project. I'd love to see someone create that. </p>\n\n<p>Why <em>not</em> have a language where you can write</p>\n\n<p><code>LOOK FOR \"<TAG\"</code></p>\n\n<p><code>THEN WORDBOUNDARY THEN ZERO-OR-MORE NOT('>') FOLLOWED-BY '>'</code></p>\n\n<p><code>THEN ZERO-OR-MORE SOMETHING REMEMBERED</code></p>\n\n<p><code>THEN NEAREST \"</TAG>\"</code></p>\n\n<p>I'm not sure who's the target audience though -- I don't think I would use it, because I've spent all this time learning regexes.</p>\n\n<p>Surely the set of 'people who need to use an expression as complex as that' pretty much maps to the set of programmers who have to deal with stuff just as complex and more on a daily basis?</p>\n"
},
{
"answer_id": 265553,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 3,
"selected": false,
"text": "<p>The are similar to BNF notation and the like, the basis of many a good language specification. So it makes sense that notation like this would be used in lexers to indicate classes of expected characters. The base symbols really aren't that cryptic. </p>\n\n<p>Then I think there was the UNIX-do-all-you-can-in-a-single-line idea that took over. After improvements in sed and grep scripts, regexes acquired new powers but shorthand denotations for them. Larry Wall incorporated them into Perl as a general tool for parsing text. I'd guess it retained compactness for the oneliners that still were important with perl. And there were shorthand names for common character classes, and even more power was asked and given to regexes. Of course, since Perl was also a language of modules, the regex syntax also worked in blocks of statements and it leveraged syntax that was more widely known. </p>\n\n<p>Their incorporation into Java is really what made people look at them, IMO. Java did nothing to accommodate them. And as a result, expressions with backslashes of moderate difficulty turned into dense jungles of backslashes. Java gave regular expressions a new market if you will, but it their most atrocious form. If you've seen those, and paid no more attention, you might think that the regex is a Thing That Should Not Be.</p>\n\n<p>It's interesting that given a clear enough syntax, for Ambrose's verbose version, somebody could come up with a module for Perl that could take the verbose regex and \"compile\" it into a compact regex that Perl understands, using simpler regexes through <code>overload::constants</code> or possibly a <code>Parse::RecDescent</code> grammar. </p>\n"
},
{
"answer_id": 265581,
"author": "Dave Sherohman",
"author_id": 18914,
"author_profile": "https://Stackoverflow.com/users/18914",
"pm_score": 2,
"selected": false,
"text": "<p>Looking over the similar question which you mentioned and its answers, I saw a few attempts at creating \"friendlier\" alternative syntaxes, from both supporters and detractors of regexes as we know them today.</p>\n\n<p>I found them to be uniformly less readable than equivalent regexes.</p>\n\n<p>Now, granted, I am a regular user of regexes, so I'm sure my comfort with them is a significant part of this. But my primary problem with them was not unfamiliarity, but rather that they quickly grew too large to take in all at once. When your 20-character regex becomes a 10-line-by-30-column pseudo-English expression, it becomes much more difficult to see how the parts of it relate to each other.</p>\n\n<p>Perhaps someone will come up with an alternative syntax to regexes which is universally more readable, even in complex cases, but I submit that such a syntax would inherently require some equivalent to subroutine calls. We don't write 200-line blocks of application code with 15 layers of nested logic because it would be a monumental task just to track the logic of it, never mind figuring out what it actually does. If we're going to explode regexes into a more English-like form, then that same problem will occur and we'll need the same tools to manage it.</p>\n"
},
{
"answer_id": 265631,
"author": "Edward Kmett",
"author_id": 34707,
"author_profile": "https://Stackoverflow.com/users/34707",
"pm_score": 2,
"selected": false,
"text": "<p>A regular expression (at least originally) describes a regular language. Regular languages have very nice theoretical properties in that they both can be described by and describe a deterministic finite automata. DFAs for non-trivial regular expressions are painful to code by hand.</p>\n\n<p>More importantly, regular expression compilers used in the back end of perl, etc. are very good at what they do. It would be very difficult to hand tune competitively performing code.</p>\n\n<p>Finally, their existence is largely a historical artifact. They've been around a long time, picked up mindshare, a lot of people know them. A tool you have and that other people can support is a lot better than a theoretical tool that doesn't yet exist.</p>\n\n<p>If it is just the syntax that turns you off, maybe you should consider looking at parser combinators in Haskell. They can express a superset of the same ideas and have a more explicit syntax.</p>\n"
},
{
"answer_id": 265684,
"author": "Brandon",
"author_id": 28916,
"author_profile": "https://Stackoverflow.com/users/28916",
"pm_score": 3,
"selected": false,
"text": "<p>Pyparsing (<a href=\"http://pyparsing.wikispaces.com/Examples\" rel=\"noreferrer\">http://pyparsing.wikispaces.com/Examples</a>) is a Python library that makes it easy to write regex-like expressions that are highly readable, like these lines that will parse \"Hello, World!\":</p>\n\n<pre><code>from pyparsing import Word, alphas\ngreet = Word( alphas ) + \",\" + Word( alphas ) + \"!\"\ngreet.parseString(\"Hello, World!\")\n</code></pre>\n\n<p>It looks like the library is very close to being able to match the power of regexes (see the examples page mentioned above).</p>\n"
},
{
"answer_id": 267354,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 3,
"selected": false,
"text": "<p>Others have hinted at this but it bears stating explicitly:</p>\n\n<p><em>Regular languages are not like programming languages. They're closer to mathematical notation.</em></p>\n\n<p>The compactness and quirkiness is more a result of attempting to coerce a precise notation out of ASCII characters than a deliberate attempt at brevity or obfuscation.</p>\n"
},
{
"answer_id": 8313294,
"author": "DejanLekic",
"author_id": 876497,
"author_profile": "https://Stackoverflow.com/users/876497",
"pm_score": 0,
"selected": false,
"text": "<p>I bet all participants in this discussion will agree that for certain <strong>small</strong> regex codes one would have to write a long paragraph in English describing what it does. Any kind of language that may be used to do what even the simplest regexp describes will probably do it with N lines of code, where N (probably) grows exponentially in comparison to the length of the regexp itself.</p>\n"
},
{
"answer_id": 10827356,
"author": "Matthew Lock",
"author_id": 74585,
"author_profile": "https://Stackoverflow.com/users/74585",
"pm_score": 2,
"selected": false,
"text": "<p>From the perl module <a href=\"http://search.cpan.org/~chromatic/Regexp-English-1.01/lib/Regexp/English.pm\" rel=\"nofollow\">Regexp::English</a>:</p>\n\n<blockquote>\n <p>Regexp::English provides an alternate regular expression syntax, one that is slightly more verbose than the standard mechanisms. In addition, it adds a few convenient features, like incremental expression building and bound captures.</p>\n</blockquote>\n\n<pre><code> use Regexp::English;\n\n my $re = Regexp::English\n -> start_of_line\n -> literal('Flippers')\n -> literal(':')\n -> optional\n -> whitespace_char\n -> end\n -> remember\n -> multiple\n -> digit;\n\n while (<INPUT>) {\n if (my $match = $re->match($_)) {\n print \"$match\\n\";\n }\n }\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] |
There is a similar question going around, but it just got the same old answers that people always give about Regex syntax, but that's not the point here, so please try to not knee jerk the same old answers about regex syntax. Try to be a little more original and personal about it this time.
Regex syntax is very VERY compact, almost too compact to be good. Its like code-golfing,
and everyone agrees code-golfing isn't a good thing in production code. However most people accept regex syntax, which seems... contradictory to say the least.
So now some common defenses one is likely to hear include :
* *Answer*: It's compact
* *Counter*: Haven't we all agreed in this day and age that code should be literate and a variable like "client" is better than "c"?
* *Answer*: It's a "domain specific language"
* *Counter*: how about all the very easy to understand, non compact, non cryptic and dare I say pretty domain languages out there like SQL or LINQ?
* *Answer*: Its easy to understand once you know it.
* *Counter*: Most great languages are easy to understand even if you've never used them before. For example anyone could jump into Python very easily even if they had never seen it before. And why do people defend Regex when its such a hard language to look at, but then go on and complain about Lisps parenthesis?
Ok now everyone try to be original and honest here, don't just pull out the same old rote answers programmers used 20 years ago to design regex. Unless you really believe they are valid propositions in this day and age.
---
**Edit:** For the record, I know Regex from years ago, use them frequently even today and might even grok them. However I suddenly had a feeling it was perhaps time to reconsider things I had taken as "truths" about regex, and look at them from a modern standpoint. Mostly because questioning principles is necessary for further development, and because so many newcomers complain vehemently about them, they can't just be flat out right, so I decided to try to step into the shoes of a newcomer and consider what are some good points against regex.
As for being **subjective**, I don't think this is less subjective OR less programmer related than **Programmer Jokes** of the days stuff. On the contrary it is very programmer related.
As for **argumentative**, thats the point of the question. To get good arguments pro and con regex outdated syntax, that can serve newcomers to actually understand more about why regex are what they are, and even better hopefully get some newcomer to come up with a better solution US old minded can't see because we are blinded by the "coolness" of regex.
---
**Quote:**
>
> The Perl 5.10 documentation for
> regexes has melted down into a heap of
> unreadable drivel because so many zany
> features have creeped into the syntax
> that no-one can write sensible
> documentation for it any more.
>
>
>
You're trying to say regex have become unmaintainable? Well then as good programmers should we consider refactoring them? Maybe cleaning up and trying over as we've done with some many other technologies?
|
Most of what I have to say were addressed by Adam and DGM, but I don't think they cover your second point very well.
"how about all the very easy to understand, non compact, non cryptic and dare I say pretty domain languages out there like SQL or LINQ?"
I think a good way to express an answer to this is to ask, how would you use English to explain a regular expression?
```
<TAG\b[^>]*>(.*?)</TAG>
```
Look for "<TAG" a word boundary zero or more of something that is not '>' followed by a '>' remember zero or more of something, stopping at the first "</TAG>"
This is a fairly simple regex. Is the English form really easier to understand? Could you do better?
Regular expressions are hard to read, but what you want from them can be just as hard to explain.
|
264,312 |
<p>I'm trying to squeeze some more performance out of my rendering pipeline. The (by far) slowest part is performing a java.awt.imaging.LookupOp on a large image. </p>
<p>The image size is about 2048x2048.</p>
<p>I have figured out that having the filter done along with the drawing operation is much faster than calling the filter method. However this still leaves us with lookup ops that take around 250ms (or 4 fps). Does anyone have any rendering tips?</p>
<p>Heres essentially what we are doing:</p>
<pre><code>public void paint(Graphics g)
{
if(recalcLUT)
{
Graphics2D g2d = (Graphics2D) displayImage.getGraphics();
g2d.drawImage(srcImage, lut, 0, 0);
}
Graphics2D g2d = (Graphics2D) g;
g2d.clearRect(0, 0, this.getWidth(), this.getHeight());
AffineTransform at = new AffineTransform();
at.setToIdentity();
at.scale(scale, scale);
g2d.drawImage(displayImage, at, null);
}
</code></pre>
<p>the lut variable is a LookupOp usually a ShortLookupOp, the image a 16bit grayscale image</p>
<p>Thanks</p>
<p><a href="https://stackoverflow.com/users/27818/ryan-boucher" title="Ryan Bucher">Ryan Bucher:</a></p>
<p>I know there are some other obvious performance optimizations that could be done here. But the major problem is just doing the LookupOp operation so im looking for advice with regard to that.</p>
<p>Lookup Ops are essentially where you create an array and instead of rendering each pixel of the image as its color, you use the color as an index into the array and render the color as the value in the index. In this particular example Im using it to do some simple brightness/contrast operations.
You can also implement this using a rescaleOp which is essentially a way to apply a linear function to the value of all the pixels. But this turns out to be slower.</p>
|
[
{
"answer_id": 272256,
"author": "Ryan Boucher",
"author_id": 27818,
"author_profile": "https://Stackoverflow.com/users/27818",
"pm_score": 1,
"selected": false,
"text": "<p>I've not used java in close to eight years so some of the syntax may be irrelevant.</p>\n\n<p>The key to any kind of performance regarding a loop is to push as many things as possible outside the loop. If you can't then only perform calculations when they change. Often it is better to wait until the last minute to recalculate so that you can cache multiple changes.</p>\n\n<ol>\n<li><p>Move all object construction outside of your render loop. If you know how many objects you need beforehand, then pass them in; if you don't then use a object pool and have the factory create objects outside of the renderloop. This will save you the construction/destruction time.</p></li>\n<li><p>Calculate your AffineTransform only when the scale changes. Push this outside the paint loop and pass it in (as a const reference... do they even exist in Java? I've been in C++ for too long)</p></li>\n<li><p>You may not need to call at.setToIdentity() as your AffineTransform should default to the Identity matrix (check this)</p></li>\n<li><p>Does recalcLUT need to get called every frame? Does it make sense to set recalcLUT to false after executing the if statement?</p></li>\n</ol>\n\n<p>I'm not sure what the goal of the LookupOp is. If you give me a bit more information about what it is doing, I may be able to suggest more.</p>\n\n<p>Hopefully this helps.</p>\n"
},
{
"answer_id": 272413,
"author": "Ryan Boucher",
"author_id": 27818,
"author_profile": "https://Stackoverflow.com/users/27818",
"pm_score": 0,
"selected": false,
"text": "<p>Do you have the ability to push this processing on to the GPU? Multiple hardware pipelines will significantly speed up the processing.</p>\n\n<p>If you can't then you should look into parallelising the LookupOp on the CPU. From what I understand of it each lookup can be done in isolation. Therefore you can spin up multiple threads (how many depends on your CPU Arch and whatever else is going on at the same time) and have each thread do a look up on a portion of the image. You will need a semaphore at the of each update run to wait for all threads to finish.</p>\n\n<p>In either case you should do the following to trade off some memory consumption for every frame that doesn't have a change. Unless your framerate is capped then the more frames you have the more chance that nothing has changed. This will save you doing unnecessary work.</p>\n\n<pre><code>//Has filter or source image changed?\n// yes, recalculate filter and cache\n// no, render cached image\n</code></pre>\n\n<p>Finally, do you have visibility into the implementation of LookupOp? What is it doing, are there any performance enhancements that can be gleaned by writing the implementation yourself (this should be a last resort).</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25920/"
] |
I'm trying to squeeze some more performance out of my rendering pipeline. The (by far) slowest part is performing a java.awt.imaging.LookupOp on a large image.
The image size is about 2048x2048.
I have figured out that having the filter done along with the drawing operation is much faster than calling the filter method. However this still leaves us with lookup ops that take around 250ms (or 4 fps). Does anyone have any rendering tips?
Heres essentially what we are doing:
```
public void paint(Graphics g)
{
if(recalcLUT)
{
Graphics2D g2d = (Graphics2D) displayImage.getGraphics();
g2d.drawImage(srcImage, lut, 0, 0);
}
Graphics2D g2d = (Graphics2D) g;
g2d.clearRect(0, 0, this.getWidth(), this.getHeight());
AffineTransform at = new AffineTransform();
at.setToIdentity();
at.scale(scale, scale);
g2d.drawImage(displayImage, at, null);
}
```
the lut variable is a LookupOp usually a ShortLookupOp, the image a 16bit grayscale image
Thanks
[Ryan Bucher:](https://stackoverflow.com/users/27818/ryan-boucher "Ryan Bucher")
I know there are some other obvious performance optimizations that could be done here. But the major problem is just doing the LookupOp operation so im looking for advice with regard to that.
Lookup Ops are essentially where you create an array and instead of rendering each pixel of the image as its color, you use the color as an index into the array and render the color as the value in the index. In this particular example Im using it to do some simple brightness/contrast operations.
You can also implement this using a rescaleOp which is essentially a way to apply a linear function to the value of all the pixels. But this turns out to be slower.
|
I've not used java in close to eight years so some of the syntax may be irrelevant.
The key to any kind of performance regarding a loop is to push as many things as possible outside the loop. If you can't then only perform calculations when they change. Often it is better to wait until the last minute to recalculate so that you can cache multiple changes.
1. Move all object construction outside of your render loop. If you know how many objects you need beforehand, then pass them in; if you don't then use a object pool and have the factory create objects outside of the renderloop. This will save you the construction/destruction time.
2. Calculate your AffineTransform only when the scale changes. Push this outside the paint loop and pass it in (as a const reference... do they even exist in Java? I've been in C++ for too long)
3. You may not need to call at.setToIdentity() as your AffineTransform should default to the Identity matrix (check this)
4. Does recalcLUT need to get called every frame? Does it make sense to set recalcLUT to false after executing the if statement?
I'm not sure what the goal of the LookupOp is. If you give me a bit more information about what it is doing, I may be able to suggest more.
Hopefully this helps.
|
264,318 |
<p>I am calling an unmanaged C++ dll that expects a char* as one of its parameters and I want to push a byte[] into it. The project is written in VB.NET. </p>
<p>What type of marshalling will work for this?</p>
|
[
{
"answer_id": 264365,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not a .net expert, but I've needed to do something similar recently.</p>\n\n<p>It is not just a matter of serialization, you also have to stop the garbage collector from cleaning up your byte array while it is being used in C++ land...</p>\n\n<p>The below snippet of C# should help.</p>\n\n<pre>// pin the byte[] (byteArray) \nGCHandle handle = GCHandle.Alloc(byteArray, GCHandleType.Pinned); \nIntPtr address = handle.AddrOfPinnedObject(); \n// Do your C++ stuff, using the address pointer.\n\n// Cleanup \nhandle.Free();</pre>\n"
},
{
"answer_id": 264605,
"author": "Chris Thompson",
"author_id": 5982,
"author_profile": "https://Stackoverflow.com/users/5982",
"pm_score": 1,
"selected": false,
"text": "<p>If you need to pin a managed structure in order to pass it as a parameter you can use the following code.</p>\n\n<pre><code> // (c) 2007 Marc Clifton\n /// <summary>\n /// A helper class for pinning a managed structure so that it is suitable for\n /// unmanaged calls. A pinned object will not be collected and will not be moved\n /// by the GC until explicitly freed.\n /// </summary>\n\n internal class PinnedObject<T> : IDisposable where T : struct\n {\n protected T managedObject;\n protected GCHandle handle;\n protected IntPtr ptr;\n protected bool disposed;\n\n public T ManangedObject\n {\n get\n {\n return (T)handle.Target;\n }\n set\n {\n Marshal.StructureToPtr(value, ptr, false);\n }\n }\n\n public IntPtr Pointer\n {\n get { return ptr; }\n }\n\n public int Size\n {\n get { return Marshal.SizeOf(managedObject); }\n }\n\n public PinnedObject()\n {\n managedObject = new T();\n handle = GCHandle.Alloc(managedObject, GCHandleType.Pinned);\n ptr = handle.AddrOfPinnedObject();\n }\n\n ~PinnedObject()\n {\n Dispose();\n }\n\n public void Dispose()\n {\n if (!disposed)\n {\n if (handle.IsAllocated)\n handle.Free();\n ptr = IntPtr.Zero;\n disposed = true;\n }\n }\n }\n}\n</code></pre>\n\n<p>You can then call the unmanaged code using PinnedObject.Pointer. In your extern declaration, use IntPtr as the Type for that parameter.</p>\n\n<pre><code>PinnedObject<BatteryQueryInformation> pinBatteryQueryInfo = new PinnedObject<BatteryQueryInformation>();\npinBatteryQueryInfo.ManangedObject = _structBatteryQueryInfo;\nUnmanaged.Method(pinBatteryQueryInfo.Pointer);\n</code></pre>\n"
},
{
"answer_id": 1775549,
"author": "shf301",
"author_id": 161455,
"author_profile": "https://Stackoverflow.com/users/161455",
"pm_score": 0,
"selected": false,
"text": "<p>In your PInvoke definition just declare the char* parameter as a byte[] and the standard marshaller will handle work.</p>\n\n<p>But this may or may not be the best idea. Is the C++ function expecting a string or is it expecting a buffer of data (C/C++ code often uses char* for a buffer, relying on the fact that a char is one byte)? </p>\n\n<p>If it is a buffer then a byte[] is certainly correct, but if it expects a string then it may be clearer if you declare the parameter as a string (to be explicit) and use Encoding.ASCII.GetString() to convert the byte[] to a string.</p>\n\n<p>Also if it C++ function expects a string and you decide to declare the parameter as a byte[], be sure the byte array ends with a zero, since that is how C/C++ determines the end of the string.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34550/"
] |
I am calling an unmanaged C++ dll that expects a char\* as one of its parameters and I want to push a byte[] into it. The project is written in VB.NET.
What type of marshalling will work for this?
|
If you need to pin a managed structure in order to pass it as a parameter you can use the following code.
```
// (c) 2007 Marc Clifton
/// <summary>
/// A helper class for pinning a managed structure so that it is suitable for
/// unmanaged calls. A pinned object will not be collected and will not be moved
/// by the GC until explicitly freed.
/// </summary>
internal class PinnedObject<T> : IDisposable where T : struct
{
protected T managedObject;
protected GCHandle handle;
protected IntPtr ptr;
protected bool disposed;
public T ManangedObject
{
get
{
return (T)handle.Target;
}
set
{
Marshal.StructureToPtr(value, ptr, false);
}
}
public IntPtr Pointer
{
get { return ptr; }
}
public int Size
{
get { return Marshal.SizeOf(managedObject); }
}
public PinnedObject()
{
managedObject = new T();
handle = GCHandle.Alloc(managedObject, GCHandleType.Pinned);
ptr = handle.AddrOfPinnedObject();
}
~PinnedObject()
{
Dispose();
}
public void Dispose()
{
if (!disposed)
{
if (handle.IsAllocated)
handle.Free();
ptr = IntPtr.Zero;
disposed = true;
}
}
}
}
```
You can then call the unmanaged code using PinnedObject.Pointer. In your extern declaration, use IntPtr as the Type for that parameter.
```
PinnedObject<BatteryQueryInformation> pinBatteryQueryInfo = new PinnedObject<BatteryQueryInformation>();
pinBatteryQueryInfo.ManangedObject = _structBatteryQueryInfo;
Unmanaged.Method(pinBatteryQueryInfo.Pointer);
```
|
264,323 |
<p>Is there a way to delete a folder, lets call it FolderX from an SVN trunk recursively? A quick search on google only tells me how to recursively delete all .svn folders and this is not what I want to do</p>
|
[
{
"answer_id": 264345,
"author": "Dana the Sane",
"author_id": 2567,
"author_profile": "https://Stackoverflow.com/users/2567",
"pm_score": 6,
"selected": true,
"text": "<p>Try something like the following on a posix system:</p>\n\n<pre><code>find ./ -name \"FolderX\" | xargs svn delete --force\n</code></pre>\n\n<p>This will find all matching files/folders starting in the current directory and perform the action on them i.e. svn delete. I'm not sure how to do this in windows though without cygwin.</p>\n\n<p>For win32, the commenter below suggests a similar solution (cmd):</p>\n\n<pre><code>for /R . %1 in (*.EXT) do svn delete %1\n</code></pre>\n"
},
{
"answer_id": 264456,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 3,
"selected": false,
"text": "<p><code>svn delete FolX --force</code> should do the trick even if there are unversioned files in the subtree.</p>\n"
},
{
"answer_id": 3364888,
"author": "harshad",
"author_id": 405937,
"author_profile": "https://Stackoverflow.com/users/405937",
"pm_score": 2,
"selected": false,
"text": "<pre><code>find . -name \".svn\" -exec rm -rf {} \\;\n</code></pre>\n\n<p>Source : <a href=\"http://www.commandlinefu.com/commands/view/902/delete-all-.svn-directories-from-current-path-recursive\" rel=\"nofollow noreferrer\">Recursive SVN delete</a></p>\n"
},
{
"answer_id": 6831794,
"author": "Eduardo Cuomo",
"author_id": 717267,
"author_profile": "https://Stackoverflow.com/users/717267",
"pm_score": 1,
"selected": false,
"text": "<p>I created a SH to run easily as a \"rm\" common.</p>\n\n<ul>\n<li>In \"/usr/bin\" I create \"<strong>rm_svn_dirs</strong>\" file, an put:</li>\n</ul>\n\n<p><code>#!/bin/bash</code></p>\n\n<p><code>if [ $\\# -eq 0 ] ; then</code></p>\n\n<pre><code> echo\n echo \"Path not found\"\n echo \"Use:\"\n echo \" $0 path\"`\n echo \" $0 /var/www/test/svn/website\"\n echo \" $0 .\"\n echo \"Operation cancelled\"\n echo\n exit 1\nfi\n\necho \necho \"Recursively delete .svn directories in:\"\nif [ $1 != \".\" ] ; then\n echo $1\nelse\n pwd\nfi\n\necho\nread -p \"Continue? [Yes/No]: \" x\nif [ \"$x\" != \"Yes\" ] ; then\n echo \"Operation cancelled\"\n echo\n exit 1\nfi\n\nfind $1 -name .svn -exec rm -rf {} \\;\necho \"End!\"\necho\nexit 0`\n</code></pre>\n\n<ul>\n<li><p>Save file, and make it executable:</p>\n\n<p><code>chmod +x rm_svn_dirs</code></p></li>\n<li><p>To use:</p>\n\n<p><code>rm_svn_dirs /var/www/svn/www</code></p>\n\n<p><code>rm_svn_dirs ./svn/www</code></p>\n\n<p><code>rm_svn_dirs .</code></p></li>\n</ul>\n"
},
{
"answer_id": 17990790,
"author": "Manikandan S",
"author_id": 1506356,
"author_profile": "https://Stackoverflow.com/users/1506356",
"pm_score": -1,
"selected": false,
"text": "<p>It's worked well for me</p>\n\n<pre><code>find directory_to_delete/ -type d -name '*.svn' | xargs rm -rf\n</code></pre>\n"
},
{
"answer_id": 32780580,
"author": "Claus-Christian Ude",
"author_id": 5375889,
"author_profile": "https://Stackoverflow.com/users/5375889",
"pm_score": 0,
"selected": false,
"text": "<p>Don't forget to double the %, if you want to use it in an batch-file:</p>\n\n<blockquote>\n <p>for /R . %1 in (*.EXT) do svn delete %1</p>\n</blockquote>\n\n<p>_ </p>\n\n<blockquote>\n <p>for /R . %%1 in (*.EXT) do svn delete %%1</p>\n</blockquote>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17211/"
] |
Is there a way to delete a folder, lets call it FolderX from an SVN trunk recursively? A quick search on google only tells me how to recursively delete all .svn folders and this is not what I want to do
|
Try something like the following on a posix system:
```
find ./ -name "FolderX" | xargs svn delete --force
```
This will find all matching files/folders starting in the current directory and perform the action on them i.e. svn delete. I'm not sure how to do this in windows though without cygwin.
For win32, the commenter below suggests a similar solution (cmd):
```
for /R . %1 in (*.EXT) do svn delete %1
```
|
264,339 |
<p>I'm not sure how to describe this problem, so I think an example is the best way to ask my question:</p>
<p>I have two tables with a manyToMany relationship:</p>
<p>DriversLicence <-> LicenceClass</p>
<p>LicenceClass is things like "Car", "Motorbike", and "Medium Rigid".</p>
<p>Using Hibernate Criteria, how can I find all licences that have both "Car" and "Motorbike" LicenceClasses?</p>
<p>UPDATE 12/11/2008
I have discovered that this can easily be achieved by using a custom ResultTransformer. However the problem is that a result transformer only gets applied AFTER the query returns its results, it does not actually become part of the SQL. So I guess my question is now "Can you do what I initially described in SQL - and is there a Hibernate Criteria analog?"</p>
|
[
{
"answer_id": 264420,
"author": "Nick",
"author_id": 34558,
"author_profile": "https://Stackoverflow.com/users/34558",
"pm_score": 0,
"selected": false,
"text": "<p>You can still use dot notation to work across the relations. For example, assuming you have a DriversLicence.licenceClass property and LicenceClass.type property, then:</p>\n\n<pre><code>session.createCriteria(DriversLicence.class)\n .add(Expression.or(\n Expression.eq(\"licenceClass.type\", \"Car\"),\n Expression.eq(\"licenceClass.type\", \"Motorbike\")\n )\n).list();\n</code></pre>\n\n<p>Personally though, I'd simply avoid using criteria in this case because it's not a dynamic query, but instead use:</p>\n\n<pre><code>session.createQuery(\"from DriversLicence where licenceClass.type in (:types)\")\n .setParameterList(\"types\", myListOfTypes)\n .list();\n</code></pre>\n"
},
{
"answer_id": 271551,
"author": "Adisesha",
"author_id": 11092,
"author_profile": "https://Stackoverflow.com/users/11092",
"pm_score": -1,
"selected": false,
"text": "<p>'I don't think this going to work. I want to find all licences that have <strong>both</strong> \"Car\" and \"Motorbike\" '</p>\n\n<p>User Expression.and(....) instead of Expression.or(....) in the snippet provided by Nick</p>\n"
},
{
"answer_id": 282898,
"author": "Nelson Miranda",
"author_id": 1130097,
"author_profile": "https://Stackoverflow.com/users/1130097",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar issue but fixed up using HQL, I have a class \"Enterprise\" that is related to class \"User\" and also related to class \"Role\", they hay a many to many relationship, when I need all the enterprises related to a specific user I do the following;</p>\n\n<pre><code>Select e from Enterprise As e inner join e.Users As u inner join u.Roles As r \nWhere u.UserCode=?\n</code></pre>\n\n<p>I suppose that in your case you should do something like;</p>\n\n<pre><code>Select dl from LicenceClass As l inner join l.DriversLicences As dl\nWhere \nl.LicenseClass.Name = ? OR \nl.LicenseClass.Name=? OR \nl.LicenseClass.Name=?\n</code></pre>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 313040,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>Here's how I finally achieved it using HQL:</p>\n\n<pre><code>public List<DriversLicence> findDriversLicencesWith(List<LicenceClass> licenceClasses) {\n String hqlString = \"select dl from DriversLicenceImpl dl where 1=1 \";\n for (int i = 0; i < licenceClasses.size(); i++) {\n hqlString += \" and :licenceClass\" + i + \" = some elements(dl.licenceClasses)\";\n }\n\n Query query = getSession().createQuery(hqlString);\n for (int i = 0; i < licenceClasses.size(); i++) {\n query.setParameter(\"licenceClass\" + i, licenceClasses.get(i));\n }\n return query.list();\n}\n</code></pre>\n\n<p>Or using Hibernate Criteria with an sqlRestriction:</p>\n\n<pre><code>for (LicenceClass licenceClass : licenceClasses) { \n criteria.add(Restrictions.sqlRestriction(\"? = some(select \" + LicenceClass.PRIMARY_KEY + \" from \" +\n LICENCE_CLASS_JOIN_TABLE + \" where {alias}.\" +\n DriversLicence.PRIMARY_KEY + \" = \" + DriversLicence.PRIMARY_KEY + \")\",\n licenceClass.getId(), Hibernate.LONG));\n}\n</code></pre>\n\n<p>LICENCE_CLASS_JOIN_TABLE is the name of the table that hibernate generates to support the many-to-many relationship between driversLicence and LicenceClass.</p>\n"
},
{
"answer_id": 39852021,
"author": "Mara B",
"author_id": 6920391,
"author_profile": "https://Stackoverflow.com/users/6920391",
"pm_score": 0,
"selected": false,
"text": "<p>Another option is to chain joins (one join per each LicenseClass). I used criteria builder and predicates like this</p>\n\n<pre><code> List<Predicate> predicates = new ArrayList<>();\n for(Integer lcId : licenceClassIdList) {\n SetJoin<DriversLicence, LicenceClass> dlClasses = dlRoot.join(DriversLicence_.licenceClasses);\n predicates.add(builder.equal(dlClasses.get(LicenseClass_.id), lcId));\n }\n Predicate predicate = builder.and(predicates.toArray(new Predicate[predicates.size()]));\n</code></pre>\n\n<p>Notice dlRoot is object of Root class and you can get it from CriteriaQuery class. Resulted predicate is what are you looking for...</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34553/"
] |
I'm not sure how to describe this problem, so I think an example is the best way to ask my question:
I have two tables with a manyToMany relationship:
DriversLicence <-> LicenceClass
LicenceClass is things like "Car", "Motorbike", and "Medium Rigid".
Using Hibernate Criteria, how can I find all licences that have both "Car" and "Motorbike" LicenceClasses?
UPDATE 12/11/2008
I have discovered that this can easily be achieved by using a custom ResultTransformer. However the problem is that a result transformer only gets applied AFTER the query returns its results, it does not actually become part of the SQL. So I guess my question is now "Can you do what I initially described in SQL - and is there a Hibernate Criteria analog?"
|
Here's how I finally achieved it using HQL:
```
public List<DriversLicence> findDriversLicencesWith(List<LicenceClass> licenceClasses) {
String hqlString = "select dl from DriversLicenceImpl dl where 1=1 ";
for (int i = 0; i < licenceClasses.size(); i++) {
hqlString += " and :licenceClass" + i + " = some elements(dl.licenceClasses)";
}
Query query = getSession().createQuery(hqlString);
for (int i = 0; i < licenceClasses.size(); i++) {
query.setParameter("licenceClass" + i, licenceClasses.get(i));
}
return query.list();
}
```
Or using Hibernate Criteria with an sqlRestriction:
```
for (LicenceClass licenceClass : licenceClasses) {
criteria.add(Restrictions.sqlRestriction("? = some(select " + LicenceClass.PRIMARY_KEY + " from " +
LICENCE_CLASS_JOIN_TABLE + " where {alias}." +
DriversLicence.PRIMARY_KEY + " = " + DriversLicence.PRIMARY_KEY + ")",
licenceClass.getId(), Hibernate.LONG));
}
```
LICENCE\_CLASS\_JOIN\_TABLE is the name of the table that hibernate generates to support the many-to-many relationship between driversLicence and LicenceClass.
|
264,350 |
<p>In traditional embedded programming, we will give a delay function like so:</p>
<pre><code>for(i=0;i<255;i++)
for(j=0;j<255;j++);
</code></pre>
<p>In the microprocessor's view, is this how the sleep() function works?</p>
<p>Is there an alternative for the sleep() function in C?</p>
|
[
{
"answer_id": 264353,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": false,
"text": "<p>The kind of loop you describe is called a \"busy wait\". In real operating systems, sleeping does not cause a busy wait; it tells the operating system to not schedule the process in until the sleep period is over.</p>\n"
},
{
"answer_id": 264359,
"author": "Tony Arkles",
"author_id": 13868,
"author_profile": "https://Stackoverflow.com/users/13868",
"pm_score": 3,
"selected": false,
"text": "<p>You talk about \"embedded programming\" in the OP. If you're doing embedded work and need something like sleep(), there are often hardware counters/timers available. This will vary from architecture to architecture, so have a look at the datasheet.</p>\n\n<p>If you're not doing embedded work, I apologize :)</p>\n"
},
{
"answer_id": 264360,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "<p>If you're using for-loops, you'd better know what they compile to and how long those instructions take at your given clock speed, <strong>and</strong> ensure the CPU runs your instructions and nothing else (this can be done in embedded systems but it's tricky since it disallows interrupts).</p>\n\n<p>Otherwise, you won't be able to tell how long it's really going to take.</p>\n\n<p>Early PC games had this problem - they were built for a 4.7MHz PC and, when the faster computers came along, they were unplayable.</p>\n\n<p>The best way a 'sleep' can work is for the CPU to know what time it is at any given point. Not necessarily the actual time (7:15 am) but at least the relative time (8612 seconds since some point in time).</p>\n\n<p>That way it can apply a delta to the current time and wait in a loop until the current+delta is reached.</p>\n\n<p>Anything that relies on number CPU cycles is inherently unreliable as the CPU may go off to another task and leave your loop hanging.</p>\n\n<p>Let's say you have a memory-mapped 16-bit I/O port which the CPU increments once a second. Let's also assume it's at memory location 0x33 in your embedded system, where ints are also 16 bits. A function called sleep then becomes something like:</p>\n\n<pre><code>void sleep (unsigned int delay) {\n unsigned int target = peek(0x33) + delay;\n while (peek(0x33) != target);\n}\n</code></pre>\n\n<p>You'll have to ensure that peek() returns the memory contents every time (so optimizing compilers don't muck up the logic) and that your while statement runs more than once per second so you don't miss the target, but these are operational issues that don't affect the concept I'm presenting.</p>\n"
},
{
"answer_id": 264363,
"author": "Michael Kohne",
"author_id": 5801,
"author_profile": "https://Stackoverflow.com/users/5801",
"pm_score": 5,
"selected": true,
"text": "<p>Alternatives depend in what you are trying to do and what OS you are on.</p>\n\n<p>If you just want to waste time, then these might help:</p>\n\n<p>On most unix-type systems you'll find a 'usleep' function, which is more or less like sleep with greater resolution. Be careful with that one because it usually can not sleep for just one microsecond.</p>\n\n<p>On some unix-type systems, the select system call can be used with all file descriptor sets zero in order to get a fairly accurate sub-second wait.</p>\n\n<p>On windows systems, you have Sleep, which is pretty much the same, but taking a number of milliseconds. </p>\n\n<p>In a multi-tasking operating system, a sleep function can sometimes be given 0 as a parameter. This generally causes the function to give up it's timeslice, but be re-scheduled immediately if no other task is ready to run.</p>\n"
},
{
"answer_id": 264378,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 5,
"selected": false,
"text": "<p>One common mechanism is to use a <code>select()</code> that is guaranteed to time out, and specify the sleep time as the timeout:</p>\n\n<pre><code>// Sleep for 1.5 sec\nstruct timeval tv;\ntv.tv_sec = 1;\ntv.tv_usec = 500000;\nselect(0, NULL, NULL, NULL, &tv);\n</code></pre>\n\n<p>The <code>select()</code> is typically used to check a set of file descriptors and wait until at least one is ready to perform I/O. If none is ready (or, in this case, if no fds are specified), it will time out.</p>\n\n<p>The advantage of <code>select()</code> over a busy loop is that it consumes very little resources while sleeping, while a busy loop monopolizes the processor as much as permitted by its priority level.</p>\n"
},
{
"answer_id": 264411,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": 1,
"selected": false,
"text": "<p>In a unix-derivative OS, you would probably schedule a signal() call, and your code would simply block the code until the signal is raised. Signals are intended for the purpose, and they are very simple and efficient. </p>\n"
},
{
"answer_id": 264418,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 3,
"selected": false,
"text": "<p>Busy-waiting is for amateurs even in an embedded system, use a real time source.</p>\n"
},
{
"answer_id": 264421,
"author": "bog",
"author_id": 20909,
"author_profile": "https://Stackoverflow.com/users/20909",
"pm_score": 3,
"selected": false,
"text": "<p>There's more information on how sleep() works <a href=\"https://stackoverflow.com/questions/175882/whats-the-algorithm-behind-sleep#176908\">here</a></p>\n\n<p>By the way, busy waiting is not necessarily for amateurs--although it does burn processor that you may want to use for some other purpose. If you are using a time source, you are limited to the granularity of that source. E.G. if you have a 1 ms timer, and want to way 500 uS, you have a problem. If your embedded system can handle the fact that you'll be buzzing in a loop for 500 uSec, that might be acceptable. And even if you have a timer with your desired granularity, you also need to get an interrupt off that timer at the right time...then dispatch ot the interrupt handler...then get to your code. Sometimes a busy loop is the most expedient solution. <strong>Sometimes.</strong></p>\n"
},
{
"answer_id": 264432,
"author": "ididak",
"author_id": 28888,
"author_profile": "https://Stackoverflow.com/users/28888",
"pm_score": 2,
"selected": false,
"text": "<p>sleep actually interfaces with operating system, where sleeping processes are placed outside of scheduling queue. I usually use:</p>\n\n<pre><code>poll(0, 0, milliseconds);\n</code></pre>\n\n<p>for POSIX compliant systems. <code>select</code> also works for windows (they must have a native API (probably called <code>Sleep</code>) for that.)</p>\n"
},
{
"answer_id": 264474,
"author": "Scott Evernden",
"author_id": 11397,
"author_profile": "https://Stackoverflow.com/users/11397",
"pm_score": 3,
"selected": false,
"text": "<p>any decent C compiler would, without extra work, remove your code entirely and the delay would vanish</p>\n"
},
{
"answer_id": 264518,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 4,
"selected": false,
"text": "<p>You would not use the code you published to sleep on an embedded system. A decent compiler would entirely remove it, and even if your compiler does not remove it is suboptimal, since running the processor in a tight loop will burn power, which is an issue for embedded system. Even systems not running on battery care about power usage, since lower power usage means cheaper power supplies and cooling.</p>\n\n<p>The way you normally do this is your CPU will implement some sort of IDLE or SLEEP instructions, that will cause it to temporarily stop processing commands. An external interrupt line connected to a timer circuit will wake the processor back up at regular intervals, and which point the CPU checks to see if it has been asleep for long enough, and if not it goes back to sleep.</p>\n\n<pre><code>//Pseudo code\nint start = getTime();\nint end = start + sleepTime;\n\nwhile (getTime() < end) {\n asm(\"SLEEP\");\n}\n</code></pre>\n\n<p>The exact details vary from processor to processor. If you are running as a process on an OS the sleep call generally just tells the scheduler to suspend your process, and then the kernel decides whether to schedule another process or to sleep the CPU. Also, the above code will not be adequete for real time systems, which want deadline guarantees, etc. In those cases you will need to get the time in the loop, know the duration of the time interrupt so ou know if you can resleep without blowing the deadline, and potentially reprogram the timer hardware or busy wait.</p>\n"
},
{
"answer_id": 8045893,
"author": "Patrick",
"author_id": 1034936,
"author_profile": "https://Stackoverflow.com/users/1034936",
"pm_score": 2,
"selected": false,
"text": "<p>Page 20 in 'Threading in C#' by Joseph Albahari has an interesting discussion of this. You cannot sleep for less than 1 ms in .Net but DateTime.Ticks has a granularity of 100-nanoseconds (= 0.1 microseconds) intervals. For controlling my 5 axis CNC stepper I only need to pause for 10 microseconds between step commands. I have used a micro controller to do the nasty looping but I think it is OK hand over a processor for the job if you have a whole bunch anyway, stop the thread when you can. At least it wont always be the same one.</p>\n"
},
{
"answer_id": 14726433,
"author": "user2046229",
"author_id": 2046229,
"author_profile": "https://Stackoverflow.com/users/2046229",
"pm_score": 0,
"selected": false,
"text": "<p>an attempt... to really solve this issue, i.e. something that works (not like the above attempts of answer) lol</p>\n\n<p>I still have to improve this code to make it out. Few add-ons are welcome.</p>\n\n<pre><code>// Sleep for both Windows and Linux: \n// Too bad? No one proposed you a solution that works? \n// Since Windows has no select.h nor poll.h, an implementation\n// is necessary.\n// \n// Solutions on boards are often refered to use either select or poll, but ok, what about C (not c++)?\n//\n/// implementation of poll is destined in this attempt for windows\n/// Ideally, you add this part of code to the header of you *.c file, and it might work through...\n\n#ifdef WIN32\n#include <time.h>\n#include <sys/time.h>\n#include <ws2tcpip.h>\n#include <Winsock2.h>\n#include <windows.h>\n/* winsock doesn't feature poll(), so there is a version implemented\n * in terms of select() in mingw.c. The following definitions\n * are copied from linux man pages. A poll() macro is defined to\n * call the version in mingw.c.\n */\n#define POLLIN 0x0001 /* There is data to read */\n#define POLLPRI 0x0002 /* There is urgent data to read */\n#define POLLOUT 0x0004 /* Writing now will not block */\n#define POLLERR 0x0008 /* Error condition */\n#define POLLHUP 0x0010 /* Hung up */\n#define POLLNVAL 0x0020 /* Invalid request: fd not open */\nstruct pollfd {\n SOCKET fd; /* file descriptor */\n short events; /* requested events */\n short revents; /* returned events */\n};\n\nint mingw_poll (struct pollfd *, unsigned int, int);\n\n#define poll(x, y, z) mingw_poll(x, y, z)\n#endif\n\n\n\n\n\nint mingw_poll(struct pollfd *fds, unsigned int nfds, int timo)\n{\n struct timeval timeout, *toptr;\n fd_set ifds, ofds, efds, *ip, *op;\n int i, rc;\n\n /* Set up the file-descriptor sets in ifds, ofds and efds. */\n FD_ZERO(&ifds);\n FD_ZERO(&ofds);\n FD_ZERO(&efds);\n for (i = 0, op = ip = 0; i < nfds; ++i) {\n fds[i].revents = 0;\n if(fds[i].events & (POLLIN|POLLPRI)) {\n ip = &ifds;\n FD_SET(fds[i].fd, ip);\n }\n if(fds[i].events & POLLOUT) {\n op = &ofds;\n FD_SET(fds[i].fd, op);\n }\n FD_SET(fds[i].fd, &efds);\n } \n\n /* Set up the timeval structure for the timeout parameter */\n if(timo < 0) {\n toptr = 0;\n } else {\n toptr = &timeout;\n timeout.tv_sec = timo / 1000;\n timeout.tv_usec = (timo - timeout.tv_sec * 1000) * 1000;\n }\n\n#ifdef DEBUG_POLL\n printf(\"Entering select() sec=%ld usec=%ld ip=%lx op=%lx\\n\",\n (long)timeout.tv_sec, (long)timeout.tv_usec, (long)ip, (long)op);\n#endif\n rc = select(0, ip, op, &efds, toptr);\n#ifdef DEBUG_POLL\n printf(\"Exiting select rc=%d\\n\", rc);\n#endif\n\n if(rc <= 0)\n return rc;\n\n if(rc > 0) {\n for (i = 0; i < nfds; ++i) {\n int fd = fds[i].fd;\n if(fds[i].events & (POLLIN|POLLPRI) && FD_ISSET(fd, &ifds))\n fds[i].revents |= POLLIN;\n if(fds[i].events & POLLOUT && FD_ISSET(fd, &ofds))\n fds[i].revents |= POLLOUT;\n if(FD_ISSET(fd, &efds))\n /* Some error was detected ... should be some way to know. */\n fds[i].revents |= POLLHUP;\n#ifdef DEBUG_POLL\n printf(\"%d %d %d revent = %x\\n\", \n FD_ISSET(fd, &ifds), FD_ISSET(fd, &ofds), FD_ISSET(fd, &efds), \n fds[i].revents\n );\n#endif\n }\n }\n return rc;\n}\n</code></pre>\n"
},
{
"answer_id": 28370606,
"author": "Rosana Aira",
"author_id": 4538058,
"author_profile": "https://Stackoverflow.com/users/4538058",
"pm_score": 0,
"selected": false,
"text": "<p>I found the function in this post (<a href=\"http://cboard.cprogramming.com/c-programming/111229-how-use-sleep-function.html\" rel=\"nofollow\">http://cboard.cprogramming.com/c-programming/111229-how-use-sleep-function.html</a>) and it works:</p>\n\n<pre><code>#include <stdio.h>\n#include <windows.h>\n\nint main()\n{\n puts(\"Hello \\n\");\n /* in windows.h is declared the Sleep (upper S) function and it takes time in \nmiliseconds */\n Sleep(3000);\n puts(\"World \\n\");\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 31411723,
"author": "Oskar Dahlberg",
"author_id": 4858189,
"author_profile": "https://Stackoverflow.com/users/4858189",
"pm_score": 2,
"selected": false,
"text": "<pre><code>#include <Windows.h>\n\nstatic NTSTATUS(__stdcall *NtDelayExecution)(BOOL Alertable, PLARGE_INTEGER DelayInterval) = (NTSTATUS(__stdcall*)(BOOL, PLARGE_INTEGER)) GetProcAddress(GetModuleHandle(\"ntdll.dll\"), \"NtDelayExecution\");\n\nstatic NTSTATUS(__stdcall *ZwSetTimerResolution)(IN ULONG RequestedResolution, IN BOOLEAN Set, OUT PULONG ActualResolution) = (NTSTATUS(__stdcall*)(ULONG, BOOLEAN, PULONG)) GetProcAddress(GetModuleHandle(\"ntdll.dll\"), \"ZwSetTimerResolution\");\n\n\n\n\nstatic void SleepShort(float milliseconds) {\n static bool once = true;\n if (once) {\n ULONG actualResolution;\n ZwSetTimerResolution(1, true, &actualResolution);\n once = false;\n }\n\n LARGE_INTEGER interval;\n interval.QuadPart = -1 * (int)(milliseconds * 10000.0f);\n NtDelayExecution(false, &interval);\n}\n</code></pre>\n"
},
{
"answer_id": 38678846,
"author": "David Nissman",
"author_id": 6658671,
"author_profile": "https://Stackoverflow.com/users/6658671",
"pm_score": 2,
"selected": false,
"text": "<p>available in linux\nusleep( int microseconds )\nnanosleep( ... ) more precision see man pages for calling arguments</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31116/"
] |
In traditional embedded programming, we will give a delay function like so:
```
for(i=0;i<255;i++)
for(j=0;j<255;j++);
```
In the microprocessor's view, is this how the sleep() function works?
Is there an alternative for the sleep() function in C?
|
Alternatives depend in what you are trying to do and what OS you are on.
If you just want to waste time, then these might help:
On most unix-type systems you'll find a 'usleep' function, which is more or less like sleep with greater resolution. Be careful with that one because it usually can not sleep for just one microsecond.
On some unix-type systems, the select system call can be used with all file descriptor sets zero in order to get a fairly accurate sub-second wait.
On windows systems, you have Sleep, which is pretty much the same, but taking a number of milliseconds.
In a multi-tasking operating system, a sleep function can sometimes be given 0 as a parameter. This generally causes the function to give up it's timeslice, but be re-scheduled immediately if no other task is ready to run.
|
264,358 |
<p>let us have a situation in which the following program prints some 10 lines of #</p>
<pre><code>for(i=0;i<10;i++)
prinf("\n#");
</code></pre>
<p>now how to go back to 5 th line and edit that # and change the color of it without clearing the screen or clearing the below 5 lines?
<p>I have tried </p>
<pre><code>window(5,0,20,20);
textcolor(GREEN);
cprintf("#");
</code></pre>
<p>but it is not editing that one but it is printing on the side of the original one.why?
<p>is there any other way of doing it and changing the color of the already printed text dynamically?
please help me..my environment is turbo c on windows</p>
|
[
{
"answer_id": 264371,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 0,
"selected": false,
"text": "<p>maybe- </p>\n\n<pre><code>cprintf(\"\\b#\");\n</code></pre>\n\n<p>'b' is for backspace</p>\n"
},
{
"answer_id": 264388,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 1,
"selected": false,
"text": "<p><code>-1:</code> Some tips for posting homework questions:</p>\n\n<p>1) Get the question right! The posted code does not perform as the description states:</p>\n\n<pre><code> for(i=0;i<10;i++)\n prinf(\"#\");\n</code></pre>\n\n<p>This will print 10 <code>#</code> characters on one line, as there is no end-of-line character. The original description talks about \"printing 10 lines.\"</p>\n\n<p>2) Give necessary details: What environment are you using: Windows? Linux? What compiler? Is this a windowed or text-based environment?</p>\n\n<p>3) STFW before posting. Look for \"ANSI Escape Sequences\" or \"positioning the cursor.\"</p>\n"
},
{
"answer_id": 264492,
"author": "Raymond Martineau",
"author_id": 33952,
"author_profile": "https://Stackoverflow.com/users/33952",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like you are mixing printf and another output library - this isn't recommended. Printf expects to be sent to a character terminal, while the output library in question may falsly assume that it has exclusive access (and might misbehave.)</p>\n\n<p>Based on one function, you're likely using conio.h. The documentation can be found <a href=\"http://poli.cs.vsb.cz/c/help/conio.htm\" rel=\"nofollow noreferrer\">here</a>, with a table of contents showing each available function. From that index, you should be able to spot the function instantly. </p>\n\n<p>The window function doesn't do what you want it to, since it only sets the area in which the cursor may change text - it doesn't move the cursor, you need to use the other library functions. </p>\n"
},
{
"answer_id": 283361,
"author": "user36834",
"author_id": 36834,
"author_profile": "https://Stackoverflow.com/users/36834",
"pm_score": 2,
"selected": true,
"text": "<p><p>window function will generally create a window from the 1st two coordinates pixel i.e, in your example (5,0) to the pixel pointed by next 2 coordinates. so your program should work <p>try it out or else use gotoxy()</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31116/"
] |
let us have a situation in which the following program prints some 10 lines of #
```
for(i=0;i<10;i++)
prinf("\n#");
```
now how to go back to 5 th line and edit that # and change the color of it without clearing the screen or clearing the below 5 lines?
I have tried
```
window(5,0,20,20);
textcolor(GREEN);
cprintf("#");
```
but it is not editing that one but it is printing on the side of the original one.why?
is there any other way of doing it and changing the color of the already printed text dynamically?
please help me..my environment is turbo c on windows
|
window function will generally create a window from the 1st two coordinates pixel i.e, in your example (5,0) to the pixel pointed by next 2 coordinates. so your program should work try it out or else use gotoxy()
|
264,381 |
<p>I'm doing some searching of tags, and some users like "cat" while others like "Cat" Go figure...</p>
<p>Anyways, is there a way to force a particular find to be case sensitive? Such as:</p>
<pre><code>Tag.find(:some-special-option-here)
</code></pre>
<p>Any ideas?</p>
|
[
{
"answer_id": 264389,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>In the mysql database, set your text's data type to utf_collate_bin. For example:</p>\n\n<pre><code>ALTER TABLE `sets` CHANGE `set_name` `set_name` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL\n</code></pre>\n\n<p>Where 'sets' is the table, 'set_name' is the column of type VARCHAR(64). You can also do this in PhpMyAdmin..</p>\n\n<p>Any binary collate will do the job; but utf8 is preferable.</p>\n\n<p>If you were wondering what the _ci at the end of your current collate is, it means \"Case Insensitive\" :p</p>\n"
},
{
"answer_id": 264645,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 6,
"selected": true,
"text": "<p>You can also do a case-sensitive search without changing your column properties. </p>\n\n<pre><code>SELECT * FROM mytable WHERE myfield='Value' \n</code></pre>\n\n<p>This query matches:</p>\n\n<ul>\n<li>Value</li>\n<li>value</li>\n<li>VALUE</li>\n<li>vAlUe</li>\n<li><em>and so on</em></li>\n</ul>\n\n<p>While...</p>\n\n<pre><code>SELECT * FROM mytable WHERE BINARY myfield='Value'\n</code></pre>\n\n<p>Matches only:</p>\n\n<ul>\n<li>Value</li>\n</ul>\n"
},
{
"answer_id": 458544,
"author": "Paul Grayson",
"author_id": 56777,
"author_profile": "https://Stackoverflow.com/users/56777",
"pm_score": 2,
"selected": false,
"text": "<p>You can make all strings case sensitive when you create the table by adding \"COLLATE utf8_bin\" to the :options string when creating the table. For example:</p>\n\n<pre><code>create_table( \"page_infos\", :force => true, :options => \"ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_bin\") do |t|\n t.string \"title\", :limit => 120\nend\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19964/"
] |
I'm doing some searching of tags, and some users like "cat" while others like "Cat" Go figure...
Anyways, is there a way to force a particular find to be case sensitive? Such as:
```
Tag.find(:some-special-option-here)
```
Any ideas?
|
You can also do a case-sensitive search without changing your column properties.
```
SELECT * FROM mytable WHERE myfield='Value'
```
This query matches:
* Value
* value
* VALUE
* vAlUe
* *and so on*
While...
```
SELECT * FROM mytable WHERE BINARY myfield='Value'
```
Matches only:
* Value
|
264,395 |
<p>I've found the "open" command in Mac OS X very handy in the command line. From "man open":</p>
<blockquote>
<p>The <code>open</code> command opens a file (or a directory or URL), just as if you had
double-clicked the file's icon. If no application name is specified, the
default application as determined via LaunchServices is used to open the
specified files.</p>
</blockquote>
<p>That is, if I want to open a PDF file with the default PDF viewer (happens to be Preview), I only need to do:</p>
<pre><code>open my.pdf
</code></pre>
<p>In Linux, however, to open a PDF file from the command line, I had to dig around to find the default PDF viewer is, for instance, "evince" (who'd have guessed??), and then</p>
<pre><code>evince my.pdf
</code></pre>
<p>So, is there a simple equivalent of the 'open' command in the Linux command line?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 264401,
"author": "number5",
"author_id": 29489,
"author_profile": "https://Stackoverflow.com/users/29489",
"pm_score": 9,
"selected": true,
"text": "<p>You could try <code>xdg-open</code>, most Linux distros have it. It will open default associated app for your file.</p>\n\n<p>FYI <a href=\"https://portland.freedesktop.org/doc/xdg-open.html\" rel=\"noreferrer\">https://portland.freedesktop.org/doc/xdg-open.html</a></p>\n"
},
{
"answer_id": 264423,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 2,
"selected": false,
"text": "<p>gnome-open</p>\n"
},
{
"answer_id": 264467,
"author": "Jeremy Visser",
"author_id": 10839,
"author_profile": "https://Stackoverflow.com/users/10839",
"pm_score": 6,
"selected": false,
"text": "<p>The equivalent you are looking for is <a href=\"http://portland.freedesktop.org/xdg-utils-1.0/xdg-open.html\" rel=\"noreferrer\"><code>xdg-open</code></a>, which can be used in the same way as OS X's <code>open</code> command. For example:</p>\n\n<pre><code>xdg-open ~/Documents/Chubby_Bubbies.odt\n</code></pre>\n\n<p>However, this is really hard to type quickly and accurately. Instead, you should make an alias to xdg-open, which makes the process much quicker.</p>\n\n<p>Of course, you can alias it to <code>open</code> to make it match OS X (you can pick anything you want), but personally, I use the right square bracket (<code>]</code>) for my shortcut for speed reasons. To use this, add the following to your <code>.bashrc</code> file:</p>\n\n<pre><code>alias ']'='xdg-open'\n</code></pre>\n\n<p>Then, to open any resource, use it like any of these examples:</p>\n\n<pre><code>] www.google.com\n] file.txt\n] ~/Pictures\n] ssh://myserver.local/home/jeremy\n</code></pre>\n\n<p>Also this lets you open a file browser (e.g. Nautilus) in the current directory:</p>\n\n<pre><code>] .\n</code></pre>\n\n<p>From experience I have found that one-letter aliases work best for the above shortcut. After all, the goal is efficiency. And you can go back and make the same alias on OS X — I leave that as an exercise to the reader. :-)</p>\n"
},
{
"answer_id": 264954,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 4,
"selected": false,
"text": "<p>Traditionally, you can use the \"see\" command. Which just uses run-mailcap. This will work without Gnome and X etc.</p>\n\n<pre><code>man see\n</code></pre>\n"
},
{
"answer_id": 9909794,
"author": "Anake",
"author_id": 299000,
"author_profile": "https://Stackoverflow.com/users/299000",
"pm_score": 4,
"selected": false,
"text": "<p>I just sorted this out myself so thought I would write down how I did it, which is specifically relevant to what Suan asked.\nThese steps allow you just type \"open \" and not your terminal covered in messages you don't need:</p>\n\n<p>Create a script called <code>open</code> in <code>~/bin</code>, the content is just:</p>\n\n<pre><code>xdg-open \"$1\" &> /dev/null &\n</code></pre>\n\n<p>Save and close the script, then type \"source .profile\" (or .bash_profile if relevant).\nThats it so typing \"open Music\" will open your music folder in the nautilus GUI and shouldn't enter anything onto your terminal.</p>\n"
},
{
"answer_id": 12700860,
"author": "WonderLi",
"author_id": 493951,
"author_profile": "https://Stackoverflow.com/users/493951",
"pm_score": -1,
"selected": false,
"text": "<p>Under Gnome Desktop environment, I use the following command:</p>\n\n<pre><code>nautilus `pwd` &\n</code></pre>\n\n<p>This is similar as \"open .\" command in Mac</p>\n"
},
{
"answer_id": 18020765,
"author": "stacksia",
"author_id": 1457221,
"author_profile": "https://Stackoverflow.com/users/1457221",
"pm_score": 2,
"selected": false,
"text": "<p>If you have your mimes setup correctly, you can use <code>mimeopen</code>. Check out its man page, since it has some useful options. </p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I've found the "open" command in Mac OS X very handy in the command line. From "man open":
>
> The `open` command opens a file (or a directory or URL), just as if you had
> double-clicked the file's icon. If no application name is specified, the
> default application as determined via LaunchServices is used to open the
> specified files.
>
>
>
That is, if I want to open a PDF file with the default PDF viewer (happens to be Preview), I only need to do:
```
open my.pdf
```
In Linux, however, to open a PDF file from the command line, I had to dig around to find the default PDF viewer is, for instance, "evince" (who'd have guessed??), and then
```
evince my.pdf
```
So, is there a simple equivalent of the 'open' command in the Linux command line?
Thanks!
|
You could try `xdg-open`, most Linux distros have it. It will open default associated app for your file.
FYI <https://portland.freedesktop.org/doc/xdg-open.html>
|
264,400 |
<p>I am trying to do the following in ASP.NET 3.5. Basically, I am binding a LINQDataSource to a DataList. There is a property called "Deleted" and if it is true, I want to display different markup. The following code throws errors:</p>
<pre><code><asp:DataList runat="server">
<ItemTemplate>
<% If CBool(Eval("Deleted")) Then%>
...
<% Else%>
...
<% End If%>
</ItemTemplate>
</asp:DataList>
</code></pre>
<p>Is this possible? If not, what are the alternatives?</p>
|
[
{
"answer_id": 264427,
"author": "Ta01",
"author_id": 7280,
"author_profile": "https://Stackoverflow.com/users/7280",
"pm_score": 2,
"selected": true,
"text": "<p>Why not just use the RowDataBound event and check the value of your fields then? RowDatabound is ideal for these situations where you want to alter data in a gridview based on values in the result set.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx\" rel=\"nofollow noreferrer\">RowDataBound Event from MSDN</a></p>\n"
},
{
"answer_id": 264431,
"author": "Ta01",
"author_id": 7280,
"author_profile": "https://Stackoverflow.com/users/7280",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps use the ItemDataBound event of a datalist. For gridview's its the rowdatabound event that is ideal for altering display of values based on other values in the result set.\n<a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.itemdatabound.aspx\" rel=\"nofollow noreferrer\">ItemDataBound event</a></p>\n\n<p>So basically on itemdatabound you can play around with your conditionals. Again, this is an educated guess since I've typically done this with the RowDataBound event on gridview's.</p>\n"
},
{
"answer_id": 264445,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 3,
"selected": false,
"text": "<p>One option as a work-around would be to utilise a panel.</p>\n\n<pre><code><asp:DataList runat=\"server\">\n <ItemTemplate>\n <asp:Panel Visible=\"<%# Eval(\"Deleted\") %>\">\n ...(deleted content here)...\n </asp:Panel>\n <asp:Panel Visible=\"<%# Not Eval(\"Deleted\") %>\">\n ...(other content here)...\n </asp:Panel>\n </ItemTemplate>\n</asp:DataList>\n</code></pre>\n"
},
{
"answer_id": 1110783,
"author": "Ben Griswold",
"author_id": 4115,
"author_profile": "https://Stackoverflow.com/users/4115",
"pm_score": 4,
"selected": false,
"text": "<p>I might suggest keeping the code-front lean and writing out the desired text via a function result:</p>\n\n<pre><code><asp:DataList runat=\"server\">\n <ItemTemplate>\n <%# GetText(Container.DataItem) %>\n </ItemTemplate>\n</asp:DataList>\n</code></pre>\n\n<p>And the code-behind:</p>\n\n<pre><code>protected static string GetText(object dataItem)\n{ \n if (Convert.ToBoolean(DataBinder.Eval(dataItem, \"Deleted\"))\n return \"Deleted\";\n\n return \"Not Deleted\";\n}\n</code></pre>\n\n<p>I hope it helps.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40/"
] |
I am trying to do the following in ASP.NET 3.5. Basically, I am binding a LINQDataSource to a DataList. There is a property called "Deleted" and if it is true, I want to display different markup. The following code throws errors:
```
<asp:DataList runat="server">
<ItemTemplate>
<% If CBool(Eval("Deleted")) Then%>
...
<% Else%>
...
<% End If%>
</ItemTemplate>
</asp:DataList>
```
Is this possible? If not, what are the alternatives?
|
Why not just use the RowDataBound event and check the value of your fields then? RowDatabound is ideal for these situations where you want to alter data in a gridview based on values in the result set.
[RowDataBound Event from MSDN](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx)
|
264,402 |
<p>I have used this in my HTML:</p>
<pre><code><q> Hai How r u </q>
</code></pre>
<p>Which shows the text in quotes, like "Hai How r u", for example.</p>
<p>This is working fine in FF but not in IE 6.0.</p>
<p>Please let me know why this happens, and any solutions you might know of. </p>
<p>I don't want to use the quote (") character in my HTML or a separate css file for this.</p>
|
[
{
"answer_id": 264405,
"author": "Karan",
"author_id": 11110,
"author_profile": "https://Stackoverflow.com/users/11110",
"pm_score": 0,
"selected": false,
"text": "<p>Why don't you just use the <code>\"</code> characters? Unlike <code><b></code> and <code><i></code> which should be replaced by strong and emphasis respectively, as appropriate, the quote tag has a direct match in meaning to the quote character. There should be no need to use <code><q></code>.</p>\n\n<p><strong>Edit</strong>: Thanks for clarifying the question Yan.\nOP: Is there a specific reason you don't want to use the quotes? The stuff I said earlier still holds, but perhaps we can help with the problem preventing you from using quotes.</p>\n\n<p><strong>Edit 2</strong>: :|</p>\n"
},
{
"answer_id": 264410,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": true,
"text": "<p>A List Apart had a whole article devoted to the <code><q></code> tag:<br>\n<a href=\"http://www.alistapart.com/articles/qtag\" rel=\"nofollow noreferrer\">Long Live The Q Tag</a></p>\n\n<p>The summary is to add CSS to <em>remove</em> the quotes from Firefox and other browsers and then manually encode them in yourself. It's a bit of a pain, but at least it levels the playing field and you know that your content will look the same cross-browser.</p>\n\n<p>If you <em>really</em> don't want to have to type the quotes in yourself, then take a look at these articles:</p>\n\n<ul>\n<li><a href=\"http://simon.incutio.com/archive/2003/04/03/fixingQuotesWithJavascript\" rel=\"nofollow noreferrer\">http://simon.incutio.com/archive/2003/04/03/fixingQuotesWithJavascript</a></li>\n<li><a href=\"http://diveintomark.org/archives/2002/05/04/the_q_tag\" rel=\"nofollow noreferrer\">http://diveintomark.org/archives/2002/05/04/the_q_tag</a></li>\n<li><a href=\"http://diveintomark.org/archives/2002/08/14/the_q_tag_revisited\" rel=\"nofollow noreferrer\">http://diveintomark.org/archives/2002/08/14/the_q_tag_revisited</a></li>\n<li><a href=\"http://www.clagnut.com/blog/157/\" rel=\"nofollow noreferrer\">http://www.clagnut.com/blog/157/</a></li>\n</ul>\n"
},
{
"answer_id": 269858,
"author": "soypunk",
"author_id": 26512,
"author_profile": "https://Stackoverflow.com/users/26512",
"pm_score": 2,
"selected": false,
"text": "<p>For what it is worth <code><q></code> is supported in Internet Explorer 8.</p>\n\n<p>There are a lot of problems with <code><q></code> concerning multiple nested <code><q></code> elements (nested quotes) and \"proper\" quoting styles per language. This has hampered both the user-agent support as well as adoption rate.</p>\n\n<p>All is not rosy in Firefox either, if go the CSS generated quotes route, when you an end-user cuts & pastes text with generated characters those characters don't make it to your clipboard. (<a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=12460\" rel=\"nofollow noreferrer\">see mozilla bug 12460</a>)</p>\n\n<p>Looking forward, there was <a href=\"http://lists.w3.org/Archives/Public/public-html/2008Oct/thread.html#msg92\" rel=\"nofollow noreferrer\">an interesting thread in the W3C HTML working group on what HTML 5 should do with <code><q></code> in October of 2008</a>.</p>\n"
},
{
"answer_id": 624495,
"author": "DisgruntledGoat",
"author_id": 37947,
"author_profile": "https://Stackoverflow.com/users/37947",
"pm_score": 0,
"selected": false,
"text": "<p>I guess this isn't really answering the question, but I ignore the fact quotation marks don't render on IE6. I set up a stylesheet with this:</p>\n\n<pre><code>q:before { content: \"\\201c\"; }\nq:after { content: \"\\201d\"; }\n\nq q:before { content: \"\\2018\"; }\nq q:after { content: \"\\2019\"; }\n</code></pre>\n\n<p>This renders <em>curly quotes</em> before and after the <code>q</code> element. Works in IE7 and the proper browsers. If you wanted straight quotes replace <code>201c</code> and <code>201d</code> with <code>0022</code>.</p>\n\n<p>What you can do to workaround the IE6 issue is either Javascript, or apply some different styles to the <code>q</code> tag, eg the following will display them italic and dark grey:</p>\n\n<pre><code>q { font-style: italic; color: #444444; }\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22162/"
] |
I have used this in my HTML:
```
<q> Hai How r u </q>
```
Which shows the text in quotes, like "Hai How r u", for example.
This is working fine in FF but not in IE 6.0.
Please let me know why this happens, and any solutions you might know of.
I don't want to use the quote (") character in my HTML or a separate css file for this.
|
A List Apart had a whole article devoted to the `<q>` tag:
[Long Live The Q Tag](http://www.alistapart.com/articles/qtag)
The summary is to add CSS to *remove* the quotes from Firefox and other browsers and then manually encode them in yourself. It's a bit of a pain, but at least it levels the playing field and you know that your content will look the same cross-browser.
If you *really* don't want to have to type the quotes in yourself, then take a look at these articles:
* <http://simon.incutio.com/archive/2003/04/03/fixingQuotesWithJavascript>
* <http://diveintomark.org/archives/2002/05/04/the_q_tag>
* <http://diveintomark.org/archives/2002/08/14/the_q_tag_revisited>
* <http://www.clagnut.com/blog/157/>
|
264,414 |
<p>I've got a Repeater and its SqlDatasource nested inside a Gridview TemplatedField.<br>
The Repeater's datasource SelectCommand is set using the FormatString of an Eval from the Gridview.<br>
The SelectCommand has a WHERE clause which is to compare a string.<br>
Because I have already used the single and double quotes, I am having trouble delimiting the string in the SQL WHERE clause.</p>
<p><strong>How do I add single quotes inside an Eval FormatString?</strong> </p>
<p>I have tried using '<a href="http://forums.asp.net/p/1116668/1732706.aspx#1732706" rel="noreferrer">Replace</a>'.<br>
I have tried using '<a href="http://www.firstobject.com/dn_markspecialchar.htm" rel="noreferrer">Special Characters</a>' (... WHERE StringField = '{0}' ...) </p>
<p>No luck so far. I appreciate any help you may be able to offer. </p>
<pre><code><asp:GridView ID="GridView1" runat="server" DataSourceID="DataSource1" DataKeyNames="Foo" AutoGenerateColumns="False" AllowSorting="true" >
<Columns>
<asp:BoundField DataField="Foo" HeaderText="Foo" SortExpression="Foo" />
<asp:BoundField DataField="Bar" HeaderText="Bar" SortExpression="Bar" />
<asp:TemplateField>
<ItemTemplate>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="DataSourceNested">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Blah") %>'></asp:Label>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="DataSourceNested" runat="server" DataFile="~/App_Data/DatabaseName"
SelectCommand='<%# Eval("Bar", "SELECT Blah FROM TableName WHERE (StringField = {0})") %>' >
</asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</code></pre>
|
[
{
"answer_id": 264426,
"author": "Ty.",
"author_id": 16948,
"author_profile": "https://Stackoverflow.com/users/16948",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried escaping the single quote characters?</p>\n\n<pre><code>... WHERE (StringField = \\'{0}\\') ...\n</code></pre>\n"
},
{
"answer_id": 264443,
"author": "Keltex",
"author_id": 28260,
"author_profile": "https://Stackoverflow.com/users/28260",
"pm_score": 2,
"selected": false,
"text": "<p>Why don't you define this WHERE clause as a const in your codebehind. Define:</p>\n\n<pre><code>protected const string SELECTCLAUSE = \n\"SELECT Blah FROM TableName WHERE (StringField = '{0}')\";\n</code></pre>\n\n<p>Then your SelectCommand property would be:</p>\n\n<pre><code>SelectCommand='<%# Eval(\"Bar\", SELECTCLAUSE ) %>'\n</code></pre>\n"
},
{
"answer_id": 264451,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 5,
"selected": true,
"text": "<p>Don't forget that a .aspx page is simply XML. You just escape the quotes as you normally would.</p>\n\n<p>For example:</p>\n\n<pre><code><asp:Repeater ID=\"repeatTheLabel\" runat=\"server\">\n <ItemTemplate>\n <asp:Label ID=\"Label1\" Text=\"<%# Eval(&quot;Id&quot;, &quot;This is item '{0}'.&quot;) %>\" runat=\"server\" />\n </ItemTemplate>\n <SeparatorTemplate>\n <br />\n </SeparatorTemplate>\n</asp:Repeater>\n</code></pre>\n\n<p>When the above expression is databound the value between <code><%#</code> and <code>%></code> becomes:</p>\n\n<blockquote>\n <p><code>Eval(\"Id\", \"This is item '{0}'.\")</code></p>\n</blockquote>\n\n<p>...which produces on the HTML page as output when databound with an array of objects with \"Id\" property values from 1 to 5:</p>\n\n<blockquote>\n <p>This is item '1'.<br />\n This is item '2'.<br />\n This is item '3'.<br />\n This is item '4'.<br />\n This is item '5'.</p>\n</blockquote>\n"
},
{
"answer_id": 264594,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 2,
"selected": false,
"text": "<p>Store your sql queries in properties in your Page class. Not only does it work :-) but it makes your code easier to read and maintain.</p>\n\n<p>Oh, and you should use parameters in your queries instead of doing string replacements. That will solve the problem by removing the need for single quotes.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/242/"
] |
I've got a Repeater and its SqlDatasource nested inside a Gridview TemplatedField.
The Repeater's datasource SelectCommand is set using the FormatString of an Eval from the Gridview.
The SelectCommand has a WHERE clause which is to compare a string.
Because I have already used the single and double quotes, I am having trouble delimiting the string in the SQL WHERE clause.
**How do I add single quotes inside an Eval FormatString?**
I have tried using '[Replace](http://forums.asp.net/p/1116668/1732706.aspx#1732706)'.
I have tried using '[Special Characters](http://www.firstobject.com/dn_markspecialchar.htm)' (... WHERE StringField = '{0}' ...)
No luck so far. I appreciate any help you may be able to offer.
```
<asp:GridView ID="GridView1" runat="server" DataSourceID="DataSource1" DataKeyNames="Foo" AutoGenerateColumns="False" AllowSorting="true" >
<Columns>
<asp:BoundField DataField="Foo" HeaderText="Foo" SortExpression="Foo" />
<asp:BoundField DataField="Bar" HeaderText="Bar" SortExpression="Bar" />
<asp:TemplateField>
<ItemTemplate>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="DataSourceNested">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Blah") %>'></asp:Label>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="DataSourceNested" runat="server" DataFile="~/App_Data/DatabaseName"
SelectCommand='<%# Eval("Bar", "SELECT Blah FROM TableName WHERE (StringField = {0})") %>' >
</asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
```
|
Don't forget that a .aspx page is simply XML. You just escape the quotes as you normally would.
For example:
```
<asp:Repeater ID="repeatTheLabel" runat="server">
<ItemTemplate>
<asp:Label ID="Label1" Text="<%# Eval("Id", "This is item '{0}'.") %>" runat="server" />
</ItemTemplate>
<SeparatorTemplate>
<br />
</SeparatorTemplate>
</asp:Repeater>
```
When the above expression is databound the value between `<%#` and `%>` becomes:
>
> `Eval("Id", "This is item '{0}'.")`
>
>
>
...which produces on the HTML page as output when databound with an array of objects with "Id" property values from 1 to 5:
>
> This is item '1'.
>
> This is item '2'.
>
> This is item '3'.
>
> This is item '4'.
>
> This is item '5'.
>
>
>
|
264,428 |
<p>I am using BSD style pty/tty pairs to implement running a sub shell. When the user exits the sub shell, how do I detect in the master process that this has occurred? I am using select(nfds, &read_fds, NULL, NULL, &timeout); with the master pty file descriptor set in the read_fds on the master side.</p>
|
[
{
"answer_id": 264449,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 2,
"selected": false,
"text": "<p>The subshell is typically created by a <code>fork()</code> of some sort. The PID of the child is returned to the master, which can check (with <code>waitpid()</code>, perhaps) if it's still running.</p>\n"
},
{
"answer_id": 267422,
"author": "Matthew Smith",
"author_id": 20889,
"author_profile": "https://Stackoverflow.com/users/20889",
"pm_score": 3,
"selected": true,
"text": "<p>I've found the answer to this question by examining the telnetd source code found in the GNU inetutils package. In telnetd, they use a SIGCHLD handler like this:</p>\n\n<pre><code>int status;\npid_t pid = waitpid((pid_t)-1, &status, WNOHANG);\nsyslog (LOG_INFO, \"child process %ld exited: %d\",\n (long) pid, WEXITSTATUS(status));\n// do cleanup code\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20889/"
] |
I am using BSD style pty/tty pairs to implement running a sub shell. When the user exits the sub shell, how do I detect in the master process that this has occurred? I am using select(nfds, &read\_fds, NULL, NULL, &timeout); with the master pty file descriptor set in the read\_fds on the master side.
|
I've found the answer to this question by examining the telnetd source code found in the GNU inetutils package. In telnetd, they use a SIGCHLD handler like this:
```
int status;
pid_t pid = waitpid((pid_t)-1, &status, WNOHANG);
syslog (LOG_INFO, "child process %ld exited: %d",
(long) pid, WEXITSTATUS(status));
// do cleanup code
```
|
264,441 |
<pre><code>function array_value_from_key($array,$key)
{
return !empty($array[$key]) ? $array[$key] : null;
}
</code></pre>
<p>The reason I ask is because I have a class function that returns an array.</p>
<p>Instead of having to do</p>
<pre><code>$myArray = myClass::giveMeArray();
$myValue = $myArray[$myKey];
</code></pre>
<p>I'd like to do something along the lines of</p>
<pre><code>$myValue = array_value_from_key(myClass::giveMeArray(),$myKey);
</code></pre>
<p>When an object is returned, you can chain the object such as</p>
<pre><code>$myValue = myClass::giveMeObject()->aValue;
</code></pre>
<p>Voila, nice and clean.. not being able to find what seems to be a simple and trivial function is driving me crazy...</p>
<p>PS.. one more example of how I'd like to use such a function</p>
<pre><code>if(arrayKeyVal(aClass::giveMeArray(),$myKey)) {
do_something();
}
</code></pre>
|
[
{
"answer_id": 264465,
"author": "Jason",
"author_id": 33975,
"author_profile": "https://Stackoverflow.com/users/33975",
"pm_score": 1,
"selected": false,
"text": "<p>I haven't tried it, but:</p>\n\n<pre><code>$myValue = @$myArray[$myKey];\n</code></pre>\n\n<p>might work, though i honestly think you would be better off using</p>\n\n<pre><code>$myValue = (array_key_exists($myKey, $myArray)) ? $myArray[$myKey] : null;\n</code></pre>\n"
},
{
"answer_id": 264493,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": -1,
"selected": false,
"text": "<p><strong>EDIT</strong>: turns out I need to brush up on my PHP5. My answer below is incorrect and only applies to PHP4, since PHP5 has <a href=\"http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html\" rel=\"nofollow noreferrer\">method chaining</a>.</p>\n\n<hr>\n\n<p>PHP doesn't allow you to chain together the return statements from functions like in many other languages. eg, in Javascript:</p>\n\n<pre><code>document.getElementById('abc').style.color = \"#fff\";\n</code></pre>\n\n<p>It's a bit of a pain, but that's just how it is. The equivalent which you have to do in PHP is by storing temporary variables. Here's the above as you'd have to write it, if it were PHP: (obviously these aren't real PHP functions)</p>\n\n<pre><code>$myElement = $document->getElementById('abc');\n$myElement->style->color = \"#fff\";\n</code></pre>\n\n<p>One little positive of this is that it makes debugging a wee bit easier.</p>\n\n<p>Note that this only applies to functions: you can \"chain\" properties of objects:</p>\n\n<pre><code>$myObject->myArray[5]->anotherProperty->anotherArray[3]->anotherObject->aFunction();\n</code></pre>\n\n<p>so, in short, if you want to use the result of a function, you have to store it temporarily first</p>\n"
},
{
"answer_id": 264635,
"author": "Dave Marshall",
"author_id": 1248,
"author_profile": "https://Stackoverflow.com/users/1248",
"pm_score": 1,
"selected": false,
"text": "<p>You could return an <a href=\"http://www.php.net/~helly/php/ext/spl/classArrayObject.html\" rel=\"nofollow noreferrer\">ArrayObject</a>, like so.</p>\n\n<pre><code><?\nclass MyClass\n{\n public static function getArray()\n {\n $arr = array('dave' => 1, 'bob' => 2, 'james' => 3);\n return new ArrayObject($arr, ArrayObject::ARRAY_AS_PROPS);\n }\n}\n\n$var = MyClass::getArray()->bob;\n\n?>\n</code></pre>\n"
},
{
"answer_id": 264791,
"author": "Jrgns",
"author_id": 6681,
"author_profile": "https://Stackoverflow.com/users/6681",
"pm_score": -1,
"selected": false,
"text": "<p>Why don't you change the giveMeArray() function like so:</p>\n\n<pre><code>function giveMeArray($key = false) {\n $array = $whatever;\n $toret = null;\n if ($key) {\n if (array_key_exists($key, $array)) {\n $toret = $array[$key];\n }\n } else {\n $toret = $array()\n }\n return $toret;\n}\n</code></pre>\n\n<p>Then you can call it as</p>\n\n<pre><code>$arr = myClass::giveMeArray(); //To get the whole array\n$value = myClass::giveMeArray($myKey); //To get the specific element\n</code></pre>\n"
},
{
"answer_id": 2863054,
"author": "psayre23",
"author_id": 53471,
"author_profile": "https://Stackoverflow.com/users/53471",
"pm_score": 0,
"selected": false,
"text": "<p>$myValue = ($tmp = myClass::giveMeArray() && $tmp[$myKey]) ? $tmp[$myKey] : null;</p>\n\n<p>It's not pretty, but it'll do it all in one line. ;-)</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34561/"
] |
```
function array_value_from_key($array,$key)
{
return !empty($array[$key]) ? $array[$key] : null;
}
```
The reason I ask is because I have a class function that returns an array.
Instead of having to do
```
$myArray = myClass::giveMeArray();
$myValue = $myArray[$myKey];
```
I'd like to do something along the lines of
```
$myValue = array_value_from_key(myClass::giveMeArray(),$myKey);
```
When an object is returned, you can chain the object such as
```
$myValue = myClass::giveMeObject()->aValue;
```
Voila, nice and clean.. not being able to find what seems to be a simple and trivial function is driving me crazy...
PS.. one more example of how I'd like to use such a function
```
if(arrayKeyVal(aClass::giveMeArray(),$myKey)) {
do_something();
}
```
|
I haven't tried it, but:
```
$myValue = @$myArray[$myKey];
```
might work, though i honestly think you would be better off using
```
$myValue = (array_key_exists($myKey, $myArray)) ? $myArray[$myKey] : null;
```
|
264,480 |
<p>My php is weak and I'm trying to change this string:</p>
<pre><code>http://www.example.com/backend.php?/c=crud&m=index&t=care
^
</code></pre>
<p>to be:</p>
<pre><code>http://www.example.com/backend.php?c=crud&m=index&t=care
^
</code></pre>
<p>removing the <code>/</code> after the <code>backend.php?</code>. Any ideas on the best way to do this?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 264485,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 3,
"selected": false,
"text": "<pre><code>$str = preg_replace('/\\?\\//', '?', $str);\n</code></pre>\n\n<p>Edit: See CMS' answer. It's late, I should know better.</p>\n"
},
{
"answer_id": 264490,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 0,
"selected": false,
"text": "<p>While a regexp would suit here just fine, I'll present you with an alternative method. It <em>might</em> be a tad faster than the equivalent regexp, but life's all about choices (...or something).</p>\n\n<pre><code>$length = strlen($urlString);\nfor ($i=0; $i<$length; i++) {\n if ($urlString[$i] === '?') {\n $urlString[$i+1] = '';\n break;\n }\n}\n</code></pre>\n\n<p>Weird, I know.</p>\n"
},
{
"answer_id": 264503,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 8,
"selected": true,
"text": "<p>I think that it's better to use simply <a href=\"http://www.php.net/str_replace\" rel=\"noreferrer\">str_replace</a>, like the manual says:</p>\n\n<blockquote>\n <p>If you don't need fancy replacing\n rules (like regular expressions), you\n should always use this function\n instead of ereg_replace() or\n preg_replace().</p>\n</blockquote>\n\n<pre><code><?\n$badUrl = \"http://www.site.com/backend.php?/c=crud&m=index&t=care\";\n$goodUrl = str_replace('?/', '?', $badUrl);\n</code></pre>\n"
},
{
"answer_id": 264504,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$splitPos = strpos($url, \"?/\");\nif ($splitPos !== false) {\n $url = substr($url, 0, $splitPos) . \"?\" . substr($url, $splitPos + 2);\n}\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34571/"
] |
My php is weak and I'm trying to change this string:
```
http://www.example.com/backend.php?/c=crud&m=index&t=care
^
```
to be:
```
http://www.example.com/backend.php?c=crud&m=index&t=care
^
```
removing the `/` after the `backend.php?`. Any ideas on the best way to do this?
Thanks!
|
I think that it's better to use simply [str\_replace](http://www.php.net/str_replace), like the manual says:
>
> If you don't need fancy replacing
> rules (like regular expressions), you
> should always use this function
> instead of ereg\_replace() or
> preg\_replace().
>
>
>
```
<?
$badUrl = "http://www.site.com/backend.php?/c=crud&m=index&t=care";
$goodUrl = str_replace('?/', '?', $badUrl);
```
|
264,482 |
<p>I am not able to access localhost https pages in firefox3. It gave the error </p>
<blockquote>
<p>'Can't connect securely because the SSL protocol has been disabled.
(Error code: ssl_error_ssl_disabled)'</p>
</blockquote>
<p>I enabled all the SSL2 related preferences through about:config and the error changed to </p>
<blockquote>
<p>'Data Transfer Error
The browser connected successfully, but the connection was interrupted while transferring information. Please try again.'</p>
</blockquote>
<p>The first error seems most likely due to a invalid certificate but can't figure out the second...</p>
|
[
{
"answer_id": 264485,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 3,
"selected": false,
"text": "<pre><code>$str = preg_replace('/\\?\\//', '?', $str);\n</code></pre>\n\n<p>Edit: See CMS' answer. It's late, I should know better.</p>\n"
},
{
"answer_id": 264490,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 0,
"selected": false,
"text": "<p>While a regexp would suit here just fine, I'll present you with an alternative method. It <em>might</em> be a tad faster than the equivalent regexp, but life's all about choices (...or something).</p>\n\n<pre><code>$length = strlen($urlString);\nfor ($i=0; $i<$length; i++) {\n if ($urlString[$i] === '?') {\n $urlString[$i+1] = '';\n break;\n }\n}\n</code></pre>\n\n<p>Weird, I know.</p>\n"
},
{
"answer_id": 264503,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 8,
"selected": true,
"text": "<p>I think that it's better to use simply <a href=\"http://www.php.net/str_replace\" rel=\"noreferrer\">str_replace</a>, like the manual says:</p>\n\n<blockquote>\n <p>If you don't need fancy replacing\n rules (like regular expressions), you\n should always use this function\n instead of ereg_replace() or\n preg_replace().</p>\n</blockquote>\n\n<pre><code><?\n$badUrl = \"http://www.site.com/backend.php?/c=crud&m=index&t=care\";\n$goodUrl = str_replace('?/', '?', $badUrl);\n</code></pre>\n"
},
{
"answer_id": 264504,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$splitPos = strpos($url, \"?/\");\nif ($splitPos !== false) {\n $url = substr($url, 0, $splitPos) . \"?\" . substr($url, $splitPos + 2);\n}\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16488/"
] |
I am not able to access localhost https pages in firefox3. It gave the error
>
> 'Can't connect securely because the SSL protocol has been disabled.
> (Error code: ssl\_error\_ssl\_disabled)'
>
>
>
I enabled all the SSL2 related preferences through about:config and the error changed to
>
> 'Data Transfer Error
> The browser connected successfully, but the connection was interrupted while transferring information. Please try again.'
>
>
>
The first error seems most likely due to a invalid certificate but can't figure out the second...
|
I think that it's better to use simply [str\_replace](http://www.php.net/str_replace), like the manual says:
>
> If you don't need fancy replacing
> rules (like regular expressions), you
> should always use this function
> instead of ereg\_replace() or
> preg\_replace().
>
>
>
```
<?
$badUrl = "http://www.site.com/backend.php?/c=crud&m=index&t=care";
$goodUrl = str_replace('?/', '?', $badUrl);
```
|
264,530 |
<p>I need to find two adjacent repeating digits in a string and replace with a single one. How to do this in Java. Some examples:</p>
<p>123345 should be 12345
77433211 should be 74321</p>
|
[
{
"answer_id": 264543,
"author": "Jake",
"author_id": 24730,
"author_profile": "https://Stackoverflow.com/users/24730",
"pm_score": 0,
"selected": false,
"text": "<p>using a regex:</p>\n\n<pre><code>var myString='123345'\nmyString.replace(/([0-9])\\1/g,'$1')\n</code></pre>\n\n<p>that will match exactly 2 repeats.</p>\n\n<pre><code>'123334'.replace(/([0-9])\\1+/g,'$1')\n</code></pre>\n"
},
{
"answer_id": 264550,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": true,
"text": "<p>Probably a <code>replaceAll(\"(\\\\d)\\\\1+\", \"$1\")</code></p>\n\n<ul>\n<li><code>$</code> plays a special role in a replacing string, designating the first capturing group.</li>\n<li><code>+</code> allows for replacing as many identical number as possible <code>(\\\\d)\\\\1</code> would only replace them by pair: <code>777xx</code> => <code>77xx</code> (thank you <a href=\"https://stackoverflow.com/users/12267/ben-doom\">Ben Doom</a> for the remark)</li>\n</ul>\n\n<p>So:</p>\n\n<pre><code>System.out.println(\"77433211\".replaceAll(\"(\\\\d)\\\\1+\", \"$1\"));\n</code></pre>\n\n<p>will return</p>\n\n<pre><code>74321\n</code></pre>\n\n<hr>\n\n<pre><code>String java.lang.String.replaceAll(String regex, String replacement)\n</code></pre>\n\n<p>Replaces each substring of this string that matches the given regular expression with the given replacement. </p>\n\n<p>An invocation of this method of the form <code>str.replaceAll(regex, repl)</code> yields exactly the same result as the expression </p>\n\n<pre><code>java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl)\n</code></pre>\n\n<hr>\n\n<p><strong>Warning</strong>: <code>String.replaceAll()</code> function does not modify the String on which it is applied. It returns a modified String (or <em>a new String with the same content</em> if the pattern does not match anything)</p>\n\n<p>So you need to affect the result of a <code>replaceAll()</code> call to itself to actually update your String with the regexp changes.</p>\n\n<pre><code>String aString = \"77433211\"\naString = aString.replaceAll(\"(\\\\d)\\\\1+\", \"$1\"));\n</code></pre>\n"
},
{
"answer_id": 264554,
"author": "Drejc",
"author_id": 6482,
"author_profile": "https://Stackoverflow.com/users/6482",
"pm_score": 0,
"selected": false,
"text": "<p>This is a regular expression mathing two repeating digits (x being the digit)</p>\n\n<pre><code>[x]{2}(?!=[x])\n</code></pre>\n"
},
{
"answer_id": 264597,
"author": "ashokgelal",
"author_id": 33203,
"author_profile": "https://Stackoverflow.com/users/33203",
"pm_score": 3,
"selected": false,
"text": "<p>I finally did it myself. Those who are looking for the solution, this is how I did it:</p>\n\n<pre><code>import java.util.regex.*;\n\npublic class RepetingDigits{\n public static void main(String[] args) {\n String word = \"77433211\";\n Pattern pattern = Pattern.compile(\"(\\\\d)\\\\1\");\n Matcher matcher = pattern.matcher(word);\n word = matcher.replaceAll(\"$1\"); \n System.out.println(word);\n }\n}\n</code></pre>\n\n<p>Even simpler:</p>\n\n<pre><code>**word = word.replaceAll(\"(\\\\d)\\\\1\", \"$1\");**\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33203/"
] |
I need to find two adjacent repeating digits in a string and replace with a single one. How to do this in Java. Some examples:
123345 should be 12345
77433211 should be 74321
|
Probably a `replaceAll("(\\d)\\1+", "$1")`
* `$` plays a special role in a replacing string, designating the first capturing group.
* `+` allows for replacing as many identical number as possible `(\\d)\\1` would only replace them by pair: `777xx` => `77xx` (thank you [Ben Doom](https://stackoverflow.com/users/12267/ben-doom) for the remark)
So:
```
System.out.println("77433211".replaceAll("(\\d)\\1+", "$1"));
```
will return
```
74321
```
---
```
String java.lang.String.replaceAll(String regex, String replacement)
```
Replaces each substring of this string that matches the given regular expression with the given replacement.
An invocation of this method of the form `str.replaceAll(regex, repl)` yields exactly the same result as the expression
```
java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl)
```
---
**Warning**: `String.replaceAll()` function does not modify the String on which it is applied. It returns a modified String (or *a new String with the same content* if the pattern does not match anything)
So you need to affect the result of a `replaceAll()` call to itself to actually update your String with the regexp changes.
```
String aString = "77433211"
aString = aString.replaceAll("(\\d)\\1+", "$1"));
```
|
264,541 |
<p>Is there such a thing? </p>
<p>I'm talking about something like a C++ <code>new</code> command i.e. allocation of memory which necessitates explicit releasing of the memory (or risk memory leaks).</p>
<p>I ask because I remember having to solve some GDI leak problems previously by setting forms/controls/other objects to <code>Nothing</code> but can't remember what or why now...</p>
<p>Do we ever have to worry about memory management when developing in VB6?</p>
|
[
{
"answer_id": 264608,
"author": "Martin",
"author_id": 1529,
"author_profile": "https://Stackoverflow.com/users/1529",
"pm_score": 2,
"selected": false,
"text": "<p>I'd like to say you never have to worry about memory management, but it's not quite true. It depends to some extent on the execution environment that your VB6 code is running in. I have certainly seen VB6 classes running under COM+ that would leak memory if they didn't explicitly set object references to Nothing when finished with them.</p>\n\n<p>Environmental issues aside, memory that you allocate within the VB6 type system will generally be cleaned up for you. I'm talking about things you allocate with the New keyword. But there is a significant exception, pointed out by rpetrich and others: -</p>\n\n<p>Because of the reference-counting mechanism that VB uses to manage the lifetime of allocated objects, it is possible to leak memory if you have any cyclic references. For example, A->B->C->A. If you have that kind of scenario you'll probably need to spot it yourself and cure it by explicitly setting references to Nothing. I am not aware of any tools that help much with identifying this kind of problem.</p>\n\n<p>Further problems come in when you're using libraries written in other languages. You might New-up a COM object written in C++ that allocates some memory internally, and find that you have to call a particular method (such as Close) to free that memory. Maybe such a COM object would be badly-written, but plenty of them exist.</p>\n\n<p>So there are no rules to follow, except perhaps: -</p>\n\n<ol>\n<li>Try to know as much as possible about the behaviour of any libraries you use, and</li>\n<li>Always run your code while watching a memory trace in Performance Monitor to make sure its memory usage isn't growing in an unbounded fashion.</li>\n<li>Try to be aware of cyclic references ;-)</li>\n</ol>\n"
},
{
"answer_id": 264621,
"author": "Daniel Kreiseder",
"author_id": 31406,
"author_profile": "https://Stackoverflow.com/users/31406",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, I had simmilar problems with various forms, so I set them explicit to nothing on each unload.</p>\n\n<p>But the problems where mostly with 3rd party controls, seems that sometimes not all COM references where cleared correctly. </p>\n\n<p>Take a look <a href=\"http://www.devx.com/tips/Tip/12285\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 265143,
"author": "RS Conley",
"author_id": 7890,
"author_profile": "https://Stackoverflow.com/users/7890",
"pm_score": 4,
"selected": true,
"text": "<p>There are several areas of concern as far as Memory management in VB6.</p>\n\n<p>The first are circular references where a child class points back to a parent and vice versa. Without explicitly setting the reference to Nothing, This is sometimes true of forms as well especially a dialog that is an editor for a Target object. Again making sure everything set to nothing will solve the problem.</p>\n\n<p>The fundamental principles are 1) If anything pointed to by an object is \"alive\" then it won't be garbage collected. So when you set the reference to the parent object of a circular reference the child is alive so the parent doesn't get garbage collected, since the parent still alive the child doesn't get garbage collected. </p>\n\n<p>The same with forms. If you don't set the Target Property of a dialog that editing an object to nothing than it won't fire the final series of events as long as the Target Object is alive.</p>\n\n<p>The most common side effects of doing this are that your application won't shut down properly and your memory footprint will grow the longer the application is used.</p>\n\n<p>As for GDI leaks, anytime you use an external DLL that uses handles, pointers. You put yourself in the same realm as C++ for those functions. So you have to make sure that you follow all the rules of the particular API or DLLs you are using which often involves explicitly destroying that which you created after you are done with it.</p>\n\n<p>There is an elegant solution for the circular reference problem. Instead of the child referencing a parent directly you use a proxy.</p>\n\n<p>First make a Proxy Class for the parent object.</p>\n\n<pre><code>Option Explicit Public Event GetRef(ByRef RHS As MyObject)\n\nPublic Function GetMyObject() As MyObject\n Dim Ref As MyObject\n RaiseEvent GetRef(Ref)\n Set GetMyObject = Ref\nEnd Function\n</code></pre>\n\n<p>Then define a private variable in the Parent</p>\n\n<pre><code>Private WithEvents MyProxy As MyObjectProxy\n\nPrivate Sub Class_Initialize()\n Set MyProxy = New MyObjectProxy\nEnd Sub\n</code></pre>\n\n<p>Then setup a read only property called Proxy and implement the GetRef event.</p>\n\n<pre><code>Public Property Get Proxy() As MyObjectProxy\n Set Proxy = MyProxy\nEnd Property\n\nPrivate Sub MyProxy_GetRef(RHS As MyObject)\n Set RHS = Me\nEnd Sub\n</code></pre>\n\n<p>For the child or anything else that needs a reference the code is as follows.</p>\n\n<pre><code>Private ParentProxy As MyObjectProxy\n\nPublic Property Get Parent() As MyObject\n If ParentProxy Is Nothing Then\n Set Parent = Nothing\n Else\n Set Parent = ParentProxy.GetRef\n End If\nEnd Property\n\nPublic Property Set Parent(RHS As MyObject)\n If RHS Is Me Then\n Set MyObjectProxy = Nothing\n ElseIf Target Is Nothing Then\n Set MyObjectProxy = Nothing\n Else\n Set MyObjectProxy = RHS.Proxy\n End If\nEnd Property\n</code></pre>\n\n<p>Because the event mechanism doesn't set references or increments the COM reference count on either object it avoids the whole circular reference problem that is the bane of many VB6 programmers.</p>\n\n<p>Note: The source I got it from called it a Proxy but thanks to Anthony's comment I find it also fits the definition of the Mediator Pattern. It uses a specific VB6 Centric feature; the Event API which isn't quite in the spirit of the Mediator Pattern.</p>\n\n<p>Also realize that the .NET framework has equivalents to VB6's Event API although it is implemented differently (delegates, etc)</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4368/"
] |
Is there such a thing?
I'm talking about something like a C++ `new` command i.e. allocation of memory which necessitates explicit releasing of the memory (or risk memory leaks).
I ask because I remember having to solve some GDI leak problems previously by setting forms/controls/other objects to `Nothing` but can't remember what or why now...
Do we ever have to worry about memory management when developing in VB6?
|
There are several areas of concern as far as Memory management in VB6.
The first are circular references where a child class points back to a parent and vice versa. Without explicitly setting the reference to Nothing, This is sometimes true of forms as well especially a dialog that is an editor for a Target object. Again making sure everything set to nothing will solve the problem.
The fundamental principles are 1) If anything pointed to by an object is "alive" then it won't be garbage collected. So when you set the reference to the parent object of a circular reference the child is alive so the parent doesn't get garbage collected, since the parent still alive the child doesn't get garbage collected.
The same with forms. If you don't set the Target Property of a dialog that editing an object to nothing than it won't fire the final series of events as long as the Target Object is alive.
The most common side effects of doing this are that your application won't shut down properly and your memory footprint will grow the longer the application is used.
As for GDI leaks, anytime you use an external DLL that uses handles, pointers. You put yourself in the same realm as C++ for those functions. So you have to make sure that you follow all the rules of the particular API or DLLs you are using which often involves explicitly destroying that which you created after you are done with it.
There is an elegant solution for the circular reference problem. Instead of the child referencing a parent directly you use a proxy.
First make a Proxy Class for the parent object.
```
Option Explicit Public Event GetRef(ByRef RHS As MyObject)
Public Function GetMyObject() As MyObject
Dim Ref As MyObject
RaiseEvent GetRef(Ref)
Set GetMyObject = Ref
End Function
```
Then define a private variable in the Parent
```
Private WithEvents MyProxy As MyObjectProxy
Private Sub Class_Initialize()
Set MyProxy = New MyObjectProxy
End Sub
```
Then setup a read only property called Proxy and implement the GetRef event.
```
Public Property Get Proxy() As MyObjectProxy
Set Proxy = MyProxy
End Property
Private Sub MyProxy_GetRef(RHS As MyObject)
Set RHS = Me
End Sub
```
For the child or anything else that needs a reference the code is as follows.
```
Private ParentProxy As MyObjectProxy
Public Property Get Parent() As MyObject
If ParentProxy Is Nothing Then
Set Parent = Nothing
Else
Set Parent = ParentProxy.GetRef
End If
End Property
Public Property Set Parent(RHS As MyObject)
If RHS Is Me Then
Set MyObjectProxy = Nothing
ElseIf Target Is Nothing Then
Set MyObjectProxy = Nothing
Else
Set MyObjectProxy = RHS.Proxy
End If
End Property
```
Because the event mechanism doesn't set references or increments the COM reference count on either object it avoids the whole circular reference problem that is the bane of many VB6 programmers.
Note: The source I got it from called it a Proxy but thanks to Anthony's comment I find it also fits the definition of the Mediator Pattern. It uses a specific VB6 Centric feature; the Event API which isn't quite in the spirit of the Mediator Pattern.
Also realize that the .NET framework has equivalents to VB6's Event API although it is implemented differently (delegates, etc)
|
264,552 |
<p>I have a big lump of binary data in a char[] array which I need to interpret as an array of packed 6-bit values.</p>
<p>I <em>could</em> sit down and write some code to do this but I'm thinking there has to be a good extant class or function somebody has written already.</p>
<p>What I need is something like:</p>
<pre><code>int get_bits(char* data, unsigned bitOffset, unsigned numBits);
</code></pre>
<p>so I could get the 7th 6-bit character in the data by calling:</p>
<pre><code>const unsigned BITSIZE = 6;
char ch = static_cast<char>(get_bits(data, 7 * BITSIZE, BITSIZE));
</code></pre>
|
[
{
"answer_id": 264574,
"author": "Igor Semenov",
"author_id": 11401,
"author_profile": "https://Stackoverflow.com/users/11401",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.boost.org/doc/libs/release/libs/dynamic_bitset/dynamic_bitset.html\" rel=\"nofollow noreferrer\">Boost.DynamicBitset</a> - try it.</p>\n"
},
{
"answer_id": 264600,
"author": "Marco M.",
"author_id": 28375,
"author_profile": "https://Stackoverflow.com/users/28375",
"pm_score": 1,
"selected": false,
"text": "<p>I think something in the line of the following might work.</p>\n\n<pre><code>int get_bit(char *data, unsigned bitoffset) // returns the n-th bit\n{\n int c = (int)(data[bitoffset >> 3]); // X>>3 is X/8\n int bitmask = 1 << (bitoffset & 7); // X&7 is X%8\n return ((c & bitmask)!=0) ? 1 : 0;\n}\n\nint get_bits(char* data, unsigned bitOffset, unsigned numBits)\n{\n int bits = 0;\n for (int currentbit = bitOffset; currentbit < bitOffset + numBits; currentbit++)\n {\n bits = bits << 1;\n bits = bits | get_bit(data, currentbit);\n }\n return bits;\n}\n</code></pre>\n\n<p>I've not debugged nor tested it, but you can use it as a start point.</p>\n\n<p>Also, take into account bit order. You might want to change </p>\n\n<pre><code> int bitmask = 1 << (bitoffset & 7); // X&7 is X%8\n</code></pre>\n\n<p>to</p>\n\n<pre><code> int bitmask = 1 << (7 - (bitoffset & 7)); // X&7 is X%8\n</code></pre>\n\n<p>depending on how the bit array has been generated.</p>\n"
},
{
"answer_id": 264670,
"author": "user34619",
"author_id": 34619,
"author_profile": "https://Stackoverflow.com/users/34619",
"pm_score": 4,
"selected": true,
"text": "<p>This may not work for sizes greater than 8, depending on endian system. It's basically what Marco posted, though I'm not entirely sure why he'd gather one bit at a time.</p>\n\n<pre><code>int get_bits(char* data, unsigned int bitOffset, unsigned int numBits) {\n numBits = pow(2,numBits) - 1; //this will only work up to 32 bits, of course\n data += bitOffset/8;\n bitOffset %= 8;\n return (*((int*)data) >> bitOffset) & numBits; //little endian\n //return (flip(data[0]) >> bitOffset) & numBits; //big endian\n}\n\n//flips from big to little or vice versa\nint flip(int x) {\n char temp, *t = (char*)&x;\n temp = t[0];\n t[0] = t[3];\n t[3] = temp;\n temp = t[1];\n t[1] = t[2];\n t[2] = temp;\n return x;\n}\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2994/"
] |
I have a big lump of binary data in a char[] array which I need to interpret as an array of packed 6-bit values.
I *could* sit down and write some code to do this but I'm thinking there has to be a good extant class or function somebody has written already.
What I need is something like:
```
int get_bits(char* data, unsigned bitOffset, unsigned numBits);
```
so I could get the 7th 6-bit character in the data by calling:
```
const unsigned BITSIZE = 6;
char ch = static_cast<char>(get_bits(data, 7 * BITSIZE, BITSIZE));
```
|
This may not work for sizes greater than 8, depending on endian system. It's basically what Marco posted, though I'm not entirely sure why he'd gather one bit at a time.
```
int get_bits(char* data, unsigned int bitOffset, unsigned int numBits) {
numBits = pow(2,numBits) - 1; //this will only work up to 32 bits, of course
data += bitOffset/8;
bitOffset %= 8;
return (*((int*)data) >> bitOffset) & numBits; //little endian
//return (flip(data[0]) >> bitOffset) & numBits; //big endian
}
//flips from big to little or vice versa
int flip(int x) {
char temp, *t = (char*)&x;
temp = t[0];
t[0] = t[3];
t[3] = temp;
temp = t[1];
t[1] = t[2];
t[2] = temp;
return x;
}
```
|
264,575 |
<p>Here is my sample code. It is meant to be an iterative procedure for gauss seidel (matrix solver). Essentially when the error is small enough it breaks out of the while loop.</p>
<pre><code>i=1
while (i>0):
x_past = x_present
j=0
while(j<3):
value=0
k=0
while(k<3):
if(k!=j):
if(i==1):
if(k>j):
value=value+0
else:
value=value+x_present[k]*eqn[j][k]
else:
value=value+x_present[k]*eqn[j][k]
else:
value=value+eqn[j][k]
k=k+1
x_present[j:j+1]=[value]
j=j+1
print "X_PAST"
print x_past
print "X_PRESENT"
print x_present
if(error(x_past, x_present)<10**-2):
break;
i=i+1
</code></pre>
<p>I've reduced the code so its more manageable. if you don't understand what its doing its not really that important to solving this problem.</p>
<p>Here is the issue. Everytime </p>
<pre><code>x_present[j:j+1]=[value]
</code></pre>
<p>is run, x_past is made equal to x_present. I don't know why this is the case as the only place i have set x_past equal to x_present is at the top of the loop. If I take away the </p>
<pre><code>x_past=x_present
</code></pre>
<p>sentence, x_past is never made equal to x_present. This leads me to think it is some combination of the two statements that is causing the issue.</p>
<p>This is a big problem cause if x_past = x_present the error = 0 every time and the loop breaks after the first iteration. The code does work, for example if I tell the code to run for 8 iterations and the break it gives me the answer its supposed to.</p>
<p>I've been trying to figure this out for the last 4 hours and am completely stumped. I haven't been working with python long, so my trouble shooting skills syntax wise aren't that great. Any help would be appreciated!!</p>
|
[
{
"answer_id": 264579,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>What are x_past and x_present? I don't know much Python, but from a .NET/Java perspective, if they're references to some data structure (a map or whatever) then making them references to the same object (as you do at the start) will mean that any changes made through one variable will be visible through the other. It sounds like you need to take a copy of the data structure instead of just doing a reference assignment. Does the data structure you're working with have any kind of \"clone\" functionality available?</p>\n\n<p>As I say though, I don't know much Python so this could be totally wrong...</p>\n"
},
{
"answer_id": 264580,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 0,
"selected": false,
"text": "<p>It looks as if x_present is a list. I suspect that this means that the assignment x_last = x_present makes x_last into an alias, i.e. they reference the same variable. Might this be the case?</p>\n"
},
{
"answer_id": 264592,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 6,
"selected": true,
"text": "<p>Yes, I think the answers here show your problem.\nJust to try and clarify a little bit.</p>\n<p>You're referencing a list, so when the list changes any reference to that list will reflect that change. To demonstrate:</p>\n<pre><code>>>> x_present = [4,5,6]\n>>>\n>>> x_past = x_present\n>>>\n>>> x_past\n[4, 5, 6]\n>>>\n>>> x_present.append(7)\n>>>\n>>> x_past\n[4, 5, 6, 7]\n>>>\n</code></pre>\n<p>If you want a copy of the list you have to do do this, <strong>listcopy = mylist[:]</strong>. (or <code>import copy;listcopy = copy.copy(mylist)</code></p>\n<pre><code>>>> x_past = x_present[:]\n>>> x_past\n[4, 5, 6, 7]\n>>>\n>>> x_present.append(8)\n>>>\n>>> x_past\n[4, 5, 6, 7]\n</code></pre>\n"
},
{
"answer_id": 264593,
"author": "Lukman",
"author_id": 34586,
"author_profile": "https://Stackoverflow.com/users/34586",
"pm_score": 0,
"selected": false,
"text": "<p>try changing the <code>x_past = x_present</code> line to <code>x_past = [x for x in x_present]</code> and see if it helps.</p>\n\n<p>the list copy shorthand is my favorite python feature since i can do one-liners that are not possible in other languages:</p>\n\n<p><code>greaterthan100 = [x for x in number if x > 100]</code></p>\n\n<p><code>notinblacklist = [x for x in mylist if x not in blacklist]</code></p>\n\n<p><code>firstchildofbigfamily = [x.child[0] for x in familylist if len(x.child) > 10]</code></p>\n"
},
{
"answer_id": 264618,
"author": "eddy147",
"author_id": 30759,
"author_profile": "https://Stackoverflow.com/users/30759",
"pm_score": 1,
"selected": false,
"text": "<p>In Python, everything is an object.\nSo the statement x_past = x_present point to the same reference.</p>\n"
},
{
"answer_id": 264715,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "<p>As others pointed out the answer is to replace: <code>x_past = x_present</code> by <code>x_past = x_present[:]</code>. In general you could use a <code>copy</code> module to copy an object in Python.</p>\n\n<pre><code>>>> import copy\n>>> a = range(10)\n>>> a\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> b = a\n>>> a += 10, 11\n>>> a\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n>>> b\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n>>> c = copy.copy(a) # shallow copy\n>>> c\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n>>> del a[3:]\n>>> a\n[0, 1, 2]\n>>> b\n[0, 1, 2]\n>>> c\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n</code></pre>\n\n<p>Your code is unpythonic to say the least.</p>\n\n<p>It could be replaced by something like the following code:</p>\n\n<pre><code>import copy\n# assert(len(x_present) >= len(eqn))\n\nfirst = True\nwhile True:\n x_past = copy.copy(x_present) # copy\n\n for j, eqj in enumerate(eqn):\n x_present[j] = sum(x_present[k] * eqj[k] \n for k in range(j if first else len(eqj)) \n if k != j)\n x_present[j] += eqj[j] \n\n print \"X_PAST\\n%s\\nX_PRESENT\\n%s\" % (x_past, x_present)\n if allequal(x_past, x_present, tolerance=10**-2):\n break\n first = False\n</code></pre>\n\n<p>Here's a definition of <code>allequal()</code> (using an absolute error. It might or might not be a good idea in your case (you could use a relative error instead)):</p>\n\n<pre><code>def allequal(x, y, tolerance):\n return (len(x) == len(y) and \n all(-tolerance < (xx - yy) < tolerance\n for xx, yy in zip(x, y)))\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338360/"
] |
Here is my sample code. It is meant to be an iterative procedure for gauss seidel (matrix solver). Essentially when the error is small enough it breaks out of the while loop.
```
i=1
while (i>0):
x_past = x_present
j=0
while(j<3):
value=0
k=0
while(k<3):
if(k!=j):
if(i==1):
if(k>j):
value=value+0
else:
value=value+x_present[k]*eqn[j][k]
else:
value=value+x_present[k]*eqn[j][k]
else:
value=value+eqn[j][k]
k=k+1
x_present[j:j+1]=[value]
j=j+1
print "X_PAST"
print x_past
print "X_PRESENT"
print x_present
if(error(x_past, x_present)<10**-2):
break;
i=i+1
```
I've reduced the code so its more manageable. if you don't understand what its doing its not really that important to solving this problem.
Here is the issue. Everytime
```
x_present[j:j+1]=[value]
```
is run, x\_past is made equal to x\_present. I don't know why this is the case as the only place i have set x\_past equal to x\_present is at the top of the loop. If I take away the
```
x_past=x_present
```
sentence, x\_past is never made equal to x\_present. This leads me to think it is some combination of the two statements that is causing the issue.
This is a big problem cause if x\_past = x\_present the error = 0 every time and the loop breaks after the first iteration. The code does work, for example if I tell the code to run for 8 iterations and the break it gives me the answer its supposed to.
I've been trying to figure this out for the last 4 hours and am completely stumped. I haven't been working with python long, so my trouble shooting skills syntax wise aren't that great. Any help would be appreciated!!
|
Yes, I think the answers here show your problem.
Just to try and clarify a little bit.
You're referencing a list, so when the list changes any reference to that list will reflect that change. To demonstrate:
```
>>> x_present = [4,5,6]
>>>
>>> x_past = x_present
>>>
>>> x_past
[4, 5, 6]
>>>
>>> x_present.append(7)
>>>
>>> x_past
[4, 5, 6, 7]
>>>
```
If you want a copy of the list you have to do do this, **listcopy = mylist[:]**. (or `import copy;listcopy = copy.copy(mylist)`
```
>>> x_past = x_present[:]
>>> x_past
[4, 5, 6, 7]
>>>
>>> x_present.append(8)
>>>
>>> x_past
[4, 5, 6, 7]
```
|
264,596 |
<p>I'm trying to deserialize an xml structure that looks like this:</p>
<pre><code><somecontainer>
<key1>Value1</key1>
<key1>Value2</key1>
<key2>Value3</key2>
<key2>Value4</key2>
</somecontainer>
</code></pre>
<p>I can basically choose what kind if element to deserialize to, maybe something like a List of Pair or something. The essence here is that the element names are the keys.</p>
<p>And no, I cannot change the xml structure. Anyone know how to do this with xstream ?</p>
|
[
{
"answer_id": 264591,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 6,
"selected": true,
"text": "<p>Edit (Aug. 2012):</p>\n<p>It turns out that currently the best solution are probably Guava 13.0's <code>Cache</code> classes, explained on <a href=\"https://github.com/google/guava/wiki/CachesExplained\" rel=\"nofollow noreferrer\">Guava's Wiki</a> - that's what I'm going to use.\nIt even supports building a <code>SoftHashMap</code> (see <code>CacheBuilder.newBuilder().softKeys()</code>), but it is probably not what you want, as Java expert Jeremy Manson explains (below you'll find the link).</p>\n<hr />\n<p>Not that <a href=\"http://www.javalobby.org/java/forums/t16581.html\" rel=\"nofollow noreferrer\">I know of</a> (Nov. 2008), but you kind find some implementation of <code>SoftHashMap</code> on the net.</p>\n<p>Like this one: <a href=\"http://www.koders.com/java/fidF6A9D06D716A6B562853A8DA95C43169F4044FC0.aspx?s=idef%3Aconfiguration\" rel=\"nofollow noreferrer\"><code>SoftHashMap</code></a> or <a href=\"http://www.krugle.org/examples/p-5RTxkghvRYJ5a4Wv/SoftHashMap.java\" rel=\"nofollow noreferrer\">this one</a>.</p>\n<hr />\n<p>Edit (Nov. 2009)<br />\nAs <a href=\"https://stackoverflow.com/users/127013/matthias\">Matthias</a> mentions in the comments, the <a href=\"https://github.com/google/guava\" rel=\"nofollow noreferrer\">Google Guava</a> <a href=\"https://github.com/google/guava/wiki/MapMakerMigration\" rel=\"nofollow noreferrer\"><strong>MapMaker</strong></a> does use SoftReferences:</p>\n<blockquote>\n<p>A <code>ConcurrentMap</code> builder, providing any combination of these features:</p>\n</blockquote>\n<blockquote>\n<ul>\n<li>soft or weak keys,</li>\n</ul>\n</blockquote>\n<ul>\n<li>soft or weak values,</li>\n<li>timed expiration, and</li>\n<li>on-demand computation of values.</li>\n</ul>\n<p>As mentioned in <a href=\"http://www.mail-archive.com/[email protected]/msg08349.html\" rel=\"nofollow noreferrer\">this thread</a>, another JSR166y candidate:</p>\n<p><a href=\"http://anonsvn.jboss.org/repos/jbosscache/experimental/jsr166/src/jsr166y/ConcurrentReferenceHashMap.java\" rel=\"nofollow noreferrer\">jsr166y.ConcurrentReferenceHashMap</a></p>\n<blockquote>\n<p>It provides an alternative concurrent reference map to the Google implementation (which relies on a background thread to evict entries)</p>\n</blockquote>\n<hr />\n<p>Edit (August 2012)</p>\n<p>The Google implementation uses a background thread only when timed expiration of entries is requested. In particular, it simply uses <code>java.util.Timer</code>, which is not so intrusive as having a separate background thread.</p>\n<p>Jeremy Manson recommends, for any cache, using this feature to avoid the dangers of SoftReference:\n<a href=\"http://jeremymanson.blogspot.de/2009/07/how-hotspot-decides-to-clear_07.html\" rel=\"nofollow noreferrer\">http://jeremymanson.blogspot.de/2009/07/how-hotspot-decides-to-clear_07.html</a></p>\n<p>There's another implementation from <a href=\"http://commons.apache.org/collections/\" rel=\"nofollow noreferrer\">Apache Commons</a>, namely <a href=\"https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/org/apache/commons/collections/map/ReferenceMap.html\" rel=\"nofollow noreferrer\">org.apache.commons.collections.map.ReferenceMap</a>; it does not support timed removal, but it does support choosing whether keys should be compared by identity or by equality. Moreover, this implementation is not concurrent - it can be made synchronized, but that works less well under accesses from multiple threads.</p>\n"
},
{
"answer_id": 264627,
"author": "jb.",
"author_id": 7918,
"author_profile": "https://Stackoverflow.com/users/7918",
"pm_score": 2,
"selected": false,
"text": "<p>There is an example implementation in <a href=\"http://www.javaspecialists.eu/archive/Issue098.html\" rel=\"nofollow noreferrer\">98 issue of java specialists newsletter</a></p>\n"
},
{
"answer_id": 265573,
"author": "luke",
"author_id": 25920,
"author_profile": "https://Stackoverflow.com/users/25920",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to implement a cache softreferences are definetly a better idea than weak references, but it puts your entire cache removal policy in the hands of the garbage collector. which is probably not what you want.</p>\n\n<p>If cache removal policy is important your are going to need to do it on your own most likely using regular references. However you are going to have to decide when to eject items and which to eject. If you only want to lose things when you are running out of heap space you can query available heap space via:</p>\n\n<pre><code>Runtime.getRuntime().getFreeMemory();\n</code></pre>\n\n<p>Then once free memory drops below a certain amount you can start either dropping items. Or you could just implement a max size for the cache and use that to decide when to drop things.</p>\n\n<p>here's an <a href=\"https://stackoverflow.com/questions/221525/how-would-you-implement-an-lru-cache-in-java-6#224256\">LRU cache</a> i designed with O(1) insertion, deletion and lookup time, that has a configurable max number of elements. If you want a cache this is going to be a better solution imho than a SoftHashMap.</p>\n\n<p>The softreferences are a great way to create a growable cache. So the ideal solution would be to use a SoftHashMap along with a regular fixed size cache. have all inserts into the cache go into both the fixed cache and the soft hash map then to reference something just see if its in the soft hashmap (and update the reference time in the cache). this way all your most important items (according to your chosen policy LRU, MFU,...) will never be removed because they are hard referenced in the cache but you will also hold on to more things (with no policy control) as long as there is sufficient memory.</p>\n"
},
{
"answer_id": 399497,
"author": "Gili",
"author_id": 14731,
"author_profile": "https://Stackoverflow.com/users/14731",
"pm_score": 4,
"selected": false,
"text": "<p>I am familiar with two libraries that offer a SoftHashMap implementation:</p>\n\n<ol>\n<li><p><a href=\"http://commons.apache.org/collections/\" rel=\"noreferrer\">Apache Commons</a>: org.apache.commons.collections.map.ReferenceMap</p></li>\n<li><p><a href=\"http://google-collections.googlecode.com/\" rel=\"noreferrer\">Google Collections</a>: com.google.common.collect.ReferenceMap</p></li>\n</ol>\n"
},
{
"answer_id": 1804677,
"author": "Joel",
"author_id": 60956,
"author_profile": "https://Stackoverflow.com/users/60956",
"pm_score": 2,
"selected": false,
"text": "<p>Have you considered using an <a href=\"https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/map/LRUMap.html\" rel=\"nofollow noreferrer\">LRUMap</a> instead of a soft HashMap? You get more control over what gets stored (or at least, how much).</p>\n"
},
{
"answer_id": 7663755,
"author": "DallinDyer",
"author_id": 400715,
"author_profile": "https://Stackoverflow.com/users/400715",
"pm_score": 2,
"selected": false,
"text": "<p>Apache <a href=\"http://en.wikipedia.org/wiki/Apache_Shiro\" rel=\"nofollow\">Shiro</a> comes with a SoftHashMap designed for caching. Its based on the article posted by jb above and licensed under Apache v2. You can find the documentation <a href=\"http://shiro.apache.org/static/1.1.0/apidocs/\" rel=\"nofollow\">here</a> and the source code <a href=\"http://shiro.apache.org/static/1.1.0/apidocs/src-html/org/apache/shiro/util/SoftHashMap.html\" rel=\"nofollow\">here</a>. </p>\n"
},
{
"answer_id": 62834985,
"author": "Richard Kotal",
"author_id": 5934449,
"author_profile": "https://Stackoverflow.com/users/5934449",
"pm_score": 1,
"selected": false,
"text": "<p>You can use for example this implementation thread-safe Soft reference HashMap:</p>\n<pre><code>package cz.b2b.jcl.util;\n\nimport java.util.*;\nimport java.lang.ref.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.AbstractMap.SimpleImmutableEntry;\n\npublic class ConcurrentSoftHashMap<K, V> extends AbstractMap {\n\n /**\n The internal HashMap that will hold the SoftReference.\n */\n private final Map<Object, SoftReference> hash = new ConcurrentHashMap<>();\n /**\n The number of "hard" references to hold internally.\n */\n private final int HARD_SIZE;\n /**\n The FIFO list of hard references, order of last access.\n */\n private final ConcurrentLinkedSetQueue hardCache = new ConcurrentLinkedSetQueue();\n /**\n Reference queue for cleared SoftReference objects.\n */\n private final ReferenceQueue queue = new ReferenceQueue();\n\n public ConcurrentSoftHashMap(int hardSize) {\n HARD_SIZE = hardSize;\n }\n\n @Override\n public Object get(Object key) {\n Object result = null;\n // We get the SoftReference represented by that key\n SoftReference soft_ref = hash.get(key);\n if (soft_ref != null) {\n // From the SoftReference we get the value, which can be\n // null if it was not in the map, or it was removed in\n // the processQueue() method defined below\n result = soft_ref.get();\n if (result == null) {\n // If the value has been garbage collected, remove the\n // entry from the HashMap.\n hash.remove(key);\n } else {\n // We now add this object to the beginning of the hard\n // reference queue. \n hardCache.enqueue(result);\n if (hardCache.size() > HARD_SIZE) {\n // Remove the last entry if list longer than HARD_SIZE\n hardCache.dequeue();\n }\n }\n }\n return result;\n }\n\n /**\n Here we put the key, value pair into the HashMap using\n a SoftValue object.\n @param key\n @param value\n @return\n */\n @Override\n public Object put(Object key, Object value) {\n processQueue(); // throw out garbage collected values first\n return hash.put(key, new SoftValue(value, key, queue));\n }\n\n @Override\n public Object remove(Object key) {\n processQueue(); // throw out garbage collected values first\n return hash.remove(key);\n }\n\n @Override\n public void clear() {\n hardCache.clear();\n processQueue(); // throw out garbage collected values\n hash.clear();\n }\n\n @Override\n public int size() {\n processQueue(); // throw out garbage collected values first\n return hash.size();\n }\n\n @Override\n public boolean containsKey(Object key) {\n processQueue(); // throw out garbage collected values first\n return hash.containsKey(key);\n }\n\n @Override\n public Set entrySet() {\n Set<Map.Entry> entry = new HashSet<>();\n Map.Entry simpleImmutableEntry = null;\n Object result = null;\n processQueue(); // throw out garbage collected values first\n for (Map.Entry<Object, SoftReference> item : hash.entrySet()) {\n if (item == null) {\n continue;\n }\n Object key = item.getKey();\n SoftReference soft_ref = item.getValue();\n if (soft_ref != null) {\n result = soft_ref.get();\n if (result == null) {\n hash.remove(key);\n } else {\n hardCache.enqueue(result);\n if (hardCache.size() > HARD_SIZE) {\n hardCache.dequeue();\n }\n simpleImmutableEntry = new SimpleImmutableEntry(key, result);\n entry.add(simpleImmutableEntry);\n\n }\n }\n\n }\n\n return entry;\n }\n\n private class ConcurrentLinkedSetQueue<E> extends ConcurrentLinkedQueue<E> {\n\n public void enqueue(E o) {\n if (!contains(o)) {\n add(o);\n }\n }\n\n public E dequeue() {\n return poll();\n }\n\n }\n\n /**\n We define our own subclass of SoftReference which contains\n not only the value but also the key to make it easier to find\n the entry in the HashMap after it's been garbage collected.\n */\n private static class SoftValue extends SoftReference {\n\n private final Object key; // always make data member final\n\n /**\n Did you know that an outer class can access private data\n members and methods of an inner class? I didn't know that!\n I thought it was only the inner class who could access the\n outer class's private information. An outer class can also\n access private members of an inner class inside its inner\n class.\n */\n private SoftValue(Object k, Object key, ReferenceQueue q) {\n super(k, q);\n this.key = key;\n }\n }\n\n /**\n Here we go through the ReferenceQueue and remove garbage\n collected SoftValue objects from the HashMap by looking them\n up using the SoftValue.key data member.\n */\n private void processQueue() {\n SoftValue sv;\n while ((sv = (SoftValue) queue.poll()) != null) {\n hash.remove(sv.key); // we can access private data!\n }\n }\n\n}\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23691/"
] |
I'm trying to deserialize an xml structure that looks like this:
```
<somecontainer>
<key1>Value1</key1>
<key1>Value2</key1>
<key2>Value3</key2>
<key2>Value4</key2>
</somecontainer>
```
I can basically choose what kind if element to deserialize to, maybe something like a List of Pair or something. The essence here is that the element names are the keys.
And no, I cannot change the xml structure. Anyone know how to do this with xstream ?
|
Edit (Aug. 2012):
It turns out that currently the best solution are probably Guava 13.0's `Cache` classes, explained on [Guava's Wiki](https://github.com/google/guava/wiki/CachesExplained) - that's what I'm going to use.
It even supports building a `SoftHashMap` (see `CacheBuilder.newBuilder().softKeys()`), but it is probably not what you want, as Java expert Jeremy Manson explains (below you'll find the link).
---
Not that [I know of](http://www.javalobby.org/java/forums/t16581.html) (Nov. 2008), but you kind find some implementation of `SoftHashMap` on the net.
Like this one: [`SoftHashMap`](http://www.koders.com/java/fidF6A9D06D716A6B562853A8DA95C43169F4044FC0.aspx?s=idef%3Aconfiguration) or [this one](http://www.krugle.org/examples/p-5RTxkghvRYJ5a4Wv/SoftHashMap.java).
---
Edit (Nov. 2009)
As [Matthias](https://stackoverflow.com/users/127013/matthias) mentions in the comments, the [Google Guava](https://github.com/google/guava) [**MapMaker**](https://github.com/google/guava/wiki/MapMakerMigration) does use SoftReferences:
>
> A `ConcurrentMap` builder, providing any combination of these features:
>
>
>
>
> * soft or weak keys,
>
>
>
* soft or weak values,
* timed expiration, and
* on-demand computation of values.
As mentioned in [this thread](http://www.mail-archive.com/[email protected]/msg08349.html), another JSR166y candidate:
[jsr166y.ConcurrentReferenceHashMap](http://anonsvn.jboss.org/repos/jbosscache/experimental/jsr166/src/jsr166y/ConcurrentReferenceHashMap.java)
>
> It provides an alternative concurrent reference map to the Google implementation (which relies on a background thread to evict entries)
>
>
>
---
Edit (August 2012)
The Google implementation uses a background thread only when timed expiration of entries is requested. In particular, it simply uses `java.util.Timer`, which is not so intrusive as having a separate background thread.
Jeremy Manson recommends, for any cache, using this feature to avoid the dangers of SoftReference:
<http://jeremymanson.blogspot.de/2009/07/how-hotspot-decides-to-clear_07.html>
There's another implementation from [Apache Commons](http://commons.apache.org/collections/), namely [org.apache.commons.collections.map.ReferenceMap](https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/org/apache/commons/collections/map/ReferenceMap.html); it does not support timed removal, but it does support choosing whether keys should be compared by identity or by equality. Moreover, this implementation is not concurrent - it can be made synchronized, but that works less well under accesses from multiple threads.
|
264,623 |
<p>Throughout or C# sourcecode we have a lot of comments that miss the actual content such like this:</p>
<pre><code>/// <summary>
/// </summary>
</code></pre>
<p>or this:</p>
<pre><code>/// <summary>
///
/// </summary>
</code></pre>
<p>or this:</p>
<pre><code>/// <param Name="flag"></param>
</code></pre>
<p>Unfortunately Visual Studio does not generate warnings for this type of missing comments. But for us it would be nice if we could just klick on an item in a list (eg. the warings list) inside visual studio and then be taken to the faulty location in source code to correct it. Also it would be nice to see the list of missing xml comment content upon each build of the xml files. Do you have any idea on how to achieve this?</p>
|
[
{
"answer_id": 264630,
"author": "bob",
"author_id": 23805,
"author_profile": "https://Stackoverflow.com/users/23805",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/FxCop\" rel=\"nofollow noreferrer\">FxCop</a> and a custom rule?</p>\n"
},
{
"answer_id": 264634,
"author": "xsl",
"author_id": 11387,
"author_profile": "https://Stackoverflow.com/users/11387",
"pm_score": 3,
"selected": false,
"text": "<p>Try <a href=\"http://www.ookii.org/software/xmlcommentchecker/\" rel=\"noreferrer\">XML Comment Checker</a>:</p>\n\n<blockquote>\n <p>XML Comment Checker is an application\n that will check the XML documentation\n for a .Net assembly for omissions. It\n offers a more comprehensive checking\n than the C# compiler itself, and is\n ideal for when you wish to check your\n comments before compiling them into\n real documentation, e.g using \n Microsoft Sandcastle.</p>\n</blockquote>\n\n<p>From the feature list:</p>\n\n<blockquote>\n <p><strong>Check for empty sections.</strong> Optionally,\n XML Comment Checker will warn if any\n of the required sections or elements\n are present, but empty. This is not\n enabled by default</p>\n</blockquote>\n\n<p>Usage from Visual Studio:</p>\n\n<blockquote>\n <p>XML Comment Checker can be set as the\n post-build event in Visual Studio to\n check an assembly automatically. <strong>The\n warnings emitted by XML Comment\n Checker have been formatted so that\n Visual Studio will recognize them</strong> and\n display them in the Error List. An\n example post-build command line:\n \"PathToCommentChecker\\CommentChecker.exe\"\n \"$(TargetPath)\" -nologo\n -warnemptysections</p>\n</blockquote>\n"
},
{
"answer_id": 2882116,
"author": "bitbonk",
"author_id": 4227,
"author_profile": "https://Stackoverflow.com/users/4227",
"pm_score": 4,
"selected": true,
"text": "<p>ReSharper is the answer to this (as many other) shortcoming of Visual Studio. I have nothing but pity for anyone who does not use it. ;)</p>\n"
},
{
"answer_id": 35051409,
"author": "ANIL KHANDEI",
"author_id": 5686453,
"author_profile": "https://Stackoverflow.com/users/5686453",
"pm_score": 0,
"selected": false,
"text": "<p>You can use an XSLT file and debug the xml against the XSLT file and then it will throw error if the xml is not well formed showing you the exact line number against which the xml is not well formed.\nThis simple XSLT file works-</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\" exclude-result-prefixes=\"msxsl\"\n>\n <xsl:output method=\"xml\" indent=\"yes\"/>\n\n <xsl:template match=\"@* | node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@* | node()\"/>\n </xsl:copy>\n </xsl:template>\n</xsl:stylesheet>\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4227/"
] |
Throughout or C# sourcecode we have a lot of comments that miss the actual content such like this:
```
/// <summary>
/// </summary>
```
or this:
```
/// <summary>
///
/// </summary>
```
or this:
```
/// <param Name="flag"></param>
```
Unfortunately Visual Studio does not generate warnings for this type of missing comments. But for us it would be nice if we could just klick on an item in a list (eg. the warings list) inside visual studio and then be taken to the faulty location in source code to correct it. Also it would be nice to see the list of missing xml comment content upon each build of the xml files. Do you have any idea on how to achieve this?
|
ReSharper is the answer to this (as many other) shortcoming of Visual Studio. I have nothing but pity for anyone who does not use it. ;)
|
264,626 |
<p>I can't seem to get Javascript debugging working for my ASP.NET MVC application even though I can for a traditional ASP.NET WebForm app.</p>
<p>I have followed the steps for unchecking the 'Disable Script Debugging' boxes for both IE and other.</p>
<p>when I add a simple function to display an alert in both the site.master and any content view the breakpoint will not fire.</p>
<p>Have i missed something obvious or do I need to use an outside tool for debugging like FireBug?</p>
<p>By the way, I'm using Visual Studio Web Developer Express 2008.</p>
<p>thx</p>
|
[
{
"answer_id": 265170,
"author": "user34280",
"author_id": 34280,
"author_profile": "https://Stackoverflow.com/users/34280",
"pm_score": -1,
"selected": false,
"text": "<p>I don't use VS.Net Express, but in VS.Net Standard you can go to the Debug menu in your solution and choose \"Attach to process\". You will then get to choose the debug type: Native, Managed, or Script. Select Script, then select your process from the list. A list of scripts will now come up in your IDE. Click on script one you want to debug, throw in a breakpoint or two, and you should be ready to go. </p>\n\n<p>If MS has nerfed the Express version so that you can't attach to a process, then I guess you're stuck and will need the $$$ upgrade (which wouldn't entirely surprise me). Hey, what do you want for free? :)</p>\n"
},
{
"answer_id": 266811,
"author": "Craig Stuntz",
"author_id": 7714,
"author_profile": "https://Stackoverflow.com/users/7714",
"pm_score": 2,
"selected": false,
"text": "<p>VS JS debugging can work, but... Honestly, get Firebug. It's free, and does much, much more than the VS debugger. </p>\n"
},
{
"answer_id": 1189189,
"author": "malckier",
"author_id": 102265,
"author_profile": "https://Stackoverflow.com/users/102265",
"pm_score": 1,
"selected": false,
"text": "<p>Here's my workaround for debugging javascript in MVC. VS2008 doesn't pick up on break points for javascript in an aspx page, but it will for a separate .js file. I create a debugJscript.js file when I'm working on a page. I create a reference to that debug page from my aspx page. I can step through javascript that way and then push the javascript code back to the aspx page when I'm happy with it.</p>\n\n<p>You can avoid caching problems, too, on that external .js file if you refer to your file like so:</p>\n\n<pre><code> <script type=\"text/javascript\" src=\"../../Scripts/DebugJScript.js?<%=DateTime.Now %>\" ></script> \n</code></pre>\n"
},
{
"answer_id": 1189953,
"author": "Jean-Francois",
"author_id": 41174,
"author_profile": "https://Stackoverflow.com/users/41174",
"pm_score": 3,
"selected": false,
"text": "<pre><code>function test()\n{\n debugger;\n alert(\"hi\");\n}\n</code></pre>\n\n<p>I don't know if it will work with express, but when IE hits the \"debugger\" instruction, it asks me if I want to debug, and with wich tool. Visual studio is present in the list of options presented to me.</p>\n\n<p>I don't know if express will be present for you though.</p>\n\n<p>\"debugger\" also works with firebug.</p>\n"
},
{
"answer_id": 5478477,
"author": "tracileemt",
"author_id": 682822,
"author_profile": "https://Stackoverflow.com/users/682822",
"pm_score": 3,
"selected": false,
"text": "<p>I just had this problem today as well. The debugger doesn't know where you script files are if you include them in the mvc view.</p>\n\n<p>Put them in an external <code>.js</code> file (say <code>default.js</code>) in the scripts folder, add a script tag in the site.master and then you will hit your breakpoints.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5132/"
] |
I can't seem to get Javascript debugging working for my ASP.NET MVC application even though I can for a traditional ASP.NET WebForm app.
I have followed the steps for unchecking the 'Disable Script Debugging' boxes for both IE and other.
when I add a simple function to display an alert in both the site.master and any content view the breakpoint will not fire.
Have i missed something obvious or do I need to use an outside tool for debugging like FireBug?
By the way, I'm using Visual Studio Web Developer Express 2008.
thx
|
```
function test()
{
debugger;
alert("hi");
}
```
I don't know if it will work with express, but when IE hits the "debugger" instruction, it asks me if I want to debug, and with wich tool. Visual studio is present in the list of options presented to me.
I don't know if express will be present for you though.
"debugger" also works with firebug.
|
264,642 |
<p>Is it possible to fork a users session (or do something similar) in a Internet Explorer plugin?</p>
<p>I want to process the page the user is on when they click a button in the toolbar. To avoid interrupting the users browsing, I'd like to "copy" everything so I can parse and process the page in the background. The processing can involve things such as loading the content of the result links on a Google search, if that's where the button was clicked.</p>
<p>So - what I basically want is to imitate <kbd>Ctrl</kbd>+<kbd>N</kbd> but hide the window from the user, so they won't be interrupted.</p>
<p>As you can see, if you fill out and submit the form on <a href="http://www.snee.com/xml/crud/posttest.html" rel="nofollow noreferrer">http://www.snee.com/xml/crud/posttest.html</a> and press <kbd>Ctrl</kbd>+<kbd>N</kbd>, everything posted will still appear in the new window, but it won't post the data twice.</p>
<p>I was thinking of somehow copying the <code>IWebBrowser2</code>, but:</p>
<ul>
<li>I'm not sure if that's possible (I haven't been able to find any information on MSDN)</li>
<li>I don't know if it copies the sessions as well.</li>
</ul>
<p>Creating a new instance of the <code>IWebBrowser2</code> and simply navigating to the current URL isn't a valid solution as <code>POST</code>-variables of course doesn't get carried over.</p>
|
[
{
"answer_id": 287080,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 0,
"selected": false,
"text": "<p>Interesting thought. Could you copy the DOM holus-bolus and then replace a new window's DOM with the copy. It's just a guess. I'm as much in the dark as you at this point.</p>\n"
},
{
"answer_id": 484527,
"author": "Michael",
"author_id": 56751,
"author_profile": "https://Stackoverflow.com/users/56751",
"pm_score": 1,
"selected": false,
"text": "<p>A BHO or plugin would work.\nThere are so many options to get the source, it's kinda. pick your poising.\nLook up IDocHostUIHandler to alter behaviour. IHTMLElementCollection to parse the page in browser. \nThe easiest thing I can think of at the moment is....</p>\n\n<p>Save the current contents to a stream. same as get/view source.</p>\n\n<p><PRE>\n// #include \nHRESULT SaveDocumenttoStream(IWebBrowser* pWebBrowser, \n IStream* pStream)\n{\nHRESULT hr;\nIDispatch* pHtmlDoc = NULL;\nIPersistStreamInit* pPersistStreamInit = NULL;\nhr = pWebBrowser->get_Document( &pHtmlDoc );\nif ( SUCCEEDED(hr) && pHtmlDoc)\n{\n // Query for IPersistStreamInit.\n hr = pHtmlDoc->QueryInterface( IID_IPersistStreamInit,\n (void**)&pPersistStreamInit );\n if ( SUCCEEDED(hr) )\n { \n hr = pPersistStreamIni->Save(, True);\n pPersistStreamInit->Release(); \n }\n pHtmlDoc->Release();\n}\n</PRE></p>\n\n<p>You supply the browser and stream.HTH</p>\n\n<p>--</p>\n\n<p>Michael</p>\n"
},
{
"answer_id": 2540789,
"author": "Heinrich Ulbricht",
"author_id": 56658,
"author_profile": "https://Stackoverflow.com/users/56658",
"pm_score": 0,
"selected": false,
"text": "<p>I think it is impossible to do because you have to think about so many details, something will always break. Just to mention two:</p>\n\n<ul>\n<li>You have to take care of embedded web browsers (frames, IFRAMEs). I think copying the main page would just copy their URLs so their content will be reloaded when you restore the serialized main page somewhere, thus the content of your page changes. So you would have to go down to the frame level. </li>\n<li>You would have to take care about scripts which behind your back try to connect to some server to send data which has already been sent by the page you forked. So you might change the logic of the page.</li>\n</ul>\n\n<p>So processing live is the only true solution to capture the state as the users sees it; if this is what you want to achieve. If you don't need so much detail it might be easier to do.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1555170/"
] |
Is it possible to fork a users session (or do something similar) in a Internet Explorer plugin?
I want to process the page the user is on when they click a button in the toolbar. To avoid interrupting the users browsing, I'd like to "copy" everything so I can parse and process the page in the background. The processing can involve things such as loading the content of the result links on a Google search, if that's where the button was clicked.
So - what I basically want is to imitate `Ctrl`+`N` but hide the window from the user, so they won't be interrupted.
As you can see, if you fill out and submit the form on <http://www.snee.com/xml/crud/posttest.html> and press `Ctrl`+`N`, everything posted will still appear in the new window, but it won't post the data twice.
I was thinking of somehow copying the `IWebBrowser2`, but:
* I'm not sure if that's possible (I haven't been able to find any information on MSDN)
* I don't know if it copies the sessions as well.
Creating a new instance of the `IWebBrowser2` and simply navigating to the current URL isn't a valid solution as `POST`-variables of course doesn't get carried over.
|
A BHO or plugin would work.
There are so many options to get the source, it's kinda. pick your poising.
Look up IDocHostUIHandler to alter behaviour. IHTMLElementCollection to parse the page in browser.
The easiest thing I can think of at the moment is....
Save the current contents to a stream. same as get/view source.
```
// #include
HRESULT SaveDocumenttoStream(IWebBrowser* pWebBrowser,
IStream* pStream)
{
HRESULT hr;
IDispatch* pHtmlDoc = NULL;
IPersistStreamInit* pPersistStreamInit = NULL;
hr = pWebBrowser->get_Document( &pHtmlDoc );
if ( SUCCEEDED(hr) && pHtmlDoc)
{
// Query for IPersistStreamInit.
hr = pHtmlDoc->QueryInterface( IID_IPersistStreamInit,
(void**)&pPersistStreamInit );
if ( SUCCEEDED(hr) )
{
hr = pPersistStreamIni->Save(, True);
pPersistStreamInit->Release();
}
pHtmlDoc->Release();
}
```
You supply the browser and stream.HTH
--
Michael
|
264,656 |
<p><code>getopt()</code> is not behaving as I expect for short options.</p>
<p>eg: Invoking the below program with a missing parameter:</p>
<p>Valid Case: <code>testopt -d dir -a action -b build</code></p>
<p>Error Case: <code>testopt -d -a action -b build</code></p>
<p>This did not throw any error as I was expecting an error message operand missing for <code>-d</code></p>
<ul>
<li>Is this a known bug? </li>
<li>If so, is there any standard fix available?</li>
</ul>
<p>My code:</p>
<pre><code>#include <unistd.h>
/* testopt.c */
/* Test program for testing getopt */
int main(int argc, char **argv)
{
int chr;
while ( ( chr = getopt(argc, argv, ":d:a:b:") ) != -1 )
{
switch(chr)
{
case 'a':
printf("Got a...\n");
break;
case 'b':
printf("Got b...\n");
break;
case 'd':
printf("Got d...\n");
break;
case ':':
printf("Missing operand for %c\n", optopt);
break;
case '?':
printf("Unknown option %c\n", optopt);
break;
}
}
printf("execution over\n");
return 0;
}
</code></pre>
|
[
{
"answer_id": 264665,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 0,
"selected": false,
"text": "<p>According to <a href=\"http://www.gnu.org/software/libtool/manual/libc/Using-Getopt.html#Using-Getopt\" rel=\"nofollow noreferrer\">the manual page</a>, you should start your option string with a colon in order to make <code>getopt()</code> return <code>':'</code> to indicate missing argument. The default seems to be returning <code>'?'</code>.</p>\n"
},
{
"answer_id": 264684,
"author": "qrdl",
"author_id": 28494,
"author_profile": "https://Stackoverflow.com/users/28494",
"pm_score": 3,
"selected": true,
"text": "<p><code>getopt()</code> thinks <code>-a</code> is an argument for <code>-d</code>, not an option.</p>\n\n<p>Try <code>testopt -a action -b build -d</code> - it should complain about missing argument.</p>\n\n<p>You need to check for <code>-d</code> option (and all other options) that <code>optarg</code> has valid value - the one without dash in the beginning.</p>\n"
},
{
"answer_id": 264789,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 0,
"selected": false,
"text": "<p>The above code works fine for me, using gcc 3.4.5 on Red Hat:</p>\n\n<pre><code>$ ./a.out -d test\nGot d...\nexecution over\n\n$ ./a.out -d\nMissing operand for d\nexecution over\n</code></pre>\n\n<p>What's your environment?</p>\n\n<p><strong>UPDATE</strong>: OK, qrdl is spot on. How come getopt() works that way?</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18657/"
] |
`getopt()` is not behaving as I expect for short options.
eg: Invoking the below program with a missing parameter:
Valid Case: `testopt -d dir -a action -b build`
Error Case: `testopt -d -a action -b build`
This did not throw any error as I was expecting an error message operand missing for `-d`
* Is this a known bug?
* If so, is there any standard fix available?
My code:
```
#include <unistd.h>
/* testopt.c */
/* Test program for testing getopt */
int main(int argc, char **argv)
{
int chr;
while ( ( chr = getopt(argc, argv, ":d:a:b:") ) != -1 )
{
switch(chr)
{
case 'a':
printf("Got a...\n");
break;
case 'b':
printf("Got b...\n");
break;
case 'd':
printf("Got d...\n");
break;
case ':':
printf("Missing operand for %c\n", optopt);
break;
case '?':
printf("Unknown option %c\n", optopt);
break;
}
}
printf("execution over\n");
return 0;
}
```
|
`getopt()` thinks `-a` is an argument for `-d`, not an option.
Try `testopt -a action -b build -d` - it should complain about missing argument.
You need to check for `-d` option (and all other options) that `optarg` has valid value - the one without dash in the beginning.
|
264,676 |
<p>Is this possible? I had troubles with SVN clients not being able to access the repository with the following error message:</p>
<blockquote>
<p>Repository moved permanently to '<a href="http://svn.example.com/test/" rel="noreferrer">http://svn.example.com/test/</a>'; please relocate</p>
</blockquote>
<p>If I added the '/' to the end of the path I was trying to access, it just strips it off again, and shows the same error message. My configuration file looks like:</p>
<pre><code><VirtualHost *>
ServerName svn.example.com
# Normal VirtualHost stuff here
<Location /svn>
# Uncomment this to enable the repository
DAV svn
SVNParentPath /some/path/to/repositories
# Setup mod_authz_svn, etc, etc here
</Location>
</VirtualHost>
</code></pre>
<p>Note: This works. But if I change the Location to just <code>/</code> it stops working again with the error above. Is it possible to use the root directory, or am I missing something here? Firefox displays the repository listing fine when serving the repositories out of the root.</p>
<p>As someone else pointed out, this only seems to be an issue inside named virtual hosts... Anyone have any smart ideas why?</p>
|
[
{
"answer_id": 266987,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 1,
"selected": false,
"text": "<p>I ended up using mod_rewrite succesfully to rewrite all access to the root directory into <code>/svn</code>, hence getting access to the repositories from <code>/repository_name</code>. For reference, this is the configuration I ended up with:</p>\n\n<pre><code># Rewrite / into /svn to avoid errors that seem to occur when using the root\n# for repositories.\nRewriteEngine On\n# Subdirectories that SHOULD be accessed directly, ie. trac\n# /svn should be here to avoid redirect loops\nRewriteCond %{REQUEST_URI} !^/(trac|svn)/\nRewriteRule ^/(.*)$ /svn/$1 [PT]\n</code></pre>\n"
},
{
"answer_id": 267029,
"author": "Davide Gualano",
"author_id": 28582,
"author_profile": "https://Stackoverflow.com/users/28582",
"pm_score": 0,
"selected": false,
"text": "<pre><code>This is working for me:\n\n<Location />\n DAV svn\n SVNPath /repository\n AuthType Basic\n AuthName \"Repository authentication\"\n AuthUserFile /repository/.svn-auth\n AuthzSVNAccessFile /repository/.svn-access\n Satisfy All\n Require valid-user\n</Location>\n</code></pre>\n\n<p>Pointing the browser to <a href=\"http://127.0.0.1\" rel=\"nofollow noreferrer\">http://127.0.0.1</a> shows me the repository content.</p>\n"
},
{
"answer_id": 267309,
"author": "Davide Gualano",
"author_id": 28582,
"author_profile": "https://Stackoverflow.com/users/28582",
"pm_score": 2,
"selected": false,
"text": "<p>Continuing from comments to my previous answer, I've tried also with a VirtualHost:</p>\n\n<pre><code><VirtualHost 127.0.0.1:80>\n<Location />\n DAV svn\n SVNPath /repository\n AuthType Basic\n AuthName \"Repository authentication\"\n AuthUserFile /repository/.svn-auth\n AuthzSVNAccessFile /repository/.svn-access\n Satisfy All\n Require valid-user\n</Location>\n</VirtualHost>\n</code></pre>\n\n<p>and it's working, I can browse the repository with firefox and can access it with the svn command line client.</p>\n"
},
{
"answer_id": 267338,
"author": "Davide Gualano",
"author_id": 28582,
"author_profile": "https://Stackoverflow.com/users/28582",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, I think we have found who to blame: named virtual hosts :)</p>\n\n<p>With this configuration:</p>\n\n<pre><code><VirtualHost dave.test>\n<Location />\n DAV svn\n SVNPath /repository\n AuthType Basic\n AuthName \"Repository authentication\"\n AuthUserFile /repository/.svn-auth\n AuthzSVNAccessFile /repository/.svn-access\n Satisfy All\n Require valid-user\n</Location>\n</VirtualHost>\n</code></pre>\n\n<p>when I run the command <code>svn ls http://dave.test</code> I got this error:</p>\n\n<pre><code>svn: Server sent unexpected return value (405 Method Not Allowed) in response to\nPROPFIND request for '/'\n</code></pre>\n\n<p>So apparently there is an issue when one tries to enable mod_dav_svn in the root directory of a named virtual host...</p>\n"
},
{
"answer_id": 374490,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks for this, finally got it working with a VirtualHost due to your comments.</p>\n\n<pre><code><VirtualHost *:80>\n ServerAdmin [email protected]\n ServerName svn.example.com\n ServerAlias svn\n DocumentRoot /home/svn.example.com/public_html\n\n RewriteEngine On\n\n RewriteCond %{REQUEST_URI} ^/svn$\n RewriteRule .* /svn/ [PT]\n\n RewriteCond %{REQUEST_URI} !^/svn/\n RewriteRule ^/(.*)$ /svn/$1 [PT]\n\n <Location /svn>\n DAV svn\n SVNParentPath /home/svn.example.com/public_html\n SVNListParentPath on\n </Location>\n\n <LocationMatch /svn/.+>\n AuthzSVNAccessFile /home/svn.example.com/support/access.cfg\n\n AuthType Basic\n AuthName \"Subversion\"\n AuthUserFile /home/svn.example.com/.htpasswd\n Require valid-user\n </LocationMatch>\n</VirtualHost>\n</code></pre>\n\n<p>As shown I found that you probably want to also add:</p>\n\n<pre><code>RewriteCond %{REQUEST_URI} ^/svn$\nRewriteRule .* /svn/ [PT]\n</code></pre>\n\n<p>In order to catch <a href=\"http://svn.example.com/svn\" rel=\"nofollow noreferrer\">http://svn.example.com/svn</a> without the ending /.</p>\n\n<p>Nige.</p>\n"
},
{
"answer_id": 374602,
"author": "azkotoki",
"author_id": 28581,
"author_profile": "https://Stackoverflow.com/users/28581",
"pm_score": 4,
"selected": true,
"text": "<p>The problem is that you are using the document root also as the repository root (I'm not blaming you, this should just work, but it doesn't).</p>\n\n<p>Try pointing the <code>DocumentRoot</code> and <code>SVNParentPath</code> directives to different physical locations, so the resulting config file should look like this (abbreviated):</p>\n\n<pre><code><VirtualHost *:80>\n DocumentRoot /home/svn.example.com/docroot\n\n <Location />\n SVNParentPath /home/svn.example.com/svnroot\n SVNListParentPath on\n </Location>\n</VirtualHost>\n</code></pre>\n\n<p>Also, as @Nigel Jewell says, remove that Rewrite block, for sanity.</p>\n"
},
{
"answer_id": 387579,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>\n DocumentRoot \"/usr/local/apache/htdocs/ForSvn\"\n ServerName xxx.xxx\n ServerAdmin xxx\n ErrorLog \"/usr/local/apache/logs/xxx-error_log\"\n TransferLog \"/usr/local/apache/logs/xxx-access_log\"</p>\n\n<pre><code>ReWriteEngine On\nRewriteCond %{REQUEST_URI} ^/svn$\nRewriteRule .* /svn/ [PT]\n\n<Location /svn>\n DAV svn\n SVNParentPath /svn/repos\n SVNListParentPath on\n\n # Limit write permission to list of valid users.\n <LimitExcept GET PROPFIND OPTIONS REPORT>\n AuthType Basic\n AuthName \"Subversion\"\n AuthUserFile /svn/authfiles/svn-htpasswd\n AuthzSVNAccessFile /svn/authfiles/svn-access.conf\n Require valid-user\n </LimitExcept>\n</Location>\n\n<LocationMatch /svn/myProject/>\n AuthType Basic\n AuthName \"Subversion (private)\"\n AuthUserFile /svn/authfiles/svn-htpasswd\n AuthzSVNAccessFile /svn/authfiles/svn-access.conf\n Require user user1 user2 user3...\n</LocationMatch>\n</code></pre>\n\n<p>and works fine with me. Thank you for this.</p>\n"
},
{
"answer_id": 1943920,
"author": "yurique",
"author_id": 236534,
"author_profile": "https://Stackoverflow.com/users/236534",
"pm_score": 2,
"selected": false,
"text": "<p>Found this in /etc/apache2/conf.d/subversion.conf (need to map error documents to defaults):</p>\n\n<pre><code><VirtualHost *>\n ServerName svn.example.com\n ErrorLog /var/log/apache2/svn.example.com-error_log\n TransferLog /var/log/apache2/svn.example.com-access_log\n #\n # Do not set DocumentRoot. It is not needed here and just causes trouble.\n #\n # Map the error documents back to their defaults.\n # Otherwise mod_dav_svn tries to find a \"error\" repository.\n #\n ErrorDocument 400 default\n ErrorDocument 401 default\n ErrorDocument 403 default\n ErrorDocument 404 default\n ErrorDocument 405 default\n ErrorDocument 408 default\n ErrorDocument 410 default\n ErrorDocument 411 default\n ErrorDocument 412 default\n ErrorDocument 413 default\n ErrorDocument 414 default\n ErrorDocument 415 default\n ErrorDocument 500 default\n ErrorDocument 501 default\n ErrorDocument 502 default\n ErrorDocument 503 default\n #\n <Location />\n...\n </Location>\n</code></pre>\n\n<p>After I've done this everything started working as expected.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
] |
Is this possible? I had troubles with SVN clients not being able to access the repository with the following error message:
>
> Repository moved permanently to '<http://svn.example.com/test/>'; please relocate
>
>
>
If I added the '/' to the end of the path I was trying to access, it just strips it off again, and shows the same error message. My configuration file looks like:
```
<VirtualHost *>
ServerName svn.example.com
# Normal VirtualHost stuff here
<Location /svn>
# Uncomment this to enable the repository
DAV svn
SVNParentPath /some/path/to/repositories
# Setup mod_authz_svn, etc, etc here
</Location>
</VirtualHost>
```
Note: This works. But if I change the Location to just `/` it stops working again with the error above. Is it possible to use the root directory, or am I missing something here? Firefox displays the repository listing fine when serving the repositories out of the root.
As someone else pointed out, this only seems to be an issue inside named virtual hosts... Anyone have any smart ideas why?
|
The problem is that you are using the document root also as the repository root (I'm not blaming you, this should just work, but it doesn't).
Try pointing the `DocumentRoot` and `SVNParentPath` directives to different physical locations, so the resulting config file should look like this (abbreviated):
```
<VirtualHost *:80>
DocumentRoot /home/svn.example.com/docroot
<Location />
SVNParentPath /home/svn.example.com/svnroot
SVNListParentPath on
</Location>
</VirtualHost>
```
Also, as @Nigel Jewell says, remove that Rewrite block, for sanity.
|
264,680 |
<p>I have a bunch of JUnit 3 classes which extend TestCase and would like to automatically migrate them to be JUnit4 tests with annotations such as <code>@Before</code>, <code>@After</code>, <code>@Test</code>, etc.<br>
Any tool out there to do this in a big batch run?</p>
|
[
{
"answer_id": 264749,
"author": "Gary",
"author_id": 396747,
"author_profile": "https://Stackoverflow.com/users/396747",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know of a tool that would do this at the moment - I'd expect Eclipse to provide some plugin fairly shortly - but you could knock up a simple source tree exploring Java class that would do it for you if you only want to do a basic conversion. I had to write something similar to automatically generate skeleton test cases for a legacy application so I've got a fair amount of the support code already. You're welcome to use it. </p>\n"
},
{
"answer_id": 672676,
"author": "akuhn",
"author_id": 24468,
"author_profile": "https://Stackoverflow.com/users/24468",
"pm_score": 2,
"selected": false,
"text": "<p>There are, to my best knowledge, no available migration tools (yet). What I know is this:</p>\n\n<ul>\n<li><p>Last year, at OOPSLA in Nashville, was a paper about API migration but alas their tools seems not be openly available. I'll provide the link to the paper, (even though I dare it is of little use for you since it is rather theory heavy): <a href=\"http://people.cs.vt.edu/~tilevich/papers/rosemari-oopsla.pdf\" rel=\"nofollow noreferrer\">\"Annotation Refactoring: Inferring Upgrade Transformations for Legacy Applications\"</a>.</p></li>\n<li><p>Above, I wrote \"no available tool (yet)\" because my student Lea Hänsenberger is currently working on an auotmated API migration from, not onyl, JUnit 4 a to JExample, but also from JUnit 3 to JUnit 4. Please <a href=\"http://twitter.com/jexample\" rel=\"nofollow noreferrer\">follow JExample on Twitter</a> to get notified when she releases a first beta.</p></li>\n</ul>\n\n<p>I hope this information was of help for you.</p>\n"
},
{
"answer_id": 677356,
"author": "guerda",
"author_id": 32043,
"author_profile": "https://Stackoverflow.com/users/32043",
"pm_score": 7,
"selected": true,
"text": "<p>In my opinion, it cannot be that hard. So let's try it:</p>\n\n<h2>0. Imports</h2>\n\n<p>You need to import three annotations:</p>\n\n<pre><code>import org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;`\n</code></pre>\n\n<p>After you've made the next few changes, you won't need <code>import junit.framework.TestCase;</code>.</p>\n\n<h2>1. Annotate <code>test*</code> Methods</h2>\n\n<p>All methods beginning with <code>public void test</code> must be preceded by the <code>@Test</code> annotation.\nThis task is easy with a regex.</p>\n\n<h2>2. Annotate SetUp and TearDown methods</h2>\n\n<p>Eclipse generates following <code>setUp()</code> method:</p>\n\n<pre><code>@Override\nprotected void setUp() throws Exception { }\n</code></pre>\n\n<p>Must be replaced by:</p>\n\n<pre><code>@Before\npublic void setUp() throws Exception { }\n</code></pre>\n\n<p>Same for <code>tearDown()</code>:</p>\n\n<pre><code>@Override\nprotected void tearDown() throws Exception { }\n</code></pre>\n\n<p>replaced by</p>\n\n<pre><code>@After\npublic void tearDown() throws Exception { }\n</code></pre>\n\n<h2>3. Get rid of <code>extends TestCase</code></h2>\n\n<p>Remove exactly one occurence per file of the string</p>\n\n<pre><code>\" extends TestCase\"\n</code></pre>\n\n<h2>4. Remove main methods?</h2>\n\n<p>Probably it's necessary to remove/refactor existing main methods that will execute the test.</p>\n\n<h2>5. Convert <code>suite()</code> method to <code>@RunWithClass</code></h2>\n\n<p>According to saua's comment, there must be a conversion of the <code>suite()</code> method. Thanks, saua!</p>\n\n<pre><code>@RunWith(Suite.class)\[email protected]({\n TestDog.class\n TestCat.class\n TestAardvark.class\n})\n</code></pre>\n\n<h2>Conclusion</h2>\n\n<p>I think, it's done very easy via a set of regular expressions, even if it will kill my brain ;)</p>\n"
},
{
"answer_id": 3130393,
"author": "Designpattern",
"author_id": 377779,
"author_profile": "https://Stackoverflow.com/users/377779",
"pm_score": 1,
"selected": false,
"text": "<p>Nice post. I did the upgrade using Netbeans with the following RegEx strings:\n(First line search-string, second one replace-string)</p>\n\n<pre><code>public void test\n@Test\\n public void test\n\n@Override\\n.*protected void onSetUp\n@Before\\n protected void onSetUp\n\n@Override\\n.*protected void onTearDown\n@After\\n protected void onTearDown\n</code></pre>\n\n<p>Don't forget to flag the Regular Expression checkbox!</p>\n"
},
{
"answer_id": 4535170,
"author": "Geoffrey De Smet",
"author_id": 472109,
"author_profile": "https://Stackoverflow.com/users/472109",
"pm_score": 5,
"selected": false,
"text": "<p>Here are the actual regular expressions I used to execute furtelwart's suggestions:</p>\n\n<pre><code>// Add @Test\nReplace:\n^[ \\t]+(public +void +test)\nWith:\n @Test\\n $1\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n// Remove double @Test's on already @Test annotated files\nReplace:\n^[ \\t]+@Test\\n[ \\t]+@Test\nWith:\n @Test\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n\n// Remove all empty setUp's\nReplace:\n^[ \\*]+((public|protected) +)?void +setUp\\(\\)[^\\{]*\\{\\s*(super\\.setUp\\(\\);)?\\s*\\}\\n([ \\t]*\\n)?\nWith nothing\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n// Add @Before to all setUp's\nReplace:\n^([ \\t]+@Override\\n)?[ \\t]+((public|protected) +)?(void +setUp\\(\\))\nWith:\n @Before\\n public void setUp()\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n// Remove double @Before's on already @Before annotated files\nReplace:\n^[ \\t]+@Before\\n[ \\t]+@Before\nWith:\n @Before\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n\n// Remove all empty tearDown's\nReplace:\n^[ \\*]+((public|protected) +)?void +tearDown\\(\\)[^\\{]*\\{\\s*(super\\.tearDown\\(\\);)?\\s*\\}\\n([ \\t]*\\n)?\nWith nothing\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n// Add @After to all tearDown's\nReplace:\n^([ \\t]+@Override\\n)?[ \\t]+((public|protected) +)?(void +tearDown\\(\\))\nWith:\n @After\\n public void tearDown()\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n// Remove double @After's on already @After annotated files\nReplace:\n^[ \\t]+@After\\n[ \\t]+@After\nWith:\n @After\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n\n// Remove old imports, add new imports\nReplace:\n^([ \\t]*import[ \\t]+junit\\.framework\\.Assert;\\n)?[ \\t]*import[ \\t]+junit\\.framework\\.TestCase;\nWith:\nimport org.junit.After;\\nimport org.junit.Before;\\nimport org.junit.Test;\\nimport static org.junit.Assert.*;\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n\n// Remove all extends TestCase\nReplace:\n[ \\t]+extends[ \\t]+TestCase[ \\t]+\\{\nWith:\n {\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n\n\n// Look for import junit.framework;\nFind:\nimport junit\\.framework\nManually fix\nRegular Expression: on\nCase sensitive: on\n\n\n// Look for ignored tests (FIXME, disabled, ...)\nFind:\npublic[ \\t]+void[ \\t]+\\w+test\nManually fix\nRegular Expression: on\nCase sensitive: on\n\n\n// Look for dummy/empty tests\nFind:\npublic[ \\t]+void[ \\t]+test[\\w\\d]*\\(\\s*\\)\\s*\\{\\s*(//[^\\n]*)?\\s*\\}\nManually fix\nRegular Expression: on\nCase sensitive: on\n</code></pre>\n\n<p>Note: it's important to do them in the order shown above.</p>\n"
},
{
"answer_id": 16731352,
"author": "Francisco",
"author_id": 766289,
"author_profile": "https://Stackoverflow.com/users/766289",
"pm_score": 3,
"selected": false,
"text": "<p>We are in the middle of migrating a reasonably large code base to JUnit4. Since this is the second time I'm doing a migration such as this, I decided to save the code somewhere:</p>\n\n<p><a href=\"https://github.com/FranciscoBorges/junit3ToJunit4\" rel=\"noreferrer\">https://github.com/FranciscoBorges/junit3ToJunit4</a></p>\n\n<p>It deals with more corner cases than the ones enumerated in answers above. Such as:</p>\n\n<ul>\n<li>calls to <code>TestCase.setUp()</code> and <code>TestCase.tearDown()</code></li>\n<li>calls to <code>TestCase(String)</code> constructor within a sub-class constructor</li>\n<li>calls to <code>TestCase.assert*</code> methods that moved to <code>Assert</code>.</li>\n<li>fixing package names <code>junit.framework</code> to <code>org.junit</code></li>\n<li>etc</li>\n</ul>\n"
},
{
"answer_id": 59204007,
"author": "psuzzi",
"author_id": 1029912,
"author_profile": "https://Stackoverflow.com/users/1029912",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to <em>automatically convert</em> your Junit3 tests <em>to Junit4</em>, you can use the Vogella's Codemodify tool, available at this address:</p>\n\n<ul>\n<li><a href=\"https://github.com/vogellacompany/codemodify\" rel=\"nofollow noreferrer\">https://github.com/vogellacompany/codemodify</a></li>\n</ul>\n\n<p>TL;DR install and use it as follows: </p>\n\n<ul>\n<li>get Eclipse if you don't use it already (it's open source)</li>\n<li>From menu: <strong>Help > Install new software</strong>, then paste the update site <a href=\"http://dl.bintray.com/vogellacompany/junit-4-tools/\" rel=\"nofollow noreferrer\">http://dl.bintray.com/vogellacompany/junit-4-tools/</a> in the <em>Work With</em> field</li>\n<li>Finish the installation, and restart if needed.</li>\n</ul>\n\n<p>Then, you can right-click any Junit3 test class, and select the <strong>Source > Convert to JUnit4</strong> menu entry to convert your class to JUnit4.</p>\n\n<p><a href=\"https://i.stack.imgur.com/lueKt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lueKt.png\" alt=\"enter image description here\"></a></p>\n\n<p>The tool will automagically <em>remove TestCase parent</em>, outdated imports, add <em>@Before</em>, <em>@After</em>, <em>@Test</em> annotations, etc.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] |
I have a bunch of JUnit 3 classes which extend TestCase and would like to automatically migrate them to be JUnit4 tests with annotations such as `@Before`, `@After`, `@Test`, etc.
Any tool out there to do this in a big batch run?
|
In my opinion, it cannot be that hard. So let's try it:
0. Imports
----------
You need to import three annotations:
```
import org.junit.After;
import org.junit.Before;
import org.junit.Test;`
```
After you've made the next few changes, you won't need `import junit.framework.TestCase;`.
1. Annotate `test*` Methods
---------------------------
All methods beginning with `public void test` must be preceded by the `@Test` annotation.
This task is easy with a regex.
2. Annotate SetUp and TearDown methods
--------------------------------------
Eclipse generates following `setUp()` method:
```
@Override
protected void setUp() throws Exception { }
```
Must be replaced by:
```
@Before
public void setUp() throws Exception { }
```
Same for `tearDown()`:
```
@Override
protected void tearDown() throws Exception { }
```
replaced by
```
@After
public void tearDown() throws Exception { }
```
3. Get rid of `extends TestCase`
--------------------------------
Remove exactly one occurence per file of the string
```
" extends TestCase"
```
4. Remove main methods?
-----------------------
Probably it's necessary to remove/refactor existing main methods that will execute the test.
5. Convert `suite()` method to `@RunWithClass`
----------------------------------------------
According to saua's comment, there must be a conversion of the `suite()` method. Thanks, saua!
```
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestDog.class
TestCat.class
TestAardvark.class
})
```
Conclusion
----------
I think, it's done very easy via a set of regular expressions, even if it will kill my brain ;)
|
264,685 |
<p>In CSS, with:</p>
<pre><code>@page { @top-right { content: "Page " counter(page) " of " counter(pages); } }
</code></pre>
<p>I can have page numbers displayed at the top of every page when the page is printed. This works great. But now, how can I make it so the page number starts with 2 instead of 1? Can I do that by modifying the CSS rule above?</p>
|
[
{
"answer_id": 264706,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": -1,
"selected": false,
"text": "<p>Don't know if this works, but why don't you try <code>counter(page+1)</code>?</p>\n"
},
{
"answer_id": 275099,
"author": "schnaader",
"author_id": 34065,
"author_profile": "https://Stackoverflow.com/users/34065",
"pm_score": 2,
"selected": false,
"text": "<p>After playing with Flying Saucer a bit, I guess there's no way to do this with CSS (or it's a very complicated one), as \"page\"/\"pages\" seem to be internal CSS variables. Perhaps it gets better with CSS 3, there seems to be a calc() function, so counter(calc(page+1)) could <em>perhaps</em> work...</p>\n\n<p>But there is another way to get the PDF starting with page 2. You can add a blank first page to the PDF by adding this line to the xhtml file:</p>\n\n<pre><code><h1 style=\"page-break-before:always\"></h1>\n</code></pre>\n\n<p>Then you can either print only pages 2-... of the PDF when using a printer or remove the first page from the PDF with some PDF editor.</p>\n"
},
{
"answer_id": 286527,
"author": "avernet",
"author_id": 5295,
"author_profile": "https://Stackoverflow.com/users/5295",
"pm_score": 3,
"selected": true,
"text": "<p>If you are using Flying Saucer (which was my case), use the following CSS:</p>\n\n<blockquote>\n <p>table { -fs-table-paginate: paginate; }</p>\n</blockquote>\n\n<p>It works like a charm. And Flying Saucer rocks :). Really highly recommended.</p>\n"
},
{
"answer_id": 1421270,
"author": "andyroberts",
"author_id": 62344,
"author_profile": "https://Stackoverflow.com/users/62344",
"pm_score": 2,
"selected": false,
"text": "<p>Have you seen the CSS documentation about counters? <a href=\"http://www.w3.org/TR/CSS2/generate.html#counters\" rel=\"nofollow noreferrer\">see here</a> It seems to me that you can call the counter-reset. By default counters are set to 0. If in your Body tag you did a \"content-reset: page 1;\" then it should force the first page to start at 2 instead of 1.</p>\n"
},
{
"answer_id": 13829987,
"author": "Brian Bell",
"author_id": 1896166,
"author_profile": "https://Stackoverflow.com/users/1896166",
"pm_score": 2,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>@page {\n counter-increment: page;\n counter-reset: page 1;\n @top-right {\n content: \"Page \" counter(page) \" of \" counter(pages);\n }\n}\n</code></pre>\n\n<p>using <code>page 1</code> will reset the starting point of the counter. You can use any integer to start counting from. The default is <code>0</code>.</p>\n"
},
{
"answer_id": 59437476,
"author": "Thirumalai Chellam Balagopalan",
"author_id": 1900397,
"author_profile": "https://Stackoverflow.com/users/1900397",
"pm_score": 0,
"selected": false,
"text": "<p>Posting this for someone else viewing this page. You can also look into another stackoverflow post provided below. This has worked for me.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/29136505/flying-saucer-page-count-with-css\">flying saucer - page count with css</a></p>\n\n<pre><code>.seq-start{\n -fs-page-sequence: start;\n}\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5295/"
] |
In CSS, with:
```
@page { @top-right { content: "Page " counter(page) " of " counter(pages); } }
```
I can have page numbers displayed at the top of every page when the page is printed. This works great. But now, how can I make it so the page number starts with 2 instead of 1? Can I do that by modifying the CSS rule above?
|
If you are using Flying Saucer (which was my case), use the following CSS:
>
> table { -fs-table-paginate: paginate; }
>
>
>
It works like a charm. And Flying Saucer rocks :). Really highly recommended.
|
264,689 |
<p>So I want to trigger an event (pausing/unpausing some media) whenever the user presses spacebar anywhere in the my Swing app.</p>
<p>Since there are so many controls and panels that could have focus, its not really possible to add keyevents to them all(not to mention gross).</p>
<p>So I found </p>
<pre><code>KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher()
</code></pre>
<p>which is awesome, you can register global keypress pre-handlers. There's a major problem though - spaces will be typed all the time in input fields, table cells, etc, and I obviously dont want to trigger the pause event then!</p>
<p>So any ideas?
Perhaps there is way to detect globally whether the cursor is focused on something that allows text input, without having to check through a list of all the editable controls(vomit!)? </p>
|
[
{
"answer_id": 264703,
"author": "Michael Neale",
"author_id": 699,
"author_profile": "https://Stackoverflow.com/users/699",
"pm_score": 3,
"selected": true,
"text": "<p>I think you answered that yourself - yes I think you can find out the current element that has focus, and if it is an instanceof a certain field class, you ignore the space for the purpose of pause event. If it seams heavy handed, don't worry, instanceof is VERY fast for the JVM (and in any cause you are talking human scale events which are an eon to a processor).</p>\n"
},
{
"answer_id": 266144,
"author": "ykaganovich",
"author_id": 10026,
"author_profile": "https://Stackoverflow.com/users/10026",
"pm_score": 1,
"selected": false,
"text": "<p>I'm rusty on my Swing, but I think you should try registering a global listener using <a href=\"http://java.sun.com/javase/6/docs/api/java/awt/Toolkit.html#addAWTEventListener(java.awt.event.AWTEventListener,%20long)\" rel=\"nofollow noreferrer\">Toolkit.addAWTEventListener</a> with a <code>KEY_EVENT_MASK</code>. You can then filter the AWTEvent processing based on its type and source. </p>\n"
},
{
"answer_id": 267044,
"author": "dalyons",
"author_id": 16925,
"author_profile": "https://Stackoverflow.com/users/16925",
"pm_score": 0,
"selected": false,
"text": "<p>Ok... \nWell im trying to filter based on source. Problem is my editable ComboBoxes...\nThey are instanceof </p>\n\n<pre><code>javax.swing.plaf.basic.BasicComboBoxEditor$BorderlessTextField\n</code></pre>\n\n<p>And since BorderlessTextField is a private inner class, I apparently cant do an instanceof check against it.</p>\n\n<p>ideas?</p>\n\n<p>EDIT: \nok so this works....</p>\n\n<pre><code> KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor(new KeyEventPostProcessor() {\n\n public boolean postProcessKeyEvent(KeyEvent e) {\n if (e.getID() == KeyEvent.KEY_PRESSED) {\n Object s = e.getComponent();\n if (!(s instanceof JTextField) &&\n !(s instanceof JTable && ((JTable) s).isEditing())\n ) {\n music_player.pauseEvent();\n }\n\n //System.out.println(s.getClass().toString());\n }\n return true;\n }\n });\n</code></pre>\n\n<p>Its totally gross and I hate it.\n I wish I could figure out a way to check if the keypress has been consumed by any component - then I could only perform the pause event when the keypress was not actioned by any component.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16925/"
] |
So I want to trigger an event (pausing/unpausing some media) whenever the user presses spacebar anywhere in the my Swing app.
Since there are so many controls and panels that could have focus, its not really possible to add keyevents to them all(not to mention gross).
So I found
```
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher()
```
which is awesome, you can register global keypress pre-handlers. There's a major problem though - spaces will be typed all the time in input fields, table cells, etc, and I obviously dont want to trigger the pause event then!
So any ideas?
Perhaps there is way to detect globally whether the cursor is focused on something that allows text input, without having to check through a list of all the editable controls(vomit!)?
|
I think you answered that yourself - yes I think you can find out the current element that has focus, and if it is an instanceof a certain field class, you ignore the space for the purpose of pause event. If it seams heavy handed, don't worry, instanceof is VERY fast for the JVM (and in any cause you are talking human scale events which are an eon to a processor).
|
264,714 |
<p>I am trying to use a business object that I am passing to the report.rdlc. The properties in my object are not directly exposed. The properties I require are embedded within another object inside the top level object. As this is a WCF project I can't control what goes on at the server end. I am just able to request these objects or Insert/Update/Delete their info from the database. It is done in this way as the back end can use multiple flavors of database. </p>
<p>Here is what I can see after adding my business object as a <code>DataSource</code>:</p>
<pre><code>-BusinessObject
-CustomerInfo
-ClientName
-ColumnName
-DisplayName
-FieldName
-IsNull
-KeyColumn
-SenondKeyColumn
-StringValue
-ClientID
-ColumnName
-DisplayName
-FieldName
-IntValue
-IsNull
-KeyColumn
-SenondKeyColumn
+ClientAddress
+Instrument
+Telephone
</code></pre>
<p>etc etc</p>
<p>I need to be able to display, for example, the <code>ClientName.StringValue</code> field.
If I drag the field I want onto the report I get: </p>
<pre><code>=First(Fields!StringValue.Value)
</code></pre>
<p>This doesn't display anything when the report is run, I assume because it can't qualify what <code>StringValue</code> it is talking about and there could be many. </p>
<p>If I try dragging the <code>ClientName</code> object I get:</p>
<pre><code>=First(Fields!ContactName.Value)
</code></pre>
<p>However this gives:</p>
<pre><code>#ERROR
</code></pre>
<p>When the report is run.</p>
<p>I would have thought you could use:</p>
<pre><code>=First(Fields!ClientName.StringValue.Value)
</code></pre>
<p>but this won't even let me build.</p>
|
[
{
"answer_id": 265685,
"author": "jezell",
"author_id": 27453,
"author_profile": "https://Stackoverflow.com/users/27453",
"pm_score": 0,
"selected": false,
"text": "<p>If you set the data source to the CustomerInfo instance (or list) returned from the service it should work. The ReportViewer control can be a little complicated when you start dealing with object hierarchies, but you don't have to do anything crazy or special if all the information is at the root level.</p>\n"
},
{
"answer_id": 274748,
"author": "Matt Johnson",
"author_id": 34628,
"author_profile": "https://Stackoverflow.com/users/34628",
"pm_score": 2,
"selected": true,
"text": "<p>The problem was that the info wasn't at the root level. I worked it out though.</p>\n\n<pre><code>=First(Fields!ClientName.Value.StringValue, \"BusinessObject_CustomerInfo\")\n</code></pre>\n\n<p>I've got a pretty good grip of the ReportViewer component now cheers.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34628/"
] |
I am trying to use a business object that I am passing to the report.rdlc. The properties in my object are not directly exposed. The properties I require are embedded within another object inside the top level object. As this is a WCF project I can't control what goes on at the server end. I am just able to request these objects or Insert/Update/Delete their info from the database. It is done in this way as the back end can use multiple flavors of database.
Here is what I can see after adding my business object as a `DataSource`:
```
-BusinessObject
-CustomerInfo
-ClientName
-ColumnName
-DisplayName
-FieldName
-IsNull
-KeyColumn
-SenondKeyColumn
-StringValue
-ClientID
-ColumnName
-DisplayName
-FieldName
-IntValue
-IsNull
-KeyColumn
-SenondKeyColumn
+ClientAddress
+Instrument
+Telephone
```
etc etc
I need to be able to display, for example, the `ClientName.StringValue` field.
If I drag the field I want onto the report I get:
```
=First(Fields!StringValue.Value)
```
This doesn't display anything when the report is run, I assume because it can't qualify what `StringValue` it is talking about and there could be many.
If I try dragging the `ClientName` object I get:
```
=First(Fields!ContactName.Value)
```
However this gives:
```
#ERROR
```
When the report is run.
I would have thought you could use:
```
=First(Fields!ClientName.StringValue.Value)
```
but this won't even let me build.
|
The problem was that the info wasn't at the root level. I worked it out though.
```
=First(Fields!ClientName.Value.StringValue, "BusinessObject_CustomerInfo")
```
I've got a pretty good grip of the ReportViewer component now cheers.
|
264,720 |
<p>I am using a GDI+ Graphic to draw a 4000*3000 image to screen, but it is really slow. It takes about 300ms. I wish it just occupy less than 10ms.</p>
<pre><code>Bitmap *bitmap = Bitmap::FromFile("XXXX",...);
</code></pre>
<p>//--------------------------------------------
// this part takes about 300ms, terrible!</p>
<pre><code>int width = bitmap->GetWidth();
int height = bitmap->GetHeight();
DrawImage(bitmap,0,0,width,height);
</code></pre>
<p>//------------------------------------------</p>
<p>I cannot use CachedBitmap, because I want to edit the bitmap later.</p>
<p>How can I improve it? Or is any thing wrong? </p>
<p>This native GDI function also draws the image into the screen, and it just take 1 ms:</p>
<pre><code>SetStretchBltMode(hDC, COLORONCOLOR);
StretchDIBits(hDC, rcDest.left, rcDest.top,
rcDest.right-rcDest.left, rcDest.bottom-rcDest.top,
0, 0, width, height,
BYTE* dib, dibinfo, DIB_RGB_COLORS, SRCCOPY);
</code></pre>
<p>//--------------------------------------------------------------</p>
<p>If I want to use StretchDIBits, I need to pass BITMAPINFO, But how can I get BITMAPINFO from a Gdi+ Bitmap Object? I did the experiment by FreeImage lib, I call StretchDIBits using FreeImageplus object, it draw really fast. But now I need to draw Bitmap, and write some algorithm on Bitmap's bits array, how can I get BITMAPINFO if I have an Bitmap object? It's really annoying -___________-|</p>
|
[
{
"answer_id": 264818,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": true,
"text": "<p>You have a screen of 4000 x 3000 resolution? Wow!</p>\n\n<p>If not, you should draw only the visible part of the image, it would be much faster...</p>\n\n<p>[EDIT after first comment] My remark is indeed a bit stupid, I suppose DrawImage will mask/skip unneeded pixels.</p>\n\n<p>After your edit (showing StretchDIBits), I guess a possible source of speed difference might come from the fact that <a href=\"http://msdn.microsoft.com/en-us/library/ms532289.aspx\" rel=\"nofollow noreferrer\" title=\"StretchDIBits\">StretchDIBits</a> is hardware accelerated (\"<em>If the driver cannot support the JPEG or PNG file image</em>\" is a hint...) while DrawImage might be (I have no proof for that!) coded in C, relying on CPU power instead of GPU's one...</p>\n\n<p>If I recall correctly, DIB images are fast (despite being \"device independent\"). See <a href=\"http://www.drdobbs.com/cpp/184403210?pgno=5\" rel=\"nofollow noreferrer\" title=\"High Speed Win32 Animation\">High Speed Win32 Animation</a>: \"<em>use CreateDIBSection to do high speed animation</em>\". OK, it applies to DIB vs. GDI, in old Windows version (1996!) but I think it is still true.</p>\n\n<p>[EDIT] Maybe <a href=\"http://msdn.microsoft.com/en-us/library/ms536295(VS.85).aspx\" rel=\"nofollow noreferrer\">Bitmap::GetHBITMAP</a> function might help you to use StretchDIBits (not tested...).</p>\n"
},
{
"answer_id": 264926,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 2,
"selected": false,
"text": "<p>Just a thought; instead of retrieving the width and height of the image before drawing, why not cache these values when you load the image?</p>\n"
},
{
"answer_id": 265187,
"author": "Will",
"author_id": 15721,
"author_profile": "https://Stackoverflow.com/users/15721",
"pm_score": 2,
"selected": false,
"text": "<p>Explore the impact of explicitly setting the interpolation mode to NearestNeighbor (where, in your example, it looks like interpolation is not actually needed! But 300ms is the kind of cost of doing high-quality interpolation when no interpolation is needed, so its worth a try)</p>\n\n<p>Another thing to explore is changing the colour depth of the bitmap.</p>\n"
},
{
"answer_id": 265615,
"author": "Cybis",
"author_id": 32998,
"author_profile": "https://Stackoverflow.com/users/32998",
"pm_score": 4,
"selected": false,
"text": "<p>If you're using GDI+, the TextureBrush class is what you need for rendering images fast. I've written a couple of 2d games with it, getting around 30 FPS or so.</p>\n\n<p>I've never written .NET code in C++, so here's a C#-ish example:</p>\n\n<pre><code>Bitmap bmp = new Bitmap(...)\nTextureBrush myBrush = new TextureBrush(bmp)\n\nprivate void Paint(object sender, PaintEventArgs e):\n{\n //Don't draw the bitmap directly. \n //Only draw TextureBrush inside the Paint event.\n e.Graphics.FillRectangle(myBrush, ...)\n}\n</code></pre>\n"
},
{
"answer_id": 265698,
"author": "Martin",
"author_id": 8157,
"author_profile": "https://Stackoverflow.com/users/8157",
"pm_score": 2,
"selected": false,
"text": "<p>Unfortunately when I had a similar problem, I found that GDI+ is known to be much slower than GDI and not generally hardware accelerated, but now Microsoft have moved on to WPF they will not come back to improve GDI+!</p>\n\n<p>All the graphics card manufacturers have moved onto 3D performance and don't seem interested in 2D acceleration, and there's no clear source of information on which functions are or can be hardware accelerated or not. Very frustrating because having written an app in .NET using GDI+, I am not happy to change to a completely different technology to speed it up to reasonable levels.</p>\n"
},
{
"answer_id": 1617930,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 2,
"selected": false,
"text": "<p>i don't think they'll make much of a different, but since you're not actually needing to resize the image, try using the overload of <a href=\"http://msdn.microsoft.com/en-us/library/ms536030.aspx\" rel=\"nofollow noreferrer\">DrawImage</a> that doesn't (attempt) to resize:</p>\n\n<pre><code>DrawImage(bitmap,0,0);\n</code></pre>\n\n<p>Like i said, i doubt it will make any difference, because i'm <em>sure</em> that <strong>DrawImage</strong> checks the <strong>Width</strong> and <strong>Height</strong> of the bitmap, and if there's no resizing needed, just calls this overload. (i would hope it doesn't bother going through all 12 million pixels performing no actual work).</p>\n\n<p>Update: My ponderings are wrong. i had since found out, but guys comment reminded me of my old answer: you <strong>want</strong> to specify the destination size; even though it matches the source size:</p>\n\n<pre><code>DrawImage(bitmap, 0, 0, bitmap.GetWidth, bitmap.GetHeight);\n</code></pre>\n\n<p>The reason is because of dpi differences between the dpi of <code>bitmap</code> and the dpi of the destination. GDI+ will perform scaling to get the image to come out the right \"size\" (i.e. in inches)</p>\n\n<hr>\n\n<p>What i've learned on my own since last October is that you really want to draw a <em>\"cached\"</em> version of your bitmap. There is a <code>CachedBitmap</code> class in GDI+. There are some tricks to using it. But in there end i have a function bit of (Delphi) code that does it.</p>\n\n<p>The caveat is that the <code>CachedBitmap</code> can become invalid - meaning it can't be used to draw. This happens if the user changes resolutions or color depths (e.g. Remote Desktop). In that case the <code>DrawImage</code> will fail, and you have to re-created the <code>CachedBitmap</code>:</p>\n\n<pre><code>class procedure TGDIPlusHelper.DrawCachedBitmap(image: TGPImage;\n var cachedBitmap: TGPCachedBitmap;\n Graphics: TGPGraphics; x, y: Integer; width, height: Integer);\nvar\n b: TGPBitmap;\nbegin\n if (image = nil) then\n begin\n //i've chosen to not throw exceptions during paint code - it gets very nasty\n Exit;\n end;\n\n if (graphics = nil) then\n begin\n //i've chosen to not throw exceptions during paint code - it gets very nasty\n Exit;\n end;\n\n //Check if we have to invalidate the cached image because of size mismatch\n //i.e. if the user has \"zoomed\" the UI\n if (CachedBitmap <> nil) then\n begin\n if (CachedBitmap.BitmapWidth <> width) or (CachedBitmap.BitmapHeight <> height) then\n FreeAndNil(CachedBitmap); //nil'ing it will force it to be re-created down below\n end;\n\n //Check if we need to create the \"cached\" version of the bitmap\n if CachedBitmap = nil then\n begin\n b := TGDIPlusHelper.ResizeImage(image, width, height);\n try\n CachedBitmap := TGPCachedBitmap.Create(b, graphics);\n finally\n b.Free;\n end;\nend;\n\n if (graphics.DrawCachedBitmap(cachedBitmap, x, y) <> Ok) then\nbegin\n //The calls to DrawCachedBitmap failed\n //The API is telling us we have to recreate the cached bitmap\n FreeAndNil(cachedBitmap);\n b := TGDIPlusHelper.ResizeImage(image, width, height);\n try\n CachedBitmap := TGPCachedBitmap.Create(b, graphics);\n finally\n b.Free;\n end;\n\n graphics.DrawCachedBitmap(cachedBitmap, x, y);\n end;\n end;\n</code></pre>\n\n<p>The <code>cachedBitmap</code> is passed in by reference. The first call to <code>DrawCachedBitmap</code> it <em>cached</em> version will be created. You then pass it in subsequent calls, e.g.:</p>\n\n<pre><code>Image imgPrintInvoice = new Image.FromFile(\"printer.png\");\nCachedBitmap imgPrintInvoiceCached = null;\n\n...\n\nint glyphSize = 16 * (GetCurrentDpi() / 96);\n\nDrawCachedBitmap(imgPrintInvoice , ref imgPrintInvoiceCached , graphics, \n 0, 0, glyphSize, glyphSize);\n</code></pre>\n\n<p>i use the routine to draw glyphs on buttons, taking into account the current DPI. The same could have been used by the Internet Explorer team to draw images when the user is running high dpi (ie is very slow drawing zoomed images, because they use GDI+).</p>\n"
},
{
"answer_id": 21456057,
"author": "eugeniy",
"author_id": 3253028,
"author_profile": "https://Stackoverflow.com/users/3253028",
"pm_score": 1,
"selected": false,
"text": "<p>Try using copy of Bitmap from file. FromFile function on some files returns \"slow\" image, but its copy will draw faster.</p>\n\n<pre><code>Bitmap *bitmap = Bitmap::FromFile(\"XXXX\",...);\n\nBitmap *bitmap2 = new Bitmap(bitmap); // make copy\n\nDrawImage(bitmap2,0,0,width,height);\n</code></pre>\n"
},
{
"answer_id": 34011819,
"author": "Sator666",
"author_id": 5451461,
"author_profile": "https://Stackoverflow.com/users/5451461",
"pm_score": 2,
"selected": false,
"text": "<p>/*\nFirst sorry for ma English, and the code is partly in polish, but it's simple to understand.\nI had the same problem and I found the best solution. Here it is.</p>\n\n<p>Dont use: Graphics graphics(hdc); graphics.DrawImage(gpBitmap, 0, 0); It is slow.</p>\n\n<p><strong>Use: GetHBITMAP(Gdiplus::Color(), &g_hBitmap) for HBITMAP and draw using my function ShowBitmapStretch().</strong></p>\n\n<p>You can resize it and it is much faster! Artur Czekalski / Poland</p>\n\n<p>*/</p>\n\n<pre><code>//--------Global-----------\nBitmap *g_pGDIBitmap; //for loading picture\nint gRozXOkna, gRozYOkna; //size of working window\nint gRozXObrazu, gRozYObrazu; //Size of picture X,Y\nHBITMAP g_hBitmap = NULL; //for displaying on window\n//------------------------------------------------------------------------------\nint ShowBitmapStretch(HDC hdc, HBITMAP hBmp, int RozX, int RozY, int RozXSkal, int RozYSkal, int PozX, int PozY) \n{\n if (hBmp == NULL) return -1;\n HDC hdc_mem = CreateCompatibleDC(hdc); //utworzenie kontekstu pamięciowego\n if (NULL == hdc_mem) return -2;\n //Trzeba połączyć BMP z hdc_mem, tzn. umieścić bitmapę w naszym kontekście pamięciowym\n if (DeleteObject(SelectObject(hdc_mem, hBmp)) == NULL) return -3; \n\n SetStretchBltMode(hdc, COLORONCOLOR); //important! for smoothness\n if (StretchBlt(hdc, PozX, PozY, RozXSkal, RozYSkal, hdc_mem, 0, 0, RozX, RozY, SRCCOPY) == 0) return -4;\n\n if (DeleteDC(hdc_mem) == 0) return -5;\n return 0; //OK\n}\n//---------------------------------------------------------------------------\nvoid ClearBitmaps(void)\n{\n if (g_hBitmap) { DeleteObject(g_hBitmap); g_hBitmap = NULL; }\n if (g_pGDIBitmap) { delete g_pGDIBitmap; g_pGDIBitmap = NULL; }\n}\n//---------------------------------------------------------------------------\nvoid MyOpenFile(HWND hWnd, szFileName)\n{\n ClearBitmaps(); //Important!\n g_pGDIBitmap = new Bitmap(szFileName); //load a picture from file\n\n if (g_pGDIBitmap == 0) return;\n //---Checking if picture was loaded\n gRozXObrazu = g_pGDIBitmap->GetWidth();\n gRozYObrazu = g_pGDIBitmap->GetHeight();\n if (gRozXObrazu == 0 || gRozYObrazu == 0) return;\n\n //---Uworzenie bitmapy do wyświatlaia; DO IT ONCE HERE!\n g_pGDIBitmap->GetHBITMAP(Gdiplus::Color(), &g_hBitmap); //creates a GDI bitmap from this Bitmap object\n if (g_hBitmap == 0) return;\n\n //---We need to force the window to redraw itself\n InvalidateRect(hWnd, NULL, TRUE);\n UpdateWindow(hWnd);\n}\n//---------------------------------------------------------------------------\nvoid MyOnPaint(HDC hdc, HWND hWnd) //in case WM_PAINT; DO IT MANY TIMES\n{\n if (g_hBitmap)\n {\n double SkalaX = 1.0, SkalaY = 1.0; //scale\n if (gRozXObrazu > gRozXOkna || gRozYObrazu > gRozYOkna || //too big picture, więc zmniejsz; \n (gRozXObrazu < gRozXOkna && gRozYObrazu < gRozYOkna)) //too small picture, można powiększyć \n {\n SkalaX = (double)gRozXOkna / (double)gRozXObrazu; //np. 0.7 dla zmniejszania; FOR DECREASE\n SkalaY = (double)gRozYOkna / (double)gRozYObrazu; //np. 1.7 dla powiększania; FOR INCREASE\n if (SkalaY < SkalaX) SkalaX = SkalaY; //ZAWSZE wybierz większe skalowanie, czyli mniejszą wartość i utaw w SkalaX\n }\n\n if (ShowBitmapStretch(hdc, g_hBitmap, gRozXObrazu, gRozYObrazu, (int)(gRozXObrazu*SkalaX), (int)(gRozYObrazu*SkalaX), 0, 0, msg) < 0) return;\n</code></pre>\n"
},
{
"answer_id": 46006572,
"author": "Mostafa Saad",
"author_id": 5082934,
"author_profile": "https://Stackoverflow.com/users/5082934",
"pm_score": 0,
"selected": false,
"text": "<p>I have made some researching and wasn't able to find a way to render images with GDI/GDI+ more faster than</p>\n\n<pre><code>Graphics.DrawImage/DrawImageUnscaled\n</code></pre>\n\n<p>and at the same time simple like it.</p>\n\n<p>Till I discovered</p>\n\n<pre><code>ImageList.Draw(GFX,Point,Index)\n</code></pre>\n\n<p>and yeah it's really so fast and simple.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25749/"
] |
I am using a GDI+ Graphic to draw a 4000\*3000 image to screen, but it is really slow. It takes about 300ms. I wish it just occupy less than 10ms.
```
Bitmap *bitmap = Bitmap::FromFile("XXXX",...);
```
//--------------------------------------------
// this part takes about 300ms, terrible!
```
int width = bitmap->GetWidth();
int height = bitmap->GetHeight();
DrawImage(bitmap,0,0,width,height);
```
//------------------------------------------
I cannot use CachedBitmap, because I want to edit the bitmap later.
How can I improve it? Or is any thing wrong?
This native GDI function also draws the image into the screen, and it just take 1 ms:
```
SetStretchBltMode(hDC, COLORONCOLOR);
StretchDIBits(hDC, rcDest.left, rcDest.top,
rcDest.right-rcDest.left, rcDest.bottom-rcDest.top,
0, 0, width, height,
BYTE* dib, dibinfo, DIB_RGB_COLORS, SRCCOPY);
```
//--------------------------------------------------------------
If I want to use StretchDIBits, I need to pass BITMAPINFO, But how can I get BITMAPINFO from a Gdi+ Bitmap Object? I did the experiment by FreeImage lib, I call StretchDIBits using FreeImageplus object, it draw really fast. But now I need to draw Bitmap, and write some algorithm on Bitmap's bits array, how can I get BITMAPINFO if I have an Bitmap object? It's really annoying -\_\_\_\_\_\_\_\_\_\_\_-|
|
You have a screen of 4000 x 3000 resolution? Wow!
If not, you should draw only the visible part of the image, it would be much faster...
[EDIT after first comment] My remark is indeed a bit stupid, I suppose DrawImage will mask/skip unneeded pixels.
After your edit (showing StretchDIBits), I guess a possible source of speed difference might come from the fact that [StretchDIBits](http://msdn.microsoft.com/en-us/library/ms532289.aspx "StretchDIBits") is hardware accelerated ("*If the driver cannot support the JPEG or PNG file image*" is a hint...) while DrawImage might be (I have no proof for that!) coded in C, relying on CPU power instead of GPU's one...
If I recall correctly, DIB images are fast (despite being "device independent"). See [High Speed Win32 Animation](http://www.drdobbs.com/cpp/184403210?pgno=5 "High Speed Win32 Animation"): "*use CreateDIBSection to do high speed animation*". OK, it applies to DIB vs. GDI, in old Windows version (1996!) but I think it is still true.
[EDIT] Maybe [Bitmap::GetHBITMAP](http://msdn.microsoft.com/en-us/library/ms536295(VS.85).aspx) function might help you to use StretchDIBits (not tested...).
|
264,745 |
<p>Imagine the following</p>
<p>A type T has a field Company.
When executing the following method it works perfectly:</p>
<pre><code>Type t = typeof(T);
t.GetProperty("Company")
</code></pre>
<p>Whith the following call I get null though</p>
<pre><code>Type t = typeof(T);
t.GetProperty("company", BindingFlags.IgnoreCase)
</code></pre>
<p>Anybody got an idea?</p>
|
[
{
"answer_id": 264748,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 6,
"selected": false,
"text": "<p>You need to add <code>BindingFlags.Public | BindingFlags.Instance</code></p>\n"
},
{
"answer_id": 264752,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 10,
"selected": true,
"text": "<p>You've overwritten the default look-up flags, if you specify new flags you need to provide all the info so that the property can be found. For example: <code>BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance</code></p>\n"
},
{
"answer_id": 1461101,
"author": "Josh Warner-Burke",
"author_id": 177271,
"author_profile": "https://Stackoverflow.com/users/177271",
"pm_score": 4,
"selected": false,
"text": "<p>Thanks, this really helped me out in a pinch today. I had audit information saved, but with incorrect casing on the property names. (The auditing is built into a datalayer.) Anyway so I had to add IgnoreCase as a binding flag, but then it still didn't work, till my coworker found this answer. The resulting function:</p>\n\n<pre><code>public static void SetProperty(Object R, string propertyName, object value)\n{\n Type type = R.GetType();\n object result;\n result = type.InvokeMember(\n propertyName, \n BindingFlags.SetProperty | \n BindingFlags.IgnoreCase | \n BindingFlags.Public | \n BindingFlags.Instance, \n null, \n R, \n new object[] { value });\n}\n</code></pre>\n\n<p>This is part of a class I call DotMagic.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] |
Imagine the following
A type T has a field Company.
When executing the following method it works perfectly:
```
Type t = typeof(T);
t.GetProperty("Company")
```
Whith the following call I get null though
```
Type t = typeof(T);
t.GetProperty("company", BindingFlags.IgnoreCase)
```
Anybody got an idea?
|
You've overwritten the default look-up flags, if you specify new flags you need to provide all the info so that the property can be found. For example: `BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance`
|
264,763 |
<p>I am using msbuild to build a C++ project and I want to suppress the 'Post-Build Event'. I have tried the following properties with no success:</p>
<pre><code>/property:PostBuildEvent=
/property:VCPostBuildEventTool=
</code></pre>
<p>Neither will make any difference and the post build events are still executed.</p>
<p>Does anyone know how to suppress these (and potentially other) events using msbuild?</p>
|
[
{
"answer_id": 264851,
"author": "Paul Fedory",
"author_id": 30023,
"author_profile": "https://Stackoverflow.com/users/30023",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried setting the build event to something other than blank? If you overwrite it with something superfluous, like a \"dir\" or something, does it still execute the original post-build steps?</p>\n\n<p>It's not the most elegant solution, but it might work.</p>\n"
},
{
"answer_id": 265129,
"author": "Rob",
"author_id": 9236,
"author_profile": "https://Stackoverflow.com/users/9236",
"pm_score": 0,
"selected": false,
"text": "<p>Ack, it looks like msbuild actually calls vcbuild which isn't as flexible, so I think I'm stuck.</p>\n"
},
{
"answer_id": 277742,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 0,
"selected": false,
"text": "<p>If you are able to modify the post-build events, you could do this with an environment variable, say <code>SKIP_POST_BUILD_EVENTS</code>. You can then set that environment variable before calling <code>msbuild</code>, and check whether the variable exists in the post-build event before executing whatever code is there.</p>\n"
},
{
"answer_id": 489354,
"author": "leftend",
"author_id": 11460,
"author_profile": "https://Stackoverflow.com/users/11460",
"pm_score": 3,
"selected": true,
"text": "<p>I just figured out how to do this. There's 2 steps involved:</p>\n\n<p>First, if you're not starting the msbuild process using a batch file already, create a batch file that calls the msbuild process. Then add a variable in the batch file before you call the msbuild process. Something like this:</p>\n\n<pre><code>set ISFULLBUILD=True\nmsbuild TFSBuild.proj >> BuildOutput.txt\n</code></pre>\n\n<p>Then, you need to modify your post build event to only do something if the variable is not set, or has the wrong value:</p>\n\n<pre><code>IF NOT '%ISFULLBUILD%'=='True' copy /y $(TargetFileName) \"..\\..\\..\\..\\..\\..\\Binaries\\$(ConfigurationName)\\\"\n</code></pre>\n\n<p>In this case - the TargetFileName (Whatever.dll) will only get copied when you're building from Visual Studio. But, when you build using your new batch file - it will NOT execute the command after the IF statement.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
I am using msbuild to build a C++ project and I want to suppress the 'Post-Build Event'. I have tried the following properties with no success:
```
/property:PostBuildEvent=
/property:VCPostBuildEventTool=
```
Neither will make any difference and the post build events are still executed.
Does anyone know how to suppress these (and potentially other) events using msbuild?
|
I just figured out how to do this. There's 2 steps involved:
First, if you're not starting the msbuild process using a batch file already, create a batch file that calls the msbuild process. Then add a variable in the batch file before you call the msbuild process. Something like this:
```
set ISFULLBUILD=True
msbuild TFSBuild.proj >> BuildOutput.txt
```
Then, you need to modify your post build event to only do something if the variable is not set, or has the wrong value:
```
IF NOT '%ISFULLBUILD%'=='True' copy /y $(TargetFileName) "..\..\..\..\..\..\Binaries\$(ConfigurationName)\"
```
In this case - the TargetFileName (Whatever.dll) will only get copied when you're building from Visual Studio. But, when you build using your new batch file - it will NOT execute the command after the IF statement.
|
264,764 |
<p>I'm currently working on a WebSphere 6.1 Web Project.</p>
<p>In my java code, how can i get the current running application port?</p>
|
[
{
"answer_id": 265080,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 3,
"selected": true,
"text": "<p>The servlet API gives you the local port in HttpServletRequest.</p>\n\n<pre><code>protected void doGet(HttpServletRequest request,\n HttpServletResponse response) throws ServletException, IOException {\n PrintWriter writer = response.getWriter();\n writer.write(\"\" + request.getLocalPort());\n writer.close();\n}\n</code></pre>\n\n<p>The ports are defined in the node's <em>serverindex.xml</em> (e.g. [WAS]/profiles/AppSrv01/config/cells/localhostNode01Cell/nodes/localhostNode01/serverindex.xml).</p>\n\n<pre><code><specialEndpoints xmi:id=\"NamedEndPoint_1214751102556\" endPointName=\"WC_defaulthost\">\n <endPoint xmi:id=\"EndPoint_1214751102556\" host=\"*\" port=\"9080\"/>\n</code></pre>\n\n<p>I'm not sure if the WAS JMX support exposes this information - you'd have to check the doc.</p>\n"
},
{
"answer_id": 25380560,
"author": "Frizz1977",
"author_id": 1794049,
"author_profile": "https://Stackoverflow.com/users/1794049",
"pm_score": 0,
"selected": false,
"text": "<p>If you use RAD you can run administrative console from IDE and then discover all the ports used by WAS </p>\n\n<p><a href=\"http://pic.dhe.ibm.com/infocenter/radhelp/v9/index.jsp?topic=%2Fcom.ibm.sca.tools.doc%2Fsamples%2Ftopics%2Fwas_ports.html\" rel=\"nofollow noreferrer\">http://pic.dhe.ibm.com/infocenter/radhelp/v9/index.jsp?topic=%2Fcom.ibm.sca.tools.doc%2Fsamples%2Ftopics%2Fwas_ports.html</a>\n<img src=\"https://i.stack.imgur.com/097kP.png\" alt=\"enter image description here\"></p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2937/"
] |
I'm currently working on a WebSphere 6.1 Web Project.
In my java code, how can i get the current running application port?
|
The servlet API gives you the local port in HttpServletRequest.
```
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
writer.write("" + request.getLocalPort());
writer.close();
}
```
The ports are defined in the node's *serverindex.xml* (e.g. [WAS]/profiles/AppSrv01/config/cells/localhostNode01Cell/nodes/localhostNode01/serverindex.xml).
```
<specialEndpoints xmi:id="NamedEndPoint_1214751102556" endPointName="WC_defaulthost">
<endPoint xmi:id="EndPoint_1214751102556" host="*" port="9080"/>
```
I'm not sure if the WAS JMX support exposes this information - you'd have to check the doc.
|
264,766 |
<p>My code works great in IE8, Firefox and Safari. But it doesn't work properly in Opera.
What happens is that the DIV is hidden but the space occupied by the DIV remains to appear in my web-page.</p>
<pre><code><div style=" z-index:-1;height :380; width:760; position:relative; text-align:center" id="new-add">
<object id="banner-flash" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"
width="769" height="382" top="0">
<param name="movie" value="exp.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="wmode" value="transparent" />
<embed src="exp.swf" wmode="transparent" quality="high" bgcolor="#ffffff" width="780" height="382"
name="mymoviename" align="" type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer">
</embed>
</object>
</div>
<div id="fechar-link" style=" font-family: Verdana,Arial,Helvetica,sans-serif; font-style: normal;
font-variant: normal; font-weight: normal; font-size: 10pt; line-height: normal; font-size-adjust: none;
font-stretch: normal; text-decoration: none; text-align:center" >
<a href="#" onclick="
document.getElementById('new-add').style.height =0;
document.getElementById('banner-flash').style.height =0;
document.getElementById('fechar-link').style.height = 0;
document.getElementById('new-add').style.visibility ='hidden';
document.getElementById('banner-flash').style.visibility ='hidden';
document.getElementById('fechar-link').style.visibility ='hidden'; " >Close</a>
</div>
</code></pre>
<p>What do I need to do, so the space occupied by the DIV disappears?</p>
<p>Thanks</p>
|
[
{
"answer_id": 264774,
"author": "Romain Linsolas",
"author_id": 26457,
"author_profile": "https://Stackoverflow.com/users/26457",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know if it will solve your problem, but you can try to use :</p>\n\n<pre><code>document.getElementById(\"xxx\").display = \"none\";\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>document.getElementById(\"xxx\").style.visibility = \"hidden\";\n</code></pre>\n"
},
{
"answer_id": 264777,
"author": "Vinzz",
"author_id": 28922,
"author_profile": "https://Stackoverflow.com/users/28922",
"pm_score": 4,
"selected": true,
"text": "<p>You might try the style.display property:</p>\n<blockquote>\n<p>Hide</p>\n<p>document.getElementById('YourElem').style.display = 'none';</p>\n<p>Show</p>\n<p>document.getElementById('YourElem').style.display = '';</p>\n</blockquote>\n<p><strong>EDIT:</strong> Took PorneL comment into acocunt in this answer</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019426/"
] |
My code works great in IE8, Firefox and Safari. But it doesn't work properly in Opera.
What happens is that the DIV is hidden but the space occupied by the DIV remains to appear in my web-page.
```
<div style=" z-index:-1;height :380; width:760; position:relative; text-align:center" id="new-add">
<object id="banner-flash" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"
width="769" height="382" top="0">
<param name="movie" value="exp.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="wmode" value="transparent" />
<embed src="exp.swf" wmode="transparent" quality="high" bgcolor="#ffffff" width="780" height="382"
name="mymoviename" align="" type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer">
</embed>
</object>
</div>
<div id="fechar-link" style=" font-family: Verdana,Arial,Helvetica,sans-serif; font-style: normal;
font-variant: normal; font-weight: normal; font-size: 10pt; line-height: normal; font-size-adjust: none;
font-stretch: normal; text-decoration: none; text-align:center" >
<a href="#" onclick="
document.getElementById('new-add').style.height =0;
document.getElementById('banner-flash').style.height =0;
document.getElementById('fechar-link').style.height = 0;
document.getElementById('new-add').style.visibility ='hidden';
document.getElementById('banner-flash').style.visibility ='hidden';
document.getElementById('fechar-link').style.visibility ='hidden'; " >Close</a>
</div>
```
What do I need to do, so the space occupied by the DIV disappears?
Thanks
|
You might try the style.display property:
>
> Hide
>
>
> document.getElementById('YourElem').style.display = 'none';
>
>
> Show
>
>
> document.getElementById('YourElem').style.display = '';
>
>
>
**EDIT:** Took PorneL comment into acocunt in this answer
|
264,817 |
<p>I have code similar to the following in many places:</p>
<pre><code>var dbParams = db.ReadParams(memberID, product, GetSubscriptionFields());
Debug.Assert(dbParams.Count == 4);
_memberCode = dbParams[0];
_password = dbParams[1];
_userName = dbParams[2];
_reasonCode = dbParams[3];
</code></pre>
<p>ReadParams() returns an array of strings, the number of strings depending on the GetSubscriptionFields() function. I could use dbParams[] directly in my code, but I find it more helpful to give meaningful names to each of the values in the array. Is there a way I can get all the results directly, without going through the array?</p>
<p>I am looking for something like:</p>
<pre><code>db.ReadParams(memberID, product, out _memberCode, out _password, out _userName, out _reasonCode);
</code></pre>
<p>or</p>
<pre><code>Tuple<_memberCode, _password, _userName, _reasonCode> = db.ReadParams(memberID, product);
</code></pre>
<p>Of course, it has to be legal C# code :)</p>
|
[
{
"answer_id": 264849,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 2,
"selected": true,
"text": "<p>Why not use constants instead?</p>\n\n<p>Then in your code you could have</p>\n\n<pre><code>dbParams[MEMBER_CODE]\ndbParams[PASSWORD]\ndbParams[USERNAME]\ndbParams[REASON_CODE]\n</code></pre>\n\n<p>which meets your goal of meaningful names without changing the way the method works.</p>\n"
},
{
"answer_id": 264855,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 1,
"selected": false,
"text": "<p>I think your Tuple idea is pretty good. You could define it like this:</p>\n\n<pre><code>public class Tuple<T1, T2, T3, T4>\n{\n public T1 Field1 { get; set; }\n public T2 Field2 { get; set; }\n public T3 Field3 { get; set; }\n public T4 Field4 { get; set; }\n}\n</code></pre>\n\n<p>You would probably want to define a few of those, with two and three properties. Unfortunately it doesn't help you naming the properties of the class. There really is no way to do that (at least not until C# 4.0, when you could use dynamic typing with an anonymous type.</p>\n"
},
{
"answer_id": 264861,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p>Not really; since the number of arguments isn't fixed, there isn't really a better way of doing it. The problem with regular tuples is that you are still working positionally - just with \".Value0\" instead of \"[0]\". And anonymous types can't be directly exposed in an API.</p>\n\n<p>Of course, you could subsequently wrap the values in your own class with properties, and just do a projection:</p>\n\n<pre><code> return new Foo {MemberCode = arr[0], ...}\n</code></pre>\n\n<p>(where Foo is your class that represents whatever this result is, with named, typed properties)</p>\n\n<p>Alternatively you could throw them into a dictionary, but this doesn't help the caller any more than an array does.</p>\n\n<p>The only other option is something <em>really</em> grungy like accepting a params array of <code>Action<string></code> that you use to assign each. I'll elaborate on the last <strong>just for fun</strong> - I don't suggest you do this:</p>\n\n<pre><code>static void Main()\n{\n string name = \"\";\n int value = 0;\n Foo(\"whatever\",\n x => { name = x; },\n x => { value = int.Parse(x); }); \n}\n// yucky; wash eyes after reading...\nstatic void Foo(string query, params Action<string>[] actions)\n{\n string[] results = Bar(query); // the actual query\n int len = actions.Length < results.Length ? actions.Length : results.Length;\n for (int i = 0; i < len; i++)\n {\n actions[i](results[i]);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 264869,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 2,
"selected": false,
"text": "<p>You are writing code in a highly object oriented language, so why don't you use objects?</p>\n\n<pre><code>Member m = db.ReadParams(memberID, product, GetSubscriptionFields());\n</code></pre>\n\n<p>and in your code you use</p>\n\n<pre><code>m.memberCode\nm.password\nm.username\nm.reasonCode\n</code></pre>\n\n<p>Of course you don't have to make the values publicly accessible, you can make them only accessible via setter/getter methods, and by only having getters, you can avoid them from being altered after object creation.</p>\n\n<p>Of course different calls to db.ReadParams should return different objects, e.g. you can create an abstract base class and inherit all possible results from db.ReadParams of it. Therefor you may have to encapsulate db.ReadParams into another method that finds out the right type of object to create:</p>\n\n<pre><code>ReadParamsResult rpr = myDb.ReadParamsAsObject(memberID, product, GetSubscriptionFields());\n\n// Verify that the expected result object has been returned\nDebug.Assert(rpr is Member);\n\n// Downcast\nMember m = (Member)rpr;\n</code></pre>\n"
},
{
"answer_id": 274504,
"author": "Marcel Popescu",
"author_id": 31793,
"author_profile": "https://Stackoverflow.com/users/31793",
"pm_score": 0,
"selected": false,
"text": "<p>I also came up with this... I kinda like it most, but it's a personal preference, I understand it's definitely not the cleanest idea:</p>\n\n<pre><code>using System.Diagnostics;\n\npublic static class ArrayExtractor\n{\n public static void Extract<T1>(this object[] array, out T1 value1)\n where T1 : class\n {\n Debug.Assert(array.Length >= 1);\n value1 = array[0] as T1;\n }\n\n public static void Extract<T1, T2>(this object[] array, out T1 value1, out T2 value2)\n where T1 : class\n where T2 : class\n {\n Debug.Assert(array.Length >= 2);\n value1 = array[0] as T1;\n value2 = array[1] as T2;\n }\n}\n</code></pre>\n\n<p>Of course, I am extending this class up to 10 or 15 arguments.</p>\n\n<p>Usage:</p>\n\n<pre><code>string fileName;\nstring contents;\nArrayExtractor.Extract(args, out fileName, out contents);\n</code></pre>\n\n<p>or even better</p>\n\n<pre><code>args.Extract(out fileName, out contents);\n</code></pre>\n\n<p>where args is, of course, an object array.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31793/"
] |
I have code similar to the following in many places:
```
var dbParams = db.ReadParams(memberID, product, GetSubscriptionFields());
Debug.Assert(dbParams.Count == 4);
_memberCode = dbParams[0];
_password = dbParams[1];
_userName = dbParams[2];
_reasonCode = dbParams[3];
```
ReadParams() returns an array of strings, the number of strings depending on the GetSubscriptionFields() function. I could use dbParams[] directly in my code, but I find it more helpful to give meaningful names to each of the values in the array. Is there a way I can get all the results directly, without going through the array?
I am looking for something like:
```
db.ReadParams(memberID, product, out _memberCode, out _password, out _userName, out _reasonCode);
```
or
```
Tuple<_memberCode, _password, _userName, _reasonCode> = db.ReadParams(memberID, product);
```
Of course, it has to be legal C# code :)
|
Why not use constants instead?
Then in your code you could have
```
dbParams[MEMBER_CODE]
dbParams[PASSWORD]
dbParams[USERNAME]
dbParams[REASON_CODE]
```
which meets your goal of meaningful names without changing the way the method works.
|
264,823 |
<p>Pretty simple question: When i have a persistable object, it usually has a property called ID (for abstract classes).</p>
<p>So .. is the naming convention ID or Id?</p>
<p>eg.</p>
<pre><code>public int ID { get; set; }
</code></pre>
<p>or</p>
<pre><code>public int Id { get; set; }
</code></pre>
<p>cheers :)</p>
<p>PS. This is for .NET btw. FXCop conformat would be a bonus.</p>
|
[
{
"answer_id": 264831,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 1,
"selected": false,
"text": "<p>I prefer ID, also in combination with other words (e.g. CustomerID), but strictly speaking that is against the regular naming conventions. </p>\n"
},
{
"answer_id": 264835,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 2,
"selected": false,
"text": "<p>We use ID internally, because Id seems to me like psychology speak, but FxCop complains, as ID is not an acronym, its an abbreviation (for Identity/Identifier). According to the FxCop rule, only acronyms that are two characters long are allowed to be all caps. Everything else should be Proper case.</p>\n\n<p>We put a SuppressMessage attribute on the ID property, and everyone is happy.</p>\n"
},
{
"answer_id": 264840,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 3,
"selected": false,
"text": "<p>Whatever you like it to be, just be consistent. ID is not a word, it's an abbreviation of identity. How to write abbreviations is something people argue about for a long time. E.g. is it</p>\n\n<pre><code>getResourceURL\n</code></pre>\n\n<p>or</p>\n\n<pre><code>getResourceUrl\n</code></pre>\n\n<p>actually both can be found in use in different frameworks. Another popular abbr. with similar problem is UTF8.</p>\n\n<p>It's just important to be consistent, because otherwise people always have to look up the correct capitalization for every method, if every method handles it in a different way. </p>\n\n<p>I have my own convention for that. If the abbr. is at the end of the name, it is all capitalized, if it's somewhere else, it follows camel notation rules. E.g.</p>\n\n<pre><code>getResourceURL\nurlOfResource\ncompareUrlToString\n</code></pre>\n\n<p>Why? I like abbr. to be capitalized. Most people expect URL or UTF to be capitalized. However, if in the middle of a name, it destroys the advantage of camel notation. The advantage of camel notation is that you see where a new word starts by capitalization. So compare:</p>\n\n<pre><code>compareURLToString\ncompareUrlToString\n</code></pre>\n\n<p>In the first case, I don't see immediately the URL is one word and To is the next one. The T might be part of URL (URLT) and be a different abbr., thus I'll use the second form. If it's at the end however, it won't play a role, no other word follows, thus I prefer the capitalized form. I stick to this convention throughout all of my code.</p>\n"
},
{
"answer_id": 264841,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 6,
"selected": true,
"text": "<p>I usually go with <em>Identifier</em>. If I really want to keep it short (as part of a longer identifier, for example), I use Id, unless it's a parameter or private member.</p>\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/ms229043.aspx\" rel=\"noreferrer\">.NET Framework Naming Guidelines</a> say this:</p>\n<blockquote>\n<p>An acronym is a word that is formed from the letters of words in a term or phrase. For example, HTML is an acronym for Hypertext Markup Language. You should include acronyms in identifiers only when they are widely known and well understood. Acronyms differ from abbreviations in that an abbreviation shortens a single word. For example, ID is an abbreviation for identifier. In general, library names should not use abbreviations.</p>\n<p>The two abbreviations that can be used in identifiers are ID and OK. In Pascal-cased identifiers they should appear as Id, and Ok. If used as the first word in a camel-cased identifier, they should appear as id and ok, respectively.</p>\n</blockquote>\n"
},
{
"answer_id": 264863,
"author": "t3mujin",
"author_id": 15968,
"author_profile": "https://Stackoverflow.com/users/15968",
"pm_score": 0,
"selected": false,
"text": "<p>We around here see things like \"Id\" or other acronyms as a word, and \"Id\" is the easy one because in the banking business we do get lots of strange letter combinations. So we treat it as a word, only with the first letter capitalized, and that's how we ended up being defined in our internal coding conventions paper.</p>\n\n<p>But the bottom line is: choose what convention is more comfortable for the developer team and other people that look at the source code and stick with it. </p>\n"
},
{
"answer_id": 264864,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 3,
"selected": false,
"text": "<p>The guidelines say \"Id\".</p>\n\n<p>Fortunately the the .Net guys were kind enough to give us \"naming guidelines\" and not \"naming laws\" ;), so basically if you strongly feel that breaking a guideline rule does add more value than following it, then by all means break it, no one will take you accountable for it if they understand your reasons (like it provides more readability and accentuates the meaning of the name)</p>\n\n<p>In my shop we use 'ID' even if the guidelines say 'Id', but no one, really feels guilty about it.</p>\n"
},
{
"answer_id": 264879,
"author": "Filini",
"author_id": 21162,
"author_profile": "https://Stackoverflow.com/users/21162",
"pm_score": 2,
"selected": false,
"text": "<p>As others pointed out, Id is right according to .NET conventions, but somehow it doesn't feel right, so many people use ID (and still live).</p>\n\n<p>I don't know what the content of your field will be (numbers, strings, guids), but if you want to skip the problem you may simply use another .NET convention for object identifiers: <strong>Name</strong></p>\n"
},
{
"answer_id": 782457,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>\"ID\" is one of abbreviations hardcoded in FxCop naming rules that are always considered wrong spelled even if they are parts of other words. The only way I found to override it is adding \"ID\" to Acronyms as ():</p>\n\n<pre><code><Dictionary>\n<Acronyms>\n <CasingExceptions>\n <Acronym>ID</Acronym>\n </CasingExceptions>\n</Acronyms>\n</Dictionary>\n</code></pre>\n\n<p>It worked with FxCop 1.36.\nP.S. In general, I think that \"Id\" is a better alternative but sometimes it's impossible to change a name if it's generated based on XML files (or web services) which we don't control</p>\n"
},
{
"answer_id": 1132326,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://en.wiktionary.org/wiki/id#Abbreviation\" rel=\"nofollow noreferrer\">http://en.wiktionary.org/wiki/id#Abbreviation</a></p>\n\n<p>Why fight it?</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
Pretty simple question: When i have a persistable object, it usually has a property called ID (for abstract classes).
So .. is the naming convention ID or Id?
eg.
```
public int ID { get; set; }
```
or
```
public int Id { get; set; }
```
cheers :)
PS. This is for .NET btw. FXCop conformat would be a bonus.
|
I usually go with *Identifier*. If I really want to keep it short (as part of a longer identifier, for example), I use Id, unless it's a parameter or private member.
The [.NET Framework Naming Guidelines](http://msdn.microsoft.com/en-us/library/ms229043.aspx) say this:
>
> An acronym is a word that is formed from the letters of words in a term or phrase. For example, HTML is an acronym for Hypertext Markup Language. You should include acronyms in identifiers only when they are widely known and well understood. Acronyms differ from abbreviations in that an abbreviation shortens a single word. For example, ID is an abbreviation for identifier. In general, library names should not use abbreviations.
>
>
> The two abbreviations that can be used in identifiers are ID and OK. In Pascal-cased identifiers they should appear as Id, and Ok. If used as the first word in a camel-cased identifier, they should appear as id and ok, respectively.
>
>
>
|
264,825 |
<p>There is a console Java application which is supposed to run until it is stopped by <kbd>Ctrl</kbd>+<kbd>C</kbd> or closing the console window. How that application can be programmed to execute a clean up code before exit?</p>
|
[
{
"answer_id": 264833,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<p>You could use a <a href=\"http://www.onjava.com/pub/a/onjava/2003/03/26/shutdownhook.html\" rel=\"noreferrer\">Shutdown Hook</a>.</p>\n\n<p>Basically you need to create a Thread which will perform your shutdown actions, and then <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)\" rel=\"noreferrer\">add it as a shutdown hook</a>. For example:</p>\n\n<pre><code>class ShutdownHook extends Thread\n{\n public void run()\n {\n // perform shutdown actions\n }\n}\n\n// Then, somewhere in your code\n\nRuntime.getRuntime().addShutdownHook(new ShutdownHook())\n</code></pre>\n"
},
{
"answer_id": 265169,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>A Shutdown hook is the way to go, but be aware that there is no guarantee that the code is actually executed. JVM crashes, power failures, or a simple \"kill -9\" on your JVM can prevent the code from cleaning up. Therefore you must ensure that your program stays in a consistent state even if it has been aborted abruptly.</p>\n\n<p>Personally, I simply use a database for all state-storage. Its transactions model makes sure that the persistent storage is in a sane state no matter what happens. They spend years making that code fool-proof, so why should I waste my time on problems already solved.</p>\n"
},
{
"answer_id": 9098218,
"author": "alok bisht",
"author_id": 1182997,
"author_profile": "https://Stackoverflow.com/users/1182997",
"pm_score": 0,
"selected": false,
"text": "<p>The code written inside a <code>Thread</code>s <code>run()</code> method will execute when the runtime object terminates...</p>\n\n<pre><code>class ShutdownHookclass extends Thread {\n public void run() {\n // perform shutdown actions\n }\n}\n\n//could be written anywhere in your code\nRuntime.getRuntime().addShutdownHook(new ShutdownHookclass())\n</code></pre>\n"
},
{
"answer_id": 9098294,
"author": "alok bisht",
"author_id": 1182997,
"author_profile": "https://Stackoverflow.com/users/1182997",
"pm_score": 1,
"selected": false,
"text": "<p>Program to delete temp file bat.bat when program is exited:</p>\n\n<pre><code>public class Backup {\n\n public static void createBackup(String s)\n {\n\n try{\n String fileName =\"C:\\\\bat\"+ \".bat\";\n FileWriter writer=new FileWriter(fileName);\n String batquery=\"cd C:\\\\Program Files\\\\MySQL\\\\MySQL Server 5.0\\\\bin\"\n + \"\\nmysqldump -uroot -proot bankdb > \\\"\"+s+\".sql\\\"\" \n +\"\\nexit\";\n\n writer.append(batquery);\n writer.close();\n }\n catch(Exception e){e.getMessage();}\n try{\n Process p =Runtime.getRuntime().exec(\"cmd /c start C:\\\\bat.bat\");\n\n }\n catch(Exception e){e.getMessage();}\n ShutDownHook sdh=new ShutDownHook();\n Runtime.getRuntime().addShutdownHook(sdh);\n }\n\n\n}\n\n class ShutDownHook extends Thread\n {\n public void run()\n {\n try\n {\n File f=new File(\"c:/bat.bat\");\n f.delete();\n }\n catch(Exception e){e.getMessage();}\n\n }\n\n }\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31993/"
] |
There is a console Java application which is supposed to run until it is stopped by `Ctrl`+`C` or closing the console window. How that application can be programmed to execute a clean up code before exit?
|
You could use a [Shutdown Hook](http://www.onjava.com/pub/a/onjava/2003/03/26/shutdownhook.html).
Basically you need to create a Thread which will perform your shutdown actions, and then [add it as a shutdown hook](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)). For example:
```
class ShutdownHook extends Thread
{
public void run()
{
// perform shutdown actions
}
}
// Then, somewhere in your code
Runtime.getRuntime().addShutdownHook(new ShutdownHook())
```
|
264,832 |
<p>I am using attribute_fu to render a nice block of rows for a particular table.</p>
<pre><code><%= f.render_associated_form(@foo.bars, :new => 5) %>
</code></pre>
<p>I would like to have the <code>bar</code> partial have some notion of a bit of state. (Because the notion is specific to the view, I do not want to externalize this to the <code>Bar</code> model itself and calculate it in the controller.) For simplicity's sake, pretend it is the index of the <code>bar</code> in the <code>@foo.bars</code> list. </p>
<p>(I am aware that if this was the case I could use the :collection => @foo.bars to enable bar_counter... this doesn't appear to function in my tests but I have seen docs for it.)</p>
<p>My question -- how do I pass a variable into the partial such that I can keep and edit the state? Naively, I assumed that doing something like </p>
<pre><code><% @tmp = {:index => 1} %>
%= f.render_associated_form(@foo.bars, :new => 5, :locals => {:tmp => @tmp}) %>
#goes in the view
<%= tmp[:index] += 1 %>
</code></pre>
<p>would work. <code>tmp</code> gets passed appropriately but calling [] throws "Uh oh, you just called a method on nil". Surprisingly to me, I can do tmp.inspect, tmp.class, etc to look at the Hash, and these have the results I would expect. But tmp[:index] or tmp[:anything_I_want] cause it to blow up. </p>
<p>Making <code>tmp</code> an array had similar results.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 271059,
"author": "Patrick McKenzie",
"author_id": 15046,
"author_profile": "https://Stackoverflow.com/users/15046",
"pm_score": 1,
"selected": false,
"text": "<p>I ended up solving this in a thoroughly Rails fashion -- patching :attribute_fu to meet my needs. Hopefully I'll be able to release my patches to the community fairly soon.</p>\n"
},
{
"answer_id": 278463,
"author": "Cameron Price",
"author_id": 35526,
"author_profile": "https://Stackoverflow.com/users/35526",
"pm_score": 0,
"selected": false,
"text": "<p>The behavior you describe above seems like it must be a bug in attribute_fu, since the local isn't getting properly passed along, which it definitely should. I'd be interested to know what you did to patch it.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15046/"
] |
I am using attribute\_fu to render a nice block of rows for a particular table.
```
<%= f.render_associated_form(@foo.bars, :new => 5) %>
```
I would like to have the `bar` partial have some notion of a bit of state. (Because the notion is specific to the view, I do not want to externalize this to the `Bar` model itself and calculate it in the controller.) For simplicity's sake, pretend it is the index of the `bar` in the `@foo.bars` list.
(I am aware that if this was the case I could use the :collection => @foo.bars to enable bar\_counter... this doesn't appear to function in my tests but I have seen docs for it.)
My question -- how do I pass a variable into the partial such that I can keep and edit the state? Naively, I assumed that doing something like
```
<% @tmp = {:index => 1} %>
%= f.render_associated_form(@foo.bars, :new => 5, :locals => {:tmp => @tmp}) %>
#goes in the view
<%= tmp[:index] += 1 %>
```
would work. `tmp` gets passed appropriately but calling [] throws "Uh oh, you just called a method on nil". Surprisingly to me, I can do tmp.inspect, tmp.class, etc to look at the Hash, and these have the results I would expect. But tmp[:index] or tmp[:anything\_I\_want] cause it to blow up.
Making `tmp` an array had similar results.
Any ideas?
|
I ended up solving this in a thoroughly Rails fashion -- patching :attribute\_fu to meet my needs. Hopefully I'll be able to release my patches to the community fairly soon.
|
264,857 |
<p>I have a simple database:</p>
<pre><code>ARTICLE
----------
ArticleId (PK),
ArticleTitle
..other stuff...
USER-ARTICLE
------------
ArchiveId (PK),
UserId,
ArticleId
..other stuff...
</code></pre>
<p>The <code>articleId</code>'s are foreign keys. </p>
<p>I want to be able to delete a user article row by <code>UserArticleId</code> using the following code,</p>
<pre><code>UserArticle myobjtodelete = PersonalArchiveDb.UserArticles.Single(ua => ua.ArchiveId == 3);
PersonalArchiveDb.UserArticles.DeleteOnSubmit(myobjtodelete);
PersonalArchiveDb.SubmitChanges();
</code></pre>
<p><sup>(Yes I'm aware I can do the statement inside the delete rather than retrieving the object, it was for debugging purposes to make sure the object definitely exists - it does.)</sup></p>
<p>When the debugger hits the <code>SubmitChanges()</code> line, I get a runtime error:</p>
<blockquote>
<p>Specified cast is not valid.</p>
</blockquote>
<p>Here is the stack trace,</p>
<blockquote>
<p>at System.Data.Linq.IdentityManager
.StandardIdentityManager
.SingleKeyManager`2.TryCreateKeyFromValues(Object[] values, V& v) at
System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache`2.Find(Object[]
keyValues) at
System.Data.Linq.IdentityManager.StandardIdentityManager.Find(MetaType
type, Object[] keyValues) at
System.Data.Linq.CommonDataServices.GetCachedObject(MetaType type,
Object[] keyValues) at
System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc,
Object instance) at
System.Data.Linq.ChangeProcessor.BuildEdgeMaps() at
System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode
failureMode) at
System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)<br>
at System.Data.Linq.DataContext.SubmitChanges() at
Driver_SOC_ASO.Controls.PersonalArchive.ArchiveListing.grdArchive_RowDeleting(Object
sender, GridViewDeleteEventArgs e) in
C:\work\Driver.Net\Driver-SOC-ASO\Driver-SOC-ASO\Controls\PersonalArchive\ArchiveListing.ascx.cs:line
78 at
System.Web.UI.WebControls.GridView.OnRowDeleting(GridViewDeleteEventArgs
e) at System.Web.UI.WebControls.GridView.HandleDelete(GridViewRow
row, Int32 rowIndex) at
System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean
causesValidation, String validationGroup) at
System.Web.UI.WebControls.GridView.RaisePostBackEvent(String
eventArgument) at
System.Web.UI.WebControls.GridView.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String
eventArgument) at
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
sourceControl, String eventArgument) at
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)<br>
at System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)</p>
</blockquote>
<p>I am at a loss, any ideas?</p>
|
[
{
"answer_id": 718301,
"author": "Rony",
"author_id": 51326,
"author_profile": "https://Stackoverflow.com/users/51326",
"pm_score": 0,
"selected": false,
"text": "<p>try setting ON CASCADE DELETE for <code>ArticleId</code></p>\n"
},
{
"answer_id": 947931,
"author": "Jim Counts",
"author_id": 36737,
"author_profile": "https://Stackoverflow.com/users/36737",
"pm_score": 1,
"selected": false,
"text": "<p>This may be an example of this <a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=351358\" rel=\"nofollow noreferrer\">bug</a>, which Microsoft says is fixed in .NET 4.0.</p>\n"
},
{
"answer_id": 2420866,
"author": "DotNetWala",
"author_id": 225174,
"author_profile": "https://Stackoverflow.com/users/225174",
"pm_score": 0,
"selected": false,
"text": "<p>In your dbml, check to see if there is incorrect an association b/w Article and UserArticle.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3193/"
] |
I have a simple database:
```
ARTICLE
----------
ArticleId (PK),
ArticleTitle
..other stuff...
USER-ARTICLE
------------
ArchiveId (PK),
UserId,
ArticleId
..other stuff...
```
The `articleId`'s are foreign keys.
I want to be able to delete a user article row by `UserArticleId` using the following code,
```
UserArticle myobjtodelete = PersonalArchiveDb.UserArticles.Single(ua => ua.ArchiveId == 3);
PersonalArchiveDb.UserArticles.DeleteOnSubmit(myobjtodelete);
PersonalArchiveDb.SubmitChanges();
```
(Yes I'm aware I can do the statement inside the delete rather than retrieving the object, it was for debugging purposes to make sure the object definitely exists - it does.)
When the debugger hits the `SubmitChanges()` line, I get a runtime error:
>
> Specified cast is not valid.
>
>
>
Here is the stack trace,
>
> at System.Data.Linq.IdentityManager
> .StandardIdentityManager
> .SingleKeyManager`2.TryCreateKeyFromValues(Object[] values, V& v) at
> System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache`2.Find(Object[]
> keyValues) at
> System.Data.Linq.IdentityManager.StandardIdentityManager.Find(MetaType
> type, Object[] keyValues) at
> System.Data.Linq.CommonDataServices.GetCachedObject(MetaType type,
> Object[] keyValues) at
> System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc,
> Object instance) at
> System.Data.Linq.ChangeProcessor.BuildEdgeMaps() at
> System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode
> failureMode) at
> System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
>
> at System.Data.Linq.DataContext.SubmitChanges() at
> Driver\_SOC\_ASO.Controls.PersonalArchive.ArchiveListing.grdArchive\_RowDeleting(Object
> sender, GridViewDeleteEventArgs e) in
> C:\work\Driver.Net\Driver-SOC-ASO\Driver-SOC-ASO\Controls\PersonalArchive\ArchiveListing.ascx.cs:line
> 78 at
> System.Web.UI.WebControls.GridView.OnRowDeleting(GridViewDeleteEventArgs
> e) at System.Web.UI.WebControls.GridView.HandleDelete(GridViewRow
> row, Int32 rowIndex) at
> System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean
> causesValidation, String validationGroup) at
> System.Web.UI.WebControls.GridView.RaisePostBackEvent(String
> eventArgument) at
> System.Web.UI.WebControls.GridView.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String
> eventArgument) at
> System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
> sourceControl, String eventArgument) at
> System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
>
> at System.Web.UI.Page.ProcessRequestMain(Boolean
> includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
>
>
>
I am at a loss, any ideas?
|
This may be an example of this [bug](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=351358), which Microsoft says is fixed in .NET 4.0.
|
264,907 |
<p>I am running a Solr instance on Jetty and when I search using the Solr admin panel, it returns the entire document. What should I do to get only specified fields from each Solr document returned by the search?</p>
|
[
{
"answer_id": 289882,
"author": "Andrew Ingram",
"author_id": 15687,
"author_profile": "https://Stackoverflow.com/users/15687",
"pm_score": 8,
"selected": true,
"text": "<pre><code>/?q=query&fl=field1,field2,field3\n</code></pre>\n"
},
{
"answer_id": 345024,
"author": "KenE",
"author_id": 43783,
"author_profile": "https://Stackoverflow.com/users/43783",
"pm_score": 3,
"selected": false,
"text": "<p>From the Solr Admin home page, click on \"Full Interface\". On that page there is a box called \"Fields to Return\". You can list the you want here (comma-separated). \"*\" means all fields.</p>\n"
},
{
"answer_id": 44922725,
"author": "Sonu",
"author_id": 5295306,
"author_profile": "https://Stackoverflow.com/users/5295306",
"pm_score": 0,
"selected": false,
"text": "<p>The best way is to run the query from Admin concole. When we run it, it also provides the actuall SQL query executed. Just copy the query and use it.</p>\n\n<p>About the question: select specific fields from the table. In the admin console look for 'FL' text box. write the field names you want to retrieve, comma sapereted. Hit the 'Execute Query' button. \nTop right side the SQL will be available.</p>\n\n<p>Generated Query: ......select?fl=FIELDNAME&indent=on&q=<em>:</em>&wt=json</p>\n"
},
{
"answer_id": 48007913,
"author": "Nanda Kumar",
"author_id": 8647198,
"author_profile": "https://Stackoverflow.com/users/8647198",
"pm_score": 1,
"selected": false,
"text": "<pre><code>http://xx.xxx.xx.xx:8983/solr/corename/select?indent=on&q=*:*&wt=json&fl=ImageID,Imagepath,Category\n</code></pre>\n\n<p>This link has fl parameter:\nfl is a field list, which will display the specified fields from the indexed list.</p>\n"
},
{
"answer_id": 49729843,
"author": "Rahul Holkar",
"author_id": 9618548,
"author_profile": "https://Stackoverflow.com/users/9618548",
"pm_score": 0,
"selected": false,
"text": "<p>you can simply pass fl parameter with required fields name in your query.</p>\n\n<p>&fl=field1,field2,field3&query=<em>:</em></p>\n\n<p>your response documents contains only mentioned fields.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2220518/"
] |
I am running a Solr instance on Jetty and when I search using the Solr admin panel, it returns the entire document. What should I do to get only specified fields from each Solr document returned by the search?
|
```
/?q=query&fl=field1,field2,field3
```
|
264,909 |
<p>do you have idea, if there would be some nice way to browse/log JMS queues? (I'm using OpenJMS)</p>
<p>For topics I can just add one consumer more and that's about it but with queues I haven't finished with a solution yet. I would like to log all the messages in certain queues and topics without "popping" them from the queue (so that the logger counld browse queues "invisible").</p>
<p>With <strong>javax.jms.QueueBrowser</strong> i can get a snapshot of the queues but that doesn't seem to provide "listener solution" - reading all the messages on the queues on infinite loop again and again and hoping that no messages happen to be both written and consumed before my snapshots - that didn't sound like a good solution.</p>
<p>Another option would be to create two queues for each "logical queue" - one for logger and one for the actual use - logger would then forward the messages to the "actual queue" - that could maybe work but there could be better solution?</p>
<p>So if somebody has a solution to get all messages in a queue by an "invisible" logger or some nice other solution for the logging, that'd be cool.</p>
|
[
{
"answer_id": 289882,
"author": "Andrew Ingram",
"author_id": 15687,
"author_profile": "https://Stackoverflow.com/users/15687",
"pm_score": 8,
"selected": true,
"text": "<pre><code>/?q=query&fl=field1,field2,field3\n</code></pre>\n"
},
{
"answer_id": 345024,
"author": "KenE",
"author_id": 43783,
"author_profile": "https://Stackoverflow.com/users/43783",
"pm_score": 3,
"selected": false,
"text": "<p>From the Solr Admin home page, click on \"Full Interface\". On that page there is a box called \"Fields to Return\". You can list the you want here (comma-separated). \"*\" means all fields.</p>\n"
},
{
"answer_id": 44922725,
"author": "Sonu",
"author_id": 5295306,
"author_profile": "https://Stackoverflow.com/users/5295306",
"pm_score": 0,
"selected": false,
"text": "<p>The best way is to run the query from Admin concole. When we run it, it also provides the actuall SQL query executed. Just copy the query and use it.</p>\n\n<p>About the question: select specific fields from the table. In the admin console look for 'FL' text box. write the field names you want to retrieve, comma sapereted. Hit the 'Execute Query' button. \nTop right side the SQL will be available.</p>\n\n<p>Generated Query: ......select?fl=FIELDNAME&indent=on&q=<em>:</em>&wt=json</p>\n"
},
{
"answer_id": 48007913,
"author": "Nanda Kumar",
"author_id": 8647198,
"author_profile": "https://Stackoverflow.com/users/8647198",
"pm_score": 1,
"selected": false,
"text": "<pre><code>http://xx.xxx.xx.xx:8983/solr/corename/select?indent=on&q=*:*&wt=json&fl=ImageID,Imagepath,Category\n</code></pre>\n\n<p>This link has fl parameter:\nfl is a field list, which will display the specified fields from the indexed list.</p>\n"
},
{
"answer_id": 49729843,
"author": "Rahul Holkar",
"author_id": 9618548,
"author_profile": "https://Stackoverflow.com/users/9618548",
"pm_score": 0,
"selected": false,
"text": "<p>you can simply pass fl parameter with required fields name in your query.</p>\n\n<p>&fl=field1,field2,field3&query=<em>:</em></p>\n\n<p>your response documents contains only mentioned fields.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28482/"
] |
do you have idea, if there would be some nice way to browse/log JMS queues? (I'm using OpenJMS)
For topics I can just add one consumer more and that's about it but with queues I haven't finished with a solution yet. I would like to log all the messages in certain queues and topics without "popping" them from the queue (so that the logger counld browse queues "invisible").
With **javax.jms.QueueBrowser** i can get a snapshot of the queues but that doesn't seem to provide "listener solution" - reading all the messages on the queues on infinite loop again and again and hoping that no messages happen to be both written and consumed before my snapshots - that didn't sound like a good solution.
Another option would be to create two queues for each "logical queue" - one for logger and one for the actual use - logger would then forward the messages to the "actual queue" - that could maybe work but there could be better solution?
So if somebody has a solution to get all messages in a queue by an "invisible" logger or some nice other solution for the logging, that'd be cool.
|
```
/?q=query&fl=field1,field2,field3
```
|
264,914 |
<p>Being used to (and potentially spoiled by) <code>MSSQL</code>, I'm wondering how I can get at tables size in <code>Oracle</code> 10g.
I have googled it so I'm now aware that I may not have as easy an option as <code>sp_spaceused</code>. Still the potential answers I got are most of the time outdated or don't work. Probably because I'm no DBA on the schema I'm working with.</p>
<p>Would anyone have solutions and or recommendations?</p>
|
[
{
"answer_id": 264928,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 3,
"selected": false,
"text": "<p>IIRC the tables you need are DBA_TABLES, DBA_EXTENTS or DBA_SEGMENTS and DBA_DATA_FILES. There are also USER_ and ALL_ versions of these for tables you can see if you don't have administration permissions on the machine.</p>\n"
},
{
"answer_id": 264975,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 3,
"selected": false,
"text": "<p>First, gather optimiser stats on the table (if you haven't already):</p>\n\n<pre><code>begin\n dbms_stats.gather_table_stats('MYSCHEMA','MYTABLE');\nend;\n/\n</code></pre>\n\n<p><em>WARNING: As Justin says in his answer, gathering optimiser stats affects query optimisation and should not be done without due care and consideration</em>!</p>\n\n<p>Then find the number of blocks occupied by the table from the generated stats:</p>\n\n<pre><code>select blocks, empty_blocks, num_freelist_blocks\nfrom all_tables\nwhere owner = 'MYSCHEMA'\nand table_name = 'MYTABLE';\n</code></pre>\n\n<ul>\n<li><p>The total number of blocks allocated to the table is blocks + empty_blocks + num_freelist_blocks.</p></li>\n<li><p>blocks is the number of blocks that actually contain data.</p></li>\n</ul>\n\n<p>Multiply the number of blocks by the block size in use (usually 8KB) to get the space consumed - e.g. 17 blocks x 8KB = 136KB.</p>\n\n<p>To do this for all tables in a schema at once:</p>\n\n<pre><code>begin\n dbms_stats.gather_schema_stats ('MYSCHEMA');\nend;\n/\n\nselect table_name, blocks, empty_blocks, num_freelist_blocks\nfrom user_tables;\n</code></pre>\n\n<p>Note: Changes made to the above after reading <a href=\"http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:266215435203\" rel=\"noreferrer\">this AskTom thread</a></p>\n"
},
{
"answer_id": 265536,
"author": "Justin Cave",
"author_id": 10397,
"author_profile": "https://Stackoverflow.com/users/10397",
"pm_score": 5,
"selected": false,
"text": "<p>First off, I would generally caution that gathering table statistics in order to do space analysis is a potentially dangerous thing to do. Gathering statistics may change query plans, particularly if the DBA has configured a statistics gathering job that uses non-default parameters that your call is not using, and will cause Oracle to re-parse queries that utilize the table in question which can be a performance hit. If the DBA has intentionally left some tables without statistics (common if your <code>OPTIMIZER_MODE</code> is CHOOSE), gathering statistics can cause Oracle to stop using the rule-based optimizer and start using the cost-based optimizer for a set of queries which can be a major performance headache if it is done unexpectedly in production. If your statistics are accurate, you can query <code>USER_TABLES</code> (or <code>ALL_TABLES</code> or <code>DBA_TABLES</code>) directly without calling <code>GATHER_TABLE_STATS</code>. If your statistics are not accurate, there is probably a reason for that and you don't want to disturb the status quo.</p>\n\n<p>Second, the closest equivalent to the SQL Server <code>sp_spaceused</code> procedure is likely Oracle's <code>DBMS_SPACE</code> package. Tom Kyte has a nice <a href=\"http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:231414051079\" rel=\"noreferrer\"><code>show_space</code> procedure</a> that provides a simple interface to this package and prints out information similar to what <code>sp_spaceused</code> prints out.</p>\n"
},
{
"answer_id": 266947,
"author": "Gary Myers",
"author_id": 25714,
"author_profile": "https://Stackoverflow.com/users/25714",
"pm_score": 1,
"selected": false,
"text": "<p>Depends what you mean by \"table's size\". \nA table doesn't relate to a specific file on the file system. A table will reside on a tablespace (possibly multiple tablespaces if it is partitioned, and possibly multiple tablespaces if you also want to take into account indexes on the table).\nA tablespace will often have multiple tables in it, and may be spread across multiple files.</p>\n\n<p>If you are estimating how much space you'll need for the table's future growth, then avg_row_len multiplied by the number of rows in the table (or number of rows you expect in the table) will be a good guide. \nBut Oracle will leave some space free on each block, partly to allow for rows to 'grow' if they are updated, partly because it may not be possible to fit another entire row on that block (eg an 8K block would only fit 2 rows of 3K, though that would be an extreme example as 3K is a lot bigger than most row sizes).\nSo BLOCKS (in USER_TABLES) might be a better guide.</p>\n\n<p>But if you had 200,000 rows in a table, deleted half of them, then the table would still 'own' the same number of blocks. It doesn't release them up for other tables to use.\nAlso, blocks are not added to a table individually, but in groups called an 'extent'. So there are generally going to be EMPTY_BLOCKS (also in USER_TABLES) in a table.</p>\n"
},
{
"answer_id": 266964,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 8,
"selected": false,
"text": "<p>You might be interested in this query. It tells you how much space is allocated for each table taking into account the indexes and any LOBs on the table. Often you are interested to know \"How much spaces the the Purchase Order table take, including any indexes\" rather than just the table itself. You can always delve into the details. Note that this requires access to the DBA_* views.</p>\n\n<pre><code>COLUMN TABLE_NAME FORMAT A32\nCOLUMN OBJECT_NAME FORMAT A32\nCOLUMN OWNER FORMAT A10\n\nSELECT\n owner, \n table_name, \n TRUNC(sum(bytes)/1024/1024) Meg,\n ROUND( ratio_to_report( sum(bytes) ) over () * 100) Percent\nFROM\n(SELECT segment_name table_name, owner, bytes\n FROM dba_segments\n WHERE segment_type IN ('TABLE', 'TABLE PARTITION', 'TABLE SUBPARTITION')\n UNION ALL\n SELECT i.table_name, i.owner, s.bytes\n FROM dba_indexes i, dba_segments s\n WHERE s.segment_name = i.index_name\n AND s.owner = i.owner\n AND s.segment_type IN ('INDEX', 'INDEX PARTITION', 'INDEX SUBPARTITION')\n UNION ALL\n SELECT l.table_name, l.owner, s.bytes\n FROM dba_lobs l, dba_segments s\n WHERE s.segment_name = l.segment_name\n AND s.owner = l.owner\n AND s.segment_type IN ('LOBSEGMENT', 'LOB PARTITION')\n UNION ALL\n SELECT l.table_name, l.owner, s.bytes\n FROM dba_lobs l, dba_segments s\n WHERE s.segment_name = l.index_name\n AND s.owner = l.owner\n AND s.segment_type = 'LOBINDEX')\nWHERE owner in UPPER('&owner')\nGROUP BY table_name, owner\nHAVING SUM(bytes)/1024/1024 > 10 /* Ignore really small tables */\nORDER BY SUM(bytes) desc\n;\n</code></pre>\n"
},
{
"answer_id": 851686,
"author": "Noam",
"author_id": 49008,
"author_profile": "https://Stackoverflow.com/users/49008",
"pm_score": 0,
"selected": false,
"text": "<p>Simple select that returns the raw sizes of the tables, based on the block size, also includes size with index</p>\n\n<p>select table_name,(nvl\n((\nselect sum( blocks)\nfrom dba_indexes a,dba_segments b\nwhere a.index_name=b.segment_name\n and a.table_name=dba_tables.table_name\n),0)+blocks)*8192/1024 TotalSize,blocks*8 tableSize\nfrom dba_tables\norder by 3</p>\n"
},
{
"answer_id": 7104978,
"author": "Vijay Chettiar",
"author_id": 900269,
"author_profile": "https://Stackoverflow.com/users/900269",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select segment_name as tablename, sum(bytes/ (1024 * 1024 * 1024)) as tablesize_in_GB\nFrom dba_segments /* if looking at tables not owned by you else use user_segments */\nwhere segment_name = 'TABLE_WHOSE_SIZE_I_WANT_TO_KNOW'\nand OWNER = 'WHO OWNS THAT TABLE' /* if user_segments is used delete this line */ \ngroup by segment_name ;\n</code></pre>\n"
},
{
"answer_id": 10109416,
"author": "grokster",
"author_id": 502441,
"author_profile": "https://Stackoverflow.com/users/502441",
"pm_score": 6,
"selected": false,
"text": "<pre><code>-- Tables + Size MB\nselect owner, table_name, round((num_rows*avg_row_len)/(1024*1024)) MB \nfrom all_tables \nwhere owner not like 'SYS%' -- Exclude system tables.\nand num_rows > 0 -- Ignore empty Tables.\norder by MB desc -- Biggest first.\n;\n\n\n--Tables + Rows\nselect owner, table_name, num_rows\n from all_tables \nwhere owner not like 'SYS%' -- Exclude system tables.\nand num_rows > 0 -- Ignore empty Tables.\norder by num_rows desc -- Biggest first.\n;\n</code></pre>\n\n<blockquote>\n <p>Note: These are estimates, made more accurate with gather statistics: </p>\n</blockquote>\n\n<pre><code>exec dbms_utility.analyze_schema(user,'COMPUTE');\n</code></pre>\n"
},
{
"answer_id": 10927004,
"author": "Geoffrey Musafu",
"author_id": 1441502,
"author_profile": "https://Stackoverflow.com/users/1441502",
"pm_score": 0,
"selected": false,
"text": "<p>I found this to be a little more accurate:</p>\n\n<pre><code>SELECT\n owner, table_name, TRUNC(sum(bytes)/1024/1024/1024) GB\nFROM\n(SELECT segment_name table_name, owner, bytes\nFROM dba_segments\nWHERE segment_type in ('TABLE','TABLE PARTITION')\nUNION ALL\nSELECT i.table_name, i.owner, s.bytes\nFROM dba_indexes i, dba_segments s\nWHERE s.segment_name = i.index_name\nAND s.owner = i.owner\nAND s.segment_type in ('INDEX','INDEX PARTITION')\nUNION ALL\nSELECT l.table_name, l.owner, s.bytes\nFROM dba_lobs l, dba_segments s\nWHERE s.segment_name = l.segment_name\nAND s.owner = l.owner\nAND s.segment_type IN ('LOBSEGMENT','LOB PARTITION')\nUNION ALL\nSELECT l.table_name, l.owner, s.bytes\nFROM dba_lobs l, dba_segments s\nWHERE s.segment_name = l.index_name\nAND s.owner = l.owner\nAND s.segment_type = 'LOBINDEX')\n---WHERE owner in UPPER('&owner')\nGROUP BY table_name, owner\nHAVING SUM(bytes)/1024/1024 > 10 /* Ignore really small tables */\nORDER BY SUM(bytes) desc\n</code></pre>\n"
},
{
"answer_id": 13947612,
"author": "rratina",
"author_id": 1915068,
"author_profile": "https://Stackoverflow.com/users/1915068",
"pm_score": 3,
"selected": false,
"text": "<p>For sub partitioned tables and indexes we can use the following query</p>\n\n<pre><code>\n\n SELECT owner, table_name, ROUND(sum(bytes)/1024/1024/1024, 2) GB\n FROM\n (SELECT segment_name table_name, owner, bytes\n FROM dba_segments\n WHERE segment_type IN ('TABLE', 'TABLE PARTITION', 'TABLE SUBPARTITION')\n UNION ALL\n SELECT i.table_name, i.owner, s.bytes\n FROM dba_indexes i, dba_segments s\n WHERE s.segment_name = i.index_name\n AND s.owner = i.owner\n AND s.segment_type IN ('INDEX', 'INDEX PARTITION', 'INDEX SUBPARTITION')\n UNION ALL\n SELECT l.table_name, l.owner, s.bytes\n FROM dba_lobs l, dba_segments s\n WHERE s.segment_name = l.segment_name\n AND s.owner = l.owner\n AND s.segment_type = 'LOBSEGMENT'\n UNION ALL\n SELECT l.table_name, l.owner, s.bytes\n FROM dba_lobs l, dba_segments s\n WHERE s.segment_name = l.index_name\n AND s.owner = l.owner\n AND s.segment_type = 'LOBINDEX')\n WHERE owner in UPPER('&owner')\n GROUP BY table_name, owner\n HAVING SUM(bytes)/1024/1024 > 10 /* Ignore really small tables */\n ORDER BY SUM(bytes) DESC\n ;\n\n</code></pre>\n"
},
{
"answer_id": 15666753,
"author": "SS64",
"author_id": 1720814,
"author_profile": "https://Stackoverflow.com/users/1720814",
"pm_score": 3,
"selected": false,
"text": "<p>Heres a variant on WWs answer, it includes partitions and sub-partitions as others above have suggested, plus a column to show the TYPE: Table/Index/LOB etc</p>\n\n<pre><code>SELECT\n owner, \"Type\", table_name \"Name\", TRUNC(sum(bytes)/1024/1024) Meg\nFROM\n( SELECT segment_name table_name, owner, bytes, 'Table' as \"Type\"\n FROM dba_segments\n WHERE segment_type in ('TABLE','TABLE PARTITION','TABLE SUBPARTITION')\n UNION ALL\n SELECT i.table_name, i.owner, s.bytes, 'Index' as \"Type\"\n FROM dba_indexes i, dba_segments s\n WHERE s.segment_name = i.index_name\n AND s.owner = i.owner\n AND s.segment_type in ('INDEX','INDEX PARTITION','INDEX SUBPARTITION')\n UNION ALL\n SELECT l.table_name, l.owner, s.bytes, 'LOB' as \"Type\"\n FROM dba_lobs l, dba_segments s\n WHERE s.segment_name = l.segment_name\n AND s.owner = l.owner\n AND s.segment_type IN ('LOBSEGMENT','LOB PARTITION','LOB SUBPARTITION')\n UNION ALL\n SELECT l.table_name, l.owner, s.bytes, 'LOB Index' as \"Type\"\n FROM dba_lobs l, dba_segments s\n WHERE s.segment_name = l.index_name\n AND s.owner = l.owner\n AND s.segment_type = 'LOBINDEX')\n WHERE owner in UPPER('&owner')\nGROUP BY table_name, owner, \"Type\"\nHAVING SUM(bytes)/1024/1024 > 10 /* Ignore really small tables */\nORDER BY SUM(bytes) desc;\n</code></pre>\n"
},
{
"answer_id": 16661034,
"author": "Sergey Stadnik",
"author_id": 10557,
"author_profile": "https://Stackoverflow.com/users/10557",
"pm_score": 3,
"selected": false,
"text": "<p>I modified the WW's query to provide more detailed information:</p>\n\n<pre><code>SELECT * FROM (\n SELECT\n owner, object_name, object_type, table_name, ROUND(bytes)/1024/1024 AS meg,\n tablespace_name, extents, initial_extent,\n ROUND(Sum(bytes/1024/1024) OVER (PARTITION BY table_name)) AS total_table_meg\n FROM (\n -- Tables\n SELECT owner, segment_name AS object_name, 'TABLE' AS object_type,\n segment_name AS table_name, bytes,\n tablespace_name, extents, initial_extent\n FROM dba_segments\n WHERE segment_type IN ('TABLE', 'TABLE PARTITION', 'TABLE SUBPARTITION')\n UNION ALL\n -- Indexes\n SELECT i.owner, i.index_name AS object_name, 'INDEX' AS object_type,\n i.table_name, s.bytes,\n s.tablespace_name, s.extents, s.initial_extent\n FROM dba_indexes i, dba_segments s\n WHERE s.segment_name = i.index_name\n AND s.owner = i.owner\n AND s.segment_type IN ('INDEX', 'INDEX PARTITION', 'INDEX SUBPARTITION')\n -- LOB Segments\n UNION ALL\n SELECT l.owner, l.column_name AS object_name, 'LOB_COLUMN' AS object_type,\n l.table_name, s.bytes,\n s.tablespace_name, s.extents, s.initial_extent\n FROM dba_lobs l, dba_segments s\n WHERE s.segment_name = l.segment_name\n AND s.owner = l.owner\n AND s.segment_type = 'LOBSEGMENT'\n -- LOB Indexes\n UNION ALL\n SELECT l.owner, l.column_name AS object_name, 'LOB_INDEX' AS object_type,\n l.table_name, s.bytes,\n s.tablespace_name, s.extents, s.initial_extent\n FROM dba_lobs l, dba_segments s\n WHERE s.segment_name = l.index_name\n AND s.owner = l.owner\n AND s.segment_type = 'LOBINDEX'\n )\n WHERE owner = UPPER('&owner')\n)\nWHERE total_table_meg > 10\nORDER BY total_table_meg DESC, meg DESC\n/\n</code></pre>\n"
},
{
"answer_id": 17177068,
"author": "user2498491",
"author_id": 2498491,
"author_profile": "https://Stackoverflow.com/users/2498491",
"pm_score": -1,
"selected": false,
"text": "<p>I have the same variant as the last ones which calculates segments of table data, table indexes and blob-fields:</p>\n\n<pre><code>CREATE OR REPLACE FUNCTION\n SYS.RAZMER_TABLICY_RAW(pNazvanie in varchar, pOwner in varchar2)\nreturn number\nis\n val number(16);\n sz number(16);\nbegin\n sz := 0;\n\n --Calculate size of table data segments\n select\n sum(t.bytes) into val\n from\n sys.dba_segments t\n where\n t.segment_name = upper(pNazvanie)\n and\n t.owner = upper(pOwner);\n sz := sz + nvl(val,0);\n\n --Calculate size of table indexes segments\n select\n sum(s.bytes) into val\n from\n all_indexes t\n inner join\n dba_segments s\n on\n t.index_name = s.segment_name\n where\n t.table_name = upper(pNazvanie)\n and\n t.owner = upper(pOwner);\n sz := sz + nvl(val,0);\n\n --Calculate size of table blob segments\n select\n sum(s.bytes) into val\n from\n all_lobs t\n inner join\n dba_segments s on t.segment_name = s.segment_name\n where\n t.table_name = upper(pNazvanie)\n and\n t.owner = upper(pOwner);\n sz := sz + nvl(val,0);\n\n return sz;\n\nend razmer_tablicy_raw;\n</code></pre>\n\n<p><a href=\"http://konurbaev-e.blogspot.ru/2013/06/oracle-database-how-to-calculate-actual.html\" rel=\"nofollow\">Source</a>.</p>\n"
},
{
"answer_id": 19784650,
"author": "mrvlad",
"author_id": 1559870,
"author_profile": "https://Stackoverflow.com/users/1559870",
"pm_score": -1,
"selected": false,
"text": "<p>there one more option that allows to get \"select\" size with joins, and table size as option too</p>\n\n<pre><code>-- 1\nEXPLAIN PLAN\n FOR\n SELECT\n Scheme.Table_name.table_column1 AS \"column1\",\n Scheme.Table_name.table_column2 AS \"column2\",\n Scheme.Table_name.table_column3 AS \"column3\",\n FROM Scheme.Table_name\n WHERE ;\n\nSELECT * FROM TABLE (DBMS_XPLAN.display);\n</code></pre>\n"
},
{
"answer_id": 20603961,
"author": "rratina",
"author_id": 3106111,
"author_profile": "https://Stackoverflow.com/users/3106111",
"pm_score": 1,
"selected": false,
"text": "<p>Correction for partitioned tables: </p>\n\n<blockquote>\n<pre><code>SELECT owner, table_name, ROUND(sum(bytes)/1024/1024/1024, 2) GB\nFROM\n(SELECT segment_name table_name, owner, bytes\n FROM dba_segments\n WHERE segment_type IN ('TABLE', 'TABLE PARTITION', 'TABLE SUBPARTITION')\n UNION ALL\n SELECT i.table_name, i.owner, s.bytes\n FROM dba_indexes i, dba_segments s\n WHERE s.segment_name = i.index_name\n AND s.owner = i.owner\n AND s.segment_type IN ('INDEX', 'INDEX PARTITION', 'INDEX SUBPARTITION')\n UNION ALL\n SELECT l.table_name, l.owner, s.bytes\n FROM dba_lobs l, dba_segments s\n WHERE s.segment_name = l.segment_name\n and s.owner = l.owner\n AND s.segment_type in ('LOBSEGMENT', 'LOB PARTITION', 'LOB SUBPARTITION')\n UNION ALL\n SELECT l.table_name, l.owner, s.bytes\n FROM dba_lobs l, dba_segments s\n WHERE s.segment_name = l.index_name\n AND s.owner = l.owner\n AND s.segment_type = 'LOBINDEX')\nWHERE owner in UPPER('&owner')\nGROUP BY table_name, owner\nHAVING SUM(bytes)/1024/1024 > 10 /* Ignore really small tables */\norder by sum(bytes) desc\n;\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 23098053,
"author": "bronx",
"author_id": 3331762,
"author_profile": "https://Stackoverflow.com/users/3331762",
"pm_score": 2,
"selected": false,
"text": "<pre><code>select segment_name,segment_type,bytes/1024/1024 MB\nfrom dba_segments\nwhere segment_name='TABLENAME' and owner ='OWNERNAME' order by mb desc;\n</code></pre>\n"
},
{
"answer_id": 47378564,
"author": "Najee Ghanim",
"author_id": 4481610,
"author_profile": "https://Stackoverflow.com/users/4481610",
"pm_score": 2,
"selected": false,
"text": "<p>I modified the query to get the schema size per tablespace ..</p>\n\n<pre><code>SELECT owner,\n tablespace_name,\n TRUNC (SUM (bytes) / 1024 / 1024) Meg,\n ROUND (ratio_to_report (SUM (bytes)) OVER () * 100) Percent\nFROM (SELECT tablespace_name, owner, bytes\n FROM dba_segments\n WHERE segment_type IN\n ('TABLE', 'TABLE PARTITION', 'TABLE SUBPARTITION')\n UNION ALL\n SELECT i.tablespace_name, i.owner, s.bytes\n FROM dba_indexes i, dba_segments s\n WHERE s.segment_name = i.index_name\n AND s.owner = i.owner\n AND s.segment_type IN\n ('INDEX', 'INDEX PARTITION', 'INDEX SUBPARTITION')\n UNION ALL\n SELECT l.tablespace_name, l.owner, s.bytes\n FROM dba_lobs l, dba_segments s\n WHERE s.segment_name = l.segment_name\n AND s.owner = l.owner\n AND s.segment_type IN ('LOBSEGMENT', 'LOB PARTITION')\n UNION ALL\n SELECT l.tablespace_name, l.owner, s.bytes\n FROM dba_lobs l, dba_segments s\n WHERE s.segment_name = l.index_name\n AND s.owner = l.owner\n AND s.segment_type = 'LOBINDEX')\nWHERE owner IN UPPER ('&owner')\nGROUP BY owner, tablespace_name\n--HAVING SUM(bytes)/1024/1024 > 10 /* Ignore really small tables */\nORDER BY tablespace_name -- desc\n;\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11477/"
] |
Being used to (and potentially spoiled by) `MSSQL`, I'm wondering how I can get at tables size in `Oracle` 10g.
I have googled it so I'm now aware that I may not have as easy an option as `sp_spaceused`. Still the potential answers I got are most of the time outdated or don't work. Probably because I'm no DBA on the schema I'm working with.
Would anyone have solutions and or recommendations?
|
You might be interested in this query. It tells you how much space is allocated for each table taking into account the indexes and any LOBs on the table. Often you are interested to know "How much spaces the the Purchase Order table take, including any indexes" rather than just the table itself. You can always delve into the details. Note that this requires access to the DBA\_\* views.
```
COLUMN TABLE_NAME FORMAT A32
COLUMN OBJECT_NAME FORMAT A32
COLUMN OWNER FORMAT A10
SELECT
owner,
table_name,
TRUNC(sum(bytes)/1024/1024) Meg,
ROUND( ratio_to_report( sum(bytes) ) over () * 100) Percent
FROM
(SELECT segment_name table_name, owner, bytes
FROM dba_segments
WHERE segment_type IN ('TABLE', 'TABLE PARTITION', 'TABLE SUBPARTITION')
UNION ALL
SELECT i.table_name, i.owner, s.bytes
FROM dba_indexes i, dba_segments s
WHERE s.segment_name = i.index_name
AND s.owner = i.owner
AND s.segment_type IN ('INDEX', 'INDEX PARTITION', 'INDEX SUBPARTITION')
UNION ALL
SELECT l.table_name, l.owner, s.bytes
FROM dba_lobs l, dba_segments s
WHERE s.segment_name = l.segment_name
AND s.owner = l.owner
AND s.segment_type IN ('LOBSEGMENT', 'LOB PARTITION')
UNION ALL
SELECT l.table_name, l.owner, s.bytes
FROM dba_lobs l, dba_segments s
WHERE s.segment_name = l.index_name
AND s.owner = l.owner
AND s.segment_type = 'LOBINDEX')
WHERE owner in UPPER('&owner')
GROUP BY table_name, owner
HAVING SUM(bytes)/1024/1024 > 10 /* Ignore really small tables */
ORDER BY SUM(bytes) desc
;
```
|
264,917 |
<p>I want to create own header.jsp file instead of the one included in the JBoss Portal 2.6 but have to support the locale set by the user.</p>
<p>The original header.jsp does not contain any i18n and I don't know how to do it, especially how to get the actual locale.</p>
|
[
{
"answer_id": 264940,
"author": "Lurtz",
"author_id": 34367,
"author_profile": "https://Stackoverflow.com/users/34367",
"pm_score": 0,
"selected": false,
"text": "<p>You can look to Thread.currenThread method to see the user's lang.</p>\n\n<p>After that you have to a framework to implement i18n, ex : struts or jsf.</p>\n"
},
{
"answer_id": 569501,
"author": "johnbr",
"author_id": 376254,
"author_profile": "https://Stackoverflow.com/users/376254",
"pm_score": 1,
"selected": false,
"text": "<p>In header.jsp, use a scriptlet:</p>\n\n<pre><code><%@ taglib uri=\"http://java.sun.com/jsp/jstl/fmt\" prefix=\"fmt\" %>\n\n<%\n locale = request.getLocale() // get the user's locale from the HttpServletRequest\n\n%>\n</code></pre>\n\n<p>and then set the property bundle:</p>\n\n<pre><code><fmt:setLocale value=\"<%= locale %>\" />\n\n<fmt:setBundle basename=\"header\" />\n</code></pre>\n\n<p>And then you can create </p>\n\n<pre>\n header_en.properties\n header_de.properties\n</pre>\n\n<p>for customized messages.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25326/"
] |
I want to create own header.jsp file instead of the one included in the JBoss Portal 2.6 but have to support the locale set by the user.
The original header.jsp does not contain any i18n and I don't know how to do it, especially how to get the actual locale.
|
In header.jsp, use a scriptlet:
```
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%
locale = request.getLocale() // get the user's locale from the HttpServletRequest
%>
```
and then set the property bundle:
```
<fmt:setLocale value="<%= locale %>" />
<fmt:setBundle basename="header" />
```
And then you can create
```
header_en.properties
header_de.properties
```
for customized messages.
|
264,924 |
<p>We have a page that ordinarily has two elements arranged side-by-side. Despite exploring a few angles for this, we can't seem to make it work. We're not averse to using JavaScript, it just feels that a CSS based solution ought to be possible. Is there a way of using just CSS (and possibly extra markup if necessary) to make <code>element2</code> centre when it appears on its own?</p>
<h1>Examples</h1>
<p>Sometimes we have two elements, side by side.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
<div id="element1">content</div>
<div id="element2">content</div>
</div></code></pre>
</div>
</div>
</p>
<p>But in some conditions only <code>element2</code> is on the page e.g.:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
<div id="element2">content</div>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 264980,
"author": "philnash",
"author_id": 28376,
"author_profile": "https://Stackoverflow.com/users/28376",
"pm_score": 4,
"selected": true,
"text": "<p>There is a pure css solution, however it won't work in versions of IE less than 7 because it won't understand the sibling selector (+), for that you may want to consider a JavaScript solution (perhaps Dean Edwards' <a href=\"http://dean.edwards.name/IE7/\" rel=\"nofollow noreferrer\">IE7</a>). Anyway, some example css:</p>\n\n<pre><code>div#element2{\n width:100px;\n margin:0 auto;\n}\ndiv#element1{\n width:50px;\n float:left;\n}\ndiv#element1 + div#element2{\n width:50px;\n float:left;\n margin:0;\n}\n</code></pre>\n\n<p>The key is the line div#element1 + div#element2 which selects div#element2 given that it directly follows div#element1.</p>\n"
},
{
"answer_id": 267146,
"author": "Steve Clay",
"author_id": 3779,
"author_profile": "https://Stackoverflow.com/users/3779",
"pm_score": 0,
"selected": false,
"text": "<p>A strict CSS2 solution:</p>\n\n<pre><code>#container {\n text-align:center;\n}\n#element1, #element2 {\n display:inline-block;\n}\n</code></pre>\n\n<p>The inner elements should layout like inline text inside #container, but remain blocks inside.</p>\n\n<p>This is standard CSS, but getting browser support might take <a href=\"http://foohack.com/2007/11/cross-browser-support-for-inline-block-styling/\" rel=\"nofollow noreferrer\">some trickery</a>.</p>\n"
},
{
"answer_id": 267167,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>it's not cool solution becouse tables are not \"trendy\" anymore but it solves the problem completly (under all ie)</p>\n\n<pre><code><style>\n #container {\n margin:0 auto;\n width:100px;\n }\n\n #container table{\n width: 100%;\n text-align:center;\n }\n\n #element1{ \n background-color:#0000ff;\n }\n\n #element2 {\n background-color: #ff0000;\n }\n</style>\n\n<div id=container>\n <table cellspacing=0 cellpadding=0>\n <tr>\n <td id=\"element1\">content</td>\n <td id=\"element2\">content</td>\n </tr>\n </table>\n</div>\n</code></pre>\n"
},
{
"answer_id": 267203,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "<p>I think Phil was on the right track, but you should try using the CSS <code>last-child</code> pseudo-class. As far as I know, <code>first-child</code> and <code>last-child</code> are the only way in CSS to approximate an <code>if</code> construct.</p>\n\n<pre><code>div#container div#element2:last-child {\n width:100px;\n margin:0 auto;\n}\n\ndiv#element1{\n width:50px;\n float:left;\n}\n\ndiv##element2{\n width:50px;\n float:left;\n margin:0;\n}\n</code></pre>\n\n<p>The CSS above basically says \"if element2 is the last child element of its parent use this set of styles, otherwise use these other styles.</p>\n\n<p>This should even work in IE7.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2977/"
] |
We have a page that ordinarily has two elements arranged side-by-side. Despite exploring a few angles for this, we can't seem to make it work. We're not averse to using JavaScript, it just feels that a CSS based solution ought to be possible. Is there a way of using just CSS (and possibly extra markup if necessary) to make `element2` centre when it appears on its own?
Examples
========
Sometimes we have two elements, side by side.
```html
<div id="container">
<div id="element1">content</div>
<div id="element2">content</div>
</div>
```
But in some conditions only `element2` is on the page e.g.:
```html
<div id="container">
<div id="element2">content</div>
</div>
```
|
There is a pure css solution, however it won't work in versions of IE less than 7 because it won't understand the sibling selector (+), for that you may want to consider a JavaScript solution (perhaps Dean Edwards' [IE7](http://dean.edwards.name/IE7/)). Anyway, some example css:
```
div#element2{
width:100px;
margin:0 auto;
}
div#element1{
width:50px;
float:left;
}
div#element1 + div#element2{
width:50px;
float:left;
margin:0;
}
```
The key is the line div#element1 + div#element2 which selects div#element2 given that it directly follows div#element1.
|
264,930 |
<p>I'm still working with this huge list of URLs, all the help I have received has been great.</p>
<p>At the moment I have the list looking like this (17000 URLs though):</p>
<ul>
<li><code>http://www.example.com/page?CONTENT_ITEM_ID=1</code></li>
<li><code>http://www.example.com/page?CONTENT_ITEM_ID=3</code></li>
<li><code>http://www.example.com/page?CONTENT_ITEM_ID=2</code></li>
<li><code>http://www.example.com/page?CONTENT_ITEM_ID=1</code></li>
<li><code>http://www.example.com/page?CONTENT_ITEM_ID=2</code></li>
<li><code>http://www.example.com/page?CONTENT_ITEM_ID=3</code></li>
<li><code>http://www.example.com/page?CONTENT_ITEM_ID=3</code></li>
</ul>
<p>I can filter out the duplicates no problem with a couple of methods, awk etc. What I am really looking to do it take out the duplicate URLs but at the same time taking a count of how many times the URL exists in the list and printing the count next to the URL with a pipe separator. After processing the list it should look like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>url</th>
<th>count</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>http://www.example.com/page?CONTENT_ITEM_ID=1</code></td>
<td>2</td>
</tr>
<tr>
<td><code>http://www.example.com/page?CONTENT_ITEM_ID=2</code></td>
<td>2</td>
</tr>
<tr>
<td><code>http://www.example.com/page?CONTENT_ITEM_ID=3</code></td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
<p>What method would be the fastest way to achieve this?</p>
|
[
{
"answer_id": 264936,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": "<p>This is probably as fast as you can get without writing code.</p>\n<pre>\n $ cat foo.txt\n http://www.example.com/page?CONTENT_ITEM_ID=1\n http://www.example.com/page?CONTENT_ITEM_ID=3\n http://www.example.com/page?CONTENT_ITEM_ID=2\n http://www.example.com/page?CONTENT_ITEM_ID=1\n http://www.example.com/page?CONTENT_ITEM_ID=2\n http://www.example.com/page?CONTENT_ITEM_ID=3\n http://www.example.com/page?CONTENT_ITEM_ID=3\n $ sort foo.txt | uniq -c\n 2 http://www.example.com/page?CONTENT_ITEM_ID=1\n 2 http://www.example.com/page?CONTENT_ITEM_ID=2\n 3 http://www.example.com/page?CONTENT_ITEM_ID=3\n</pre>\n<p>Did a bit of testing, and it's not particularly fast, although for 17k it'll take little more than 1 second (on a loaded P4 2.8Ghz machine)</p>\n<pre>\n$ wc -l foo.txt\n174955 foo.txt\nvinko@mithril:~/i3media/2008/product/Pending$ time sort foo.txt | uniq -c\n 54482 http://www.example.com/page?CONTENT_ITEM_ID=1\n 48212 http://www.example.com/page?CONTENT_ITEM_ID=2\n 72261 http://www.example.com/page?CONTENT_ITEM_ID=3\n\nreal 0m23.534s\nuser 0m16.817s\nsys 0m0.084s\n\n$ wc -l foo.txt\n14955 foo.txt\n$ time sort foo.txt | uniq -c\n 4233 http://www.example.com/page?CONTENT_ITEM_ID=1\n 4290 http://www.example.com/page?CONTENT_ITEM_ID=2\n 6432 http://www.example.com/page?CONTENT_ITEM_ID=3\n\nreal 0m1.349s\nuser 0m1.216s\nsys 0m0.012s\n</pre>\n<p>Although O() wins the game hands down, as usual. Tested S.Lott's solution and</p>\n<pre>\n\n$ cat pythoncount.py\nfrom collections import defaultdict\nmyFile = open( \"foo.txt\", \"ru\" )\nfq= defaultdict( int )\nfor n in myFile:\n fq[n] += 1\nfor n in fq.items():\n print \"%s|%s\" % (n[0].strip(),n[1])\n\n$ wc -l foo.txt\n14955 foo.txt\n\n$ time python pythoncount.py\nhttp://www.example.com/page?CONTENT_ITEM_ID=2|4290\nhttp://www.example.com/page?CONTENT_ITEM_ID=1|4233\nhttp://www.example.com/page?CONTENT_ITEM_ID=3|6432\n\nreal 0m0.072s\nuser 0m0.028s\nsys 0m0.012s\n\n$ wc -l foo.txt\n1778955 foo.txt\n\n$ time python pythoncount.py\nhttp://www.example.com/page?CONTENT_ITEM_ID=2|504762\nhttp://www.example.com/page?CONTENT_ITEM_ID=1|517557\nhttp://www.example.com/page?CONTENT_ITEM_ID=3|756636\n\nreal 0m2.718s\nuser 0m2.440s\nsys 0m0.072s\n</pre>\n"
},
{
"answer_id": 264942,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "<p>See <a href=\"https://stackoverflow.com/questions/261655/converting-a-list-of-tuples-into-a-dict-in-python\">Converting a list of tuples into a dict in python</a>.</p>\n\n<p>Essentially, you're doing the same thing with an int instead of a list.</p>\n\n<p>This may be faster than the system sort because it's O(n). However, it's also Python, not C.</p>\n\n<pre><code>from collections import defaultdict\nmyFile = open( \"urlFile\", \"ru\" )\nfq= defaultdict( int )\nfor n in myFile:\n fq[n] += 1\n\nfor url, count in fq.iteritems():\n print url.rstrip(), \"|\", count\n</code></pre>\n\n<p>On my little Dell D830, this processes 17000 URL's in 0.015 seconds.</p>\n"
},
{
"answer_id": 264969,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 2,
"selected": false,
"text": "<p>In perl</p>\n\n<p>[disclaimer: not able to test this code at the moment]</p>\n\n<pre><code>while (<>) {\n chomp;\n $occurences{$_}++;\n}\nforeach $url (sort keys %occurences) {\n printf \"%s|%d\\n\", $url, $occurences{$url};\n}\n</code></pre>\n"
},
{
"answer_id": 265145,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 3,
"selected": true,
"text": "<p>Are you're going to do this over and over again? If not, then \"fastest\" as in fastest to implement is probably</p>\n\n<pre><code>sort </file/of/urls | uniq --count | awk '{ print $2, \" | \", $1}'\n</code></pre>\n\n<p>(not tested, I'm not near a UNIX command line)</p>\n"
},
{
"answer_id": 297512,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 1,
"selected": false,
"text": "<p>Here is another version in Python:</p>\n<pre><code>import fileinput, itertools\n\nurls = sorted(fileinput.input())\nfor url, sameurls in itertools.groupby(urls):\n print url.rstrip(), "|", sum(1 for _ in sameurls)\n</code></pre>\n<p>Example:</p>\n<pre><code>$ cat foo.txt\nhttp://www.example.com/page?CONTENT_ITEM_ID=1\nhttp://www.example.com/page?CONTENT_ITEM_ID=3\nhttp://www.example.com/page?CONTENT_ITEM_ID=2\nhttp://www.example.com/page?CONTENT_ITEM_ID=1\nhttp://www.example.com/page?CONTENT_ITEM_ID=2\nhttp://www.example.com/page?CONTENT_ITEM_ID=3\nhttp://www.example.com/page?CONTENT_ITEM_ID=3\n\n$ python countuniq.py foo.txt\nhttp://www.example.com/page?CONTENT_ITEM_ID=1 | 2\nhttp://www.example.com/page?CONTENT_ITEM_ID=2 | 2\nhttp://www.example.com/page?CONTENT_ITEM_ID=3 | 3\n</code></pre>\n<p>Performance:</p>\n<pre><code>C:\\> timethis "sort urls17000.txt|uniq -c"\n...\nTimeThis : Elapsed Time : 00:00:00.688\n\nC:\\> timethis python countuniq.py urls17000.txt\n...\nTimeThis : Elapsed Time : 00:00:00.625\n\nC:\\> timethis python slott.py urls17000.txt\n...\nTimeThis : Elapsed Time : 00:00:00.562\n\nC:\\> timethis perl toolkit.pl urls17000.txt\n...\nTimeThis : Elapsed Time : 00:00:00.187\n</code></pre>\n<p><strong>Conclusion</strong>: All solutions are under 1 second. The pipe is the slowest, <a href=\"https://stackoverflow.com/questions/264930/count-duplicate-urls-fastest-method-possible#264942\">S.Lott's solution</a> is faster then the above python's version and <a href=\"https://stackoverflow.com/questions/264930/count-duplicate-urls-fastest-method-possible#264969\">toolkit's Perl solution</a> is the fastest.</p>\n<hr />\n<pre><code>C:\\> timethis perl toolkit.pl urls1778955.txt\n...\nTimeThis : Elapsed Time : 00:00:17.656\n\nC:\\> timethis "sort urls1778955.txt|uniq -c"\n...\nTimeThis : Elapsed Time : 00:01:54.234\n\n$ wc urls1778955.txt\n1778955 1778955 81831930 urls1778955.txt\n</code></pre>\n<p>Hashing beats sorting for a large number of URLs.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30786/"
] |
I'm still working with this huge list of URLs, all the help I have received has been great.
At the moment I have the list looking like this (17000 URLs though):
* `http://www.example.com/page?CONTENT_ITEM_ID=1`
* `http://www.example.com/page?CONTENT_ITEM_ID=3`
* `http://www.example.com/page?CONTENT_ITEM_ID=2`
* `http://www.example.com/page?CONTENT_ITEM_ID=1`
* `http://www.example.com/page?CONTENT_ITEM_ID=2`
* `http://www.example.com/page?CONTENT_ITEM_ID=3`
* `http://www.example.com/page?CONTENT_ITEM_ID=3`
I can filter out the duplicates no problem with a couple of methods, awk etc. What I am really looking to do it take out the duplicate URLs but at the same time taking a count of how many times the URL exists in the list and printing the count next to the URL with a pipe separator. After processing the list it should look like this:
| url | count |
| --- | --- |
| `http://www.example.com/page?CONTENT_ITEM_ID=1` | 2 |
| `http://www.example.com/page?CONTENT_ITEM_ID=2` | 2 |
| `http://www.example.com/page?CONTENT_ITEM_ID=3` | 3 |
What method would be the fastest way to achieve this?
|
Are you're going to do this over and over again? If not, then "fastest" as in fastest to implement is probably
```
sort </file/of/urls | uniq --count | awk '{ print $2, " | ", $1}'
```
(not tested, I'm not near a UNIX command line)
|
264,937 |
<p>Currently i have this method:</p>
<pre><code>static boolean checkDecimalPlaces(double d, int decimalPlaces){
if (d==0) return true;
double multiplier = Math.pow(10, decimalPlaces);
double check = d * multiplier;
check = Math.round(check);
check = check/multiplier;
return (d==check);
}
</code></pre>
<p>But this method fails for <code>checkDecmialPlaces(649632196443.4279, 4)</code> probably because I do base 10 math on a base 2 number.</p>
<p>So how can this check be done correctly?</p>
<p>I thought of getting a string representation of the double value and then check that with a regexp - but that felt weird.</p>
<p><strong>EDIT:</strong>
Thanks for all the answers. There are cases where I really get a double and for those cases I implemented the following: </p>
<pre><code>private static boolean checkDecimalPlaces(double d, int decimalPlaces) {
if (d == 0) return true;
final double epsilon = Math.pow(10.0, ((decimalPlaces + 1) * -1));
double multiplier = Math.pow(10, decimalPlaces);
double check = d * multiplier;
long checkLong = (long) Math.abs(check);
check = checkLong / multiplier;
double e = Math.abs(d - check);
return e < epsilon;
}
</code></pre>
<p>I changed the <code>round</code> to a truncation. Seems that the computation done in <code>round</code> increases the inaccuracy too much. At least in the failing testcase.<br>
As some of you pointed out if I could get to the 'real' string input I should use <code>BigDecimal</code> to check and so I have done: </p>
<pre><code>BigDecimal decimal = new BigDecimal(value);
BigDecimal checkDecimal = decimal.movePointRight(decimalPlaces);
return checkDecimal.scale() == 0;
</code></pre>
<p>The <code>double</code> value I get comes from the Apache POI API that reads excel files. I did a few tests and found out that although the API returns <code>double</code> values for numeric cells I can get a accurate representation when I immediately format that <code>double</code> with the <code>DecimalFormat</code>: </p>
<pre><code>DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setMaximumIntegerDigits(Integer.MAX_VALUE);
// don't use grouping for numeric-type cells
decimalFormat.setGroupingUsed(false);
decimalFormat.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
value = decimalFormat.format(numericValue);
</code></pre>
<p>This also works for values that can't be represented exactly in binary format.</p>
|
[
{
"answer_id": 264947,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "<p>As with all floating point arithmetic, you should not check for equality, but rather that the error (epsilon) is sufficiently small.</p>\n\n<p>If you replace:</p>\n\n<pre><code>return (d==check);\n</code></pre>\n\n<p>with something like</p>\n\n<pre><code>return (Math.abs(d-check) <= 0.0000001);\n</code></pre>\n\n<p>it should work. Obviously, the epsilon should be selected to be small enough compared with the number of decimals you're checking for.</p>\n"
},
{
"answer_id": 264952,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>double</code> type is a binary floating point number. There are always apparent inaccuracies in dealing with them as if they were decimal floating point numbers. I don't know that you'll ever be able to write your function so that it works the way you want.</p>\n\n<p>You will likely have to go back to the original source of the number (a string input perhaps) and keep the decimal representation if it is important to you.</p>\n"
},
{
"answer_id": 264968,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 3,
"selected": false,
"text": "<p>If your goal is to represent a number with exactly <em>n</em> significant figures to the right of the decimal, <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html\" rel=\"noreferrer\">BigDecimal</a> is the class to use.</p>\n\n<blockquote>\n <p>Immutable, arbitrary-precision signed\n decimal numbers. A BigDecimal consists\n of an arbitrary precision integer\n unscaled value and a 32-bit integer\n scale. If zero or positive, the scale\n is the number of digits to the right\n of the decimal point. If negative, the\n unscaled value of the number is\n multiplied by ten to the power of the\n negation of the scale. The value of\n the number represented by the\n BigDecimal is therefore (unscaledValue\n × 10-scale).</p>\n</blockquote>\n\n<p><code>scale</code> can be set via <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#setScale(int)\" rel=\"noreferrer\">setScale(int)</a></p>\n"
},
{
"answer_id": 265011,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure that this is really doable in general. For example, how many decimal places does <code>1.0e-13</code> have? What if it resulted from some rounding error while doing arithmetic and really is just <code>0</code> in disguise? If on, the other hand you are asking if there are any non-zero digits in the first <strong>n</strong> decimal places you can do something like:</p>\n\n<pre><code> static boolean checkDecimalPlaces(double d, unsigned int decimalPlaces){\n // take advantage of truncation, may need to use BigInt here\n // depending on your range\n double d_abs = Math.abs(d);\n unsigned long d_i = d_abs; \n unsigned long e = (d_abs - d_i) * Math.pow(10, decimalPlaces);\n return e > 0;\n }\n</code></pre>\n"
},
{
"answer_id": 265082,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 4,
"selected": true,
"text": "<p>The test fails, because you have reached the accuracy of the binary floating point representation, which is approximately 16 digits with <a href=\"http://en.wikipedia.org/wiki/Double_precision\" rel=\"nofollow noreferrer\">IEEE754 double precision</a>. Multiplying by 649632196443.4279 by 10000 will truncate the binary representation, leading to errors when rounding and dividing afterwards, thereby invalidating the result of your function completely.</p>\n\n<p>For more details see <a href=\"http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems</a></p>\n\n<p>A better way would be to check whether the <code>n+1</code> decimal places are below a certain threshold. If <code>d - round(d)</code> is less than <a href=\"http://en.wikipedia.org/wiki/Epsilon\" rel=\"nofollow noreferrer\"><code>epsilon</code></a> (see <a href=\"http://en.wikipedia.org/wiki/Limit_(mathematics)\" rel=\"nofollow noreferrer\">limit</a>), the decimal representation of <code>d</code> has no significant decimal places. Similarly if <code>(d - round(d)) * 10^n</code> is less than <code>epsilon</code>, d can have at most <code>n</code> significant places. </p>\n\n<p>Use <a href=\"https://stackoverflow.com/users/22656/jon-skeet\">Jon Skeet</a>'s <a href=\"http://pobox.com/~skeet/csharp/DoubleConverter.cs\" rel=\"nofollow noreferrer\"><code>DoubleConverter</code></a> to check for the cases where <code>d</code> isn't accurate enough to hold the decimal places you are looking for.</p>\n"
},
{
"answer_id": 266691,
"author": "Glenn",
"author_id": 29771,
"author_profile": "https://Stackoverflow.com/users/29771",
"pm_score": 1,
"selected": false,
"text": "<p>If you can switch to BigDecimal, then as Ken G explains, that's what you should be using.</p>\n\n<p>If not, then you have to deal with a host of issues as mentioned in the other answers. To me, you are dealing with a binary number (double) and asking a question about a decimal representation of that number; i.e., you are asking about a String. I think your intuition is correct.</p>\n"
},
{
"answer_id": 4625738,
"author": "Norm Wright",
"author_id": 412153,
"author_profile": "https://Stackoverflow.com/users/412153",
"pm_score": 1,
"selected": false,
"text": "<p>I think this is better\nConvert to string and interrogate the value for the exponent</p>\n\n<pre><code> public int calcBase10Exponet (Number increment)\n {\n //toSting of 0.0=0.0\n //toSting of 1.0=1.0\n //toSting of 10.0=10.0\n //toSting of 100.0=100.0\n //toSting of 1000.0=1000.0\n //toSting of 10000.0=10000.0\n //toSting of 100000.0=100000.0\n //toSting of 1000000.0=1000000.0\n //toSting of 1.0E7=1.0E7\n //toSting of 1.0E8=1.0E8\n //toSting of 1.0E9=1.0E9\n //toSting of 1.0E10=1.0E10\n //toSting of 1.0E11=1.0E11\n //toSting of 0.1=0.1\n //toSting of 0.01=0.01\n //toSting of 0.0010=0.0010 <== need to trim off this extra zero\n //toSting of 1.0E-4=1.0E-4\n //toSting of 1.0E-5=1.0E-5\n //toSting of 1.0E-6=1.0E-6\n //toSting of 1.0E-7=1.0E-7\n //toSting of 1.0E-8=1.0E-8\n //toSting of 1.0E-9=1.0E-9\n //toSting of 1.0E-10=1.0E-10\n //toSting of 1.0E-11=1.0E-11\n double dbl = increment.doubleValue ();\n String str = Double.toString (dbl);\n// System.out.println (\"NumberBoxDefaultPatternCalculator: toSting of \" + dbl + \"=\" + str);\n if (str.contains (\"E\"))\n {\n return Integer.parseInt (str.substring (str.indexOf (\"E\") + 1));\n }\n if (str.endsWith (\".0\"))\n {\n return str.length () - 3;\n }\n while (str.endsWith (\"0\"))\n {\n str = str.substring (0, str.length () - 1);\n }\n return - (str.length () - str.indexOf (\".\") - 1);\n }\n</code></pre>\n"
},
{
"answer_id": 57309113,
"author": "Dt D",
"author_id": 8614269,
"author_profile": "https://Stackoverflow.com/users/8614269",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe it will be helpful. Here is my method</p>\n\n<pre><code>private int checkPrecisionOfDouble(Double atribute) {\n String s = String.valueOf(atribute);\n String[] split = s.split(\"\\\\.\");\n return split[1].length();\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>private boolean checkPrecisionOfDouble(Double atribute, int decimalPlaces) {\n String s = String.valueOf(atribute);\n String[] split = s.split(\"\\\\.\");\n\n return split[1].length() == decimalPlaces;\n}\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5271/"
] |
Currently i have this method:
```
static boolean checkDecimalPlaces(double d, int decimalPlaces){
if (d==0) return true;
double multiplier = Math.pow(10, decimalPlaces);
double check = d * multiplier;
check = Math.round(check);
check = check/multiplier;
return (d==check);
}
```
But this method fails for `checkDecmialPlaces(649632196443.4279, 4)` probably because I do base 10 math on a base 2 number.
So how can this check be done correctly?
I thought of getting a string representation of the double value and then check that with a regexp - but that felt weird.
**EDIT:**
Thanks for all the answers. There are cases where I really get a double and for those cases I implemented the following:
```
private static boolean checkDecimalPlaces(double d, int decimalPlaces) {
if (d == 0) return true;
final double epsilon = Math.pow(10.0, ((decimalPlaces + 1) * -1));
double multiplier = Math.pow(10, decimalPlaces);
double check = d * multiplier;
long checkLong = (long) Math.abs(check);
check = checkLong / multiplier;
double e = Math.abs(d - check);
return e < epsilon;
}
```
I changed the `round` to a truncation. Seems that the computation done in `round` increases the inaccuracy too much. At least in the failing testcase.
As some of you pointed out if I could get to the 'real' string input I should use `BigDecimal` to check and so I have done:
```
BigDecimal decimal = new BigDecimal(value);
BigDecimal checkDecimal = decimal.movePointRight(decimalPlaces);
return checkDecimal.scale() == 0;
```
The `double` value I get comes from the Apache POI API that reads excel files. I did a few tests and found out that although the API returns `double` values for numeric cells I can get a accurate representation when I immediately format that `double` with the `DecimalFormat`:
```
DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setMaximumIntegerDigits(Integer.MAX_VALUE);
// don't use grouping for numeric-type cells
decimalFormat.setGroupingUsed(false);
decimalFormat.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
value = decimalFormat.format(numericValue);
```
This also works for values that can't be represented exactly in binary format.
|
The test fails, because you have reached the accuracy of the binary floating point representation, which is approximately 16 digits with [IEEE754 double precision](http://en.wikipedia.org/wiki/Double_precision). Multiplying by 649632196443.4279 by 10000 will truncate the binary representation, leading to errors when rounding and dividing afterwards, thereby invalidating the result of your function completely.
For more details see <http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems>
A better way would be to check whether the `n+1` decimal places are below a certain threshold. If `d - round(d)` is less than [`epsilon`](http://en.wikipedia.org/wiki/Epsilon) (see [limit](http://en.wikipedia.org/wiki/Limit_(mathematics))), the decimal representation of `d` has no significant decimal places. Similarly if `(d - round(d)) * 10^n` is less than `epsilon`, d can have at most `n` significant places.
Use [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet)'s [`DoubleConverter`](http://pobox.com/~skeet/csharp/DoubleConverter.cs) to check for the cases where `d` isn't accurate enough to hold the decimal places you are looking for.
|
264,950 |
<p>I am using a machine on which I do not have root access and would like to access files on a Samba server in random access mode. I know I can transfer the files in their entirety using smbclient but the files are very large (>1GB) and I would rather just treat them as remote files on which I can do random access.</p>
<p>The problem as noted is that I don't have root access to this machine (a Linux box) so I can't mount the remote Samba file system. </p>
<p>Is there a user-level solution that will let me randomly access the contents of a file on a Samba server? Seems it should be possible to do everything that the kernel file system client is doing but from a user-level application.</p>
<p>I only need read-only access btw and the remote file is guaranteed not to change.</p>
|
[
{
"answer_id": 264963,
"author": "xsl",
"author_id": 11387,
"author_profile": "https://Stackoverflow.com/users/11387",
"pm_score": 0,
"selected": false,
"text": "<p>Try to use <code>smbmount</code> to mount the filesystem without root permissions:</p>\n\n<pre><code>mkdir ~/temp\nsmbmount //{server}/{share} ~/temp -o username=username={username},password={password}\n</code></pre>\n\n<p><em>Edit: Updated to use <code>smbmount</code> instead of <code>mount</code>.</em></p>\n"
},
{
"answer_id": 268478,
"author": "Dave Griffiths",
"author_id": 15379,
"author_profile": "https://Stackoverflow.com/users/15379",
"pm_score": 3,
"selected": true,
"text": "<p>To answer my own question after digging around in the Samba source: there is a client library libsmbclient which includes all the usual file handling stuff: smbc_open, smbc_fstat, smbc_lseek, smbc_read etc. For instance, here is a snippet I just wrote which reads a file backwards (just to check it was doing a true seek):</p>\n\n<pre><code>fd = smbc_open(path, O_RDONLY, 0);\nsmbc_fstat(fd, &st);\n\nfor (offset = st.st_size - BUFLEN; offset > 0; offset -= BUFLEN) {\n smbc_lseek(fd, offset, SEEK_SET);\n smbc_read(fd, buffer, BUFLEN);\n}\n</code></pre>\n\n<p>(error checking removed for clarity)</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15379/"
] |
I am using a machine on which I do not have root access and would like to access files on a Samba server in random access mode. I know I can transfer the files in their entirety using smbclient but the files are very large (>1GB) and I would rather just treat them as remote files on which I can do random access.
The problem as noted is that I don't have root access to this machine (a Linux box) so I can't mount the remote Samba file system.
Is there a user-level solution that will let me randomly access the contents of a file on a Samba server? Seems it should be possible to do everything that the kernel file system client is doing but from a user-level application.
I only need read-only access btw and the remote file is guaranteed not to change.
|
To answer my own question after digging around in the Samba source: there is a client library libsmbclient which includes all the usual file handling stuff: smbc\_open, smbc\_fstat, smbc\_lseek, smbc\_read etc. For instance, here is a snippet I just wrote which reads a file backwards (just to check it was doing a true seek):
```
fd = smbc_open(path, O_RDONLY, 0);
smbc_fstat(fd, &st);
for (offset = st.st_size - BUFLEN; offset > 0; offset -= BUFLEN) {
smbc_lseek(fd, offset, SEEK_SET);
smbc_read(fd, buffer, BUFLEN);
}
```
(error checking removed for clarity)
|
264,962 |
<p>I need to search a string in the string array. I dont want to use any for looping in it</p>
<pre><code>string [] arr = {"One","Two","Three"};
string theString = "One"
</code></pre>
<p>I need to check whether theString variable is present in arr.</p>
|
[
{
"answer_id": 264970,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 7,
"selected": false,
"text": "<p>Well, something is going to have to look, and looping is more efficient than recursion (since tail-end recursion isn't fully implemented)... so if you just don't want to loop yourself, then either of:</p>\n\n<pre><code>bool has = arr.Contains(var); // .NET 3.5\n</code></pre>\n\n<p>or</p>\n\n<pre><code>bool has = Array.IndexOf(arr, var) >= 0;\n</code></pre>\n\n<p>For info: <strong>avoid names like var</strong> - this is a keyword in C# 3.0.</p>\n"
},
{
"answer_id": 264974,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 5,
"selected": false,
"text": "<p>Does it have to be a string[] ? A List<String> would give you what you need.</p>\n\n<pre><code>List<String> testing = new List<String>();\ntesting.Add(\"One\");\ntesting.Add(\"Two\");\ntesting.Add(\"Three\");\ntesting.Add(\"Mouse\");\nbool inList = testing.Contains(\"Mouse\");\n</code></pre>\n"
},
{
"answer_id": 264976,
"author": "VolkerK",
"author_id": 4833,
"author_profile": "https://Stackoverflow.com/users/4833",
"pm_score": 3,
"selected": false,
"text": "<p>Each class implementing IList has a method <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.ilist.contains.aspx\" rel=\"noreferrer\">Contains(Object value)</a>. And so does System.Array.</p>\n"
},
{
"answer_id": 264985,
"author": "mohammedn",
"author_id": 29268,
"author_profile": "https://Stackoverflow.com/users/29268",
"pm_score": 4,
"selected": false,
"text": "<pre><code>bool exists = arr.Contains(\"One\");\n</code></pre>\n"
},
{
"answer_id": 264986,
"author": "GvS",
"author_id": 11492,
"author_profile": "https://Stackoverflow.com/users/11492",
"pm_score": 3,
"selected": false,
"text": "<p>If the array is sorted, you can use <a href=\"http://msdn.microsoft.com/en-us/library/system.array.binarysearch.aspx\" rel=\"noreferrer\">BinarySearch</a>. This is a O(log n) operation, so it is faster as looping. If you need to apply multiple searches and speed is a concern, you could sort it (or a copy) before using it.</p>\n"
},
{
"answer_id": 265008,
"author": "Salman Kasbati",
"author_id": 33931,
"author_profile": "https://Stackoverflow.com/users/33931",
"pm_score": 2,
"selected": false,
"text": "<p>At first shot, I could come up with something like this (but it's pseudo code and assuming you cannot use any .NET built-in libaries). Might require a bit of tweaking and re-thinking, but should be good enough for a head-start, maybe?</p>\n\n<pre><code>int findString(String var, String[] stringArray, int currentIndex, int stringMaxIndex)\n {\n if currentIndex > stringMaxIndex \n return (-stringMaxIndex-1);\n else if var==arr[currentIndex] //or use any string comparison op or function\n return 0;\n else \n return findString(var, stringArray, currentIndex++, stringMaxIndex) + 1 ;\n }\n\n\n\n //calling code\n int index = findString(var, arr, 0, getMaxIndex(arr));\n\n if index == -1 printOnScreen(\"Not found\");\n else printOnScreen(\"Found on index: \" + index);\n</code></pre>\n"
},
{
"answer_id": 265048,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 2,
"selected": false,
"text": "<p>In C#, if you can use an ArrayList, you can use the Contains method, which returns a boolean:</p>\n\n<pre><code>if MyArrayList.Contains(\"One\")\n</code></pre>\n"
},
{
"answer_id": 265067,
"author": "bendin",
"author_id": 33412,
"author_profile": "https://Stackoverflow.com/users/33412",
"pm_score": 2,
"selected": false,
"text": "<p>Why the prohibition \"I don't want to use any looping\"? That's the most obvious solution. When given the chance to be obvious, take it! </p>\n\n<p>Note that calls like <code>arr.Contains(...)</code> are still going to <em>loop</em>, it just won't be you who has written the loop.</p>\n\n<p>Have you considered an alternate representation that's more amenable to searching?</p>\n\n<ul>\n<li>A good Set implementation would perform well. (HashSet, TreeSet or the local equivalent).</li>\n<li>If you can be sure that <code>arr</code> is sorted, you could use binary search (which would need to recurse or loop, but not as often as a straight linear search). </li>\n</ul>\n"
},
{
"answer_id": 265181,
"author": "Tamir",
"author_id": 30879,
"author_profile": "https://Stackoverflow.com/users/30879",
"pm_score": 7,
"selected": true,
"text": "<p>Every method, mentioned earlier does looping either internally or externally, so it is not really important how to implement it. Here another example of finding all references of target string</p>\n\n<pre><code> string [] arr = {\"One\",\"Two\",\"Three\"};\n var target = \"One\";\n var results = Array.FindAll(arr, s => s.Equals(target));\n</code></pre>\n"
},
{
"answer_id": 2523012,
"author": "Joe Cheri Ross",
"author_id": 302481,
"author_profile": "https://Stackoverflow.com/users/302481",
"pm_score": 4,
"selected": false,
"text": "<p>I think it is better to use <strong><em>Array.Exists</em></strong> than <em>Array.FindAll</em>.</p>\n"
},
{
"answer_id": 19809325,
"author": "Sharp Coders",
"author_id": 1449894,
"author_profile": "https://Stackoverflow.com/users/1449894",
"pm_score": 4,
"selected": false,
"text": "<p>Its pretty simple. I always use this code to search string from a string array</p>\n\n<pre><code>string[] stringArray = { \"text1\", \"text2\", \"text3\", \"text4\" };\nstring value = \"text3\";\nint pos = Array.IndexOf(stringArray, value);\nif (pos > -1)\n{\n return true;\n}\nelse\n{\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 26803126,
"author": "Yuliia Ashomok",
"author_id": 3627736,
"author_profile": "https://Stackoverflow.com/users/3627736",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"http://msdn.microsoft.com/en-us/library/d9hy2xwa(v=vs.110).aspx\" rel=\"nofollow\">Find</a> method of Array type. From .NET 3.5 and higher. </p>\n\n<pre><code>public static T Find<T>(\n T[] array,\n Predicate<T> match\n)\n</code></pre>\n\n<p>Here is some examples:</p>\n\n<pre><code>// we search an array of strings for a name containing the letter “a”:\nstatic void Main()\n{\n string[] names = { \"Rodney\", \"Jack\", \"Jill\" };\n string match = Array.Find (names, ContainsA);\n Console.WriteLine (match); // Jack\n}\nstatic bool ContainsA (string name) { return name.Contains (\"a\"); }\n</code></pre>\n\n<p>Here’s the same code shortened with an anonymous method:</p>\n\n<pre><code>string[] names = { \"Rodney\", \"Jack\", \"Jill\" };\nstring match = Array.Find (names, delegate (string name)\n { return name.Contains (\"a\"); } ); // Jack\n</code></pre>\n\n<p>A lambda expression shortens it further:</p>\n\n<pre><code>string[] names = { \"Rodney\", \"Jack\", \"Jill\" };\nstring match = Array.Find (names, n => n.Contains (\"a\")); // Jack\n</code></pre>\n"
},
{
"answer_id": 27312104,
"author": "Ahmad",
"author_id": 2651073,
"author_profile": "https://Stackoverflow.com/users/2651073",
"pm_score": 2,
"selected": false,
"text": "<p>You can check the element existence by </p>\n\n<pre><code>arr.Any(x => x == \"One\")\n</code></pre>\n"
},
{
"answer_id": 62878211,
"author": "Ali",
"author_id": 6741585,
"author_profile": "https://Stackoverflow.com/users/6741585",
"pm_score": 0,
"selected": false,
"text": "<p>it is old one ,but this is the way i do it ,</p>\n<p><code>enter code here</code>var result = Array.Find(names, element => element == "One");</p>\n"
},
{
"answer_id": 63104947,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'm surprised that no one suggested using <code>Array.IndexOf</code> Method.</p>\n<p>Indeed, <code>Array.IndexOf</code> has two advantages :</p>\n<ul>\n<li>It allows searching if an element is included into an array,</li>\n<li>It gets at the same time the index into the array.</li>\n</ul>\n<pre><code>int stringIndex = Array.IndexOf(arr, theString);\nif (stringIndex >= 0)\n{\n // theString has been found\n}\n</code></pre>\n<p>Inline version :</p>\n<pre><code>if (Array.IndexOf(arr, theString) >= 0)\n{\n // theString has been found\n}\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22162/"
] |
I need to search a string in the string array. I dont want to use any for looping in it
```
string [] arr = {"One","Two","Three"};
string theString = "One"
```
I need to check whether theString variable is present in arr.
|
Every method, mentioned earlier does looping either internally or externally, so it is not really important how to implement it. Here another example of finding all references of target string
```
string [] arr = {"One","Two","Three"};
var target = "One";
var results = Array.FindAll(arr, s => s.Equals(target));
```
|
264,984 |
<p>We are in the process of upgrading our VS2008 to the new SP1, but noticed a change in the csproj files for something that we can't find information on. Seems that the ProductVersion in the csproj file is changed from:</p>
<pre><code><ProductVersion>9.0.21022</ProductVersion>
</code></pre>
<p>to</p>
<pre><code><ProductVersion>9.0.30729</ProductVersion>
</code></pre>
<p>It looks like some property signalling that the csproj file is/can be consumed by VS 2008 SP1 (perhaps for the Solution Selector to peek into) but are there other hidden side-effects of this property change that we should be looking out for?</p>
|
[
{
"answer_id": 265031,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": true,
"text": "<p>I think it's more likely to be the product version that <em>produced</em> the file rather than saying what it can be consumed by. I'd be very surprised to see the build version make any tangible difference.</p>\n"
},
{
"answer_id": 265039,
"author": "Zuhaib",
"author_id": 25138,
"author_profile": "https://Stackoverflow.com/users/25138",
"pm_score": 1,
"selected": false,
"text": "<p>The major version is all that matters to the Visual Studio Version Selector to select which version of visual studio to open (incase you have both 2005 and 2008).</p>\n\n<p>I guess if you have created a project in a Visual Studio with SP1 installed then it may complain and ask you to install sp1?</p>\n\n<p>I dont have any VS 2008 without SP1 to test this :)</p>\n"
},
{
"answer_id": 1109490,
"author": "Dan Is Fiddling By Firelight",
"author_id": 85661,
"author_profile": "https://Stackoverflow.com/users/85661",
"pm_score": 0,
"selected": false,
"text": "<p>My coworker just got SP1 courtesy of of a ninja update from corporate IT (presumably I'll be getting it after rebooting). My RTM copy doesn't seem to care about the newer version string in all the csproj files.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9222/"
] |
We are in the process of upgrading our VS2008 to the new SP1, but noticed a change in the csproj files for something that we can't find information on. Seems that the ProductVersion in the csproj file is changed from:
```
<ProductVersion>9.0.21022</ProductVersion>
```
to
```
<ProductVersion>9.0.30729</ProductVersion>
```
It looks like some property signalling that the csproj file is/can be consumed by VS 2008 SP1 (perhaps for the Solution Selector to peek into) but are there other hidden side-effects of this property change that we should be looking out for?
|
I think it's more likely to be the product version that *produced* the file rather than saying what it can be consumed by. I'd be very surprised to see the build version make any tangible difference.
|
265,018 |
<p>How can I create unicode console application with Delphi 2009?</p>
<p>If I do like this:</p>
<pre><code>{$APPTYPE CONSOLE}
uses
SysUtils;
begin
writeln('öüğşç سيمانتت');
end.
</code></pre>
<p>I get the following:</p>
<pre><code>ougsc ???????
</code></pre>
|
[
{
"answer_id": 265034,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 3,
"selected": false,
"text": "<p>You can't (At least not with the standard library). The console functions are the only non Unicode functions in Delphi 2009.</p>\n"
},
{
"answer_id": 265036,
"author": "Michał Niklas",
"author_id": 22595,
"author_profile": "https://Stackoverflow.com/users/22595",
"pm_score": 0,
"selected": false,
"text": "<p>Windows console cannot display unicode charactes,\nso try to send output to file with:</p>\n\n<pre><code>my_app.exe > unicode_file.txt\n</code></pre>\n\n<p>and try viewing unicode_file.txt with good text editor.</p>\n"
},
{
"answer_id": 266305,
"author": "mghie",
"author_id": 30568,
"author_profile": "https://Stackoverflow.com/users/30568",
"pm_score": 4,
"selected": true,
"text": "<p>I'm not sure that is what you're after, but you can create Unicode console applications in all 32-bit Delphi versions by using the Windows API functions. I just tried with Delphi 4:</p>\n\n<pre><code>program test;\n\n{$APPTYPE CONSOLE}\n\nuses\n Windows;\n\nvar\n s: WideString;\n i: integer;\n Written: Cardinal;\nbegin\n SetLength(s, 80);\n for i := 1 to 80 do\n s[i] := WideChar(48 + i);\n WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), PWideChar(s), 80, Written,\n nil);\nend.\n</code></pre>\n\n<p>I don't have Delphi 2009 to try how entering Unicode strings in the editor works...</p>\n"
},
{
"answer_id": 267932,
"author": "mghie",
"author_id": 30568,
"author_profile": "https://Stackoverflow.com/users/30568",
"pm_score": 1,
"selected": false,
"text": "<p>@Kabrol: With the raster font set I don't see either of the chars, but with Lucida Console I see at least widechar($11f) - \"ğ\".</p>\n\n<p>Please see <a href=\"http://support.microsoft.com/kb/99795\" rel=\"nofollow noreferrer\">\"SetConsoleOutputCP Only Effective with Unicode Fonts\"</a> and in general the description of console API functions at <a href=\"http://msdn.microsoft.com/en-us/library/ms682087(VS.85).aspx\" rel=\"nofollow noreferrer\">\"Console Reference\"</a>. </p>\n"
},
{
"answer_id": 268202,
"author": "Ondrej Kelle",
"author_id": 11480,
"author_profile": "https://Stackoverflow.com/users/11480",
"pm_score": 4,
"selected": false,
"text": "<p>Writeln in Delphi 2009 still uses ANSI (see System TTextRec) but you can use UTF8Encode and change the console's output code page to UTF8 by calling SetConsoleOutputCP(CP_UTF8). You will also need a good font to actually display Unicode characters.</p>\n"
},
{
"answer_id": 278204,
"author": "PatrickvL",
"author_id": 12170,
"author_profile": "https://Stackoverflow.com/users/12170",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, there is a way to do this with standard WriteLn() calls, but it involves patching a bug in the Delphi 2009 RTL.\nThe thing is, Delphi does some compiler magic for WriteLn. For UnicodeString arguments, this results in a call to _WriteUString. That method can be seen in System.pas, although you can't call it directly. In it you'll see a call to _WriteLString, but that method receives a AnsiString argument. So when this call is taking place, your UnicodeString is being downcasted to AnsiString.</p>\n\n<p>The solution is, to change this UnicodeString->AnsiString cast into a UnicodeString->UTF8String cast.</p>\n\n<p>Now, when you set the console to UTF8, all your characters will go through untouched (and yes, ofcourse you'll need a font with support for the characters you want to show) :</p>\n\n<pre><code>SetConsoleOutputCP(CP_UTF8)\n</code></pre>\n\n<p>For this RTL fix, you'll need to do some nifty code-hooking. I've done this already, and a collegue of mine is busy writing an article about this. I'll post a link once it's available online.</p>\n\n<p>Cheers!</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How can I create unicode console application with Delphi 2009?
If I do like this:
```
{$APPTYPE CONSOLE}
uses
SysUtils;
begin
writeln('öüğşç سيمانتت');
end.
```
I get the following:
```
ougsc ???????
```
|
I'm not sure that is what you're after, but you can create Unicode console applications in all 32-bit Delphi versions by using the Windows API functions. I just tried with Delphi 4:
```
program test;
{$APPTYPE CONSOLE}
uses
Windows;
var
s: WideString;
i: integer;
Written: Cardinal;
begin
SetLength(s, 80);
for i := 1 to 80 do
s[i] := WideChar(48 + i);
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), PWideChar(s), 80, Written,
nil);
end.
```
I don't have Delphi 2009 to try how entering Unicode strings in the editor works...
|
265,062 |
<p>I'm looking for an example of how to load an image from file and print it on a page using WPF. I'm having a hard time finding good information about WPF printing.</p>
|
[
{
"answer_id": 265127,
"author": "MojoFilter",
"author_id": 93,
"author_profile": "https://Stackoverflow.com/users/93",
"pm_score": 0,
"selected": false,
"text": "<p>Just load the image and apply it to a visual. Then use the PrintDialog to do the work.</p>\n\n<pre><code>...\nPrintDialog printer = new PrintDialog();\n\nif (printer.ShowDialog()) {\n printer.PrintVisual(myVisual, \"A Page Title\");\n}\n</code></pre>\n"
},
{
"answer_id": 265155,
"author": "Tamir",
"author_id": 30879,
"author_profile": "https://Stackoverflow.com/users/30879",
"pm_score": 6,
"selected": true,
"text": "<pre><code>var bi = new BitmapImage();\nbi.BeginInit();\nbi.CacheOption = BitmapCacheOption.OnLoad;\nbi.UriSource = new Uri(\"\");\nbi.EndInit();\n\nvar vis = new DrawingVisual();\nusing (var dc = vis.RenderOpen())\n{\n dc.DrawImage(bi, new Rect { Width = bi.Width, Height = bi.Height });\n}\n\nvar pdialog = new PrintDialog();\nif (pdialog.ShowDialog() == true)\n{\n pdialog.PrintVisual(vis, \"My Image\");\n}\n</code></pre>\n"
},
{
"answer_id": 265345,
"author": "Nir",
"author_id": 3509,
"author_profile": "https://Stackoverflow.com/users/3509",
"pm_score": 2,
"selected": false,
"text": "<p>If you want more control then PrintDialog.PrintVisual gives you you have to wrap your image in a FixedDocumet.</p>\n\n<p>You can find simple code that creates a fixed document here:\n<a href=\"http://www.ericsink.com/wpf3d/B_Printing.html\" rel=\"nofollow noreferrer\">http://www.ericsink.com/wpf3d/B_Printing.html</a></p>\n"
},
{
"answer_id": 63384548,
"author": "schorsch1989",
"author_id": 1542368,
"author_profile": "https://Stackoverflow.com/users/1542368",
"pm_score": 1,
"selected": false,
"text": "<p>did playing around with this.</p>\n<p>Tamir's answer is a great answer, but the problem is, that it's using the original size of the image.\n<br><br><br>\nwrite a solution myself , whitch doesn't stretch the image if it's smaller than the pagesize and bring the image if it's to large at the page.<br>\nIt can be used for multiply copies and can be used with both orientations.</p>\n<pre><code> PrintDialog dlg = new PrintDialog();\n\n if (dlg.ShowDialog() == true)\n {\n BitmapImage bmi = new BitmapImage(new Uri(strPath));\n\n Image img = new Image();\n img.Source = bmi;\n\n if (bmi.PixelWidth < dlg.PrintableAreaWidth ||\n bmi.PixelHeight < dlg.PrintableAreaHeight)\n {\n img.Stretch = Stretch.None;\n img.Width = bmi.PixelWidth;\n img.Height = bmi.PixelHeight;\n }\n\n\n if (dlg.PrintTicket.PageBorderless == PageBorderless.Borderless)\n {\n img.Margin = new Thickness(0);\n }\n else\n {\n img.Margin = new Thickness(48);\n }\n img.VerticalAlignment = VerticalAlignment.Top;\n img.HorizontalAlignment = HorizontalAlignment.Left;\n\n for (int i = 0; i < dlg.PrintTicket.CopyCount; i++)\n {\n dlg.PrintVisual(img, "Print a Large Image");\n }\n }\n</code></pre>\n<p>It only works for pictures from files with a path at the moment, but with a little bit work you can adept it and passing only a BitmapImage. <br>\nAnd it is useable with borderless prints (if your printer does support it)</p>\n<p><br>Had to go the way with BitmapImage because it loads the default size of the image.<br>\nWindows.Controls.Image doesn't shows the right height and width if you're loading the image directly there.</p>\n<p><br>I'm knowing, that the question is very old, but it was very difficult to found some useful information during searching this.<br>\nHopefully my post will help other people.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18153/"
] |
I'm looking for an example of how to load an image from file and print it on a page using WPF. I'm having a hard time finding good information about WPF printing.
|
```
var bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.UriSource = new Uri("");
bi.EndInit();
var vis = new DrawingVisual();
using (var dc = vis.RenderOpen())
{
dc.DrawImage(bi, new Rect { Width = bi.Width, Height = bi.Height });
}
var pdialog = new PrintDialog();
if (pdialog.ShowDialog() == true)
{
pdialog.PrintVisual(vis, "My Image");
}
```
|
265,073 |
<p>I'm trying to make a PHP script, I have the script finished but it takes like 10 minutes to finish the process it is designed to do. This is not a problem, however I presume I have to keep the page loaded all this time which is annoying. Can I have it so that I start the process and then come back 10mins later and just view the log file it has generated?</p>
|
[
{
"answer_id": 265085,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I think shell_exec command is what you are looking for.</p>\n\n<p>However, it is disables in safe mode.</p>\n\n<p>The PHP manual article about it is here: <a href=\"http://php.net/shell_exec\" rel=\"nofollow noreferrer\">http://php.net/shell_exec</a></p>\n\n<p>There is an article about it here: <a href=\"http://nsaunders.wordpress.com/2007/01/12/running-a-background-process-in-php/\" rel=\"nofollow noreferrer\">http://nsaunders.wordpress.com/2007/01/12/running-a-background-process-in-php/</a></p>\n"
},
{
"answer_id": 265088,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "<p>You could use <a href=\"http://www.php.net/ignore_user_abort\" rel=\"nofollow noreferrer\"><code>ignore_user_abort()</code></a> - that way the script will continue to run even if you close your browser or go to a different page.</p>\n"
},
{
"answer_id": 265090,
"author": "bastiandoeen",
"author_id": 371953,
"author_profile": "https://Stackoverflow.com/users/371953",
"pm_score": 7,
"selected": true,
"text": "<p>Well, you can use \"<a href=\"http://de2.php.net/manual/en/function.ignore-user-abort.php\" rel=\"noreferrer\">ignore_user_abort</a>(true)\"</p>\n\n<p>So the script will continue to work (keep an eye on script duration, perhaps add \"<a href=\"http://de2.php.net/manual/en/function.set-time-limit.php\" rel=\"noreferrer\">set_time_limit</a>(0)\")</p>\n\n<p>But a warning here: You will not be able to stop a script with these two lines:</p>\n\n<pre><code>ignore_user_abort(true); \nset_time_limit(0);\n</code></pre>\n\n<p>Except you can directly access the server and kill the process there! (Been there, done an endless loop, calling itself over and over again, made the server come to a screeching stop, got shouted at...)</p>\n"
},
{
"answer_id": 265221,
"author": "Christopher Lightfoot",
"author_id": 24525,
"author_profile": "https://Stackoverflow.com/users/24525",
"pm_score": 3,
"selected": false,
"text": "<p>I had lots of issues with this sort of process under windows; My situation was a little different in that I didn't care about the response of the \"script\"- I wanted the script to start and allow other page requests to go through while it was busy working away.</p>\n\n<p>For some reason; I had issues with it either hanging other requests or timing out after about 60 seconds (both apache and php were set to time out after about 20 minutes); It also turns out that firefox times out after 5 minutes (by default) anyway so after that point you can't know what's going on through the browser without changing settings in firefox.</p>\n\n<p>I ended up using the process open and process close methods to open up a php in cli mode like so:</p>\n\n<p><code>pclose(popen(\"start php myscript.php\", \"r\"));</code></p>\n\n<p>This would ( using start ) open the php process and then kill the start process leaving php running for however long it needed - again you'd need to kill the process to manually shut it down. It didn't need you to set any time outs and you could let the current page that called it continue and output some more details.</p>\n\n<p>The only issue with this is that if you need to send the script any data, you'd either do it via another source or pass it along the \"command line\" as parameters; which isn't so secure.</p>\n\n<p>Worked nicely for what we needed though and ensures the script always starts and is allowed to run without any interruptions.</p>\n"
},
{
"answer_id": 265759,
"author": "Gary Richardson",
"author_id": 2506,
"author_profile": "https://Stackoverflow.com/users/2506",
"pm_score": 5,
"selected": false,
"text": "<p>Sounds like you should have a queue and an external script for processing the queue. </p>\n\n<p>For example, your PHP script should put an entry into a database table and return right away. Then, a cron running every minute checks the queue and forks a process for each job.</p>\n\n<p>The advantage here is that you don't lock an apache thread up for 10 minutes. </p>\n"
},
{
"answer_id": 267853,
"author": "Ronald Conco",
"author_id": 16092,
"author_profile": "https://Stackoverflow.com/users/16092",
"pm_score": 2,
"selected": false,
"text": "<p>There is another option which you can use, run the script CLI...It will run in the background and you can even run it as a cronjob if you want.</p>\n\n<p>e.g </p>\n\n<pre><code>> #!/usr/bin/php -q\n\n<?php\n\n//process logs\n\n?>\n</code></pre>\n\n<p>This can be setup as a cronjob and will execute with no time limitation....this examples is for unix based operation system though. </p>\n\n<p>FYI\nI have a php script running with an infinite loop which does some processing and has been running for the past 3 months non stop.</p>\n"
},
{
"answer_id": 17300149,
"author": "Gowri",
"author_id": 430112,
"author_profile": "https://Stackoverflow.com/users/430112",
"pm_score": 2,
"selected": false,
"text": "<p>Think about <a href=\"http://www.php.net/manual/en/book.gearman.php\" rel=\"nofollow\"><strong>Gearman</strong></a></p>\n\n<blockquote>\n <p>Gearman is a generic application framework for farming out work to\n multiple machines or processes. It allows applications to complete\n tasks in parallel, to load balance processing, and to call functions\n between languages. The framework can be used in a variety of\n applications, from high-availability web sites to the transport of\n database replication events.</p>\n \n <p>This extension provides classes for writing Gearman clients and\n workers.\n - Source php manual</p>\n</blockquote>\n\n<p>Offical website of <a href=\"http://gearman.org/\" rel=\"nofollow\">Gearman</a></p>\n"
},
{
"answer_id": 21063019,
"author": "Nader",
"author_id": 2336478,
"author_profile": "https://Stackoverflow.com/users/2336478",
"pm_score": 1,
"selected": false,
"text": "<p>Zuk.</p>\n\n<p>I'm pretty sure this will work:</p>\n\n<pre><code><?php \n\npclose(popen('php /path/to/file/server.php &'));\necho \"Server started. [OK]\"; \n\n?>\n</code></pre>\n\n<p><strong>The '&' is important. It tells the shell not to wait for the process to exit.</strong></p>\n\n<p>Also You can use this code in your php (as \"bastiandoeen\" said)</p>\n\n<pre><code>ignore_user_abort(true); \nset_time_limit(0);\n</code></pre>\n\n<p>in your server stop command:</p>\n\n<pre><code><?php\n\n$output;\nexec('ps aux | grep -ie /path/to/file/server.php | awk \\'{print $2}\\' | xargs kill -9 ', $output);\n echo \"Server stopped. [OK]\";\n\n?>\n</code></pre>\n"
},
{
"answer_id": 28646163,
"author": "RafaSashi",
"author_id": 2456038,
"author_profile": "https://Stackoverflow.com/users/2456038",
"pm_score": 2,
"selected": false,
"text": "<p>In addition to bastiandoeen's answer you can combine <code>ignore_user_abort(true);</code> with a <strong>cUrl request</strong>.</p>\n\n<p>Fake a request abortion setting a low <code>CURLOPT_TIMEOUT_MS</code> and keep processing after the connection closed:</p>\n\n<pre><code>function async_curl($background_process=''){\n\n //-------------get curl contents----------------\n\n $ch = curl_init($background_process);\n curl_setopt_array($ch, array(\n CURLOPT_HEADER => 0,\n CURLOPT_RETURNTRANSFER =>true,\n CURLOPT_NOSIGNAL => 1, //to timeout immediately if the value is < 1000 ms\n CURLOPT_TIMEOUT_MS => 50, //The maximum number of mseconds to allow cURL functions to execute\n CURLOPT_VERBOSE => 1,\n CURLOPT_HEADER => 1\n ));\n $out = curl_exec($ch);\n\n //-------------parse curl contents----------------\n\n //$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);\n //$header = substr($out, 0, $header_size);\n //$body = substr($out, $header_size);\n\n curl_close($ch);\n\n return true;\n}\n\nasync_curl('http://example.com/background_process_1.php');\n</code></pre>\n\n<p><strong>NB</strong></p>\n\n<blockquote>\n <p>If you want cURL to timeout in less than one second, you can use\n CURLOPT_TIMEOUT_MS, although there is a bug/\"feature\" on \"Unix-like\n systems\" that causes libcurl to timeout immediately if the value is <\n 1000 ms with the error \"cURL Error (28): Timeout was reached\". The\n explanation for this behavior is:</p>\n \n <p>[...]</p>\n \n <p>The solution is to disable signals using CURLOPT_NOSIGNAL</p>\n</blockquote>\n\n<p><strong>pros</strong></p>\n\n<ul>\n<li>No need to switch methods (Compatible windows & linux)</li>\n<li>No need to implement connection handling via headers and buffer (Independent from Browser and PHP version)</li>\n</ul>\n\n<p><strong>cons</strong></p>\n\n<ul>\n<li>Need curl extension</li>\n</ul>\n\n<p><strong>Resources</strong></p>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/7987584/curl-timeout-less-than-1000ms-always-fails\">curl timeout less than 1000ms always fails?</a></p></li>\n<li><p><a href=\"http://www.php.net/manual/en/function.curl-setopt.php#104597\" rel=\"nofollow noreferrer\">http://www.php.net/manual/en/function.curl-setopt.php#104597</a></p></li>\n<li><p><a href=\"http://php.net/manual/en/features.connection-handling.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/features.connection-handling.php</a></p></li>\n</ul>\n"
},
{
"answer_id": 51540421,
"author": "user3684669",
"author_id": 3684669,
"author_profile": "https://Stackoverflow.com/users/3684669",
"pm_score": -1,
"selected": false,
"text": "<p>Just call StartBuffer() before any output, and EndBuffer() when you want client to close connection. The code after calling EndBuffer() will be executed on server without client connection.</p>\n\n<pre>\n\n private function StartBuffer(){\n @ini_set('zlib.output_compression',0);\n @ini_set('implicit_flush',1);\n @ob_end_clean();\n @set_time_limit(0);\n @ob_implicit_flush(1);\n @ob_start();\n }\n\n private function EndBuffer(){\n $size = ob_get_length();\n header(\"Content-Length: $size\");\n header('Connection: close');\n ob_flush();ob_implicit_flush(1);\n }\n\n</pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26823/"
] |
I'm trying to make a PHP script, I have the script finished but it takes like 10 minutes to finish the process it is designed to do. This is not a problem, however I presume I have to keep the page loaded all this time which is annoying. Can I have it so that I start the process and then come back 10mins later and just view the log file it has generated?
|
Well, you can use "[ignore\_user\_abort](http://de2.php.net/manual/en/function.ignore-user-abort.php)(true)"
So the script will continue to work (keep an eye on script duration, perhaps add "[set\_time\_limit](http://de2.php.net/manual/en/function.set-time-limit.php)(0)")
But a warning here: You will not be able to stop a script with these two lines:
```
ignore_user_abort(true);
set_time_limit(0);
```
Except you can directly access the server and kill the process there! (Been there, done an endless loop, calling itself over and over again, made the server come to a screeching stop, got shouted at...)
|
265,081 |
<p>when installing SQLServer2005 developer edition (not express) I created a named instance:</p>
<pre><code>MYSERVERNAME/MYINSTANCENAME
</code></pre>
<p>Is it possible to </p>
<p>1) change the name of my named instance to default:</p>
<pre><code>MYSERVERNAME
</code></pre>
<p>OR</p>
<p>2) create a new default instance (MYSERVERNAME as above).</p>
<p>any help would be appreciated!</p>
|
[
{
"answer_id": 265110,
"author": "Alan",
"author_id": 31223,
"author_profile": "https://Stackoverflow.com/users/31223",
"pm_score": 4,
"selected": true,
"text": "<p>Hm, when I use the \"Change\" button in Add/Remove Programs, SQL Server 2005 setup offers me the instance selection screen, and even allows me to list the existing instances. (I'm running XP SP2, by the way.)</p>\n\n<p>I selected the \"To install a new component, click here\" link in the setup program, then selected SQL Server Database Services on the \"Components to Install\" screen to arrive at the instance selection screen that allows me to install a new default instance.</p>\n"
},
{
"answer_id": 265116,
"author": "Jeremiah Peschka",
"author_id": 11780,
"author_profile": "https://Stackoverflow.com/users/11780",
"pm_score": 2,
"selected": false,
"text": "<p>Going off of Alan's answer, when you install a new instance as the default instance, take note of the directories it is using to store data and log files (or create a default location like D:\\MSSQL\\Log and D:\\MSSQL\\Data).</p>\n\n<p>You can then detach the databases from the named instance and move the files to the new data and log directories and re-attach them in SSMS.</p>\n"
},
{
"answer_id": 3664110,
"author": "Michael",
"author_id": 441968,
"author_profile": "https://Stackoverflow.com/users/441968",
"pm_score": 3,
"selected": false,
"text": "<p>A default instance has a default instance name, but captures the computer's name, and uses it as an alias. Even if you change the computer name, the default instance will capture the new computer name, and use it as its alias. But the default instance name remains the same (like MSSQLSERVER).</p>\n\n<p>This is why a default instance cannot be renamed. The default instance name is fixed, and it captures the computer name and uses it for its alias. Thus, only one (1) default instance can exist on a computer, because the default instance has a fixed name, and it always captures and uses the computer name for an alias. In other words, the default instance name is joined at the hip with the computer name (as an alias). Neither can be changed programmatically. Changing the computer name simply changes the alias attached to the default instance name.</p>\n\n<p>If a default instance already exists, all other SQL installations on that computer will be forced to use a named instance (an alias, which cannot be the computer name).</p>\n\n<p>Now in your case, during your first SQL installation, you chose to install it as a named instance, not a default instance. Thus you had no default instance, and thus you used an alias that was different from the computer name. You've never installed a default instance, therefore the installation did not capture the computer name for its alias.</p>\n\n<p>The major thing about default instances is that they capture and use the computer name as an alias, and there is absolutely no way to programmatically change a default instance name. However, you can change its alias by changing the computer name. But the computer name is still joined to the default instance name.</p>\n\n<p>An alias simply points to an SQL installation, so that the alias may use its engine. If the installation was not designated as a default instance, it simply means the installation is not attached at the hip with the computer name as its alias.</p>\n\n<p>I hope this helps, but if this is clear as mud, please forgive me.</p>\n"
},
{
"answer_id": 9114676,
"author": "Terence",
"author_id": 1185444,
"author_profile": "https://Stackoverflow.com/users/1185444",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks. This worked for me with sql server 2008 r2 express as well.</p>\n\n<p>I had a default instance of 2005 installed, and only a named instance for a subsequent install of 2008.</p>\n\n<p>I uninstalled 2005 (Important: Copy any 2005 databases to a separate folder first).</p>\n\n<p>Then I reinstalled 2008. You can get the installation exe from microsoft if you don't still have it.</p>\n\n<ol>\n<li>Start installation and select \"new installation or add feature\".</li>\n<li>Select option button for \"new installation or add feature\".</li>\n<li>Accept default instances feature. NEXT.</li>\n<li>Select default instance option. NEXT. (note instance ID is MSSQLSERVER).</li>\n<li>Continue to accept defauls unless you have a reason not to.</li>\n</ol>\n"
},
{
"answer_id": 30163151,
"author": "Moe Eshaq",
"author_id": 4818968,
"author_profile": "https://Stackoverflow.com/users/4818968",
"pm_score": 0,
"selected": false,
"text": "<p>If you have installed a named instance. You cannot change the name to default. You can however:\n* make the named instance listen to the default port.\n* OR create aliases (with name like MSSQLServer or the IP address, as a trick) to make your clients work.\n* If this workaround doesn't help then your best bet is to uninstall SQL Complete and re-install again but chances are that the new installation might take the named instance's name again even if you selected 'default instance'. You can verify this in the SQL services to see if it is still taking the old name.\nIn this case, the best way (which worked for me) is to install a new instance with the explicit name of MSSQLServer which is known to be the default instance name.</p>\n\n<p>Keep in mind also that SQL takes the computer name and uses it as an alias. </p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1311500/"
] |
when installing SQLServer2005 developer edition (not express) I created a named instance:
```
MYSERVERNAME/MYINSTANCENAME
```
Is it possible to
1) change the name of my named instance to default:
```
MYSERVERNAME
```
OR
2) create a new default instance (MYSERVERNAME as above).
any help would be appreciated!
|
Hm, when I use the "Change" button in Add/Remove Programs, SQL Server 2005 setup offers me the instance selection screen, and even allows me to list the existing instances. (I'm running XP SP2, by the way.)
I selected the "To install a new component, click here" link in the setup program, then selected SQL Server Database Services on the "Components to Install" screen to arrive at the instance selection screen that allows me to install a new default instance.
|
265,096 |
<p>I'm trying to use <code>System.DirectoryServices</code> in a web site project and I'm getting this error:</p>
<blockquote>
<p>The type or namespace name 'DirectoryServices' does not exist in the namespace 'System' (are you missing an assembly reference?)</p>
</blockquote>
<p>My project has a reference to <code>System.DirectoryServices</code> in <code>web.config</code>: </p>
<pre><code><add assembly="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
</code></pre>
<p>And I do have <code>using System.DirectoryServices</code> in the files where I want to use it.</p>
<p>Does anybody have a clue where to look for the problem?</p>
|
[
{
"answer_id": 265104,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>Is this a web <em>site</em> project, or a web <em>application</em> project. With the latter, references are handled via the .csproj - i.e. via the \"References\" node in Solution Explorer.</p>\n"
},
{
"answer_id": 265133,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 3,
"selected": false,
"text": "<p>Shot in the dark: have you tried adding to the web.config:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><compilation debug=\"true\">\n <assemblies>\n <add assembly=\"System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A\"/>\n </assemblies>\n</compilation>\n</code></pre>\n"
},
{
"answer_id": 265163,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "<p>Is the web-server (IIS or whatever) configured to run the folder as an application (i.e. shows as a cog), and is it using the correct version of ASP.NET? If it is running as 1.1, bits of it might work - but it would fail to find that 2.0 assembly in the 1.1 GAC.</p>\n"
},
{
"answer_id": 9197108,
"author": "Salman Siddiqui",
"author_id": 894133,
"author_profile": "https://Stackoverflow.com/users/894133",
"pm_score": 3,
"selected": false,
"text": "<p>This is a very old thread but just to provide a complete answer for the sake of posterity ;)</p>\n\n<p>This issue occurs if the project is missing a reference to the .Net Component <strong>System.DirectoryServices</strong></p>\n\n<p>Adding this reference in the usual manner prefered by you will resolve the issue.</p>\n"
},
{
"answer_id": 14148434,
"author": "user1947015",
"author_id": 1947015,
"author_profile": "https://Stackoverflow.com/users/1947015",
"pm_score": 7,
"selected": false,
"text": "<ol>\n<li>Right click on References under your solution. </li>\n<li>Select Add Reference.\nThe reference can be found under the Framework Assemblies list.\nSelect <em>System.DirectoryServices</em> and click Add.</li>\n</ol>\n"
},
{
"answer_id": 17129451,
"author": "Ntsikelelo Ndleleni",
"author_id": 2148239,
"author_profile": "https://Stackoverflow.com/users/2148239",
"pm_score": 1,
"selected": false,
"text": "<p>On Solution Explorer right-click your project, then from the resulting menu, click on Add Reference, then under the .NET tab navigate to DirectoryServices.AccountManagement</p>\n"
},
{
"answer_id": 42107456,
"author": "Navid Golforoushan",
"author_id": 2253691,
"author_profile": "https://Stackoverflow.com/users/2253691",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem when I tried to convert website to web-app.\nIt looks like vs failing to load the assembly should be related to versioning.\nswitch to <code>web.config</code> and add the assembly to it as bellow. make sure the DLL version is matching your application targeted .NET version.</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><configuration>\n <system.web>\n <compilation debug=\"true\" targetFramework=\"4.0\">\n <assemblies>\n <add assembly=\"System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"/>\n </assemblies>\n </compilation>\n </system.web>\n</configuration>\n</code></pre>\n\n<p>for getting a public key you need to launch <code>Developer Command Prompt for VS</code>. Change to GAC directory related framework on above ex <code>C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319</code>\nand call </p>\n\n<pre><code>sn -T System.DirectoryServices.dll\n</code></pre>\n"
},
{
"answer_id": 46180174,
"author": "Basma Elshoky",
"author_id": 2925809,
"author_profile": "https://Stackoverflow.com/users/2925809",
"pm_score": 3,
"selected": false,
"text": "<p>I think you should install Directory Services Package.</p>\n\n<pre><code>Install-Package System.DirectoryServices -Version 4.0.0 \n</code></pre>\n\n<p><a href=\"https://www.nuget.org/packages/System.DirectoryServices/4.0.0\" rel=\"noreferrer\">Directory Services Package</a></p>\n"
},
{
"answer_id": 55000311,
"author": "Pratheek S",
"author_id": 8625413,
"author_profile": "https://Stackoverflow.com/users/8625413",
"pm_score": 1,
"selected": false,
"text": "<p>These problems occur when you are working with older .net version and trying to build with the latest IDE </p>\n\n<p>It depends on which version of IDE you are using and also the current code version.</p>\n\n<p>Check the web config,</p>\n\n<p>In my case, I was using the Latest version i.e 4.7 and <code>directoryService</code> assembly are still referring to C#4.0.</p>\n\n<p>Add below if you are using Latest version of id i.e 4.7</p>\n\n<pre><code> <system.web>\n <location>\n\n<compilation debug=\"false\" numRecompilesBeforeAppRestart=\"100\" targetFramework=\"4.7\">\n <assemblies>\n<add assembly=\"System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A\" />\n<add assembly=\"System.DirectoryServices.AccountManagement, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\" />\n </assemblies>\n </compilation>\n</system.web>\n </location>\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12111/"
] |
I'm trying to use `System.DirectoryServices` in a web site project and I'm getting this error:
>
> The type or namespace name 'DirectoryServices' does not exist in the namespace 'System' (are you missing an assembly reference?)
>
>
>
My project has a reference to `System.DirectoryServices` in `web.config`:
```
<add assembly="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
```
And I do have `using System.DirectoryServices` in the files where I want to use it.
Does anybody have a clue where to look for the problem?
|
Is the web-server (IIS or whatever) configured to run the folder as an application (i.e. shows as a cog), and is it using the correct version of ASP.NET? If it is running as 1.1, bits of it might work - but it would fail to find that 2.0 assembly in the 1.1 GAC.
|
265,117 |
<p>OK, I have just been reading and trying for the last hour to import a CSV file from access into MySQL, but I can not get it to do it correctly, no matter what I try.</p>
<p>My table is like so:</p>
<pre><code>+-----------------+-------------
| Field | Type
+-----------------+-------------
| ARTICLE_NO | varchar(20)
| ARTICLE_NAME | varchar(100)
| SUBTITLE | varchar(20)
| CURRENT_BID | varchar(20)
| START_PRICE | varchar(20)
| BID_COUNT | varchar(20)
| QUANT_TOTAL | varchar(20)
| QUANT_SOLD | varchar(20)
| STARTS | datetime
| ENDS | datetime
| ORIGIN_END | datetime
| SELLER_ID | varchar(20)
| BEST_BIDDER_ID | varchar(20)
| FINISHED | varchar(20)
| WATCH | varchar(20)
| BUYITNOW_PRICE | varchar(20)
| PIC_URL | varchar(20)
| PRIVATE_AUCTION | varchar(20)
| AUCTION_TYPE | varchar(20)
| INSERT_DATE | datetime
| UPDATE_DATE | datetime
| CAT_1_ID | varchar(20)
| CAT_2_ID | varchar(20)
| ARTICLE_DESC | varchar(20)
| DESC_TEXTONLY | varchar(20)
| COUNTRYCODE | varchar(20)
| LOCATION | varchar(20)
| CONDITIONS | varchar(20)
| REVISED | varchar(20)
| PAYPAL_ACCEPT | tinyint(4)
| PRE_TERMINATED | varchar(20)
| SHIPPING_TO | varchar(20)
| FEE_INSERTION | varchar(20)
| FEE_FINAL | varchar(20)
| FEE_LISTING | varchar(20)
| PIC_XXL | tinyint(4)
| PIC_DIASHOW | tinyint(4)
| PIC_COUNT | varchar(20)
| ITEM_SITE_ID | varchar(20)
</code></pre>
<p>Which should be fine, and my data is currently semicolon delimited, an example of a row from my csv file is thus:</p>
<pre><code>"110268889894";"ORIGINAL 2008 ED HARDY GÜRTEL* MYSTERY LOVE * M *BLACK";"";0,00 €;0,00 €;0;1;0;8.7.2008 17:18:37;5.11.2008 16:23:37;6.10.2008 17:23:37;29;0;0;0;125,00 €;"";0;2;6.10.2008 16:21:51;6.10.2008 14:19:08;80578;0;;0;77;"";0;0;1;0;-1;0,00 €;0,00 €;0,00 €;0;0;0;77
"110293328957";"Orig. Ed Hardy Shirt - Tank Top - Gr. XS- OVP/NEU";"";25,05 €;0,00 €;7;1;0;27.9.2008 06:26:27;6.10.2008 18:26:21;6.10.2008 18:26:21;49;0;0;0;0,00 €;"";0;1;6.10.2008 16:21:56;6.10.2008 16:33:20;31058;0;;0;77;"";1;0;0;0;-1;0,00 €;0,00 €;0,00 €;0;0;0;77
</code></pre>
<p>I am using a simple PHP page to output the table data, and it is completely wrong. The problem is not with the PHP page as a simple table with just text displays perfectly. I am wondering if I have selected incorrect field types or the columns do not match up, but I see no reason this would be the case. Could something be happening because the data is trying to be displayed as HTML?</p>
<p>I have tried to keep this question as specific as possible, and am not asking for people to do it for me as others have suggested, but I honestly can not see where the problem is.</p>
<p>edit: When trying to display the data through PHP, at the moment the page is completely black with some table cells having borders and others not, othertimes when trying different delimiters, the fields do not match the columns. The starts field has never displayed correctly.</p>
<p>I am loading the file from a CSV file with this command: </p>
<pre><code>LOAD DATA LOCAL INFILE 'C:/Dokumente und Einstellungen/hom/Desktop/tblAuction.txt' INTO TABLE Auctions FIELDS TERMINATED BY '\"' LINES TERMINATED BY '\n';
</code></pre>
<p>It looks fine in the DB as far as I have been able to tell, apart from the starts field, which is not the main problem at the moment.</p>
<p>edit2: I have serialized the result, and this is what was output to the screen:</p>
<pre><code>i:0;
</code></pre>
<p>I have absolutely no idea what that means.</p>
<p>edit3: I had tried updating the terminated by a delimiter, and after changing \" to ; the problem still remains of data not being put into the correct columns etc.., I don't understand what I have missed.</p>
|
[
{
"answer_id": 265150,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 1,
"selected": true,
"text": "<p>The error can be caused by corrupt data in your DB, by the query to retrieve it from the DB, or in the way you output it. You need to narrow it down to one of those causes.</p>\n\n<ol>\n<li>Have a direct look at the table you are selecting from. I suggest <a href=\"http://www.phpmyadmin.net/\" rel=\"nofollow noreferrer\">phpMyAdmin</a> for this.</li>\n<li>Directly print the result of your query to the screen. A very crude but workable way could be to <a href=\"http://fr3.php.net/serialize\" rel=\"nofollow noreferrer\">serialise</a> it:, e.g. <code>echo serialize($result);</code></li>\n<li>If you can exclude 1 and 2 as causes of your error, the problem must lie in the processing of the query.</li>\n</ol>\n\n<p>Once you have identified <em>where</em> the cause is, it gets much easier to nail down <em>what</em> the cause is ;-)</p>\n\n<p>As Ted Elliot mentioned: <em>Your fields are terminated by \";\" not \"\\\"\". Change <code>FIELDS TERMINATED BY '\\\"'</code>\nto <code>FIELDS TERMINATED BY ';'</code></em></p>\n\n<p>Also, the correct format for importing data into datetime fields in mysql seems to be the ISO format: YYYY-MM-DD HH:mm:ss (e.g. 2007-07-31 00:00:00).</p>\n"
},
{
"answer_id": 265174,
"author": "Ted Elliott",
"author_id": 16501,
"author_profile": "https://Stackoverflow.com/users/16501",
"pm_score": 3,
"selected": false,
"text": "<p>Your fields are terminated by \";\" not \"\\\"\". Change</p>\n\n<pre><code> FIELDS TERMINATED BY '\\\"'\n</code></pre>\n\n<p>to</p>\n\n<pre><code> FIELDS TERMINATED BY ';'\n</code></pre>\n\n<p>You could add this as well:</p>\n\n<pre><code> OPTIONALLY ENCLOSED BY '\"'\n</code></pre>\n\n<p>which I think is what you were trying to do with the TERMINATED BY clause.</p>\n"
},
{
"answer_id": 265347,
"author": "Gene T",
"author_id": 413049,
"author_profile": "https://Stackoverflow.com/users/413049",
"pm_score": -1,
"selected": false,
"text": "<p>it commonly happens that what you're using as the \"FIELDS TERMINATED BY\" string actually occurs inside one of the fields, check this by writing a little program to .split() each line in the file and count the fields. Hopefully, you control how the input file is generated and can use somehting extremely unlikely, like \"~~~~~\"</p>\n\n<p>Also, (not directly relevent, but you shd know) you still have to do \"\\N\" to enter nulls in the db, and empty strings in input file can turn into zero's in numeric fields</p>\n\n<p><a href=\"http://bugs.mysql.com/bug.php?id=23212\" rel=\"nofollow noreferrer\">http://bugs.mysql.com/bug.php?id=23212</a></p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
OK, I have just been reading and trying for the last hour to import a CSV file from access into MySQL, but I can not get it to do it correctly, no matter what I try.
My table is like so:
```
+-----------------+-------------
| Field | Type
+-----------------+-------------
| ARTICLE_NO | varchar(20)
| ARTICLE_NAME | varchar(100)
| SUBTITLE | varchar(20)
| CURRENT_BID | varchar(20)
| START_PRICE | varchar(20)
| BID_COUNT | varchar(20)
| QUANT_TOTAL | varchar(20)
| QUANT_SOLD | varchar(20)
| STARTS | datetime
| ENDS | datetime
| ORIGIN_END | datetime
| SELLER_ID | varchar(20)
| BEST_BIDDER_ID | varchar(20)
| FINISHED | varchar(20)
| WATCH | varchar(20)
| BUYITNOW_PRICE | varchar(20)
| PIC_URL | varchar(20)
| PRIVATE_AUCTION | varchar(20)
| AUCTION_TYPE | varchar(20)
| INSERT_DATE | datetime
| UPDATE_DATE | datetime
| CAT_1_ID | varchar(20)
| CAT_2_ID | varchar(20)
| ARTICLE_DESC | varchar(20)
| DESC_TEXTONLY | varchar(20)
| COUNTRYCODE | varchar(20)
| LOCATION | varchar(20)
| CONDITIONS | varchar(20)
| REVISED | varchar(20)
| PAYPAL_ACCEPT | tinyint(4)
| PRE_TERMINATED | varchar(20)
| SHIPPING_TO | varchar(20)
| FEE_INSERTION | varchar(20)
| FEE_FINAL | varchar(20)
| FEE_LISTING | varchar(20)
| PIC_XXL | tinyint(4)
| PIC_DIASHOW | tinyint(4)
| PIC_COUNT | varchar(20)
| ITEM_SITE_ID | varchar(20)
```
Which should be fine, and my data is currently semicolon delimited, an example of a row from my csv file is thus:
```
"110268889894";"ORIGINAL 2008 ED HARDY GÜRTEL* MYSTERY LOVE * M *BLACK";"";0,00 €;0,00 €;0;1;0;8.7.2008 17:18:37;5.11.2008 16:23:37;6.10.2008 17:23:37;29;0;0;0;125,00 €;"";0;2;6.10.2008 16:21:51;6.10.2008 14:19:08;80578;0;;0;77;"";0;0;1;0;-1;0,00 €;0,00 €;0,00 €;0;0;0;77
"110293328957";"Orig. Ed Hardy Shirt - Tank Top - Gr. XS- OVP/NEU";"";25,05 €;0,00 €;7;1;0;27.9.2008 06:26:27;6.10.2008 18:26:21;6.10.2008 18:26:21;49;0;0;0;0,00 €;"";0;1;6.10.2008 16:21:56;6.10.2008 16:33:20;31058;0;;0;77;"";1;0;0;0;-1;0,00 €;0,00 €;0,00 €;0;0;0;77
```
I am using a simple PHP page to output the table data, and it is completely wrong. The problem is not with the PHP page as a simple table with just text displays perfectly. I am wondering if I have selected incorrect field types or the columns do not match up, but I see no reason this would be the case. Could something be happening because the data is trying to be displayed as HTML?
I have tried to keep this question as specific as possible, and am not asking for people to do it for me as others have suggested, but I honestly can not see where the problem is.
edit: When trying to display the data through PHP, at the moment the page is completely black with some table cells having borders and others not, othertimes when trying different delimiters, the fields do not match the columns. The starts field has never displayed correctly.
I am loading the file from a CSV file with this command:
```
LOAD DATA LOCAL INFILE 'C:/Dokumente und Einstellungen/hom/Desktop/tblAuction.txt' INTO TABLE Auctions FIELDS TERMINATED BY '\"' LINES TERMINATED BY '\n';
```
It looks fine in the DB as far as I have been able to tell, apart from the starts field, which is not the main problem at the moment.
edit2: I have serialized the result, and this is what was output to the screen:
```
i:0;
```
I have absolutely no idea what that means.
edit3: I had tried updating the terminated by a delimiter, and after changing \" to ; the problem still remains of data not being put into the correct columns etc.., I don't understand what I have missed.
|
The error can be caused by corrupt data in your DB, by the query to retrieve it from the DB, or in the way you output it. You need to narrow it down to one of those causes.
1. Have a direct look at the table you are selecting from. I suggest [phpMyAdmin](http://www.phpmyadmin.net/) for this.
2. Directly print the result of your query to the screen. A very crude but workable way could be to [serialise](http://fr3.php.net/serialize) it:, e.g. `echo serialize($result);`
3. If you can exclude 1 and 2 as causes of your error, the problem must lie in the processing of the query.
Once you have identified *where* the cause is, it gets much easier to nail down *what* the cause is ;-)
As Ted Elliot mentioned: *Your fields are terminated by ";" not "\"". Change `FIELDS TERMINATED BY '\"'`
to `FIELDS TERMINATED BY ';'`*
Also, the correct format for importing data into datetime fields in mysql seems to be the ISO format: YYYY-MM-DD HH:mm:ss (e.g. 2007-07-31 00:00:00).
|
265,140 |
<p><a href="http://www.springsource.org/extensions/se-workflow" rel="noreferrer">Spring Workflow</a> has now been published.</p>
<ul>
<li>Have you tried it yet? For what kind of scenario?</li>
<li>What is your impression? How do you find it stacks up against other workflow libs?</li>
<li>Found any good docs or tutorials?</li>
</ul>
|
[
{
"answer_id": 453212,
"author": "SenoCtar",
"author_id": 56174,
"author_profile": "https://Stackoverflow.com/users/56174",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think it's a good idea to try it yet, it's just a release to proove the concept. First of all you have to manually build your library, after that, leran how to use it with no example or documentation, just using the scarcely documented code and test code. And when you have an idea about it you realise it can't do very mutch right now.</p>\n"
},
{
"answer_id": 467127,
"author": "SenoCtar",
"author_id": 56174,
"author_profile": "https://Stackoverflow.com/users/56174",
"pm_score": 3,
"selected": true,
"text": "<p>OK, ignoring my beliefs shown in my previous post I did try spring workflow, only to find out that I was right. Getting the sources and building is not that hard, they use svn, ant and ivy as repository manager.</p>\n\n<p>Making it work is another story. I took the sample sources, an placed them in a new project. At this poit I had to rename all imports since they were built for test eviron ment i guess. This is easy with help from the IDE in classes, but you also have to rename them in spring's XML context files. Further on, it starts to look bad once you try to run the project. First you get a NullPointerException, because of the following lines :</p>\n\n<pre><code>public final void afterPropertiesSet() throws Exception {\n if (this.flowInstanceDescriptorPersisters == null) {\n this.flowInstanceDescriptorPersisters.put(DEFAULT_PERSISTER, new DefaultFlowInstanceDescriptorPersister());\n }\n}\n</code></pre>\n\n<p>I simply created a new HashMap, rebuit the project and gave it another try. Now it will fail at an Assert if you did not include spring security. There is a hidded dependency (because reflection is used). Added the lib. and ran it again. I got another Assert fail, and when I looked that up I realised the samples are not even supposed to work. A method intentionally returns null and it shouldn't. I went to the interface, of cource, no javadoc, but i suspected what it should return from it's name, so i placed a hardcode value. At this point it biulds and it runs but it does not work, it's supposed to (at least i think it is, there are no docs.) do a transition, but the flow remains unchanged after the performTransition call.</p>\n\n<p>So there you have it. Dont try it just yet.</p>\n"
},
{
"answer_id": 1372751,
"author": "ILX",
"author_id": 122674,
"author_profile": "https://Stackoverflow.com/users/122674",
"pm_score": 0,
"selected": false,
"text": "<p>There is a presentation on parleys.com:</p>\n\n<p>Spring & Spring MVC in production</p>\n\n<p>from authors of spring workflow: cakesolutions.net</p>\n\n<p>You might take a look at the presentation to find out how they use it in production at <a href=\"http://www.ukinvest.gov.uk/\" rel=\"nofollow noreferrer\">http://www.ukinvest.gov.uk/</a></p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20065/"
] |
[Spring Workflow](http://www.springsource.org/extensions/se-workflow) has now been published.
* Have you tried it yet? For what kind of scenario?
* What is your impression? How do you find it stacks up against other workflow libs?
* Found any good docs or tutorials?
|
OK, ignoring my beliefs shown in my previous post I did try spring workflow, only to find out that I was right. Getting the sources and building is not that hard, they use svn, ant and ivy as repository manager.
Making it work is another story. I took the sample sources, an placed them in a new project. At this poit I had to rename all imports since they were built for test eviron ment i guess. This is easy with help from the IDE in classes, but you also have to rename them in spring's XML context files. Further on, it starts to look bad once you try to run the project. First you get a NullPointerException, because of the following lines :
```
public final void afterPropertiesSet() throws Exception {
if (this.flowInstanceDescriptorPersisters == null) {
this.flowInstanceDescriptorPersisters.put(DEFAULT_PERSISTER, new DefaultFlowInstanceDescriptorPersister());
}
}
```
I simply created a new HashMap, rebuit the project and gave it another try. Now it will fail at an Assert if you did not include spring security. There is a hidded dependency (because reflection is used). Added the lib. and ran it again. I got another Assert fail, and when I looked that up I realised the samples are not even supposed to work. A method intentionally returns null and it shouldn't. I went to the interface, of cource, no javadoc, but i suspected what it should return from it's name, so i placed a hardcode value. At this point it biulds and it runs but it does not work, it's supposed to (at least i think it is, there are no docs.) do a transition, but the flow remains unchanged after the performTransition call.
So there you have it. Dont try it just yet.
|
265,146 |
<p>I currently have a 32 bit dll that was created with Visual Studio 2003 in C++ using <a href="http://en.wikipedia.org/wiki/Managed_Extensions_for_C%2B%2B" rel="nofollow noreferrer">Managed Extensions</a>. I'm now trying to compile a 64 bit version without having to upgrade to C++/CLI. I've been following the tutorial at <a href="http://www.eggheadcafe.com/forumarchives/vclanguage/Aug2005/post23130822.asp" rel="nofollow noreferrer">this location</a>. I'm getting the following error:</p>
<blockquote>
<p> fatal error C1197:
cannot reference
'c:\windows\microsoft.net\framework\v1.1.4322\mscorlib.dll'
as the progam has already referenced
'c:\windows\microsoft.net\framework\v2.0.50727\mscorlib.dll'</p>
</blockquote>
<p>I can't figure out what is referencing the .NET 2.0 version of the dll.</p>
|
[
{
"answer_id": 265167,
"author": "UberJumper",
"author_id": 34395,
"author_profile": "https://Stackoverflow.com/users/34395",
"pm_score": 1,
"selected": false,
"text": "<p>Do you manually call the .dll file in the code? Like in this?</p>\n\n<pre><code>#using \"C:\\Windows\\Microsoft.NET\\Framework\\v1.1.4322\\mscorlib.dll\n</code></pre>\n\n<p>If so, you can change this line to just:</p>\n\n<pre><code>#using \"mscorlib.dll\"\n</code></pre>\n"
},
{
"answer_id": 634956,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 0,
"selected": false,
"text": "<p>Are you including a library that links to a different version of mscorlib?</p>\n\n<p>Are you specifying both the /clr option and doing a #using \"mscorlib.dll\" ?</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9539/"
] |
I currently have a 32 bit dll that was created with Visual Studio 2003 in C++ using [Managed Extensions](http://en.wikipedia.org/wiki/Managed_Extensions_for_C%2B%2B). I'm now trying to compile a 64 bit version without having to upgrade to C++/CLI. I've been following the tutorial at [this location](http://www.eggheadcafe.com/forumarchives/vclanguage/Aug2005/post23130822.asp). I'm getting the following error:
>
> fatal error C1197:
> cannot reference
> 'c:\windows\microsoft.net\framework\v1.1.4322\mscorlib.dll'
> as the progam has already referenced
> 'c:\windows\microsoft.net\framework\v2.0.50727\mscorlib.dll'
>
>
>
I can't figure out what is referencing the .NET 2.0 version of the dll.
|
Do you manually call the .dll file in the code? Like in this?
```
#using "C:\Windows\Microsoft.NET\Framework\v1.1.4322\mscorlib.dll
```
If so, you can change this line to just:
```
#using "mscorlib.dll"
```
|
265,166 |
<p>I need to pause for maybe 500 miliseconds before I submit a form. Here is what I have so far:</p>
<pre><code> $(".rowqty input").bind("keyup", function() { $("#ViewCartPage form").animate({ opacity: 1.0 }, 3000).submit() });
</code></pre>
<p>so when someone changes the quantity of the input field it submits the form, but I want it to wait for a slight amount of time incase they need a moment to type 2 or 3 numbers. </p>
<p>As you can see I tried the animate function to try and delay things but with no luck.</p>
<p>I know I could use this: <a href="http://blog.mythin.net/projects/jquery.php" rel="nofollow noreferrer">http://blog.mythin.net/projects/jquery.php</a></p>
<p>I'd rather not add another JS to my site if there is a way around it.</p>
<p>EDIT: Actually the pause plugin above is not working for me either.</p>
|
[
{
"answer_id": 265172,
"author": "Chris Van Opstal",
"author_id": 7264,
"author_profile": "https://Stackoverflow.com/users/7264",
"pm_score": 3,
"selected": true,
"text": "<p>Give this a shot:</p>\n\n<pre><code>$(\".rowqty input\").bind(\"keyup\", function() { setTimeout(\"$('#ViewCartPage form').submit()\", 500 });\n</code></pre>\n"
},
{
"answer_id": 10460448,
"author": "khaled_webdev",
"author_id": 1376051,
"author_profile": "https://Stackoverflow.com/users/1376051",
"pm_score": 0,
"selected": false,
"text": "<pre><code>setTimeout(function () {$(\"#formID\").submit()},1000);\n</code></pre>\n\n<p>it works for me (no quotes)</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34548/"
] |
I need to pause for maybe 500 miliseconds before I submit a form. Here is what I have so far:
```
$(".rowqty input").bind("keyup", function() { $("#ViewCartPage form").animate({ opacity: 1.0 }, 3000).submit() });
```
so when someone changes the quantity of the input field it submits the form, but I want it to wait for a slight amount of time incase they need a moment to type 2 or 3 numbers.
As you can see I tried the animate function to try and delay things but with no luck.
I know I could use this: <http://blog.mythin.net/projects/jquery.php>
I'd rather not add another JS to my site if there is a way around it.
EDIT: Actually the pause plugin above is not working for me either.
|
Give this a shot:
```
$(".rowqty input").bind("keyup", function() { setTimeout("$('#ViewCartPage form').submit()", 500 });
```
|
265,175 |
<p>Any idea anyone? Is it possible that we specify the name of the form input field?
How to go about doing that?</p>
|
[
{
"answer_id": 265191,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>It's generated as formId:fieldId</p>\n\n<p>So, if you had the following:</p>\n\n<pre><code><h:form id=\"searchForm\">\n <h:inputText id=\"searchField\" ... />\n</h:form>\n</code></pre>\n\n<p>The name (and HTML ID) of the search field would be:</p>\n\n<p>searchForm:searchField</p>\n"
},
{
"answer_id": 265210,
"author": "Romain Linsolas",
"author_id": 26457,
"author_profile": "https://Stackoverflow.com/users/26457",
"pm_score": 3,
"selected": false,
"text": "<p>More generally, all JSF components have an ID.\nIf you don't provide one, JSF will create an automatic ID, using the format j<code>_</code>idXXX (<em>XXX</em> is a incremented number).</p>\n\n<p>Some components implement the javax.faces.component.NamingContainer interface, in particular <code><h:form></code>.\nThis means that all children of this component will have their ID prefixed by the ID of this container, separated by a ':'.\nSo, in the example:</p>\n\n<pre><code><h:form id=\"myForm\">\n <h:inputText id=\"myInput\" .../>\n</h:form>\n</code></pre>\n\n<p>the <em>real</em> ID of the input (i.e. the ID of the HTML input object) will be <strong>myForm:myInput</strong>.</p>\n"
},
{
"answer_id": 265561,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 3,
"selected": false,
"text": "<p>As has been stated, the HTML name and id attributes are generated by the naming containers and based on the application namespace. This prevents collisions when controls are children of repeating controls (like a <code>UIData</code>) or a JSP is rendered twice in one page (like in a portlet environment). The id rendered to the HTML is the <strong>clientId</strong>.</p>\n\n<p>It is possible to hardcode or build the <code>clientId</code> manually, but this is a very fragile approach. It is better to use the component's <em>getClientId(FacesContext)</em> method; this is what the renderers use.</p>\n\n<p>A bean that can get the <code>clientId</code> for a bound component:</p>\n\n<pre><code>/** Request scope */\npublic class IdBean implements Serializable {\n private UIComponent mytext;\n\n public String getClientId() {\n return mytext.getClientId(FacesContext.getCurrentInstance());\n }\n\n public UIComponent getMytext() { return mytext; }\n public void setMytext(UIComponent mytext) { this.mytext = mytext; }\n\n public List<String> getRows() {\n List<String> rows = new ArrayList<String>();\n for (int i = 0; i < 10; i++) {\n rows.add(\"row\" + i);\n }\n return rows;\n }\n}\n</code></pre>\n\n<p>The view:</p>\n\n<pre><code> <f:view>\n <h:form>\n <h:dataTable value=\"#{idBean.rows}\" var=\"row\">\n <h:column>\n <h:outputLabel value=\"#{row}\" />\n <h:inputText binding=\"#{idBean.mytext}\"\n onclick=\"foo('#{idBean.clientId}');\" />\n </h:column>\n </h:dataTable>\n </h:form>\n </f:view>\n\n <script type=\"text/javascript\">\n function foo(name) {\n alert('You clicked '+name);\n }\n </script>\n</code></pre>\n\n<p>The <em>mytext</em> control is rendered 10 times, so any code that emits its name must also be a child of the dataTable.</p>\n"
},
{
"answer_id": 266623,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>For most pages which contain a view, form and some components, the clientID will be the colon seperated string contained the form-id and component-id. Example:</p>\n\n<p>\n \n \n \n</p>\n\n<p>The input text client ID would be \"myForm:myInputText\". If you have nested within a subview, then that will be the first thing in the list, for example:</p>\n\n<p>\n \n \n \n</p>\n\n<p>Now the input text client ID would be \"mySubview:myForm:myInputText\". </p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Any idea anyone? Is it possible that we specify the name of the form input field?
How to go about doing that?
|
More generally, all JSF components have an ID.
If you don't provide one, JSF will create an automatic ID, using the format j`_`idXXX (*XXX* is a incremented number).
Some components implement the javax.faces.component.NamingContainer interface, in particular `<h:form>`.
This means that all children of this component will have their ID prefixed by the ID of this container, separated by a ':'.
So, in the example:
```
<h:form id="myForm">
<h:inputText id="myInput" .../>
</h:form>
```
the *real* ID of the input (i.e. the ID of the HTML input object) will be **myForm:myInput**.
|
265,180 |
<p>Is there any security issue if let say in one application we do a hidden post to another application to make use of that application functionality?</p>
|
[
{
"answer_id": 265191,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>It's generated as formId:fieldId</p>\n\n<p>So, if you had the following:</p>\n\n<pre><code><h:form id=\"searchForm\">\n <h:inputText id=\"searchField\" ... />\n</h:form>\n</code></pre>\n\n<p>The name (and HTML ID) of the search field would be:</p>\n\n<p>searchForm:searchField</p>\n"
},
{
"answer_id": 265210,
"author": "Romain Linsolas",
"author_id": 26457,
"author_profile": "https://Stackoverflow.com/users/26457",
"pm_score": 3,
"selected": false,
"text": "<p>More generally, all JSF components have an ID.\nIf you don't provide one, JSF will create an automatic ID, using the format j<code>_</code>idXXX (<em>XXX</em> is a incremented number).</p>\n\n<p>Some components implement the javax.faces.component.NamingContainer interface, in particular <code><h:form></code>.\nThis means that all children of this component will have their ID prefixed by the ID of this container, separated by a ':'.\nSo, in the example:</p>\n\n<pre><code><h:form id=\"myForm\">\n <h:inputText id=\"myInput\" .../>\n</h:form>\n</code></pre>\n\n<p>the <em>real</em> ID of the input (i.e. the ID of the HTML input object) will be <strong>myForm:myInput</strong>.</p>\n"
},
{
"answer_id": 265561,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 3,
"selected": false,
"text": "<p>As has been stated, the HTML name and id attributes are generated by the naming containers and based on the application namespace. This prevents collisions when controls are children of repeating controls (like a <code>UIData</code>) or a JSP is rendered twice in one page (like in a portlet environment). The id rendered to the HTML is the <strong>clientId</strong>.</p>\n\n<p>It is possible to hardcode or build the <code>clientId</code> manually, but this is a very fragile approach. It is better to use the component's <em>getClientId(FacesContext)</em> method; this is what the renderers use.</p>\n\n<p>A bean that can get the <code>clientId</code> for a bound component:</p>\n\n<pre><code>/** Request scope */\npublic class IdBean implements Serializable {\n private UIComponent mytext;\n\n public String getClientId() {\n return mytext.getClientId(FacesContext.getCurrentInstance());\n }\n\n public UIComponent getMytext() { return mytext; }\n public void setMytext(UIComponent mytext) { this.mytext = mytext; }\n\n public List<String> getRows() {\n List<String> rows = new ArrayList<String>();\n for (int i = 0; i < 10; i++) {\n rows.add(\"row\" + i);\n }\n return rows;\n }\n}\n</code></pre>\n\n<p>The view:</p>\n\n<pre><code> <f:view>\n <h:form>\n <h:dataTable value=\"#{idBean.rows}\" var=\"row\">\n <h:column>\n <h:outputLabel value=\"#{row}\" />\n <h:inputText binding=\"#{idBean.mytext}\"\n onclick=\"foo('#{idBean.clientId}');\" />\n </h:column>\n </h:dataTable>\n </h:form>\n </f:view>\n\n <script type=\"text/javascript\">\n function foo(name) {\n alert('You clicked '+name);\n }\n </script>\n</code></pre>\n\n<p>The <em>mytext</em> control is rendered 10 times, so any code that emits its name must also be a child of the dataTable.</p>\n"
},
{
"answer_id": 266623,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>For most pages which contain a view, form and some components, the clientID will be the colon seperated string contained the form-id and component-id. Example:</p>\n\n<p>\n \n \n \n</p>\n\n<p>The input text client ID would be \"myForm:myInputText\". If you have nested within a subview, then that will be the first thing in the list, for example:</p>\n\n<p>\n \n \n \n</p>\n\n<p>Now the input text client ID would be \"mySubview:myForm:myInputText\". </p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Is there any security issue if let say in one application we do a hidden post to another application to make use of that application functionality?
|
More generally, all JSF components have an ID.
If you don't provide one, JSF will create an automatic ID, using the format j`_`idXXX (*XXX* is a incremented number).
Some components implement the javax.faces.component.NamingContainer interface, in particular `<h:form>`.
This means that all children of this component will have their ID prefixed by the ID of this container, separated by a ':'.
So, in the example:
```
<h:form id="myForm">
<h:inputText id="myInput" .../>
</h:form>
```
the *real* ID of the input (i.e. the ID of the HTML input object) will be **myForm:myInput**.
|
265,192 |
<p>I have the following code:</p>
<pre><code>Using cmd As SqlCommand = Connection.CreateCommand
cmd.CommandText = "UPDATE someTable SET Value = @Value"
cmd.CommandText &= " WHERE Id = @Id"
cmd.Parameters.AddWithValue("@Id", 1234)
cmd.Parameters.AddWithValue("@Value", "myValue")
cmd.ExecuteNonQuery
End Using
</code></pre>
<p>I wonder if there is any way to get the final SQL statment as a String, which should look like this:</p>
<pre class="lang-sql prettyprint-override"><code>UPDATE someTable SET Value = "myValue" WHERE Id = 1234
</code></pre>
<p>If anyone wonders why I would do this:</p>
<ul>
<li>for logging (failed) statements</li>
<li>for having the possibility to copy & paste it to the Enterprise Manager for testing purposes</li>
</ul>
|
[
{
"answer_id": 265241,
"author": "Rockcoder",
"author_id": 5290,
"author_profile": "https://Stackoverflow.com/users/5290",
"pm_score": 3,
"selected": false,
"text": "<p>If you're using SQL Server, you could use SQL Server Profiler (if you have it) to view the command string that is actually executed. That would be useful for copy/paste testing purpuses but not for logging I'm afraid.</p>\n"
},
{
"answer_id": 265253,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 6,
"selected": false,
"text": "<p>You can't, because it does not generate any SQL.</p>\n\n<p>The parameterized query (the one in <code>CommandText</code>) is sent to the SQL Server as the equivalent of a prepared statement. When you execute the command, the parameters and the query text are treated separately. At no point in time a complete SQL string is generated.</p>\n\n<p>You can use SQL Profiler to take a look behind the scenes.</p>\n"
},
{
"answer_id": 265259,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 2,
"selected": false,
"text": "<p>Profiler is hands-down your best option. </p>\n\n<p>You might need to copy a set of statements from profiler due to the prepare + execute steps involved.</p>\n"
},
{
"answer_id": 265261,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 7,
"selected": false,
"text": "<p>For logging purposes, I'm afraid there's no nicer way of doing this but to construct the string yourself:</p>\n\n<pre><code>string query = cmd.CommandText;\n\nforeach (SqlParameter p in cmd.Parameters)\n{\n query = query.Replace(p.ParameterName, p.Value.ToString());\n}\n</code></pre>\n"
},
{
"answer_id": 4146573,
"author": "Flapper",
"author_id": 391383,
"author_profile": "https://Stackoverflow.com/users/391383",
"pm_score": 8,
"selected": true,
"text": "<p>Whilst not perfect, here's something I knocked up for TSQL - could be easily tweaked for other flavors... If nothing else it will give you a start point for your own improvements :)</p>\n\n<p>This does an OK job on data types and output parameters etc similar to using \"execute stored procedure\" in SSMS. We mostly used SPs so the \"text\" command doesn't account for parameters etc</p>\n\n<pre><code> public static String ParameterValueForSQL(this SqlParameter sp)\n {\n String retval = \"\";\n\n switch (sp.SqlDbType)\n {\n case SqlDbType.Char:\n case SqlDbType.NChar:\n case SqlDbType.NText:\n case SqlDbType.NVarChar:\n case SqlDbType.Text:\n case SqlDbType.Time:\n case SqlDbType.VarChar:\n case SqlDbType.Xml:\n case SqlDbType.Date:\n case SqlDbType.DateTime:\n case SqlDbType.DateTime2:\n case SqlDbType.DateTimeOffset:\n retval = \"'\" + sp.Value.ToString().Replace(\"'\", \"''\") + \"'\";\n break;\n\n case SqlDbType.Bit:\n retval = (sp.Value.ToBooleanOrDefault(false)) ? \"1\" : \"0\";\n break;\n\n default:\n retval = sp.Value.ToString().Replace(\"'\", \"''\");\n break;\n }\n\n return retval;\n }\n\n public static String CommandAsSql(this SqlCommand sc)\n {\n StringBuilder sql = new StringBuilder();\n Boolean FirstParam = true;\n\n sql.AppendLine(\"use \" + sc.Connection.Database + \";\");\n switch (sc.CommandType)\n {\n case CommandType.StoredProcedure:\n sql.AppendLine(\"declare @return_value int;\");\n\n foreach (SqlParameter sp in sc.Parameters)\n {\n if ((sp.Direction == ParameterDirection.InputOutput) || (sp.Direction == ParameterDirection.Output))\n {\n sql.Append(\"declare \" + sp.ParameterName + \"\\t\" + sp.SqlDbType.ToString() + \"\\t= \");\n\n sql.AppendLine(((sp.Direction == ParameterDirection.Output) ? \"null\" : sp.ParameterValueForSQL()) + \";\");\n\n }\n }\n\n sql.AppendLine(\"exec [\" + sc.CommandText + \"]\");\n\n foreach (SqlParameter sp in sc.Parameters)\n {\n if (sp.Direction != ParameterDirection.ReturnValue)\n {\n sql.Append((FirstParam) ? \"\\t\" : \"\\t, \");\n\n if (FirstParam) FirstParam = false;\n\n if (sp.Direction == ParameterDirection.Input)\n sql.AppendLine(sp.ParameterName + \" = \" + sp.ParameterValueForSQL());\n else\n\n sql.AppendLine(sp.ParameterName + \" = \" + sp.ParameterName + \" output\");\n }\n }\n sql.AppendLine(\";\");\n\n sql.AppendLine(\"select 'Return Value' = convert(varchar, @return_value);\");\n\n foreach (SqlParameter sp in sc.Parameters)\n {\n if ((sp.Direction == ParameterDirection.InputOutput) || (sp.Direction == ParameterDirection.Output))\n {\n sql.AppendLine(\"select '\" + sp.ParameterName + \"' = convert(varchar, \" + sp.ParameterName + \");\");\n }\n }\n break;\n case CommandType.Text:\n sql.AppendLine(sc.CommandText);\n break;\n }\n\n return sql.ToString();\n }\n</code></pre>\n\n<p>this generates output along these lines...</p>\n\n<pre><code>use dbMyDatabase;\ndeclare @return_value int;\ndeclare @OutTotalRows BigInt = null;\nexec [spMyStoredProc]\n @InEmployeeID = 1000686\n , @InPageSize = 20\n , @InPage = 1\n , @OutTotalRows = @OutTotalRows output\n;\nselect 'Return Value' = convert(varchar, @return_value);\nselect '@OutTotalRows' = convert(varchar, @OutTotalRows);\n</code></pre>\n"
},
{
"answer_id": 5563678,
"author": "dummy",
"author_id": 6297,
"author_profile": "https://Stackoverflow.com/users/6297",
"pm_score": 0,
"selected": false,
"text": "<p>This solution works for me right now. Maybe it is usefull to someone. Please excuse all the redundancy. </p>\n\n<pre><code> Public Shared Function SqlString(ByVal cmd As SqlCommand) As String\n Dim sbRetVal As New System.Text.StringBuilder()\n For Each item As SqlParameter In cmd.Parameters\n Select Case item.DbType\n Case DbType.String\n sbRetVal.AppendFormat(\"DECLARE {0} AS VARCHAR(255)\", item.ParameterName)\n sbRetVal.AppendLine()\n sbRetVal.AppendFormat(\"SET {0} = '{1}'\", item.ParameterName, item.Value)\n sbRetVal.AppendLine()\n\n Case DbType.DateTime\n sbRetVal.AppendFormat(\"DECLARE {0} AS DATETIME\", item.ParameterName)\n sbRetVal.AppendLine()\n sbRetVal.AppendFormat(\"SET {0} = '{1}'\", item.ParameterName, item.Value)\n sbRetVal.AppendLine()\n\n Case DbType.Guid\n sbRetVal.AppendFormat(\"DECLARE {0} AS UNIQUEIDENTIFIER\", item.ParameterName)\n sbRetVal.AppendLine()\n sbRetVal.AppendFormat(\"SET {0} = '{1}'\", item.ParameterName, item.Value)\n sbRetVal.AppendLine()\n\n Case DbType.Int32\n sbRetVal.AppendFormat(\"DECLARE {0} AS int\", item.ParameterName)\n sbRetVal.AppendLine()\n sbRetVal.AppendFormat(\"SET {0} = {1}\", item.ParameterName, item.Value)\n sbRetVal.AppendLine()\n\n Case Else\n Stop\n\n End Select\n Next\n\n sbRetVal.AppendLine(\"\")\n sbRetVal.AppendLine(cmd.CommandText)\n\n Return sbRetVal.ToString()\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 17777169,
"author": "Mitch",
"author_id": 138200,
"author_profile": "https://Stackoverflow.com/users/138200",
"pm_score": 5,
"selected": false,
"text": "<p>I needed a similar command to string transformer to allow for more verbose logging, so I wrote this one. It will produce the text needed to re-execute the command in a new session including output parameters and structured parameters. It is lightly tested, but caveat emptor.</p>\n<p>Example:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>SqlCommand cmd = new SqlCommand("GetEntity", con);\ncmd.Parameters.AddWithValue("@foobar", 1);\ncmd.Parameters.Add(new SqlParameter(){\n ParameterName = "@outParam",\n Direction = ParameterDirection.Output,\n SqlDbType = System.Data.SqlDbType.Int\n});\ncmd.Parameters.Add(new SqlParameter(){\n Direction = ParameterDirection.ReturnValue\n});\ncmd.CommandType = CommandType.StoredProcedure;\n</code></pre>\n<p>Will produce:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>-- BEGIN COMMAND\nDECLARE @foobar INT = 1;\nDECLARE @outParam INT = NULL;\nDECLARE @returnValue INT;\n-- END PARAMS\nEXEC @returnValue = GetEntity @foobar = @foobar, @outParam = @outParam OUTPUT\n-- RESULTS\nSELECT 1 as Executed, @returnValue as ReturnValue, @outParam as [@outParam];\n-- END COMMAND\n</code></pre>\n<p>Implementation:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class SqlCommandDumper\n{\n public static string GetCommandText(SqlCommand sqc)\n {\n StringBuilder sbCommandText = new StringBuilder();\n\n sbCommandText.AppendLine("-- BEGIN COMMAND");\n\n // params\n for (int i = 0; i < sqc.Parameters.Count; i++)\n logParameterToSqlBatch(sqc.Parameters[i], sbCommandText);\n sbCommandText.AppendLine("-- END PARAMS");\n\n // command\n if (sqc.CommandType == CommandType.StoredProcedure)\n {\n sbCommandText.Append("EXEC ");\n\n bool hasReturnValue = false;\n for (int i = 0; i < sqc.Parameters.Count; i++)\n {\n if (sqc.Parameters[i].Direction == ParameterDirection.ReturnValue)\n hasReturnValue = true;\n }\n if (hasReturnValue)\n {\n sbCommandText.Append("@returnValue = ");\n }\n\n sbCommandText.Append(sqc.CommandText);\n\n bool hasPrev = false;\n for (int i = 0; i < sqc.Parameters.Count; i++)\n {\n var cParam = sqc.Parameters[i];\n if (cParam.Direction != ParameterDirection.ReturnValue)\n {\n if (hasPrev)\n sbCommandText.Append(",");\n sbCommandText.Append(" ");\n\n sbCommandText.Append(cParam.ParameterName);\n sbCommandText.Append(" = ");\n sbCommandText.Append(cParam.ParameterName);\n\n if (cParam.Direction.HasFlag(ParameterDirection.Output))\n sbCommandText.Append(" OUTPUT");\n\n hasPrev = true;\n }\n }\n }\n else\n {\n sbCommandText.AppendLine(sqc.CommandText);\n }\n\n sbCommandText.AppendLine("-- RESULTS");\n sbCommandText.Append("SELECT 1 as Executed");\n for (int i = 0; i < sqc.Parameters.Count; i++)\n {\n var cParam = sqc.Parameters[i];\n\n if (cParam.Direction == ParameterDirection.ReturnValue)\n {\n sbCommandText.Append(", @returnValue as ReturnValue");\n }\n else if (cParam.Direction.HasFlag(ParameterDirection.Output))\n {\n sbCommandText.Append(", ");\n sbCommandText.Append(cParam.ParameterName);\n sbCommandText.Append(" as [");\n sbCommandText.Append(cParam.ParameterName);\n sbCommandText.Append(']');\n }\n }\n sbCommandText.AppendLine(";");\n\n sbCommandText.AppendLine("-- END COMMAND");\n return sbCommandText.ToString();\n }\n\n private static void logParameterToSqlBatch(SqlParameter param, StringBuilder sbCommandText)\n {\n sbCommandText.Append("DECLARE ");\n if (param.Direction == ParameterDirection.ReturnValue)\n {\n sbCommandText.AppendLine("@returnValue INT;");\n }\n else\n {\n sbCommandText.Append(param.ParameterName);\n\n sbCommandText.Append(' ');\n if (param.SqlDbType != SqlDbType.Structured)\n {\n logParameterType(param, sbCommandText);\n sbCommandText.Append(" = ");\n logQuotedParameterValue(param.Value, sbCommandText);\n\n sbCommandText.AppendLine(";");\n }\n else\n {\n logStructuredParameter(param, sbCommandText);\n }\n }\n }\n\n private static void logStructuredParameter(SqlParameter param, StringBuilder sbCommandText)\n {\n sbCommandText.AppendLine(" {List Type};");\n var dataTable = (DataTable)param.Value;\n\n for (int rowNo = 0; rowNo < dataTable.Rows.Count; rowNo++)\n {\n sbCommandText.Append("INSERT INTO ");\n sbCommandText.Append(param.ParameterName);\n sbCommandText.Append(" VALUES (");\n\n bool hasPrev = false;\n for (int colNo = 0; colNo < dataTable.Columns.Count; colNo++)\n {\n if (hasPrev)\n {\n sbCommandText.Append(", ");\n }\n logQuotedParameterValue(dataTable.Rows[rowNo].ItemArray[colNo], sbCommandText);\n hasPrev = true;\n }\n sbCommandText.AppendLine(");");\n }\n }\n\n const string DATETIME_FORMAT_ROUNDTRIP = "o";\n private static void logQuotedParameterValue(object value, StringBuilder sbCommandText)\n {\n try\n {\n if (value == null)\n {\n sbCommandText.Append("NULL");\n }\n else\n {\n value = unboxNullable(value);\n\n if (value is string\n || value is char\n || value is char[]\n || value is System.Xml.Linq.XElement\n || value is System.Xml.Linq.XDocument)\n {\n sbCommandText.Append("N'");\n sbCommandText.Append(value.ToString().Replace("'", "''"));\n sbCommandText.Append('\\'');\n }\n else if (value is bool)\n {\n // True -> 1, False -> 0\n sbCommandText.Append(Convert.ToInt32(value));\n }\n else if (value is sbyte\n || value is byte\n || value is short\n || value is ushort\n || value is int\n || value is uint\n || value is long\n || value is ulong\n || value is float\n || value is double\n || value is decimal)\n {\n sbCommandText.Append(value.ToString());\n }\n else if (value is DateTime)\n {\n // SQL Server only supports ISO8601 with 3 digit precision on datetime,\n // datetime2 (>= SQL Server 2008) parses the .net format, and will \n // implicitly cast down to datetime.\n // Alternatively, use the format string "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK"\n // to match SQL server parsing\n sbCommandText.Append("CAST('");\n sbCommandText.Append(((DateTime)value).ToString(DATETIME_FORMAT_ROUNDTRIP));\n sbCommandText.Append("' as datetime2)");\n }\n else if (value is DateTimeOffset)\n {\n sbCommandText.Append('\\'');\n sbCommandText.Append(((DateTimeOffset)value).ToString(DATETIME_FORMAT_ROUNDTRIP));\n sbCommandText.Append('\\'');\n }\n else if (value is Guid)\n {\n sbCommandText.Append('\\'');\n sbCommandText.Append(((Guid)value).ToString());\n sbCommandText.Append('\\'');\n }\n else if (value is byte[])\n {\n var data = (byte[])value;\n if (data.Length == 0)\n {\n sbCommandText.Append("NULL");\n }\n else\n {\n sbCommandText.Append("0x");\n for (int i = 0; i < data.Length; i++)\n {\n sbCommandText.Append(data[i].ToString("x"));\n }\n }\n }\n else\n {\n sbCommandText.Append("/* UNKNOWN DATATYPE: ");\n sbCommandText.Append(value.GetType().ToString());\n sbCommandText.Append(" *" + "/ N'");\n sbCommandText.Append(value.ToString());\n sbCommandText.Append('\\'');\n }\n }\n }\n\n catch (Exception ex)\n {\n sbCommandText.AppendLine("/* Exception occurred while converting parameter: ");\n sbCommandText.AppendLine(ex.ToString());\n sbCommandText.AppendLine("*/");\n }\n }\n\n private static object unboxNullable(object value)\n {\n var typeOriginal = value.GetType();\n if (typeOriginal.IsGenericType\n && typeOriginal.GetGenericTypeDefinition() == typeof(Nullable<>))\n {\n // generic value, unboxing needed\n return typeOriginal.InvokeMember("GetValueOrDefault",\n System.Reflection.BindingFlags.Public |\n System.Reflection.BindingFlags.Instance |\n System.Reflection.BindingFlags.InvokeMethod,\n null, value, null);\n }\n else\n {\n return value;\n }\n }\n\n private static void logParameterType(SqlParameter param, StringBuilder sbCommandText)\n {\n switch (param.SqlDbType)\n {\n // variable length\n case SqlDbType.Char:\n case SqlDbType.NChar:\n case SqlDbType.Binary:\n {\n sbCommandText.Append(param.SqlDbType.ToString().ToUpper());\n sbCommandText.Append('(');\n sbCommandText.Append(param.Size);\n sbCommandText.Append(')');\n }\n break;\n case SqlDbType.VarBinary:\n case SqlDbType.Image:\n {\n sbCommandText.Append("VARBINARY");\n sbCommandText.Append("(MAX /* Specified as ");\n sbCommandText.Append(param.Size);\n sbCommandText.Append(" */)");\n }\n break;\n case SqlDbType.VarChar:\n case SqlDbType.Text:\n {\n sbCommandText.Append("VARCHAR");\n sbCommandText.Append("(MAX /* Specified as ");\n sbCommandText.Append(param.Size);\n sbCommandText.Append(" */)");\n }\n break;\n case SqlDbType.NVarChar:\n case SqlDbType.NText:\n {\n sbCommandText.Append("NVARCHAR");\n sbCommandText.Append("(MAX /* Specified as ");\n sbCommandText.Append(param.Size);\n sbCommandText.Append(" */)");\n }\n break;\n // fixed length\n case SqlDbType.Bit:\n case SqlDbType.TinyInt:\n case SqlDbType.SmallInt:\n case SqlDbType.Int:\n case SqlDbType.BigInt:\n case SqlDbType.SmallMoney:\n case SqlDbType.Money:\n case SqlDbType.Decimal:\n case SqlDbType.Real:\n case SqlDbType.Float:\n case SqlDbType.Date:\n case SqlDbType.DateTime:\n case SqlDbType.DateTime2:\n case SqlDbType.DateTimeOffset:\n case SqlDbType.UniqueIdentifier:\n {\n sbCommandText.Append(param.SqlDbType.ToString().ToUpper());\n }\n break;\n // Unknown\n case SqlDbType.Timestamp:\n default:\n {\n sbCommandText.Append("/* UNKNOWN DATATYPE: ");\n sbCommandText.Append(param.SqlDbType.ToString().ToUpper());\n sbCommandText.Append(" *" + "/ ");\n sbCommandText.Append(param.SqlDbType.ToString().ToUpper());\n }\n break;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 21166471,
"author": "MPelletier",
"author_id": 210916,
"author_profile": "https://Stackoverflow.com/users/210916",
"pm_score": 1,
"selected": false,
"text": "<p>If it's only to check how a parameter is formatted in the result query, most DBMS's will allow querying literals from nothing. Thus:</p>\n\n<pre><code>Using cmd As SqlCommand = Connection.CreateCommand\n cmd.CommandText = \"SELECT @Value\"\n cmd.Parameters.AddWithValue(\"@Value\", \"myValue\")\n Return cmd.ExecuteScalar\nEnd Using\n</code></pre>\n\n<p>That way you can see if quotes are doubled, etc.</p>\n"
},
{
"answer_id": 21938880,
"author": "alan",
"author_id": 255858,
"author_profile": "https://Stackoverflow.com/users/255858",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same exact question and after reading these responses mistakenly decided it wasn't possible to get the exact resulting query. I was wrong. </p>\n\n<p><strong>Solution:</strong>\nOpen <code>Activity Monitor</code> in <code>SQL Server Management Studio</code>, narrow the processes section to the login username, database or application name that your application is using in the connection string. When the call is made to the db refresh <code>Activity Monitor</code>. When you see the process, right click on it and <code>View Details</code>.</p>\n\n<p>Note, this may not be a viable option for a busy db. But you should be able to narrow the result considerably using these steps.</p>\n"
},
{
"answer_id": 26043894,
"author": "Shawn J. Molloy",
"author_id": 589509,
"author_profile": "https://Stackoverflow.com/users/589509",
"pm_score": 1,
"selected": false,
"text": "<p>This is what I use to output parameter lists for a stored procedure into the debug console:</p>\n\n<pre><code>string query = (from SqlParameter p in sqlCmd.Parameters where p != null where p.Value != null select string.Format(\"Param: {0} = {1}, \", p.ParameterName, p.Value.ToString())).Aggregate(sqlCmd.CommandText, (current, parameter) => current + parameter);\nDebug.WriteLine(query);\n</code></pre>\n\n<p>This will generate a console outputt simlar to this:</p>\n\n<pre><code>Customer.prGetCustomerDetails: @Offset = 1, Param: @Fetch = 10, Param: @CategoryLevel1ID = 3, Param: @VehicleLineID = 9, Param: @SalesCode1 = bce, \n</code></pre>\n\n<p>I place this code directly below any procedure I wish to debug and is similar to a sql profiler session but in C#. </p>\n"
},
{
"answer_id": 29086720,
"author": "HouseCat",
"author_id": 3072640,
"author_profile": "https://Stackoverflow.com/users/3072640",
"pm_score": 1,
"selected": false,
"text": "<p>Modified version of <a href=\"https://stackoverflow.com/a/265261\">Kon's answer</a> as it only partially works with similar named parameters. The down side of using String Replace function. Other than that, I give him full credit on the solution.</p>\n\n<pre><code>private string GetActualQuery(SqlCommand sqlcmd)\n{\n string query = sqlcmd.CommandText;\n string parameters = \"\";\n string[] strArray = System.Text.RegularExpressions.Regex.Split(query, \" VALUES \");\n\n //Reconstructs the second half of the SQL Command\n parameters = \"(\";\n\n int count = 0;\n foreach (SqlParameter p in sqlcmd.Parameters)\n {\n if (count == (sqlcmd.Parameters.Count - 1))\n {\n parameters += p.Value.ToString();\n }\n else\n {\n parameters += p.Value.ToString() + \", \";\n }\n count++;\n }\n\n parameters += \")\";\n\n //Returns the string recombined.\n return strArray[0] + \" VALUES \" + parameters;\n}\n</code></pre>\n"
},
{
"answer_id": 30630876,
"author": "Barry-Dean",
"author_id": 4971445,
"author_profile": "https://Stackoverflow.com/users/4971445",
"pm_score": 2,
"selected": false,
"text": "<p>Used part of <a href=\"https://stackoverflow.com/a/4146573/\">Flapper's code</a> for my solution, which returns the entire SQL string including parameter values to run in MS SQL SMS.</p>\n\n<pre><code>public string ParameterValueForSQL(SqlParameter sp)\n {\n string retval = \"\";\n\n switch (sp.SqlDbType)\n {\n case SqlDbType.Char:\n case SqlDbType.NChar:\n case SqlDbType.NText:\n case SqlDbType.NVarChar:\n case SqlDbType.Text:\n case SqlDbType.Time:\n case SqlDbType.VarChar:\n case SqlDbType.Xml:\n case SqlDbType.Date:\n case SqlDbType.DateTime:\n case SqlDbType.DateTime2:\n case SqlDbType.DateTimeOffset:\n if (sp.Value == DBNull.Value)\n {\n retval = \"NULL\";\n }\n else\n {\n retval = \"'\" + sp.Value.ToString().Replace(\"'\", \"''\") + \"'\";\n }\n break;\n\n case SqlDbType.Bit:\n if (sp.Value == DBNull.Value)\n {\n retval = \"NULL\";\n }\n else\n {\n retval = ((bool)sp.Value == false) ? \"0\" : \"1\";\n }\n break;\n\n default:\n if (sp.Value == DBNull.Value)\n {\n retval = \"NULL\";\n }\n else\n {\n retval = sp.Value.ToString().Replace(\"'\", \"''\");\n }\n break;\n }\n\n return retval;\n }\n\n\n public string CommandAsSql(SqlCommand sc)\n {\n string sql = sc.CommandText;\n\n sql = sql.Replace(\"\\r\\n\", \"\").Replace(\"\\r\", \"\").Replace(\"\\n\", \"\");\n sql = System.Text.RegularExpressions.Regex.Replace(sql, @\"\\s+\", \" \");\n\n foreach (SqlParameter sp in sc.Parameters)\n {\n string spName = sp.ParameterName;\n string spValue = ParameterValueForSQL(sp);\n sql = sql.Replace(spName, spValue);\n }\n\n sql = sql.Replace(\"= NULL\", \"IS NULL\");\n sql = sql.Replace(\"!= NULL\", \"IS NOT NULL\");\n return sql;\n }\n</code></pre>\n"
},
{
"answer_id": 31431181,
"author": "JotaSantana",
"author_id": 3338558,
"author_profile": "https://Stackoverflow.com/users/3338558",
"pm_score": 0,
"selected": false,
"text": "<p>As @pkExec and @Alok mentioned, use Replace does not work in 100% of cases.\nThis is the solution I've used in our DAL that uses RegExp to \"match whole word\" only and format the datatypes correctly. Thus the SQL generated can be tested directly in MySQL Workbench (or SQLSMS, etc ...) :)</p>\n\n<p>(Replace the MySQLHelper.EscapeString() function according to the DBMS used.)</p>\n\n<pre><code>Dim query As String = cmd.CommandText\nquery = query.Replace(\"SET\", \"SET\" & vbNewLine)\nquery = query.Replace(\"WHERE\", vbNewLine & \"WHERE\")\nquery = query.Replace(\"GROUP BY\", vbNewLine & \"GROUP BY\")\nquery = query.Replace(\"ORDER BY\", vbNewLine & \"ORDER BY\")\nquery = query.Replace(\"INNER JOIN\", vbNewLine & \"INNER JOIN\")\nquery = query.Replace(\"LEFT JOIN\", vbNewLine & \"LEFT JOIN\")\nquery = query.Replace(\"RIGHT JOIN\", vbNewLine & \"RIGHT JOIN\")\nIf query.Contains(\"UNION ALL\") Then\n query = query.Replace(\"UNION ALL\", vbNewLine & \"UNION ALL\" & vbNewLine)\nElseIf query.Contains(\"UNION DISTINCT\") Then\n query = query.Replace(\"UNION DISTINCT\", vbNewLine & \"UNION DISTINCT\" & vbNewLine)\nElse\n query = query.Replace(\"UNION\", vbNewLine & \"UNION\" & vbNewLine)\nEnd If\n\nFor Each par In cmd.Parameters\n If par.Value Is Nothing OrElse IsDBNull(par.Value) Then\n query = RegularExpressions.Regex.Replace(query, par.ParameterName & \"\\b\", \"NULL\")\n ElseIf TypeOf par.Value Is Date Then\n query = RegularExpressions.Regex.Replace(query, par.ParameterName & \"\\b\", \"'\" & Format(par.Value, \"yyyy-MM-dd HH:mm:ss\") & \"'\")\n ElseIf TypeOf par.Value Is TimeSpan Then\n query = RegularExpressions.Regex.Replace(query, par.ParameterName & \"\\b\", \"'\" & par.Value.ToString & \"'\")\n ElseIf TypeOf par.Value Is Double Or TypeOf par.Value Is Decimal Or TypeOf par.Value Is Single Then\n query = RegularExpressions.Regex.Replace(query, par.ParameterName & \"\\b\", Replace(par.Value.ToString, \",\", \".\"))\n ElseIf TypeOf par.Value Is Integer Or TypeOf par.Value Is UInteger Or TypeOf par.Value Is Long Or TypeOf par.Value Is ULong Then\n query = RegularExpressions.Regex.Replace(query, par.ParameterName & \"\\b\", par.Value.ToString)\n Else\n query = RegularExpressions.Regex.Replace(query, par.ParameterName & \"\\b\", \"'\" & MySqlHelper.EscapeString(CStr(par.Value)) & \"'\")\n End If\nNext\n</code></pre>\n\n<p>Example: </p>\n\n<pre><code>SELECT * FROM order WHERE order_status = @order_status AND order_date = @order_date\n</code></pre>\n\n<p>Will be generated:</p>\n\n<pre><code>SELECT * FROM order WHERE order_status = 'C' AND order_date = '2015-01-01 00:00:00'\n</code></pre>\n"
},
{
"answer_id": 32351885,
"author": "Jeroen Pot",
"author_id": 878609,
"author_profile": "https://Stackoverflow.com/users/878609",
"pm_score": 3,
"selected": false,
"text": "<p>I also had this issue where some parameterized queries or sp's would give me a SqlException (mostly the string or binary data would be truncated), and the statements where hard to debug (As far as i know there currently is no sql-profiler support for SQL Azure)</p>\n\n<p>I see a lot of simular code in reactions here. I ended up putting my solution in a Sql-Library project for future use. </p>\n\n<p>The generator is available here:\n<a href=\"https://github.com/jeroenpot/SqlHelper/blob/master/Source/Mirabeau.MsSql.Library/SqlGenerator.cs\" rel=\"noreferrer\">https://github.com/jeroenpot/SqlHelper/blob/master/Source/Mirabeau.MsSql.Library/SqlGenerator.cs</a></p>\n\n<p>It supports both CommandType.Text and CommandType.StoredProcedure</p>\n\n<p>And if you install the <a href=\"https://www.nuget.org/packages/MsSqlHelper\" rel=\"noreferrer\">nuget-package</a> you can generate it with this statement:</p>\n\n<pre><code>SqlDebugHelper.CreateExecutableSqlStatement(sql, parameters);\n</code></pre>\n"
},
{
"answer_id": 37842825,
"author": "Martin.Martinsson",
"author_id": 434209,
"author_profile": "https://Stackoverflow.com/users/434209",
"pm_score": 2,
"selected": false,
"text": "<p>My Solution:</p>\n\n<pre><code>public static class DbHelper\n{\n public static string ToString(this DbParameterCollection parameters, string sqlQuery)\n {\n return parameters.Cast<DbParameter>().Aggregate(sqlQuery, (current, p) => current.Replace(p.ParameterName, p.Value.ToString()));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 40993397,
"author": "o_link",
"author_id": 7256266,
"author_profile": "https://Stackoverflow.com/users/7256266",
"pm_score": 0,
"selected": false,
"text": "<p>the sql command queries will be executed with exec sp_executesql, so here's another way to get the statement as a string (SqlCommand extension method):</p>\n\n<pre><code>public static string ToSqlStatement(this SqlCommand cmd)\n{\n return $@\"EXECUTE sp_executesql N'{cmd.CommandText.Replace(\"'\", \"''\")}'{cmd.Parameters.ToSqlParameters()}\";\n}\n\nprivate static string ToSqlParameters(this SqlParameterCollection col)\n{\n if (col.Count == 0)\n return string.Empty;\n var parameters = new List<string>();\n var parameterValues = new List<string>();\n foreach (SqlParameter param in col)\n {\n parameters.Add($\"{param.ParameterName}{param.ToSqlParameterType()}\");\n parameterValues.Add($\"{param.ParameterName} = {param.ToSqlParameterValue()}\");\n }\n return $\",N\\'{string.Join(\",\", parameters)}\\',{string.Join(\",\", parameterValues)}\";\n}\n\nprivate static object ToSqlParameterType(this SqlParameter param)\n{\n var paramDbType = param.SqlDbType.ToString().ToLower();\n if (param.Precision != 0 && param.Scale != 0)\n return $\"{paramDbType}({param.Precision},{param.Scale})\";\n if (param.Precision != 0)\n return $\"{paramDbType}({param.Precision})\";\n switch (param.SqlDbType)\n {\n case SqlDbType.VarChar:\n case SqlDbType.NVarChar:\n string s = param.SqlValue?.ToString() ?? string.Empty;\n return paramDbType + (s.Length > 0 ? $\"({s.Length})\" : string.Empty);\n default:\n return paramDbType;\n }\n}\n\nprivate static string ToSqlParameterValue(this SqlParameter param)\n{\n switch (param.SqlDbType)\n {\n case SqlDbType.Char:\n case SqlDbType.Date:\n case SqlDbType.DateTime:\n case SqlDbType.DateTime2:\n case SqlDbType.DateTimeOffset:\n case SqlDbType.NChar:\n case SqlDbType.NText:\n case SqlDbType.NVarChar:\n case SqlDbType.Text:\n case SqlDbType.Time:\n case SqlDbType.VarChar:\n case SqlDbType.Xml:\n return $\"\\'{param.SqlValue.ToString().Replace(\"'\", \"''\")}\\'\";\n case SqlDbType.Bit:\n return param.SqlValue.ToBooleanOrDefault() ? \"1\" : \"0\";\n default:\n return param.SqlValue.ToString().Replace(\"'\", \"''\");\n }\n}\n\npublic static bool ToBooleanOrDefault(this object o, bool defaultValue = false)\n{\n if (o == null)\n return defaultValue;\n string value = o.ToString().ToLower();\n switch (value)\n {\n case \"yes\":\n case \"true\":\n case \"ok\":\n case \"y\":\n return true;\n case \"no\":\n case \"false\":\n case \"n\":\n return false;\n default:\n bool b;\n if (bool.TryParse(o.ToString(), out b))\n return b;\n break;\n }\n return defaultValue;\n}\n</code></pre>\n"
},
{
"answer_id": 42398495,
"author": "CheesusCrust",
"author_id": 3277777,
"author_profile": "https://Stackoverflow.com/users/3277777",
"pm_score": -1,
"selected": false,
"text": "<p>One liner:</p>\n\n<pre><code>string.Join(\",\", from SqlParameter p in cmd.Parameters select p.ToString()) \n</code></pre>\n"
},
{
"answer_id": 45378224,
"author": "Daghan Karakasoglu",
"author_id": 2140434,
"author_profile": "https://Stackoverflow.com/users/2140434",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote this method for me. I use some part of <a href=\"https://forums.asp.net/t/1351973.aspx?How+to+view+a+cmd+CommandText+with+parameters+value+in+debugger\" rel=\"nofollow noreferrer\">Bruno Ratnieks's</a> code. Maybe it is useful to someone.</p>\n\n<pre><code> public static string getQueryFromCommand(SqlCommand cmd)\n {\n StringBuilder CommandTxt = new StringBuilder();\n CommandTxt.Append(\"DECLARE \");\n List<string> paramlst = new List<string>();\n foreach (SqlParameter parms in cmd.Parameters)\n {\n paramlst.Add(parms.ParameterName);\n CommandTxt.Append(parms.ParameterName + \" AS \");\n CommandTxt.Append(parms.SqlDbType.ToString());\n CommandTxt.Append(\",\");\n }\n\n if (CommandTxt.ToString().Substring(CommandTxt.Length-1, 1) == \",\")\n CommandTxt.Remove(CommandTxt.Length-1, 1);\n CommandTxt.AppendLine();\n int rownr = 0;\n foreach (SqlParameter parms in cmd.Parameters)\n {\n string val = String.Empty;\n if (parms.DbType.Equals(DbType.String) || parms.DbType.Equals(DbType.DateTime))\n val = \"'\" + Convert.ToString(parms.Value).Replace(@\"\\\", @\"\\\\\").Replace(\"'\", @\"\\'\") + \"'\";\n if (parms.DbType.Equals(DbType.Int16) || parms.DbType.Equals(DbType.Int32) || parms.DbType.Equals(DbType.Int64) || parms.DbType.Equals(DbType.Decimal) || parms.DbType.Equals(DbType.Double))\n val = Convert.ToString(parms.Value);\n\n CommandTxt.AppendLine();\n CommandTxt.Append(\"SET \" + paramlst[rownr].ToString() + \" = \" + val.ToString());\n rownr += 1;\n }\n CommandTxt.AppendLine();\n CommandTxt.AppendLine();\n CommandTxt.Append(cmd.CommandText);\n return CommandTxt.ToString();\n }\n</code></pre>\n"
},
{
"answer_id": 52409927,
"author": "George Birbilis",
"author_id": 903783,
"author_profile": "https://Stackoverflow.com/users/903783",
"pm_score": 0,
"selected": false,
"text": "<p>needed to cover non-Stored procedures too so I augmented CommandAsSql library (see comments under @Flapper's answer above) with this logic:</p>\n\n<pre><code> private static void CommandAsSql_Text(this SqlCommand command, System.Text.StringBuilder sql)\n {\n string query = command.CommandText;\n\n foreach (SqlParameter p in command.Parameters)\n query = Regex.Replace(query, \"\\\\B\" + p.ParameterName + \"\\\\b\", p.ParameterValueForSQL()); //the first one is \\B, the 2nd one is \\b, since ParameterName starts with @ which is a non-word character in RegEx (see https://stackoverflow.com/a/2544661)\n\n sql.AppendLine(query);\n }\n</code></pre>\n\n<p>the pull request is at:\n<a href=\"https://github.com/jphellemons/CommandAsSql/pull/3/commits/527d696dc6055c5bcf858b9700b83dc863f04896\" rel=\"nofollow noreferrer\">https://github.com/jphellemons/CommandAsSql/pull/3/commits/527d696dc6055c5bcf858b9700b83dc863f04896</a></p>\n\n<p>the Regex idea was based on @stambikk's and EvZ's comments above and the \"Update:\" section of <a href=\"https://stackoverflow.com/a/2544661/903783\">https://stackoverflow.com/a/2544661/903783</a> that mentions \"negative look-behind assertion\". The use of \\B instead of \\b for word boundary detection at the start of the regular expression is because the p.parameterName will always start with a \"@\" which is not a word character.</p>\n\n<p>note that ParameterValueForSQL() is an extension method defined at the CommandAsSql library to handle issues like single-quoting string parameter values etc.</p>\n"
},
{
"answer_id": 56265036,
"author": "Paul Sturm",
"author_id": 879170,
"author_profile": "https://Stackoverflow.com/users/879170",
"pm_score": 3,
"selected": false,
"text": "<p>Late answer, I know but I too wanted this so I could log the SQL. The following is short and meets my needs.</p>\n\n<p>The following produces SQL you can copy/paste in SSMS (it replaces the parameters with the values properly). You can add more types but this meets all I use in this case.</p>\n\n<pre><code> private static void LogSQL(SqlCommand cmd)\n {\n string query = cmd.CommandText;\n\n foreach (SqlParameter prm in cmd.Parameters)\n {\n switch (prm.SqlDbType)\n {\n case SqlDbType.Bit:\n int boolToInt = (bool)prm.Value ? 1 : 0;\n query = query.Replace(prm.ParameterName, string.Format(\"{0}\", (bool)prm.Value ? 1 : 0));\n break;\n case SqlDbType.Int:\n query = query.Replace(prm.ParameterName, string.Format(\"{0}\", prm.Value));\n break;\n case SqlDbType.VarChar:\n query = query.Replace(prm.ParameterName, string.Format(\"'{0}'\", prm.Value));\n break;\n default:\n query = query.Replace(prm.ParameterName, string.Format(\"'{0}'\", prm.Value));\n break;\n }\n }\n\n // the following is my how I write to my log - your use will vary\n logger.Debug(\"{0}\", query);\n\n return;\n }\n</code></pre>\n\n<p>Now I can log the SQL just before I execute it:</p>\n\n<pre><code>LogSQL(queryCmd)\nqueryCmd.ExecuteNonQuery()\n</code></pre>\n"
},
{
"answer_id": 57780016,
"author": "user11982798",
"author_id": 11982798,
"author_profile": "https://Stackoverflow.com/users/11982798",
"pm_score": -1,
"selected": false,
"text": "<p>From parameter command to non parameter command, You Can change this one</p>\n\n<pre><code>Using cmd As SqlCommand = Connection.CreateCommand\n cmd.CommandText = \"UPDATE someTable SET Value = @Value\"\n cmd.CommandText &= \" WHERE Id = @Id\"\n cmd.Parameters.AddWithValue(\"@Id\", 1234)\n cmd.Parameters.AddWithValue(\"@Value\", \"myValue\")\n cmd.ExecuteNonQuery\nEnd Using\n</code></pre>\n\n<p>To</p>\n\n<pre><code>Private sub Update( byval myID as Int32, byval myVal as String)\n Using cmd As SqlCommand = Connection.CreateCommand\n cmd.CommandText = \"UPDATE someTable SET Value = '\" & myVaL & \"'\" & _\n \" WHERE Id = \" & myID \n cmd.ExecuteNonQuery\n End Using\nEnd sub\n</code></pre>\n"
},
{
"answer_id": 57780188,
"author": "user11982798",
"author_id": 11982798,
"author_profile": "https://Stackoverflow.com/users/11982798",
"pm_score": 0,
"selected": false,
"text": "<p>If you will convert the commandtext:</p>\n\n<pre><code>Private Function ConvToNonParm(ByRef Cmd As SqlClient.SqlCommand) As String\n For myCnt As Int16 = 1 To Cmd.Parameters.Count\n Dim myVal As String = Cmd.Parameters(myCnt - 1).Value\n Select Case Cmd.Parameters(myCnt - 1).SqlDbType\n Case SqlDbType.Char, SqlDbType.NChar, SqlDbType.VarChar, SqlDbType.NChar, SqlDbType.NVarChar 'and so on\n myVal = \"'\" & myVal & \"'\"\n 'Case \"others....\"\n\n Case Else\n 'please assing\n End Select\n Cmd.CommandText = Replace(Cmd.CommandText, Cmd.Parameters(myCnt - 1).ToString, myVal)\n Next\n Cmd.Parameters.Clear()\n Return Cmd.CommandText\nEnd Function\n</code></pre>\n\n<p>Now you can get the non parameter commandtext as follows:</p>\n\n<pre><code> myCmd.CommandText = \"UPDATE someTable SET Value = @Value\"\n myCmd.CommandText &= \" WHERE Id = @Id\"\n myCmd.Parameters.AddWithValue(\"@Id\", 1234)\n myCmd.Parameters.AddWithValue(\"@Value\", \"myValue\")\n\n myCmd.CommandText = ConvToNonParm(myCmd)\n</code></pre>\n\n<p>and the Result is \"UPDATE someTable SET Value = 'myValue' WHERE Id = 1234\" without parameter anymore</p>\n"
},
{
"answer_id": 58191712,
"author": "CAK2",
"author_id": 773906,
"author_profile": "https://Stackoverflow.com/users/773906",
"pm_score": 0,
"selected": false,
"text": "<p>Extended <a href=\"https://stackoverflow.com/a/265261/773906\">Kon's code</a> to help debug a stored procedure:</p>\n\n<pre><code> private void ExtractSqlCommandForDebugging(SqlCommand cmd)\n {\n string sql = \"exec \" + cmd.CommandText;\n bool first = true;\n foreach (SqlParameter p in cmd.Parameters)\n {\n string value = ((p.Value == DBNull.Value) ? \"null\"\n : (p.Value is string) ? \"'\" + p.Value + \"'\"\n : p.Value.ToString());\n if (first)\n {\n sql += string.Format(\" {0}={1}\", p.ParameterName, value);\n first = false;\n }\n else\n {\n sql += string.Format(\"\\n , {0}={1}\", p.ParameterName, value);\n }\n }\n sql += \"\\nGO\";\n Debug.WriteLine(sql);\n }\n</code></pre>\n\n<p>In my first test case, it generated:</p>\n\n<pre><code>exec dbo.MyStoredProcName @SnailMail=False\n , @Email=True\n , @AcceptSnailMail=False\n , @AcceptEmail=False\n , @DistanceMiles=-1\n , @DistanceLocationList=''\n , @ExcludeDissatisfied=True\n , @ExcludeCodeRed=True\n , @MinAge=null\n , @MaxAge=18\n , @GenderTypeID=-1\n , @NewThisYear=-1\n , @RegisteredThisYear=-1\n , @FormersTermGroupList=''\n , @RegistrationStartDate=null\n , @RegistrationEndDate=null\n , @DivisionList='25'\n , @LocationList='29,30'\n , @OneOnOneOPL=-1\n , @JumpStart=-1\n , @SmallGroup=-1\n , @PurchasedEAP=-1\n , @RedeemedEAP=-1\n , @ReturnPlanYes=False\n , @MinNetPromoter=-1\n , @MinSurveyScore=-1\n , @VIPExclusionTypes='-2'\n , @FieldSelectionMask=65011584\n , @DisplayType=0\nGO\n</code></pre>\n\n<p>You will probably need to add some more conditional \"..is...\" type assignments, e.g. for dates and times.</p>\n"
},
{
"answer_id": 65753622,
"author": "Seyed Hossein Mirheydari",
"author_id": 12054364,
"author_profile": "https://Stackoverflow.com/users/12054364",
"pm_score": 2,
"selected": false,
"text": "<p>If your database was Oracle and the sql text contains dynamic variables named like <code>:1,:2 ,...</code> then you can use:</p>\n<pre><code>string query = cmd.CommandText;\nint i = 1;\nforeach (OracleParameter p in cmd.Parameters)\n {\n query = query.Replace(":"+i.ToString(),((p.Value==null)?"":p.Value.ToString()));\n i++;\n }\n</code></pre>\n"
},
{
"answer_id": 74242000,
"author": "Ramakrishna Talla",
"author_id": 849030,
"author_profile": "https://Stackoverflow.com/users/849030",
"pm_score": 0,
"selected": false,
"text": "<pre><code>//For Oracle db in the sql text the parameters could be like :ID,:NAME etc.\n//This is same as above Seyed Hossein Mirheydari, but slightly improved, \n//this works with parameter names well.\n//Further is straight simple one, you need to format for datatypes \n//after query is generated.\n private string GetFullOraQuery(OracleCommand cmd)\n {\n string query = cmd.CommandText;\n foreach (OracleParameter p in cmd.Parameters)\n {\n query = query.Replace(":" + p.ParameterName, ((p.Value == null) ? "" : p.Value.ToString()));\n }\n return query;\n }\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6297/"
] |
I have the following code:
```
Using cmd As SqlCommand = Connection.CreateCommand
cmd.CommandText = "UPDATE someTable SET Value = @Value"
cmd.CommandText &= " WHERE Id = @Id"
cmd.Parameters.AddWithValue("@Id", 1234)
cmd.Parameters.AddWithValue("@Value", "myValue")
cmd.ExecuteNonQuery
End Using
```
I wonder if there is any way to get the final SQL statment as a String, which should look like this:
```sql
UPDATE someTable SET Value = "myValue" WHERE Id = 1234
```
If anyone wonders why I would do this:
* for logging (failed) statements
* for having the possibility to copy & paste it to the Enterprise Manager for testing purposes
|
Whilst not perfect, here's something I knocked up for TSQL - could be easily tweaked for other flavors... If nothing else it will give you a start point for your own improvements :)
This does an OK job on data types and output parameters etc similar to using "execute stored procedure" in SSMS. We mostly used SPs so the "text" command doesn't account for parameters etc
```
public static String ParameterValueForSQL(this SqlParameter sp)
{
String retval = "";
switch (sp.SqlDbType)
{
case SqlDbType.Char:
case SqlDbType.NChar:
case SqlDbType.NText:
case SqlDbType.NVarChar:
case SqlDbType.Text:
case SqlDbType.Time:
case SqlDbType.VarChar:
case SqlDbType.Xml:
case SqlDbType.Date:
case SqlDbType.DateTime:
case SqlDbType.DateTime2:
case SqlDbType.DateTimeOffset:
retval = "'" + sp.Value.ToString().Replace("'", "''") + "'";
break;
case SqlDbType.Bit:
retval = (sp.Value.ToBooleanOrDefault(false)) ? "1" : "0";
break;
default:
retval = sp.Value.ToString().Replace("'", "''");
break;
}
return retval;
}
public static String CommandAsSql(this SqlCommand sc)
{
StringBuilder sql = new StringBuilder();
Boolean FirstParam = true;
sql.AppendLine("use " + sc.Connection.Database + ";");
switch (sc.CommandType)
{
case CommandType.StoredProcedure:
sql.AppendLine("declare @return_value int;");
foreach (SqlParameter sp in sc.Parameters)
{
if ((sp.Direction == ParameterDirection.InputOutput) || (sp.Direction == ParameterDirection.Output))
{
sql.Append("declare " + sp.ParameterName + "\t" + sp.SqlDbType.ToString() + "\t= ");
sql.AppendLine(((sp.Direction == ParameterDirection.Output) ? "null" : sp.ParameterValueForSQL()) + ";");
}
}
sql.AppendLine("exec [" + sc.CommandText + "]");
foreach (SqlParameter sp in sc.Parameters)
{
if (sp.Direction != ParameterDirection.ReturnValue)
{
sql.Append((FirstParam) ? "\t" : "\t, ");
if (FirstParam) FirstParam = false;
if (sp.Direction == ParameterDirection.Input)
sql.AppendLine(sp.ParameterName + " = " + sp.ParameterValueForSQL());
else
sql.AppendLine(sp.ParameterName + " = " + sp.ParameterName + " output");
}
}
sql.AppendLine(";");
sql.AppendLine("select 'Return Value' = convert(varchar, @return_value);");
foreach (SqlParameter sp in sc.Parameters)
{
if ((sp.Direction == ParameterDirection.InputOutput) || (sp.Direction == ParameterDirection.Output))
{
sql.AppendLine("select '" + sp.ParameterName + "' = convert(varchar, " + sp.ParameterName + ");");
}
}
break;
case CommandType.Text:
sql.AppendLine(sc.CommandText);
break;
}
return sql.ToString();
}
```
this generates output along these lines...
```
use dbMyDatabase;
declare @return_value int;
declare @OutTotalRows BigInt = null;
exec [spMyStoredProc]
@InEmployeeID = 1000686
, @InPageSize = 20
, @InPage = 1
, @OutTotalRows = @OutTotalRows output
;
select 'Return Value' = convert(varchar, @return_value);
select '@OutTotalRows' = convert(varchar, @OutTotalRows);
```
|
265,208 |
<p>I have a list of integers in C#. I wish to remove duplicates.
In C++ I would run it through the std::sort and then std::unique algorithms for a very efficient way of obtaining the unique list.</p>
<p>What's the best way to do the same thing in C#? In other words, I'm looking for a more elegant way to do the following code:</p>
<pre><code> private static int[] unique(int[] ids)
{
IDictionary<int, object> d = new Dictionary<int, object>();
foreach(int i in ids)
d[i] = null;
int[] results = new int[d.Count];
int j = 0;
foreach(int id in d.Keys)
results[j++] = id;
return results;
}
</code></pre>
|
[
{
"answer_id": 265214,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "<p>What version of .NET are you using?</p>\n\n<p>In .NET 3.5 that's as simple as calling the <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx\" rel=\"noreferrer\">Distinct()</a> extension method and then <a href=\"http://msdn.microsoft.com/en-us/library/bb298736.aspx\" rel=\"noreferrer\">ToArray()</a> if you really need an array again.</p>\n\n<p>For example:</p>\n\n<pre><code>int[] x = new[] { 1, 4, 23, 4, 1 };\nint[] distinct = x.Distinct().ToArray();\n// distinct is now { 1, 4, 23 } (but not necessarily in that order)\n</code></pre>\n"
},
{
"answer_id": 265223,
"author": "Paul Hollingsworth",
"author_id": 34685,
"author_profile": "https://Stackoverflow.com/users/34685",
"pm_score": 0,
"selected": false,
"text": "<p>Alas I only have .NET 2.0 to work with</p>\n"
},
{
"answer_id": 265238,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>Even with .NET 2.0, you could get the same with <a href=\"http://www.albahari.com/nutshell/linqbridge.aspx\" rel=\"nofollow noreferrer\">LINQBridge</a>. This will be easier to use with C# 3.0 (even with .NET 2.0), but should be usable with C# 2.0 and .NET 2.0 - you'd simply have to use Enumerable.Distinct(x) rather than x.Distinct();</p>\n\n<p>Of course, ultimately these are just pre-wrapped versions of the code you posted earlier (give-or-take things like iterator blocks), so you could just push that code into a utility class and (re)use it from there.</p>\n"
},
{
"answer_id": 265260,
"author": "Tamir",
"author_id": 30879,
"author_profile": "https://Stackoverflow.com/users/30879",
"pm_score": 2,
"selected": false,
"text": "<p>if you considering STL methods as \"very efficient\", so use following:</p>\n\n<pre><code> var vals = new List<int> { 1, 2, 3, 2, 1, 2, 3, 2, 3, 4, 3, 2, 3 };\n vals.Sort();\n var uniques = new HashSet<int>(vals);\n</code></pre>\n\n<p>For 2.0 equivalent</p>\n\n<pre><code>List<int> vals = new List<int>();\nvals.Add(1);\nvals.Add(2);\nvals.Add(3);\nvals.Add(2);\n...\nvals.Sort();\nList<int> uniques = new List<int>();\nvals.ForEach(delegate(int v) {\n if (!uniques.Contains(v)) uniques.Add(v);\n});\n</code></pre>\n"
},
{
"answer_id": 265287,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 0,
"selected": false,
"text": "<p>On a half-way related note, C# has a <a href=\"http://msdn.microsoft.com/en-us/library/system.array.sort(VS.80).aspx\" rel=\"nofollow noreferrer\">System.Array.Sort</a> static method that you can use to sort real arrays without using a collection.</p>\n"
},
{
"answer_id": 265288,
"author": "slf",
"author_id": 13263,
"author_profile": "https://Stackoverflow.com/users/13263",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know how big your collection is, but if you aren't dealing with thousands of integers this might be good enough:</p>\n\n<pre><code>public IEnumerable<int> unique(int[] ids)\n{\n List<int> l = new List<int>();\n foreach (int id in ids)\n {\n if (!l.Contains(id))\n {\n l.Add(id);\n yield return id;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2181589,
"author": "Cine",
"author_id": 264022,
"author_profile": "https://Stackoverflow.com/users/264022",
"pm_score": 0,
"selected": false,
"text": "<pre><code> private static List<T> GetUnique<T>(List<T> list) where T : IEquatable<T>\n {\n list.Sort();\n int count = list.Count;\n List<T> unique = new List<T>(count);\n T last = default(T);\n for (int i = 0; i < count; i++)\n {\n T val = list[i];\n if (i != 0 && last.Equals(val)) continue;\n last = val;\n unique.Add(val);\n }\n return unique;\n }\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34685/"
] |
I have a list of integers in C#. I wish to remove duplicates.
In C++ I would run it through the std::sort and then std::unique algorithms for a very efficient way of obtaining the unique list.
What's the best way to do the same thing in C#? In other words, I'm looking for a more elegant way to do the following code:
```
private static int[] unique(int[] ids)
{
IDictionary<int, object> d = new Dictionary<int, object>();
foreach(int i in ids)
d[i] = null;
int[] results = new int[d.Count];
int j = 0;
foreach(int id in d.Keys)
results[j++] = id;
return results;
}
```
|
What version of .NET are you using?
In .NET 3.5 that's as simple as calling the [Distinct()](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx) extension method and then [ToArray()](http://msdn.microsoft.com/en-us/library/bb298736.aspx) if you really need an array again.
For example:
```
int[] x = new[] { 1, 4, 23, 4, 1 };
int[] distinct = x.Distinct().ToArray();
// distinct is now { 1, 4, 23 } (but not necessarily in that order)
```
|
265,228 |
<p>I have some function to find a value:</p>
<pre><code>struct FindPredicate
{
FindPredicate(const SomeType& t) : _t(t) {
}
bool operator()(SomeType& t) {
return t == _t;
}
private:
const SomeType& _t;
};
bool ContainsValue(std::vector<SomeType>& v, SomeType& valueToFind) {
return find_if(v.begin(), v.end(), FindPredicate(valueToFind)) != v.end();
}
</code></pre>
<p>Now I would like to write a function that checks if all members of a vector satisfy that predicate:</p>
<pre><code>bool AllSatisfy(std::vector<SomeType>& v) {
/* ... */
}
</code></pre>
<p>One solution is to use the <code>std::count_if</code> algorithm.</p>
<p>Does anyone know a solution that involves negating the predicate?</p>
|
[
{
"answer_id": 265307,
"author": "Luc Touraille",
"author_id": 20984,
"author_profile": "https://Stackoverflow.com/users/20984",
"pm_score": 5,
"selected": true,
"text": "<p>The best solution is to use the <a href=\"http://www.keithschwarz.com/cs106l/fall2007/handouts/200_STL_Functional_Library.pdf\" rel=\"noreferrer\">STL functional library</a>. By deriving your predicate from <code>unary_function<SomeType, bool></code> , you'll then be able to use the <code>not1</code> function, which does precisely what you need (i.e. negating a unary predicate).</p>\n\n<p>Here is how you could do that :</p>\n\n<pre><code>struct FindPredicate : public unary_function<SomeType, bool>\n{\n FindPredicate(const SomeType& t) : _t(t) {}\n\n bool operator()(const SomeType& t) const {\n return t == _t;\n }\n\nprivate:\n const SomeType& _t;\n};\n\nbool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind)\n{\n return find_if(v.begin(), \n v.end(), \n not1(FindPredicate(valueToFind))) == v.end();\n}\n</code></pre>\n\n<hr>\n\n<p>If you want to roll your own solution (which is, IMHO, not the best option...), well, you could write another predicate that is the negation of the first one :</p>\n\n<pre><code>struct NotFindPredicate\n{\n\n NotFindPredicate(const SomeType& t) : _t(t) {\n }\n bool operator()(SomeType& t) {\n return t != _t;\n }\n\nprivate:\n const SomeType& _t;\n};\n\nbool AllSatisfy(std::vector<SomeType>& v) {\n return find_if(v.begin(), \n v.end(), \n NotFindPredicate(valueToFind)) == v.end();\n}\n</code></pre>\n\n<p>Or you could do better and write a template functor negator, like :</p>\n\n<pre><code>template <class Functor>\nstruct Not\n{\n Not(Functor & f) : func(f) {}\n\n template <typename ArgType>\n bool operator()(ArgType & arg) { return ! func(arg); }\n\n private:\n Functor & func;\n};\n</code></pre>\n\n<p>that you could use as follow :</p>\n\n<pre><code>bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind)\n{\n FindPredicate f(valueToFind);\n return find_if(v.begin(), v.end(), Not<FindPredicate>(f)) == v.end();\n}\n</code></pre>\n\n<p>Of course, the latter solution is better because you can reuse the <em>Not</em> struct with every functor you want.</p>\n"
},
{
"answer_id": 265323,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 3,
"selected": false,
"text": "<p>See the std library functor <a href=\"http://www.cplusplus.com/reference/misc/functional/not1.html\" rel=\"nofollow noreferrer\">not1</a>, it returns a functor that is the logical not of whatever the functor you give it would return.</p>\n\n<p>You should be able to do something like:</p>\n\n<pre><code>bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind) {\n return find_if(v.begin(), v.end(), not1(FindPredicate(valueToFind))) != v.end();\n}\n</code></pre>\n"
},
{
"answer_id": 265451,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 2,
"selected": false,
"text": "<p>The first time I used <code>not1</code> I wondered why it wasn't simply called <code>not</code>.</p>\n\n<p>The answer surprised me a bit (see comment).</p>\n"
},
{
"answer_id": 273722,
"author": "Sanjaya R",
"author_id": 9353,
"author_profile": "https://Stackoverflow.com/users/9353",
"pm_score": 0,
"selected": false,
"text": "<p>As you are using it, you don't need the FindPredicate functor, since in the example you are only testing equality.</p>\n\n<pre><code>bool all_equal(std::vector<SomeType>& v, SomeType& valueToFind)\n{\n return v.end() == find_if(v.begin(), v.end(), std::bind1st (equal_to (), valueToFind) );\n}\n\nbool all_not_equal( std::vector<SomeType>& v, SomeType &valueToFind ) {\n{\n return v.end() == find_if(v.begin(), v.end(), std::bind1st (not_equal_to (), valueToFind) );\n}\n</code></pre>\n\n<p>And you could just make this a template by itself.</p>\n\n<pre><code>template< typename InputIterator , typename Predicate >\nbool test_all( InputIterator first, InputIterator last, Predicate pred )\n{\n return last == find_if( first, last, pred );\n}\n\ntest_all( v.begin(), v.end(), std::bind1st( not_equals_to_( value )) );\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17650/"
] |
I have some function to find a value:
```
struct FindPredicate
{
FindPredicate(const SomeType& t) : _t(t) {
}
bool operator()(SomeType& t) {
return t == _t;
}
private:
const SomeType& _t;
};
bool ContainsValue(std::vector<SomeType>& v, SomeType& valueToFind) {
return find_if(v.begin(), v.end(), FindPredicate(valueToFind)) != v.end();
}
```
Now I would like to write a function that checks if all members of a vector satisfy that predicate:
```
bool AllSatisfy(std::vector<SomeType>& v) {
/* ... */
}
```
One solution is to use the `std::count_if` algorithm.
Does anyone know a solution that involves negating the predicate?
|
The best solution is to use the [STL functional library](http://www.keithschwarz.com/cs106l/fall2007/handouts/200_STL_Functional_Library.pdf). By deriving your predicate from `unary_function<SomeType, bool>` , you'll then be able to use the `not1` function, which does precisely what you need (i.e. negating a unary predicate).
Here is how you could do that :
```
struct FindPredicate : public unary_function<SomeType, bool>
{
FindPredicate(const SomeType& t) : _t(t) {}
bool operator()(const SomeType& t) const {
return t == _t;
}
private:
const SomeType& _t;
};
bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind)
{
return find_if(v.begin(),
v.end(),
not1(FindPredicate(valueToFind))) == v.end();
}
```
---
If you want to roll your own solution (which is, IMHO, not the best option...), well, you could write another predicate that is the negation of the first one :
```
struct NotFindPredicate
{
NotFindPredicate(const SomeType& t) : _t(t) {
}
bool operator()(SomeType& t) {
return t != _t;
}
private:
const SomeType& _t;
};
bool AllSatisfy(std::vector<SomeType>& v) {
return find_if(v.begin(),
v.end(),
NotFindPredicate(valueToFind)) == v.end();
}
```
Or you could do better and write a template functor negator, like :
```
template <class Functor>
struct Not
{
Not(Functor & f) : func(f) {}
template <typename ArgType>
bool operator()(ArgType & arg) { return ! func(arg); }
private:
Functor & func;
};
```
that you could use as follow :
```
bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind)
{
FindPredicate f(valueToFind);
return find_if(v.begin(), v.end(), Not<FindPredicate>(f)) == v.end();
}
```
Of course, the latter solution is better because you can reuse the *Not* struct with every functor you want.
|
265,258 |
<p>I am doing 2^1000 and I am getting this:</p>
<p>1.07151e+301</p>
<p>Is there any way to actually turn this into a proper number without the e+301, or at least can anyone show me where I can see how to turn this in to a real number, by some way working with the e+301 part?</p>
|
[
{
"answer_id": 265272,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 3,
"selected": false,
"text": "<p>You need to use a number class specifically designed for long numbers.</p>\n\n<p>To represent 2^1000 as an exact number then by definition you need a number format that actually holds 1001 binary bits. The longest normal primitive integer format is usually only 64 bits.</p>\n\n<p>BTW, the answer is:</p>\n\n<pre><code>% perl -Mbigint -e 'print 2**1000'\n10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376\n</code></pre>\n"
},
{
"answer_id": 265278,
"author": "tloach",
"author_id": 14092,
"author_profile": "https://Stackoverflow.com/users/14092",
"pm_score": 0,
"selected": false,
"text": "<p>You are getting as precise a number as the variable type can support. That number is on the order of 1 followed by 301 zeroes. To get a precise number you'll have to work with a library that supports large numbers, or work with a language that is made for that kind of math (maple, matlab, etc)</p>\n"
},
{
"answer_id": 265284,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 4,
"selected": false,
"text": "<p>There is a practical limit to how large a number that can be directly manipulated in machine registers can be. if you are using double precision floats there are a total of 64 bits, some of which are devoted to the mantissa, some to the exponent, and 1 to the sign bit.</p>\n\n<p>2^1000 needs a 1001 bit integer to be represented without losing precision. In order to work with numbers like that you will need to use a library that has big number support, such as <a href=\"http://gmplib.org/\" rel=\"nofollow noreferrer\">GNU MP</a>.</p>\n"
},
{
"answer_id": 265308,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>cout << fixed << your_number;</p>\n\n<p>But it won't probably show the whole number. As someone said before, you need to write a class.</p>\n"
},
{
"answer_id": 265330,
"author": "schnaader",
"author_id": 34065,
"author_profile": "https://Stackoverflow.com/users/34065",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to do it yourself in C++, you can for example create an digit array and do the calculation yourself. Tested and verified example:</p>\n\n<pre><code>unsigned int result[400]; // result digits\nunsigned int i, j, carry;\n\n// Initialize result digits\nfor (i = 0; i < 399; i++) {\n result[i] = 0;\n}\nresult[399] = 2;\n\nfor (i = 2; i <= 1000; i++) { // Calculate 2^i\n carry = 0;\n for (j = 399; j > 0; j--) {\n result[j] <<= 1; // multiply with 2\n result[j] += carry; // add carry\n carry = result[j] / 10;\n result[j] %= 10; // we want one digit (0-9) only\n }\n}\n\nprintf(\"2 ^ 1000 = \");\n// print result digits\nfor (i = 0; i < 400; i++) {\n if (result[i] != 0) { // no leading zeros, please\n for (j = i; j < 400; j++) {\n printf(\"%d\", result[j]);\n }\n break;\n }\n}\nprintf(\"\\n\");\n</code></pre>\n"
},
{
"answer_id": 265365,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 5,
"selected": true,
"text": "<p>So, I'm thinking that what you really want is just the ability to print it without scientific notation. If you're using <code>printf</code>, what you want is:</p>\n\n<pre><code>printf( \"%f1000.0\", value );\n// note that 1000 is way larger than need be,\n// I'm just too lazy to count the digits\n</code></pre>\n\n<p>With <code>cout</code>, try something like:</p>\n\n<pre><code>cout.setf(ios::fixed);\ncout << setprecision(0) << value;\n</code></pre>\n\n<p>If you want to print it as a power of two (2^1000 vs 10715...), you're on your own.</p>\n"
},
{
"answer_id": 265380,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 2,
"selected": false,
"text": "<p>One option, if your application logic will allow it is to change the units you are manipulating.... </p>\n\n<p>If you are measuring the distance from New York to Paris in Angstroms, choose Miles or Kilometers instead.... \nExcept for pure mathematical requirements, (like say factoring prime numbers for cryptology or, ... research into the Reimann Hypothesis), there is seldom any need to retain that many digits of accuracy. </p>\n\n<p>On the other hand, if you are doing something that requires perfectly accurate integer values with that many digits, then you should probably get specialized software designed to handle large numbers... Such software is definitely available, although I'm not familiar with that area. (costs, vendors, capabilities etc.) \nIf cost is an issue, and you're thinking of writing your own, I don't know enough about what's involved in to know if that approach is worth the effort... </p>\n"
},
{
"answer_id": 49108333,
"author": "C AJAY KARTHIKEYAN",
"author_id": 9445117,
"author_profile": "https://Stackoverflow.com/users/9445117",
"pm_score": 0,
"selected": false,
"text": "<p>Include the header <code>limits.h</code> and <code>cmath.h</code></p>\n\n<pre><code>cout.precision(0);\ncout<< fixed<< pow(2,31); //OR ANY NUMBER HERE\n</code></pre>\n\n<p>Use cout.precision to set the precision.</p>\n"
},
{
"answer_id": 65357452,
"author": "Raj Aryan",
"author_id": 14348823,
"author_profile": "https://Stackoverflow.com/users/14348823",
"pm_score": 0,
"selected": false,
"text": "<p>I was facing the same issue. I was trying to directly print <code>2^34</code> and the output was\n<code>3.43597e+010</code>.</p>\n<p>You should consider storing it in a variable, as this solved my problem. For example,</p>\n<pre><code>long long int a= pow(2,34)-2;\ncout<<a;\n</code></pre>\n<p>And the output was a real number, just as I wanted - <code>34359738366</code></p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8715/"
] |
I am doing 2^1000 and I am getting this:
1.07151e+301
Is there any way to actually turn this into a proper number without the e+301, or at least can anyone show me where I can see how to turn this in to a real number, by some way working with the e+301 part?
|
So, I'm thinking that what you really want is just the ability to print it without scientific notation. If you're using `printf`, what you want is:
```
printf( "%f1000.0", value );
// note that 1000 is way larger than need be,
// I'm just too lazy to count the digits
```
With `cout`, try something like:
```
cout.setf(ios::fixed);
cout << setprecision(0) << value;
```
If you want to print it as a power of two (2^1000 vs 10715...), you're on your own.
|
265,293 |
<p>I have an ASP.Net MVC Ajax.BeginForm that submits and updates my page properly when I click the submit button. </p>
<p>The problem is I need additional events to do the same thing, like when they change the text of an input. The additonal events do properly submit the form but they circumvent the onsubmit javascript generated on the form tag by the Ajax.BeginForm.</p>
<p>Here is the form tag generated by Ajax.BeingForm:</p>
<pre><code><form action="/Store/UpdateCart" method="post" onsubmit="Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: 'updatedContent' });">
</code></pre>
<p>And here is the jQuery to bind my other events that need to submit the form via Ajax:</p>
<pre><code> $("#ShippingType, #ViewCart .ddl").bind("change", function() { $("#ViewCartPage form").submit() });
</code></pre>
<p>Any ideas on how to get these additional events to trigger onsubmit like I need it too?</p>
|
[
{
"answer_id": 265473,
"author": "Andrew Stanton-Nurse",
"author_id": 29813,
"author_profile": "https://Stackoverflow.com/users/29813",
"pm_score": 0,
"selected": false,
"text": "<p>This is a bit of a tricky issue in the current Beta of MVC. You can't use the \"submit()\" function because it won't trigger the onsubmit handler. Instead, you should call the onsubmit handler directly. The only trick is you need to pass an argument to onsubmit() when you call it. This argument is what becomes the \"event\" parameter in the handler (see the \"new Sys.UI.DomEvent(event)\" part). The \"event\" parameter is used by the MVC Ajax scripts to cancel the default behaviour, when you click the Submit button so that the Ajax stuff can happen uninterrupted.</p>\n\n<p>So, if you change your code to this:</p>\n\n<pre><code>$(\"#ShippingType, #ViewCart .ddl\").bind(\"change\", function() { $(\"#ViewCartPage form\").onsubmit({ preventDefault: function() {} }) });\n</code></pre>\n\n<p>The onsubmit() event will be triggered when the form fields change. The code creates a \"fake\" event object that implements the preventDefault() method (which is the only one the MVC Ajax helpers use) so you don't get errors.</p>\n"
},
{
"answer_id": 288186,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Change - </p>\n\n<pre><code>bind(\"change\", function() { $(\"#ViewCartPage form\").submit() });\n</code></pre>\n\n<p>to -</p>\n\n<pre><code>bind(\"change\", function() { $(\"#ViewCartPage form\").onsubmit() });\n</code></pre>\n"
},
{
"answer_id": 299347,
"author": "Slee",
"author_id": 34548,
"author_profile": "https://Stackoverflow.com/users/34548",
"pm_score": 4,
"selected": true,
"text": "<p>Decided to just use a regular form and then the jQuery.Form plugin and this worked in 2 seconds! Wish i would have just went this route orginally.</p>\n\n<pre><code>var options = {\n target: '#updatedContent', // target element(s) to be updated with server response \n beforeSubmit: showRequest, // pre-submit callback \n success: showResponse // post-submit callback \n };\n\n$('#ViewCartPage form').ajaxForm(options);\n</code></pre>\n\n<p>Man I love jQuery</p>\n"
},
{
"answer_id": 1234602,
"author": "Sichbo",
"author_id": 113396,
"author_profile": "https://Stackoverflow.com/users/113396",
"pm_score": 2,
"selected": false,
"text": "<p>Microsoft will probably break us, but:</p>\n\n<pre><code>function SubmitMvcAjaxForm(formName) {\n eval('var event = new Object(); event.type=\"keypress\"; ' + document.forms[formName].attributes[\"onsubmit\"].value.replace('(this,', '(document.forms[\"' + formName + '\"],'));\n}\n</code></pre>\n"
},
{
"answer_id": 7701833,
"author": "David Fidge",
"author_id": 637151,
"author_profile": "https://Stackoverflow.com/users/637151",
"pm_score": 0,
"selected": false,
"text": "<p>I was using Sichbo's answer in MVC2, but I have found that with MVC3 you no longer need these workarounds (i.e. $('#yourformid').submit(); will now work for ajax calls).</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34548/"
] |
I have an ASP.Net MVC Ajax.BeginForm that submits and updates my page properly when I click the submit button.
The problem is I need additional events to do the same thing, like when they change the text of an input. The additonal events do properly submit the form but they circumvent the onsubmit javascript generated on the form tag by the Ajax.BeginForm.
Here is the form tag generated by Ajax.BeingForm:
```
<form action="/Store/UpdateCart" method="post" onsubmit="Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: 'updatedContent' });">
```
And here is the jQuery to bind my other events that need to submit the form via Ajax:
```
$("#ShippingType, #ViewCart .ddl").bind("change", function() { $("#ViewCartPage form").submit() });
```
Any ideas on how to get these additional events to trigger onsubmit like I need it too?
|
Decided to just use a regular form and then the jQuery.Form plugin and this worked in 2 seconds! Wish i would have just went this route orginally.
```
var options = {
target: '#updatedContent', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
$('#ViewCartPage form').ajaxForm(options);
```
Man I love jQuery
|
265,302 |
<p>First some background. I am trying to run <a href="http://www.communityengine.org/" rel="nofollow noreferrer">Community Engine</a> on a fresh install of Ubuntu. CE is a open src social networking plugin running on Rails. I was able to get CE up and running on my windows box w/o issue. I have decided to use Ubuntu 8.10 as my development environment now, and am stuck on this issue. I have researched this for the last couple nights and am still stuck.</p>
<p>What happens is, when i get to this step of the instruction (<a href="http://github.com/bborn/communityengine/tree/master" rel="nofollow noreferrer">found here</a>):</p>
<pre><code> Generate the community engine migrations:
$ script/generate plugin_migration
</code></pre>
<p>I get the following error:</p>
<pre><code>myuser@compy:~/Projects/MyProject$ script/generate plugin_migration
/home/myuser/Projects/MyProject/config/../vendor/plugins/engines/boot.rb:4: This version of the engines plugin requires Rails 2.1.1 or later! (RuntimeError)
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
from /home/myuser/Projects/MyProject/config/environment.rb:12
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
from /home/myuser/Projects/MyProject/vendor/rails/railties/lib/commands/generate.rb:1
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
from script/generate:3
</code></pre>
<p>Here's my version of ruby:</p>
<pre><code>myuser@compy:~/Projects/MyProject$ ruby -v
ruby 1.8.7 (2008-08-11 patchlevel 72) [i486-linux]
</code></pre>
<p>and my installed gems:</p>
<pre><code>myuser@compy:~/Projects/MyProject$ gem list
*** LOCAL GEMS ***
actionmailer (2.2.0, 2.1.2, 2.1.1)
actionpack (2.2.0, 2.1.2, 2.1.1)
activerecord (2.2.0, 2.1.2, 2.1.1)
activeresource (2.2.0, 2.1.2, 2.1.1)
activesupport (2.2.0, 2.1.2, 2.1.1)
aws-s3 (0.5.1)
builder (2.1.2)
capistrano (2.5.0)
cgi_multipart_eof_fix (2.5.0)
daemons (1.0.10)
fastthread (1.0.1)
gem_plugin (0.2.3)
haml (2.0.4)
highline (1.4.0)
hpricot (0.6.164)
htmlentities (4.0.0)
mime-types (1.15)
mongrel (1.1.5)
net-scp (1.0.1)
net-sftp (2.0.1)
net-ssh (2.0.4)
net-ssh-gateway (1.0.0)
rails (2.2.0, 2.1.2, 2.1.1) <--- clearly I have rails 2.1.1 or greater
rake (0.8.3)
RedCloth (4.1.0)
rmagick (2.7.1)
sqlite3-ruby (1.2.4)
xml-simple (1.0.11)
</code></pre>
<p>I got this error when i only had rails 2.1.1 as well.</p>
<p>Yes, I have way more gems than i need for CE, but in trying to track this down, this is what i ended up with. I have a sneaking suspicion that whatever the issue is, it's dumb and i should of caught it. But at this point, I've grown very frustrated with what was a simple process on an XP box.</p>
<p>I have asked this question in the Community Engine google group, however, I have a feeling that this is more related to my setup of Ruby and Rails on my machine than to CE itself.</p>
<p>Help would be appreciated.</p>
|
[
{
"answer_id": 266520,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 3,
"selected": false,
"text": "<p>The \"problem\" is not coming from CommunityEngine itself, but with the underlying 'engines' plugin (<a href=\"http://github.com/lazyatom/engines\" rel=\"nofollow noreferrer\">http://github.com/lazyatom/engines</a>).</p>\n\n<p><a href=\"http://github.com/lazyatom/engines/tree/master/boot.rb\" rel=\"nofollow noreferrer\">looking at the source code of boot.rb in the engines plugin</a> we can see that it just checks the standard Rails::VERSION fields, so the problem isn't there either.</p>\n\n<p>Now, when you create a rails app, it is tied to the specific version that you used <em>when you first created the rails app</em>. Just having the rails 2.1.1/2 gems sitting on your system doesn't mean that they'll automatically get used.</p>\n\n<p>To check your actual rails app itself, look at the <code>config/environment.rb</code> file in your rails app. You will see something like this:</p>\n\n<pre><code># Specifies gem version of Rails to use when vendor/rails is not present\nRAILS_GEM_VERSION = '2.1.0' unless defined? RAILS_GEM_VERSION\n</code></pre>\n\n<p>If it is less than 2.1.1, then you'll need to upgrade your rails app.<br>\nThis is pretty simply:</p>\n\n<ol>\n<li>Change the <code>RAILS_GEM_VERSION</code> string in <code>config/environment.rb</code> to 2.1.1 or greater</li>\n<li>run <code>rake rails:upgrade</code></li>\n</ol>\n\n<p>Hopefully this solves your problem :-)</p>\n"
},
{
"answer_id": 270216,
"author": "Levi Rosol",
"author_id": 23458,
"author_profile": "https://Stackoverflow.com/users/23458",
"pm_score": 3,
"selected": true,
"text": "<p>This issue ended up being due to not usind sudo to install rails. I ended up blowing away ruby completely and reinstalling it. I also paid closer attention to the output of the various gems i needed to install to make sure they downloaded and ran. I was surprised to see that many of them would fail to download and had to be run a second, or even third time before they would install.</p>\n\n<p>regarding Orion's suggestion, I had checked the RAILS_GEM_VERSION and it was 2.1.1 or greater. That's what was causing the most confusion with this issue since it was saying what version was needed, and then gem -v would show me the right version.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23458/"
] |
First some background. I am trying to run [Community Engine](http://www.communityengine.org/) on a fresh install of Ubuntu. CE is a open src social networking plugin running on Rails. I was able to get CE up and running on my windows box w/o issue. I have decided to use Ubuntu 8.10 as my development environment now, and am stuck on this issue. I have researched this for the last couple nights and am still stuck.
What happens is, when i get to this step of the instruction ([found here](http://github.com/bborn/communityengine/tree/master)):
```
Generate the community engine migrations:
$ script/generate plugin_migration
```
I get the following error:
```
myuser@compy:~/Projects/MyProject$ script/generate plugin_migration
/home/myuser/Projects/MyProject/config/../vendor/plugins/engines/boot.rb:4: This version of the engines plugin requires Rails 2.1.1 or later! (RuntimeError)
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
from /home/myuser/Projects/MyProject/config/environment.rb:12
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
from /home/myuser/Projects/MyProject/vendor/rails/railties/lib/commands/generate.rb:1
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
from script/generate:3
```
Here's my version of ruby:
```
myuser@compy:~/Projects/MyProject$ ruby -v
ruby 1.8.7 (2008-08-11 patchlevel 72) [i486-linux]
```
and my installed gems:
```
myuser@compy:~/Projects/MyProject$ gem list
*** LOCAL GEMS ***
actionmailer (2.2.0, 2.1.2, 2.1.1)
actionpack (2.2.0, 2.1.2, 2.1.1)
activerecord (2.2.0, 2.1.2, 2.1.1)
activeresource (2.2.0, 2.1.2, 2.1.1)
activesupport (2.2.0, 2.1.2, 2.1.1)
aws-s3 (0.5.1)
builder (2.1.2)
capistrano (2.5.0)
cgi_multipart_eof_fix (2.5.0)
daemons (1.0.10)
fastthread (1.0.1)
gem_plugin (0.2.3)
haml (2.0.4)
highline (1.4.0)
hpricot (0.6.164)
htmlentities (4.0.0)
mime-types (1.15)
mongrel (1.1.5)
net-scp (1.0.1)
net-sftp (2.0.1)
net-ssh (2.0.4)
net-ssh-gateway (1.0.0)
rails (2.2.0, 2.1.2, 2.1.1) <--- clearly I have rails 2.1.1 or greater
rake (0.8.3)
RedCloth (4.1.0)
rmagick (2.7.1)
sqlite3-ruby (1.2.4)
xml-simple (1.0.11)
```
I got this error when i only had rails 2.1.1 as well.
Yes, I have way more gems than i need for CE, but in trying to track this down, this is what i ended up with. I have a sneaking suspicion that whatever the issue is, it's dumb and i should of caught it. But at this point, I've grown very frustrated with what was a simple process on an XP box.
I have asked this question in the Community Engine google group, however, I have a feeling that this is more related to my setup of Ruby and Rails on my machine than to CE itself.
Help would be appreciated.
|
This issue ended up being due to not usind sudo to install rails. I ended up blowing away ruby completely and reinstalling it. I also paid closer attention to the output of the various gems i needed to install to make sure they downloaded and ran. I was surprised to see that many of them would fail to download and had to be run a second, or even third time before they would install.
regarding Orion's suggestion, I had checked the RAILS\_GEM\_VERSION and it was 2.1.1 or greater. That's what was causing the most confusion with this issue since it was saying what version was needed, and then gem -v would show me the right version.
|
265,335 |
<p>My table has the following schema:</p>
<p>id, parent_id, text</p>
<p>Given the following data I would like to return an xml hierarchy:</p>
<p>Data: (1,null,'x'), (2,1,'y'), (3,1,'z'), (4,2,'a')</p>
<p>XML:<br>
[row text="x"]<br>
[row text="y"]<br>
[row text="a"/]<br>
[/row]<br>
[row text="z"/]<br>
[/row] </p>
<hr>
<p>Added: the hierachy has no maximum depth</p>
|
[
{
"answer_id": 265359,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": -1,
"selected": false,
"text": "<p>This requires a \"transitive closure\". You need to process the data recursively to find all children under a given parent.</p>\n\n<p>Roughly the algorithm looks like this.</p>\n\n<pre><code>for top in cursor( nodes where each parent==null ):\n build_tree( top )\n\ndef build_tree( parent ):\n emit opening tag\n for child in cursor( nodes where parent == parent ):\n build_tree( child )\n emit closing tag\n</code></pre>\n\n<p>Note that some SQL interpreters may have trouble with the recursion -- they may not open a fresh, new cursor as necessary. Each cursor, however, must be distinct, since you will have as many open cursors as your tree has levels.</p>\n"
},
{
"answer_id": 265479,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 1,
"selected": false,
"text": "<p>If you have a finite depth the there's a quickie that looks like this:</p>\n\n<pre><code>SELECT T.*, T2.*, T3.* /*, ...*/ FROM myTable T \nINNER JOIN myTable T2 ON T2.parent_id=T.id\nINNER JOIN myTable T3 ON T3.parent_id=T2.id\n/* ... */\nWHERE T.parent_id IS NULL\nFOR XML AUTO\n</code></pre>\n\n<p>I'm not sure but it might be possible to devise a similar result using <a href=\"http://msdn.microsoft.com/en-us/library/ms186243.aspx\" rel=\"nofollow noreferrer\">recursive queries</a>. Of course, it's much easier (and probably makes more sense) in the application level.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2133/"
] |
My table has the following schema:
id, parent\_id, text
Given the following data I would like to return an xml hierarchy:
Data: (1,null,'x'), (2,1,'y'), (3,1,'z'), (4,2,'a')
XML:
[row text="x"]
[row text="y"]
[row text="a"/]
[/row]
[row text="z"/]
[/row]
---
Added: the hierachy has no maximum depth
|
If you have a finite depth the there's a quickie that looks like this:
```
SELECT T.*, T2.*, T3.* /*, ...*/ FROM myTable T
INNER JOIN myTable T2 ON T2.parent_id=T.id
INNER JOIN myTable T3 ON T3.parent_id=T2.id
/* ... */
WHERE T.parent_id IS NULL
FOR XML AUTO
```
I'm not sure but it might be possible to devise a similar result using [recursive queries](http://msdn.microsoft.com/en-us/library/ms186243.aspx). Of course, it's much easier (and probably makes more sense) in the application level.
|
265,339 |
<p>I'd like to automate the FTP download of a database backup file using PowerShell. The file name includes the date so I can't just run the same FTP script every day. Is there a clean way to do this built into PowerShell or using the .NET framework?</p>
<p>I want to use a secure FTP session.</p>
|
[
{
"answer_id": 265397,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 0,
"selected": false,
"text": "<p>This isn't as simple as I wish it would be. There are three options that I know of.</p>\n<ol>\n<li><p>.NET - You can use the .NET framework to do this in PowerShell, but it involves raw socket manipulation that I wouldn't want to do in a script. If I were going this route, then I would wrap up all the FTP junk into a DLL in C# and then use that DLL from PowerShell.</p>\n</li>\n<li><p>Manipulating a file - If you know the pattern of the name of the file that you need to get each day then you could just open your FTP script with PowerShell and change the name of the file in the script. Then run the script.</p>\n</li>\n<li><p>Pipe text to FTP - The last option is to use PowerShell to pipe information into and out of your FTP session. See <a href=\"http://jameslikesbeer.blogspot.com/2007/03/look-what-you-can-do-in-powershell-ftp.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n</li>\n</ol>\n"
},
{
"answer_id": 265402,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 3,
"selected": false,
"text": "<p>Taken from <a href=\"http://www.vistax64.com/powershell/17000-using-powershell-automate-ftp-transfers.html\" rel=\"nofollow noreferrer\">here</a>:</p>\n<pre><code>$source = "ftp://ftp.microsoft.com/ResKit/win2000/dureg.zip"\n$target = "c:\\temp\\dureg.zip"\n$WebClient = New-Object System.Net.WebClient\n$WebClient.DownloadFile($source, $target)\n</code></pre>\n<p>It works for me.</p>\n"
},
{
"answer_id": 265924,
"author": "Peter Seale",
"author_id": 25911,
"author_profile": "https://Stackoverflow.com/users/25911",
"pm_score": -1,
"selected": false,
"text": "<p>I have successfully used the Indy Project .NET library to do FTP. And...ugh, looks like the hosted .NET build is no longer available.</p>\n"
},
{
"answer_id": 265955,
"author": "Alex",
"author_id": 26564,
"author_profile": "https://Stackoverflow.com/users/26564",
"pm_score": -1,
"selected": false,
"text": "<pre><code>$realdate = (Get-Date).ToString("yyyyMMdd")\n\n$path = "D:\\samplefolderstructure\\filename" + $realdate + ".msi"\n\nftps -f $path -s:D:\\FTP.txt\n</code></pre>\n<p>ftp.txt is the way we keep all of our connection information to the FTP server. <code>ftps</code> is the client we use obviously, so you might have to change a few things. But, this should help you get the idea.</p>\n"
},
{
"answer_id": 266511,
"author": "tomasr",
"author_id": 10292,
"author_profile": "https://Stackoverflow.com/users/10292",
"pm_score": 2,
"selected": false,
"text": "<p>As far as PowerShell goes, the /n Software <a href=\"http://nsoftware.com/powershell/\" rel=\"nofollow noreferrer\">NetCmdlets</a> package includes FTP cmdlets (including support for both secure FTP types) that you could use pretty easily for this.</p>\n"
},
{
"answer_id": 268907,
"author": "Eric Ness",
"author_id": 18891,
"author_profile": "https://Stackoverflow.com/users/18891",
"pm_score": 5,
"selected": false,
"text": "<p>After some experimentation I came up with this way to automate a secure FTP download in PowerShell. This script runs off the <a href=\"http://www.secureftp-test.com/\" rel=\"noreferrer\">public test FTP server</a> administered by Chilkat Software. So you can copy and paste this code and it will run without modification.</p>\n\n<pre><code>$sourceuri = \"ftp://ftp.secureftp-test.com/hamlet.zip\"\n$targetpath = \"C:\\hamlet.zip\"\n$username = \"test\"\n$password = \"test\"\n\n# Create a FTPWebRequest object to handle the connection to the ftp server\n$ftprequest = [System.Net.FtpWebRequest]::create($sourceuri)\n\n# set the request's network credentials for an authenticated connection\n$ftprequest.Credentials =\n New-Object System.Net.NetworkCredential($username,$password)\n\n$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile\n$ftprequest.UseBinary = $true\n$ftprequest.KeepAlive = $false\n\n# send the ftp request to the server\n$ftpresponse = $ftprequest.GetResponse()\n\n# get a download stream from the server response\n$responsestream = $ftpresponse.GetResponseStream()\n\n# create the target file on the local system and the download buffer\n$targetfile = New-Object IO.FileStream ($targetpath,[IO.FileMode]::Create)\n[byte[]]$readbuffer = New-Object byte[] 1024\n\n# loop through the download stream and send the data to the target file\ndo{\n $readlength = $responsestream.Read($readbuffer,0,1024)\n $targetfile.Write($readbuffer,0,$readlength)\n}\nwhile ($readlength -ne 0)\n\n$targetfile.close()\n</code></pre>\n\n<p>I found a lot of helpful information at these links</p>\n\n<ul>\n<li><a href=\"http://www.techtalkz.com/microsoft-windows-powershell/190388-ftp-downloads-encoding-problems.html\" rel=\"noreferrer\">FTP downloads: encoding problems</a></li>\n<li><a href=\"http://www.codeproject.com/KB/IP/SimpleFTPDemo.aspx\" rel=\"noreferrer\">Simple FTP demo application</a></li>\n<li><a href=\"http://rcovelo.blogspot.com/2008/10/powershell-very-simple-ftp-client.html\" rel=\"noreferrer\">Very Simple FTP Client</a></li>\n</ul>\n\n<p>If you want to use an SSL connection you need to add the line</p>\n\n<pre><code>$ftprequest.EnableSsl = $true\n</code></pre>\n\n<p>to the script before you call GetResponse(). Sometimes you may need to deal with a server security certificate that is expired (like I unfortunately do). There is a page at the <a href=\"http://poshcode.org/634\" rel=\"noreferrer\">PowerShell Code Repository</a> that has a code snippet to do that. The first 28 lines are the most relevant for the purposes of downloading a file.</p>\n"
},
{
"answer_id": 5574652,
"author": "user695859",
"author_id": 695859,
"author_profile": "https://Stackoverflow.com/users/695859",
"pm_score": 1,
"selected": false,
"text": "<p>The JAMS Job Scheduler offers some cmdlets that would make this task simple. It has a variety of FTP cmdlets for secure sessions as well as date cmdlets for converting natural dates into .NET date objects such as "Last day of month":</p>\n<p><a href=\"http://www.jamsscheduler.com/PowerShell.aspx\" rel=\"nofollow noreferrer\">JAMS Job Scheduler Cmdlets</a></p>\n"
},
{
"answer_id": 10622686,
"author": "Nathan",
"author_id": 497982,
"author_profile": "https://Stackoverflow.com/users/497982",
"pm_score": 0,
"selected": false,
"text": "<p>Something like this could work:</p>\n<pre><code>$bkdir = "E:\\BackupsPWS" #backups location directory\n$7Zip = 'C:\\"Program Files"\\7-Zip\\7z.exe' #compression utility\n$files_to_transfer = New-Object System.Collections.ArrayList #list of zipped files to be transferred over FTP\n$ftp_uri="myftpserver"\n$user="myftpusername"\n$pass="myftppassword"\n\n# Find .bak files not zipped yet, zip them, add them to the list to be transferrd\nget-childitem -path $bkdir | Sort-Object length |\nwhere { $_.extension -match ".(bak)" -and\n -not (test-path ($_.fullname -replace "(bak)", "7z")) } |\nforeach {\n $zipfilename = ($_.fullname -replace "bak", "7z")\n Invoke-Expression "$7Zip a $zipfilename $($_.FullName)"\n $files_to_transfer.Add($zipfilename)\n}\n\n# Find .bak files, if they've been zipped, delete the .bak file\nget-childitem -path $bkdir |\nwhere { $_.extension -match ".(bak)" -and\n (test-path ($_.fullname -replace "(bak)", "7z")) } |\nforeach { del $_.fullname }\n\n# Transfer each zipped file over FTP\nforeach ($file in $files_to_transfer)\n{\n $webclient = New-Object System.Net.WebClient\n $webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass) # FTP credentials\n $ftp_urix = $ftp_uri + "/" + $file.Substring($bkdir.Length + 1) # ftp address where to transfer the file\n $uri=[system.URI] $ftp_urix\n $webclient.UploadFile($uri, $file) #transfer the file\n}\n</code></pre>\n<p>Check this: <a href=\"http://jhonatantirado.wordpress.com/2011/06/26/powershell-compress-backups-and-ftp-transfer/\" rel=\"nofollow noreferrer\">Powershell: compress backups and FTP transfer</a></p>\n"
},
{
"answer_id": 62217774,
"author": "Martin Prikryl",
"author_id": 850848,
"author_profile": "https://Stackoverflow.com/users/850848",
"pm_score": 1,
"selected": false,
"text": "<p>The most voted self-answer by @Eric is working, but it is:</p>\n\n<ul>\n<li>inefficient with only 1KB buffer; </li>\n<li>unnecessarily complicated with reimplementing, what can easily and more efficiently be done with <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.copyto\" rel=\"nofollow noreferrer\"><code>Stream.CopyTo</code></a>:</li>\n</ul>\n\n<pre><code>$fileUrl = \"ftp://ftp.example.com/remote/path/file.zip\"\n$localFilePath = \"C:\\local\\path\\file.zip\"\n\n$downloadRequest = [Net.WebRequest]::Create($fileUrl)\n$downloadRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile\n$downloadRequest.Credentials =\n New-Object System.Net.NetworkCredential(\"username\", \"password\")\n# Enable secure FTPS (FTP over TLS/SSL)\n$downloadRequest.EnableSsl = $True\n\n$sourceStream = $downloadRequest.GetResponse().GetResponseStream()\n$targetStream = [System.IO.File]::Create($localFilePath)\n$sourceStream.CopyTo($targetStream);\n\n$sourceStream.Dispose()\n$targetStream.Dispose()\n</code></pre>\n\n<hr>\n\n<p>For an upload, see <a href=\"https://stackoverflow.com/q/1867385/850848#46582183\">Upload files with FTP using PowerShell</a>.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18891/"
] |
I'd like to automate the FTP download of a database backup file using PowerShell. The file name includes the date so I can't just run the same FTP script every day. Is there a clean way to do this built into PowerShell or using the .NET framework?
I want to use a secure FTP session.
|
After some experimentation I came up with this way to automate a secure FTP download in PowerShell. This script runs off the [public test FTP server](http://www.secureftp-test.com/) administered by Chilkat Software. So you can copy and paste this code and it will run without modification.
```
$sourceuri = "ftp://ftp.secureftp-test.com/hamlet.zip"
$targetpath = "C:\hamlet.zip"
$username = "test"
$password = "test"
# Create a FTPWebRequest object to handle the connection to the ftp server
$ftprequest = [System.Net.FtpWebRequest]::create($sourceuri)
# set the request's network credentials for an authenticated connection
$ftprequest.Credentials =
New-Object System.Net.NetworkCredential($username,$password)
$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$ftprequest.UseBinary = $true
$ftprequest.KeepAlive = $false
# send the ftp request to the server
$ftpresponse = $ftprequest.GetResponse()
# get a download stream from the server response
$responsestream = $ftpresponse.GetResponseStream()
# create the target file on the local system and the download buffer
$targetfile = New-Object IO.FileStream ($targetpath,[IO.FileMode]::Create)
[byte[]]$readbuffer = New-Object byte[] 1024
# loop through the download stream and send the data to the target file
do{
$readlength = $responsestream.Read($readbuffer,0,1024)
$targetfile.Write($readbuffer,0,$readlength)
}
while ($readlength -ne 0)
$targetfile.close()
```
I found a lot of helpful information at these links
* [FTP downloads: encoding problems](http://www.techtalkz.com/microsoft-windows-powershell/190388-ftp-downloads-encoding-problems.html)
* [Simple FTP demo application](http://www.codeproject.com/KB/IP/SimpleFTPDemo.aspx)
* [Very Simple FTP Client](http://rcovelo.blogspot.com/2008/10/powershell-very-simple-ftp-client.html)
If you want to use an SSL connection you need to add the line
```
$ftprequest.EnableSsl = $true
```
to the script before you call GetResponse(). Sometimes you may need to deal with a server security certificate that is expired (like I unfortunately do). There is a page at the [PowerShell Code Repository](http://poshcode.org/634) that has a code snippet to do that. The first 28 lines are the most relevant for the purposes of downloading a file.
|
265,361 |
<p>I am trying to get a simple demo started with ActiveMQ that will demonstrate a TCP to TCP route. I am coding the endpoints and routes in a camel context in my activemq.xml configuration file.</p>
<pre><code><camelContext id="camel" xmlns="http://activemq.apache.org/camel/schema/spring">
<package>org.myorg.codec</package>
<endpoint id="listener_A" uri="mina:tcp://localhost:42000?sync=false&amp;textline=true"/>
<endpoint id="listener_B" uri="mina:tcp://localhost:42001?sync=false&amp;textline=true"/>
<route>
<from uri="activemq:listener_A"/>
<to uri="activemq:listener_B"/>
</route>
<route>
<from uri="activemq:listener_B"/>
<to uri="activemq:listener_A"/>
</route>
</camelContext>
</code></pre>
<p>Any idea why this doesn't work?</p>
<p>The AMQ server does not seem to be opening a listening port.</p>
<p>Edit: The intent here, as a simple demonstation, is to connect to ActiveMQ with two telnet terminals (A and B) and be able to route messages from one to another through the message queue server. Later, I may try filtering or routing based on content.</p>
|
[
{
"answer_id": 265539,
"author": "James Strachan",
"author_id": 2068211,
"author_profile": "https://Stackoverflow.com/users/2068211",
"pm_score": 2,
"selected": true,
"text": "<p>I'm a bit confused by your configuration file. What exactly are you trying to do? </p>\n\n<p>You've defined 2 endpoints for using MINA (which won't use ActiveMQ at all); then you are using a route from an ActievMQ queue listener_A to listener_B then listener_B to listener_A (which is a recursive loop).</p>\n\n<p>Maybe if you start describing what you want to do we can figure out what the XML should look like.</p>\n\n<p>Incidentally if you just want to refer to endpoints you've defined, use the <em>ref=\"name\"</em> attribute rather than <em>uri=\"...\"</em>.</p>\n\n<p>e.g.</p>\n\n<pre><code><route>\n <from ref=\"listener_A\"/>\n <to ref=\"listener_B\"/>\n</route>\n</code></pre>\n\n<p>All that being said - you tend to get better & faster support on Camel via the <a href=\"http://activemq.apache.org/camel/discussion-forums.html\" rel=\"nofollow noreferrer\">Camel User Forum</a></p>\n"
},
{
"answer_id": 270690,
"author": "JeffV",
"author_id": 445087,
"author_profile": "https://Stackoverflow.com/users/445087",
"pm_score": 0,
"selected": false,
"text": "<p>More on this:</p>\n\n<p>When the endpoint is defined as a mina tcp connection, it cannot be identified as \"activemq::listener_A\" </p>\n\n<pre><code><endpoint id=\"listener_A\" uri=\"mina:tcp://localhost:42000?sync=false&amp;textline=true\"/> \n</code></pre>\n\n<p>this is wrong:</p>\n\n<pre><code> <from uri=\"activemq:listener_A\"/> \n</code></pre>\n\n<p>this works: </p>\n\n<pre><code> <from ref=\"listener_A\"/> \n</code></pre>\n\n<p>so does this:</p>\n\n<pre><code> <from ref=\"mina:tcp://localhost:42000?sync=false&amp;textline=true\"/>\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] |
I am trying to get a simple demo started with ActiveMQ that will demonstrate a TCP to TCP route. I am coding the endpoints and routes in a camel context in my activemq.xml configuration file.
```
<camelContext id="camel" xmlns="http://activemq.apache.org/camel/schema/spring">
<package>org.myorg.codec</package>
<endpoint id="listener_A" uri="mina:tcp://localhost:42000?sync=false&textline=true"/>
<endpoint id="listener_B" uri="mina:tcp://localhost:42001?sync=false&textline=true"/>
<route>
<from uri="activemq:listener_A"/>
<to uri="activemq:listener_B"/>
</route>
<route>
<from uri="activemq:listener_B"/>
<to uri="activemq:listener_A"/>
</route>
</camelContext>
```
Any idea why this doesn't work?
The AMQ server does not seem to be opening a listening port.
Edit: The intent here, as a simple demonstation, is to connect to ActiveMQ with two telnet terminals (A and B) and be able to route messages from one to another through the message queue server. Later, I may try filtering or routing based on content.
|
I'm a bit confused by your configuration file. What exactly are you trying to do?
You've defined 2 endpoints for using MINA (which won't use ActiveMQ at all); then you are using a route from an ActievMQ queue listener\_A to listener\_B then listener\_B to listener\_A (which is a recursive loop).
Maybe if you start describing what you want to do we can figure out what the XML should look like.
Incidentally if you just want to refer to endpoints you've defined, use the *ref="name"* attribute rather than *uri="..."*.
e.g.
```
<route>
<from ref="listener_A"/>
<to ref="listener_B"/>
</route>
```
All that being said - you tend to get better & faster support on Camel via the [Camel User Forum](http://activemq.apache.org/camel/discussion-forums.html)
|
265,362 |
<p>Is there any way to create - manipulate calendar events in Exchange Server 2003 ?
I'm using VB.NET 2005. I don't want to use MAPI because everytime I will have to type user name and passwords. Is there any other way ? I used redemption.dll but everytime I want to add for eg. a calendar event it displays the login screen.</p>
<p>Any suggestions ?</p>
<p>Appreciate your help</p>
<p>Thank you</p>
|
[
{
"answer_id": 265539,
"author": "James Strachan",
"author_id": 2068211,
"author_profile": "https://Stackoverflow.com/users/2068211",
"pm_score": 2,
"selected": true,
"text": "<p>I'm a bit confused by your configuration file. What exactly are you trying to do? </p>\n\n<p>You've defined 2 endpoints for using MINA (which won't use ActiveMQ at all); then you are using a route from an ActievMQ queue listener_A to listener_B then listener_B to listener_A (which is a recursive loop).</p>\n\n<p>Maybe if you start describing what you want to do we can figure out what the XML should look like.</p>\n\n<p>Incidentally if you just want to refer to endpoints you've defined, use the <em>ref=\"name\"</em> attribute rather than <em>uri=\"...\"</em>.</p>\n\n<p>e.g.</p>\n\n<pre><code><route>\n <from ref=\"listener_A\"/>\n <to ref=\"listener_B\"/>\n</route>\n</code></pre>\n\n<p>All that being said - you tend to get better & faster support on Camel via the <a href=\"http://activemq.apache.org/camel/discussion-forums.html\" rel=\"nofollow noreferrer\">Camel User Forum</a></p>\n"
},
{
"answer_id": 270690,
"author": "JeffV",
"author_id": 445087,
"author_profile": "https://Stackoverflow.com/users/445087",
"pm_score": 0,
"selected": false,
"text": "<p>More on this:</p>\n\n<p>When the endpoint is defined as a mina tcp connection, it cannot be identified as \"activemq::listener_A\" </p>\n\n<pre><code><endpoint id=\"listener_A\" uri=\"mina:tcp://localhost:42000?sync=false&amp;textline=true\"/> \n</code></pre>\n\n<p>this is wrong:</p>\n\n<pre><code> <from uri=\"activemq:listener_A\"/> \n</code></pre>\n\n<p>this works: </p>\n\n<pre><code> <from ref=\"listener_A\"/> \n</code></pre>\n\n<p>so does this:</p>\n\n<pre><code> <from ref=\"mina:tcp://localhost:42000?sync=false&amp;textline=true\"/>\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Is there any way to create - manipulate calendar events in Exchange Server 2003 ?
I'm using VB.NET 2005. I don't want to use MAPI because everytime I will have to type user name and passwords. Is there any other way ? I used redemption.dll but everytime I want to add for eg. a calendar event it displays the login screen.
Any suggestions ?
Appreciate your help
Thank you
|
I'm a bit confused by your configuration file. What exactly are you trying to do?
You've defined 2 endpoints for using MINA (which won't use ActiveMQ at all); then you are using a route from an ActievMQ queue listener\_A to listener\_B then listener\_B to listener\_A (which is a recursive loop).
Maybe if you start describing what you want to do we can figure out what the XML should look like.
Incidentally if you just want to refer to endpoints you've defined, use the *ref="name"* attribute rather than *uri="..."*.
e.g.
```
<route>
<from ref="listener_A"/>
<to ref="listener_B"/>
</route>
```
All that being said - you tend to get better & faster support on Camel via the [Camel User Forum](http://activemq.apache.org/camel/discussion-forums.html)
|
265,370 |
<p>what is the best way to convert a UTF-16 files to UTF-8? I need to use this in a cmd script.</p>
|
[
{
"answer_id": 265381,
"author": "Tor Haugen",
"author_id": 32050,
"author_profile": "https://Stackoverflow.com/users/32050",
"pm_score": 3,
"selected": false,
"text": "<p>Certainly, the <strong>easiest</strong> way is to load the script into notepad, then save it again with the UTF-8 encoding. It's an option in the Save As dialog box..</p>\n"
},
{
"answer_id": 265412,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "<p>If you have a ruby distribution installed, you can call a ruby script taking care of the conversion:</p>\n\n<p><a href=\"http://www.websideattractions.com/2007/10/24/ruby-script-to-convert-files-character-encoding/\" rel=\"nofollow noreferrer\">Ruby script to convert file(s) character encoding</a></p>\n\n<p>In the same spirit: <a href=\"http://www.perlmonks.org/?node_id=719216\" rel=\"nofollow noreferrer\">Perl script</a></p>\n\n<p>In the absence of script support, you would have to code it like this <a href=\"http://www.codeproject.com/KB/string/utfConvert.aspx\" rel=\"nofollow noreferrer\">C++ source</a> using a WideCharToMultiByte() call...</p>\n"
},
{
"answer_id": 265444,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>An alternative to Ruby would be to write a small .NET program in C# (.NET 1.0 would be fine, although 2.0 would be simpler :) - it's a pretty trivial bit of code. Were you hoping to do it without any other applications at all? If you want a bit of code to do it, add a comment and I'll fill in the answer...</p>\n\n<p>EDIT:\nOkay, this is without any kind of error checking, but...</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Text;\n\nclass FileConverter\n{\n static void Main(string[] args)\n {\n string inputFile = args[0];\n string outputFile = args[1];\n using (StreamReader reader = new StreamReader(inputFile, Encoding.Unicode))\n {\n using (StreamWriter writer = new StreamWriter(outputFile, false, Encoding.UTF8))\n {\n CopyContents(reader, writer);\n }\n }\n }\n\n static void CopyContents(TextReader input, TextWriter output)\n {\n char[] buffer = new char[8192];\n int len;\n while ((len = input.Read(buffer, 0, buffer.Length)) != 0)\n {\n output.Write(buffer, 0, len);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 265852,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": false,
"text": "<p>Perhaps with <a href=\"http://www.fileformat.info/tip/linux/iconv.htm\" rel=\"noreferrer\" title=\"Using iconv to change character encodings\">iconv</a>?</p>\n"
},
{
"answer_id": 266279,
"author": "Kaarel",
"author_id": 12547,
"author_profile": "https://Stackoverflow.com/users/12547",
"pm_score": 6,
"selected": true,
"text": "<p>There is a GNU tool <a href=\"http://www.gnu.org/software/recode/recode.html\" rel=\"noreferrer\">recode</a> which you can also use on Windows.\nE.g.</p>\n\n<pre><code>recode utf16..utf8 text.txt\n</code></pre>\n"
},
{
"answer_id": 55801894,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 3,
"selected": false,
"text": "<p>You can do this easily with built-in PowerShell cmdlets, which you can invoke from cmd:</p>\n<pre><code>C:\\> powershell -c "Get-Content mytext.txt | Set-Content -Encoding utf8 mytext_utf8.txt"\n</code></pre>\n<p>Edit: obviously if you're already in powershell, this would be simplified. Using aliases would also simplify things:</p>\n<pre><code>> gc mytext.txt | sc -Encoding utf8 mytext_utf8.txt\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5363/"
] |
what is the best way to convert a UTF-16 files to UTF-8? I need to use this in a cmd script.
|
There is a GNU tool [recode](http://www.gnu.org/software/recode/recode.html) which you can also use on Windows.
E.g.
```
recode utf16..utf8 text.txt
```
|
265,371 |
<p>I'm working on an app that takes data from our DB and outputs an xml file using the FOR XML AUTO, ELEMENTS on the end of the generated query, followed by an XSLT to transform it the way we want. However in a particular case where we are generating some data using an sql scalar function, it always puts that element into a sub-table node named the same as the table node it's already in (so say it's a table xyz, it'd be <code>print("<xyz><node1></node1><xyz><generated-node-from-function></generated-node-from-function></xyz>");</code></p>
<p>No matter what I try (even directly manipulating a copy of the sql as generated by the app) it always seems to create this extra node layer, which causes problems later when we try to process this xml to extract the data later. Is there any particular property causing the xml generator in sql server to work this way, and is there any way to prevent it so I can keep the generated data node on the same level as the rest of the data for the table it's associated with?</p>
<p>Edit: renamed columns/tables in some cases but otherwise should be the same sql.</p>
<pre><code>SELECT * FROM (SELECT column1,column2,column3,iduser,jstart,jstop,jbatchperiod,jinactive,processed,column4,lock,column5,batchticketmicr,machineid,sjobopex,szopexrefid,jreceived,jstartopex,jstopopex,idspecialmicr,idp2batchoriginal,stateflags,bcrossrefid,bidentifier1,bidentifier2,bidentifier3,bidentifier4,bidentifier5,idexport,idimport,rsahash FROM table1) table1
LEFT JOIN (SELECT column21,ienvelope,isort,column1,idtemplate,processed,column4,lock,envelopetypecode,szqueuesvisitedunique,exportdate,jcompleted,status,ipriority,idbankaccount,iprioritybeforerzbump,fstoredrecondata,cscountyid,column10,column11,checkbox1,checkbox2,column12,column13,column14,xxxempfein,column15,column16,originalenvelopeid,column17,column18,xxxoag,trackingnumber,csldc,ecrossrefid,postmark,routingflags,eidentifier1,eidentifier2,eidentifier3,eidentifier4,eidentifier5,idexport FROM envelope) envelope ON table1.column1=Envelope.column1
LEFT JOIN (SELECT column21,column22,isort,column23,processed,side,pagetypecode,rawmicrline,rawscanline,rawbarcode,exportid,szlocandconf,szlocandconfpagefields,idformtemplate,szparms,rawmarksense,audittrail,audittrailelectronic,pixheight,pixwidth,ocrattemptcounter,idspecialmicr,idpageexception,pagemodifierflags,column10,csldc,rejectdate,rejectuser,rejectqueue,fsupervisorreject,xxxempno,xxxtraceno,xxxemplcnt,checkbox1,keyword,templatealtered,templateflags,pidentifier1,pidentifier2,pidentifier3,pidentifier4,pidentifier5,isscanlinevalid,idexport,clickcount FROM Table2) Table2 ON Envelope.column21=Page.column21
LEFT JOIN (select column22, column21, dbo.Fileimagepath(column21, column22) as path from Table2) Fileimg ON Table2.column21=FileImg.column21 AND Table2.column22=FileImg.column22
WHERE Envelope.column21 = 8
FOR XML AUTO, ELEMENTS
</code></pre>
<p>Another edit: basically FileImg's results are getting wrapped in an extra set of Table2 tags inside existing table2 tab with the rest of the data.</p>
<p>Yet another Edit: Testing against another database with the same sql it worked correctly, it appears there is a bad setting in my database or the stored proc is different <em>goes to investigate farther</em>.</p>
<p>If that doesn't work I'll try some of the other suggestions above, thanks for the help so far :)</p>
|
[
{
"answer_id": 265640,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 1,
"selected": false,
"text": "<p>I would try to get rid of the sub query parts \"(SELECT...\" and do regular joins, like:</p>\n\n<pre><code>SELECT table1.column1, table1.column2, ..., envelope.column21, ...\nFROM table1 LEFT JOIN envelope on table1.column1 = envelope.column1 ...\nWHERE envelope.column21 = 8\nFOR XML AUTO, ELEMENTS \n</code></pre>\n\n<p>To be clearer I ommitted most of your columns and joins. Just insert the columns you need and the njoins which are necessary.</p>\n\n<p>Does this return you the right XML or am I missing the point? </p>\n"
},
{
"answer_id": 265744,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 1,
"selected": false,
"text": "<p>I can't reproduce it with one of my functions (I tried to do it the same way you do it). </p>\n\n<p>But I have a suspicion: is there a SELECT query in the <code>FileImagePath</code> function which isn't used for the final result? Maybe this creates the artifact you are experiencing?</p>\n\n<p>Try to insert</p>\n\n<pre><code>return 'test'\n</code></pre>\n\n<p>as first line of the function <em>(if you can do that in your development database - or if you're the only one using that function)</em>. And see, if the behaviour changes.</p>\n"
},
{
"answer_id": 265751,
"author": "Valerion",
"author_id": 16156,
"author_profile": "https://Stackoverflow.com/users/16156",
"pm_score": 1,
"selected": false,
"text": "<p>Have a look at FOR XML EXPLICIT - it's more complicated but you define the structure as you want it.</p>\n"
},
{
"answer_id": 279536,
"author": "Runevault",
"author_id": 3326,
"author_profile": "https://Stackoverflow.com/users/3326",
"pm_score": 1,
"selected": true,
"text": "<p>Doing some further reserach, as of now it appears running a db in 2000 compat mode while on a 2005 sql server this problem is created, will not pin this until confirmed.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3326/"
] |
I'm working on an app that takes data from our DB and outputs an xml file using the FOR XML AUTO, ELEMENTS on the end of the generated query, followed by an XSLT to transform it the way we want. However in a particular case where we are generating some data using an sql scalar function, it always puts that element into a sub-table node named the same as the table node it's already in (so say it's a table xyz, it'd be `print("<xyz><node1></node1><xyz><generated-node-from-function></generated-node-from-function></xyz>");`
No matter what I try (even directly manipulating a copy of the sql as generated by the app) it always seems to create this extra node layer, which causes problems later when we try to process this xml to extract the data later. Is there any particular property causing the xml generator in sql server to work this way, and is there any way to prevent it so I can keep the generated data node on the same level as the rest of the data for the table it's associated with?
Edit: renamed columns/tables in some cases but otherwise should be the same sql.
```
SELECT * FROM (SELECT column1,column2,column3,iduser,jstart,jstop,jbatchperiod,jinactive,processed,column4,lock,column5,batchticketmicr,machineid,sjobopex,szopexrefid,jreceived,jstartopex,jstopopex,idspecialmicr,idp2batchoriginal,stateflags,bcrossrefid,bidentifier1,bidentifier2,bidentifier3,bidentifier4,bidentifier5,idexport,idimport,rsahash FROM table1) table1
LEFT JOIN (SELECT column21,ienvelope,isort,column1,idtemplate,processed,column4,lock,envelopetypecode,szqueuesvisitedunique,exportdate,jcompleted,status,ipriority,idbankaccount,iprioritybeforerzbump,fstoredrecondata,cscountyid,column10,column11,checkbox1,checkbox2,column12,column13,column14,xxxempfein,column15,column16,originalenvelopeid,column17,column18,xxxoag,trackingnumber,csldc,ecrossrefid,postmark,routingflags,eidentifier1,eidentifier2,eidentifier3,eidentifier4,eidentifier5,idexport FROM envelope) envelope ON table1.column1=Envelope.column1
LEFT JOIN (SELECT column21,column22,isort,column23,processed,side,pagetypecode,rawmicrline,rawscanline,rawbarcode,exportid,szlocandconf,szlocandconfpagefields,idformtemplate,szparms,rawmarksense,audittrail,audittrailelectronic,pixheight,pixwidth,ocrattemptcounter,idspecialmicr,idpageexception,pagemodifierflags,column10,csldc,rejectdate,rejectuser,rejectqueue,fsupervisorreject,xxxempno,xxxtraceno,xxxemplcnt,checkbox1,keyword,templatealtered,templateflags,pidentifier1,pidentifier2,pidentifier3,pidentifier4,pidentifier5,isscanlinevalid,idexport,clickcount FROM Table2) Table2 ON Envelope.column21=Page.column21
LEFT JOIN (select column22, column21, dbo.Fileimagepath(column21, column22) as path from Table2) Fileimg ON Table2.column21=FileImg.column21 AND Table2.column22=FileImg.column22
WHERE Envelope.column21 = 8
FOR XML AUTO, ELEMENTS
```
Another edit: basically FileImg's results are getting wrapped in an extra set of Table2 tags inside existing table2 tab with the rest of the data.
Yet another Edit: Testing against another database with the same sql it worked correctly, it appears there is a bad setting in my database or the stored proc is different *goes to investigate farther*.
If that doesn't work I'll try some of the other suggestions above, thanks for the help so far :)
|
Doing some further reserach, as of now it appears running a db in 2000 compat mode while on a 2005 sql server this problem is created, will not pin this until confirmed.
|
265,398 |
<p>I have an application that uses <code>window.open()</code> to generate dynamic popups. Unfortunately, I've had trouble creating the content of the new windows using the standard DOM functions (<code>createElement</code>, <code>appendChild</code>), and I've gone to using <code>document.write()</code> to generate the page.</p>
<p>Concretely, how can I go from this:</p>
<pre><code>function writePopup()
{
var popup = window.open("", "popup", "height=400px, width=400px");
var doc = popup.document;
doc.write("<html>");
doc.write("<head>");
doc.write("<title>Written Popup</title>");
doc.write("</head>");
doc.write("<body>");
doc.write("<p>Testing Write</p>");
doc.write("</body>");
doc.write("</html>");
doc.close();
}
</code></pre>
<p>To a function that creates the same popup using the DOM? </p>
<p>Edit: I did consider using an absolutely positioned element to simulate a popup, and though it looks better, the users need to be able to print the information being shown.</p>
|
[
{
"answer_id": 265409,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": true,
"text": "<p>Why not use a library function such as <a href=\"http://plugins.jquery.com/project/modaldialog\" rel=\"nofollow noreferrer\">http://plugins.jquery.com/project/modaldialog</a> instead of reinventing the wheel?</p>\n\n<p>[EDIT] OR</p>\n\n<pre><code>function writePopup(){\n var popup = window.open(\"\", \"_blank\", \"height=400px, width=400px\");\n var doc = popup.document;\n doc.title = 'Written Popup';\n\n var p = doc.createElement('p');\n p.innerHTML = 'Testing Write';\n doc.body.appendChild(p);\n}\n</code></pre>\n"
},
{
"answer_id": 265416,
"author": "Wes P",
"author_id": 13611,
"author_profile": "https://Stackoverflow.com/users/13611",
"pm_score": 0,
"selected": false,
"text": "<p>Would it be possible to have another page that generates the dynamic content, and pop it open, passing arguments that identify the content you want generated, instead of trying to write to a new window?</p>\n"
},
{
"answer_id": 265521,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 2,
"selected": false,
"text": "<p>Just doing quick tests, I can get doc to append DOM created HTML to my popup like so:</p>\n\n<pre><code>var popup = window.open(\"\", \"popup\", \"height=400px, width=400px\"); \nvar doc = popup.document.documentElement;\nvar p = document.createElement(\"p\"); \np.innerHTML = \"blah\"; \ndoc.appendChild(p);\n</code></pre>\n\n<p>My example produces totally invalid HTML I know, but it works (with limited testing obviously).</p>\n"
},
{
"answer_id": 265540,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 2,
"selected": false,
"text": "<p>One dump of .innerHTML should perform better than a zillion lines of document.write();</p>\n\n<p>I would build up the DOM as needed and dump in using</p>\n\n<pre><code>doc.innerHTML = newDOM;\n</code></pre>\n\n<p>Still kind of hacky, but better than document.write();</p>\n"
},
{
"answer_id": 541456,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>I've gone to using document.write() to generate the page.</p>\n</blockquote>\n\n<p>I think you will probably have to use at least some document.write(), to put a skeleton page in place before you can interact with the DOM:</p>\n\n<pre><code>doc.write('<!DOCTYPE ...><html><head></head><body></body></html>');\ndoc.close();\ndoc.body.appendChild(...);\n</code></pre>\n\n<p>Before write() has been called, a new window's document is in an indeterminate state, there is no document yet to interact with. Firefox at least puts a temporary skeleton document in until you first call document.write(), but I can't see that this is actually documented anywhere so it's probably best not relied upon.</p>\n\n<blockquote>\n <p>var popup = window.open(\"\", \"popup\", \"height=400px, width=400px\");</p>\n</blockquote>\n\n<p>No ‘px’ unit needed in window.open.</p>\n"
},
{
"answer_id": 4012095,
"author": "tmim",
"author_id": 263123,
"author_profile": "https://Stackoverflow.com/users/263123",
"pm_score": 0,
"selected": false,
"text": "<p>you could use something like</p>\n\n<pre><code>function writePopup(){\n var htmlString=[\n \"<html>\",\n \"<head>\",\n \"<title>Written popup</title>\",\n \"</head><body>\",\n \"<p>Testing write</p>\",\n \"</body></html>\"\n ].join(\"\\n\");\n window.open(\"data:text/html,\"+encodeURIComponent(htmlString), \"_blank\", \"height=400px, width=400px\");\n}\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32771/"
] |
I have an application that uses `window.open()` to generate dynamic popups. Unfortunately, I've had trouble creating the content of the new windows using the standard DOM functions (`createElement`, `appendChild`), and I've gone to using `document.write()` to generate the page.
Concretely, how can I go from this:
```
function writePopup()
{
var popup = window.open("", "popup", "height=400px, width=400px");
var doc = popup.document;
doc.write("<html>");
doc.write("<head>");
doc.write("<title>Written Popup</title>");
doc.write("</head>");
doc.write("<body>");
doc.write("<p>Testing Write</p>");
doc.write("</body>");
doc.write("</html>");
doc.close();
}
```
To a function that creates the same popup using the DOM?
Edit: I did consider using an absolutely positioned element to simulate a popup, and though it looks better, the users need to be able to print the information being shown.
|
Why not use a library function such as <http://plugins.jquery.com/project/modaldialog> instead of reinventing the wheel?
[EDIT] OR
```
function writePopup(){
var popup = window.open("", "_blank", "height=400px, width=400px");
var doc = popup.document;
doc.title = 'Written Popup';
var p = doc.createElement('p');
p.innerHTML = 'Testing Write';
doc.body.appendChild(p);
}
```
|
265,403 |
<p>I'm using jQuery to handle all my ajax needs for an ASP.NET site coded in VB. When I use the built in $.ajax function to POST to a code-behind function and there is an exception, it simply exits the function, and shows an error on the client side.</p>
<p>Besides making debugging difficult when coding, the bigger issue is that the Application_Error function in Global.asax isn't firing when those exceptions occur. This is making it almost impossible to track production errors.</p>
<p>Why would it not bubble up to Application_Error? Is the answer to wrap the code-behind function in a Catch statement?</p>
<p>jQuery ajax function:</p>
<pre><code>$.ajax({
type: "POST",
url: "page.aspx/GetData",
data: "{'param':'" + param_value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
processData(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus + " - " + errorThrown);
}
});
</code></pre>
<p>VB.NET function:</p>
<pre><code><Script.Services.ScriptMethod()> _
<WebMethod()> _
Public Shared Function GetData(ByVal param As Integer) As String
'Parse some data
Return data
End Function
</code></pre>
|
[
{
"answer_id": 265792,
"author": "Martin",
"author_id": 11481,
"author_profile": "https://Stackoverflow.com/users/11481",
"pm_score": 0,
"selected": false,
"text": "<p>With .Net 3.5 you can pull in the <a href=\"http://www.asp.net/Ajax/Documentation/Live/overview/ScriptManagerOverview.aspx\" rel=\"nofollow noreferrer\">ScriptManager object</a> and register your javascript with it, this allows .Net to manage the scripts (it's not jsut for MS Ajax, it works with third party libraries), this could be a solution.</p>\n"
},
{
"answer_id": 350284,
"author": "Josiah I.",
"author_id": 12322,
"author_profile": "https://Stackoverflow.com/users/12322",
"pm_score": 1,
"selected": false,
"text": "<p>I figured out a work around. Although I did not find a way to directly get the error to fire the Application_Error event, I discovered a property on the jQuery XMLHttpRequest object that contains the actual exception text.</p>\n\n<p>Here is an example that will show the error in an alert:</p>\n\n<pre><code>error: function(XMLHttpRequest, textStatus, errorThrown) {\n alert(\"Error: \" + XMLHttpRequest.responseText);\n}\n</code></pre>\n\n<p>Another idea is to submit the error via AJAX to a web method that will handle all the error event logic.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12322/"
] |
I'm using jQuery to handle all my ajax needs for an ASP.NET site coded in VB. When I use the built in $.ajax function to POST to a code-behind function and there is an exception, it simply exits the function, and shows an error on the client side.
Besides making debugging difficult when coding, the bigger issue is that the Application\_Error function in Global.asax isn't firing when those exceptions occur. This is making it almost impossible to track production errors.
Why would it not bubble up to Application\_Error? Is the answer to wrap the code-behind function in a Catch statement?
jQuery ajax function:
```
$.ajax({
type: "POST",
url: "page.aspx/GetData",
data: "{'param':'" + param_value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
processData(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus + " - " + errorThrown);
}
});
```
VB.NET function:
```
<Script.Services.ScriptMethod()> _
<WebMethod()> _
Public Shared Function GetData(ByVal param As Integer) As String
'Parse some data
Return data
End Function
```
|
I figured out a work around. Although I did not find a way to directly get the error to fire the Application\_Error event, I discovered a property on the jQuery XMLHttpRequest object that contains the actual exception text.
Here is an example that will show the error in an alert:
```
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + XMLHttpRequest.responseText);
}
```
Another idea is to submit the error via AJAX to a web method that will handle all the error event logic.
|
265,410 |
<p>This is a generic way to select data from a table and show the results in an HTML table using JSP taglibs. What is the generic way to do this in Grails? That is, take a few lines of SQL and generate an HTML table from scratch in Grails, including the column names as headers.</p>
<pre>
<sql:query var="results" dataSource="${dsource}">
select * from foo
</sql:query>
(# of rows: ${results.rowCount})
<table border="1">
<!-- column headers -->
<tr bgcolor=cyan>
<c:forEach var="columnName" items="${results.columnNames}">
<th><c:out value="${columnName}"/></th>
</c:forEach>
</tr>
<!-- column data -->
<c:forEach var="row" items="${results.rowsByIndex}">
<tr>
<c:forEach var="column" items="${row}">
<td><c:out value="${column}"/></td>
</c:forEach>
</tr>
</c:forEach>
</table>
</pre>
|
[
{
"answer_id": 265848,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 0,
"selected": false,
"text": "<p>You could use the taglib as described. You just need to make Grails aware of it.</p>\n"
},
{
"answer_id": 266608,
"author": "Daniel Honig",
"author_id": 1129162,
"author_profile": "https://Stackoverflow.com/users/1129162",
"pm_score": 2,
"selected": false,
"text": "<p>This question could be rephrased as, how do I write code like a naive ASP.NET developer?\n(Not all ASP.NET developers are naive, some can be quite good)</p>\n\n<ol>\n<li>Any static method is available to you in a gsp page. You can use any MyDomain.findBy, list(), count you want from page scope.</li>\n<li><p>You could also use a criteria query MyDomain.createCriteria()\nYou can then pass the result to a taglib.</p>\n\n<p>But all of this seems to violate MVC principles. Your view should just be a view....</p></li>\n</ol>\n\n<p>What you asked really isn't idomatic to a grails application. I realize it is commonplace in the Microsoft world, execute a query, pass it to a datagrid....But there is no direct analouge in Grails and probably for good reason</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
This is a generic way to select data from a table and show the results in an HTML table using JSP taglibs. What is the generic way to do this in Grails? That is, take a few lines of SQL and generate an HTML table from scratch in Grails, including the column names as headers.
```
<sql:query var="results" dataSource="${dsource}">
select * from foo
</sql:query>
(# of rows: ${results.rowCount})
<table border="1">
<!-- column headers -->
<tr bgcolor=cyan>
<c:forEach var="columnName" items="${results.columnNames}">
<th><c:out value="${columnName}"/></th>
</c:forEach>
</tr>
<!-- column data -->
<c:forEach var="row" items="${results.rowsByIndex}">
<tr>
<c:forEach var="column" items="${row}">
<td><c:out value="${column}"/></td>
</c:forEach>
</tr>
</c:forEach>
</table>
```
|
This question could be rephrased as, how do I write code like a naive ASP.NET developer?
(Not all ASP.NET developers are naive, some can be quite good)
1. Any static method is available to you in a gsp page. You can use any MyDomain.findBy, list(), count you want from page scope.
2. You could also use a criteria query MyDomain.createCriteria()
You can then pass the result to a taglib.
But all of this seems to violate MVC principles. Your view should just be a view....
What you asked really isn't idomatic to a grails application. I realize it is commonplace in the Microsoft world, execute a query, pass it to a datagrid....But there is no direct analouge in Grails and probably for good reason
|
265,423 |
<p>I have to build an HTML table that shows data for users versus pages visited. It seems klunky to use for and/or foreach loops, but I can't think of anything better. I'm using PHP, but I would assume that this is language agnostic.</p>
|
[
{
"answer_id": 265437,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>Well, if you have multiple rows, with data formatted similarly in each row, I can't think of a way to create a table that avoids using a loop. That type of thing is basically what loops were invented for.</p>\n\n<p>If you gave us more details on the table you want to build, maybe we can formulate a better method.</p>\n"
},
{
"answer_id": 265439,
"author": "Gareth",
"author_id": 31582,
"author_profile": "https://Stackoverflow.com/users/31582",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't use <em>some</em> kind of loop then you need to hardcode the number of rows and columns in your code, which is probably a much worse idea</p>\n"
},
{
"answer_id": 265441,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 2,
"selected": false,
"text": "<p>If the data in the table is dynamic then you have to use a loop. Even if you get a component that generates the table for you, internally it will use a loop.</p>\n"
},
{
"answer_id": 265447,
"author": "Maxam",
"author_id": 15310,
"author_profile": "https://Stackoverflow.com/users/15310",
"pm_score": 1,
"selected": false,
"text": "<p>That depends on your definition of \"best\". FOR loops will do the job just fine. I'm not a PHP programmer, but in .NET, you can use the Repeater, a sort of template that you can use to declare the table HTML. It has templates for the header, the footer and each item. You bind a data source to the repeater, and it will generate the table HTML for you a bit more elegantly than using FOR loops. I imagine there might be some sort of templating equivalent in PHP.</p>\n\n<p>In the end, though, even the Repeater uses some sort of loop...</p>\n"
},
{
"answer_id": 265461,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": true,
"text": "<p>Avoiding loops is probably not possible, if not in implementation, then it will still happen at machine level. </p>\n\n<p>However, if you want to try stay 'pure' without nasty code, you can at least do: </p>\n\n<pre><code>$tableformat = '<table><thead>%s</thead><tbody>%s</tbody></table>';\n$rowformat = '<tr>%s</tr>'; \n$cellformat = '<td>%s</td>'; \n\n$hdata = '';\nforeach( $data[0] as $cellname => $cellvalue )\n{\n $hdata .= sprintf( $cellformat, $cellname ); \n}\n$hdata = sprintf( $rowformat, $hdata ); \n$rdata = \"\";\nforeach( $data as $rownum => $rowvalue ) \n{ \n $row = \"\";\n foreach( $rowvalue as $colname => $colvalue ) \n {\n $row .= sprintf( $cellformat, $colvalue ); \n }\n $rdata .= sprintf($rowformat,$row); \n}\nreturn sprintf( $tableformat, $hdata, $rdata ); \n</code></pre>\n\n<p>At least that way it might be somewhat maintainable. and you don't have much worry about incomplete strings. </p>\n\n<p>You could also subsitutue some of that code with </p>\n\n<pre><code> $hdata = \"<tr><td>\" . implode( \"</td><td>\", array_keys( $data[0] )) . \"</td></tr>\";\n $rdata .= \"<tr><td>\" . implode( \"</td><td>\", $rowvalue ) . \"</td></tr>\"; \n</code></pre>\n\n<p>Which while being rather concise, will possibly get you in a bit of hot water eventually and it will need recoding. ( and implode internally runs a loop, so its a lose-lose ).</p>\n\n<p>If you don't mind the over head of extra function calls ( and still running loops ) this could make for more concise code without too many negatives: </p>\n\n<pre><code> $tableformat = '<table><thead>%s</thead><tbody>%s</tbody></table>';\n $rowformat = '<tr>%s</tr>'; \n $cellformat = '<td>%s</td>'; \n\nfunction tr( $cells )\n{ \n $o = \"\";\n foreach( $cells as $i => $v )\n { \n $o .= sprintf( $cellformat, $v ); \n }\n return sprintf( $rowformat, $o ); \n}\n\n\nreturn sprintf( $tableformat, \n tr( array_keys($data[0])), \n implode(\"\", array_map( 'tr', $data )) ); \n</code></pre>\n\n<p>But beware, thats hard to read, and you keep that up one day you'll wake up with lisp. </p>\n"
},
{
"answer_id": 265577,
"author": "rmeador",
"author_id": 10861,
"author_profile": "https://Stackoverflow.com/users/10861",
"pm_score": 2,
"selected": false,
"text": "<p>I highly recommend the <a href=\"http://www.smarty.net/\" rel=\"nofollow noreferrer\">Smarty</a> templating engine for PHP. This will permit you to move your table (and the associated loop, which is unavoidable) into the template using Smarty syntax, so it will be clearer and more separated from your business logic. You would be able to replace nearly all the code in your example with a few simple tags in an HTML snippet. Check out the crash course on the Smarty page for an example of using a table.</p>\n"
},
{
"answer_id": 265623,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": -1,
"selected": false,
"text": "<p>I usually use loops and <code>implode</code> for this, in PHP. In a language, which supports functional programming I would do it differently.</p>\n\n<pre><code>function render_table($data) {\n $html = '<table>';\n $tr = array();\n foreach (array_keys($data[0]) as $key) {\n $tr[] = '<th>' . htmlspecialchars($key) . '</th>';\n }\n $html .= \"\\n\" . '<thead>' . \"\\n\" . '<tr>' . \"\\n\" . implode(\"\\n\", $tr) . '</tr>' . '</thead>';\n $tbody = array();\n foreach ($data as $row) {\n $tr = array();\n foreach ($row as $value) {\n $tr[] = '<td>' . htmlspecialchars($value) . '</td>';\n }\n $tbody[] = '<tr>' . \"\\n\" . implode(\"\\n\", $tr) . '</tr>';\n }\n $html .= \"\\n\" . '<tbody>' . \"\\n\" . implode(\"\\n\", $tbody) . '</tbody>';\n $html .= '</table>';\n return $html;\n}\n</code></pre>\n"
},
{
"answer_id": 266390,
"author": "Hugh Bothwell",
"author_id": 33258,
"author_profile": "https://Stackoverflow.com/users/33258",
"pm_score": 0,
"selected": false,
"text": "<p>Why do you want to avoid loops? If you have a set of items, and you want to display each item, surely looping over the set is the obvious solution?</p>\n\n<p>If you are trying to separate the model from the view, or write more readable code, good; but loops are not inherently bad.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
I have to build an HTML table that shows data for users versus pages visited. It seems klunky to use for and/or foreach loops, but I can't think of anything better. I'm using PHP, but I would assume that this is language agnostic.
|
Avoiding loops is probably not possible, if not in implementation, then it will still happen at machine level.
However, if you want to try stay 'pure' without nasty code, you can at least do:
```
$tableformat = '<table><thead>%s</thead><tbody>%s</tbody></table>';
$rowformat = '<tr>%s</tr>';
$cellformat = '<td>%s</td>';
$hdata = '';
foreach( $data[0] as $cellname => $cellvalue )
{
$hdata .= sprintf( $cellformat, $cellname );
}
$hdata = sprintf( $rowformat, $hdata );
$rdata = "";
foreach( $data as $rownum => $rowvalue )
{
$row = "";
foreach( $rowvalue as $colname => $colvalue )
{
$row .= sprintf( $cellformat, $colvalue );
}
$rdata .= sprintf($rowformat,$row);
}
return sprintf( $tableformat, $hdata, $rdata );
```
At least that way it might be somewhat maintainable. and you don't have much worry about incomplete strings.
You could also subsitutue some of that code with
```
$hdata = "<tr><td>" . implode( "</td><td>", array_keys( $data[0] )) . "</td></tr>";
$rdata .= "<tr><td>" . implode( "</td><td>", $rowvalue ) . "</td></tr>";
```
Which while being rather concise, will possibly get you in a bit of hot water eventually and it will need recoding. ( and implode internally runs a loop, so its a lose-lose ).
If you don't mind the over head of extra function calls ( and still running loops ) this could make for more concise code without too many negatives:
```
$tableformat = '<table><thead>%s</thead><tbody>%s</tbody></table>';
$rowformat = '<tr>%s</tr>';
$cellformat = '<td>%s</td>';
function tr( $cells )
{
$o = "";
foreach( $cells as $i => $v )
{
$o .= sprintf( $cellformat, $v );
}
return sprintf( $rowformat, $o );
}
return sprintf( $tableformat,
tr( array_keys($data[0])),
implode("", array_map( 'tr', $data )) );
```
But beware, thats hard to read, and you keep that up one day you'll wake up with lisp.
|
265,449 |
<p>I've got a minidump file from a crash in one of our apps. It's a 32-bit native app, and it was running on 64-bit Windows.</p>
<p>If I load the minidump file into WinDbg, WinDbg won't load the symbols for the system DLLs. I've got my symbol paths configured correctly:</p>
<pre><code>_NT_SYMBOL_PATH=SRV*C:\WebSymbols*http://msdl.microsoft.com/download/symbols
</code></pre>
<p>...because WinDbg correctly loads symbols for minidumps created on 32-bit Windows. It just won't load symbols for DLLs in the SysWOW64 directory.</p>
<p>I've tried 32-bit WinDbg (from Debugging Tools 6.9) on 32-bit Windows 2003, and 64-bit WinDbg (also from Debugging Tools 6.9) on 64-bit Windows 2008. Both fail to load the symbols. This is from the 32-bit WinDbg:</p>
<pre>0:014> !sym noisy
noisy mode - symbol prompts on
0:014> .reload
....................................................................................
Loading unloaded module list
..
SYMSRV: C:\WebSymbols\ntdll.dll\48E714D0170000\ntdll.dll not found
SYMSRV: http://msdl.microsoft.com/download/symbols/ntdll.dll/48E714D0170000/ntdll.dll not found
DBGENG: C:\Windows\SysWOW64\ntdll.dll - Couldn't map image from disk.
Unable to load image C:\Windows\SysWOW64\ntdll.dll, Win32 error 0n2
DBGENG: ntdll.dll - Partial symbol image load missing image info
DBGHELP: Module is not fully loaded into memory.
DBGHELP: Searching for symbols using debugger-provided data.
SYMSRV: C:\WebSymbols\wntdll.pdb\6686D0C5D0554E14953396093DA218A92\wntdll.pdb not found
SYMSRV: http://msdl.microsoft.com/download/symbols/wntdll.pdb/6686D0C5D0554E14953396093DA218A92/wntdll.pdb not found
DBGHELP: wntdll.pdb - file not found
*** WARNING: Unable to verify timestamp for ntdll.dll
*** ERROR: Module load completed but symbols could not be loaded for ntdll.dll
DBGHELP: ntdll - no symbols loaded
SYMSRV: C:\WebSymbols\kernel32.dll\48E7156Cf0000\kernel32.dll not found
SYMSRV: http://msdl.microsoft.com/download/symbols/kernel32.dll/48E7156Cf0000/kernel32.dll not found
DBGENG: C:\Windows\SysWOW64\kernel32.dll - Couldn't map image from disk.
Unable to load image C:\Windows\SysWOW64\kernel32.dll, Win32 error 0n2
DBGENG: kernel32.dll - Partial symbol image load missing image info
DBGHELP: Module is not fully loaded into memory.
DBGHELP: Searching for symbols using debugger-provided data.
SYMSRV: C:\WebSymbols\wkernel32.pdb\B0C3B36CC7EF4F3E9C168E186A5A6FEB2\wkernel32.pdb not found
SYMSRV: http://msdl.microsoft.com/download/symbols/wkernel32.pdb/B0C3B36CC7EF4F3E9C168E186A5A6FEB2/wkernel32.pdb not found
DBGHELP: wkernel32.pdb - file not found
*** WARNING: Unable to verify timestamp for kernel32.dll
*** ERROR: Module load completed but symbols could not be loaded for kernel32.dll
DBGHELP: kernel32 - no symbols loaded
SYMSRV: C:\WebSymbols\KERNELBASE.dll\48E7156D5a000\KERNELBASE.dll not found
SYMSRV: http://msdl.microsoft.com/download/symbols/KERNELBASE.dll/48E7156D5a000/KERNELBASE.dll not found
DBGENG: C:\Windows\SysWOW64\KERNELBASE.dll - Couldn't map image from disk.
DBGENG: KERNELBASE.dll - Partial symbol image load missing image info
DBGHELP: Module is not fully loaded into memory.
DBGHELP: Searching for symbols using debugger-provided data.
SYMSRV: C:\WebSymbols\wkernelbase.pdb\A8683F0C515F469B833E3FA562E0DB251\wkernelbase.pdb not found
SYMSRV: http://msdl.microsoft.com/download/symbols/wkernelbase.pdb/A8683F0C515F469B833E3FA562E0DB251/wkernelbase.pdb not found
DBGHELP: wkernelbase.pdb - file not found
*** WARNING: Unable to verify timestamp for KERNELBASE.dll
*** ERROR: Module load completed but symbols could not be loaded for KERNELBASE.dll
DBGHELP: KERNELBASE - no symbols loaded</pre>
<p>Any ideas? Are the symbols just not available on Microsoft's symbol server?</p>
|
[
{
"answer_id": 265488,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 3,
"selected": false,
"text": "<p>Are you debugging on a 32-bit or 64-bit system, and with the 32 or 64-bit version of WinDBG? You typically have to debug on the same architecture package you took the dump from:</p>\n\n<p><a href=\"http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx\" rel=\"noreferrer\"><a href=\"http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx\" rel=\"noreferrer\">http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx</a></a></p>\n\n<blockquote>\n <p>\"The 32-bit version of Debugging Tools for Windows is the best choice, unless you are debugging an application on a 64-bit processor. In that case, you should use a 64-bit package.\"</p>\n</blockquote>\n\n<p>Also, take a look at this article where he is debugging a 32-bit app running on a 64-bit platform:</p>\n\n<p><a href=\"http://blogs.msdn.com/alejacma/archive/2008/07/18/How-to-use-Windbg-to-debug-a-dump-of-a-32bit-.NET-app-running-on-a-x64-machine.aspx\" rel=\"noreferrer\"><a href=\"http://blogs.msdn.com/alejacma/archive/2008/07/18/How-to-use-Windbg-to-debug-a-dump-of-a-32bit-.NET-app-running-on-a-x64-machine.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/alejacma/archive/2008/07/18/How-to-use-Windbg-to-debug-a-dump-of-a-32bit-.NET-app-running-on-a-x64-machine.aspx</a></a></p>\n"
},
{
"answer_id": 1553015,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Consider the workaround mentionned here where syswo64\\ntdll.dll is copied to Syswow64\\ntdll32.dll</p>\n\n<p><a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98781&wa=wsignin1.0\" rel=\"nofollow noreferrer\">https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98781&wa=wsignin1.0</a></p>\n\n<p>Works for me.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446/"
] |
I've got a minidump file from a crash in one of our apps. It's a 32-bit native app, and it was running on 64-bit Windows.
If I load the minidump file into WinDbg, WinDbg won't load the symbols for the system DLLs. I've got my symbol paths configured correctly:
```
_NT_SYMBOL_PATH=SRV*C:\WebSymbols*http://msdl.microsoft.com/download/symbols
```
...because WinDbg correctly loads symbols for minidumps created on 32-bit Windows. It just won't load symbols for DLLs in the SysWOW64 directory.
I've tried 32-bit WinDbg (from Debugging Tools 6.9) on 32-bit Windows 2003, and 64-bit WinDbg (also from Debugging Tools 6.9) on 64-bit Windows 2008. Both fail to load the symbols. This is from the 32-bit WinDbg:
```
0:014> !sym noisy
noisy mode - symbol prompts on
0:014> .reload
....................................................................................
Loading unloaded module list
..
SYMSRV: C:\WebSymbols\ntdll.dll\48E714D0170000\ntdll.dll not found
SYMSRV: http://msdl.microsoft.com/download/symbols/ntdll.dll/48E714D0170000/ntdll.dll not found
DBGENG: C:\Windows\SysWOW64\ntdll.dll - Couldn't map image from disk.
Unable to load image C:\Windows\SysWOW64\ntdll.dll, Win32 error 0n2
DBGENG: ntdll.dll - Partial symbol image load missing image info
DBGHELP: Module is not fully loaded into memory.
DBGHELP: Searching for symbols using debugger-provided data.
SYMSRV: C:\WebSymbols\wntdll.pdb\6686D0C5D0554E14953396093DA218A92\wntdll.pdb not found
SYMSRV: http://msdl.microsoft.com/download/symbols/wntdll.pdb/6686D0C5D0554E14953396093DA218A92/wntdll.pdb not found
DBGHELP: wntdll.pdb - file not found
*** WARNING: Unable to verify timestamp for ntdll.dll
*** ERROR: Module load completed but symbols could not be loaded for ntdll.dll
DBGHELP: ntdll - no symbols loaded
SYMSRV: C:\WebSymbols\kernel32.dll\48E7156Cf0000\kernel32.dll not found
SYMSRV: http://msdl.microsoft.com/download/symbols/kernel32.dll/48E7156Cf0000/kernel32.dll not found
DBGENG: C:\Windows\SysWOW64\kernel32.dll - Couldn't map image from disk.
Unable to load image C:\Windows\SysWOW64\kernel32.dll, Win32 error 0n2
DBGENG: kernel32.dll - Partial symbol image load missing image info
DBGHELP: Module is not fully loaded into memory.
DBGHELP: Searching for symbols using debugger-provided data.
SYMSRV: C:\WebSymbols\wkernel32.pdb\B0C3B36CC7EF4F3E9C168E186A5A6FEB2\wkernel32.pdb not found
SYMSRV: http://msdl.microsoft.com/download/symbols/wkernel32.pdb/B0C3B36CC7EF4F3E9C168E186A5A6FEB2/wkernel32.pdb not found
DBGHELP: wkernel32.pdb - file not found
*** WARNING: Unable to verify timestamp for kernel32.dll
*** ERROR: Module load completed but symbols could not be loaded for kernel32.dll
DBGHELP: kernel32 - no symbols loaded
SYMSRV: C:\WebSymbols\KERNELBASE.dll\48E7156D5a000\KERNELBASE.dll not found
SYMSRV: http://msdl.microsoft.com/download/symbols/KERNELBASE.dll/48E7156D5a000/KERNELBASE.dll not found
DBGENG: C:\Windows\SysWOW64\KERNELBASE.dll - Couldn't map image from disk.
DBGENG: KERNELBASE.dll - Partial symbol image load missing image info
DBGHELP: Module is not fully loaded into memory.
DBGHELP: Searching for symbols using debugger-provided data.
SYMSRV: C:\WebSymbols\wkernelbase.pdb\A8683F0C515F469B833E3FA562E0DB251\wkernelbase.pdb not found
SYMSRV: http://msdl.microsoft.com/download/symbols/wkernelbase.pdb/A8683F0C515F469B833E3FA562E0DB251/wkernelbase.pdb not found
DBGHELP: wkernelbase.pdb - file not found
*** WARNING: Unable to verify timestamp for KERNELBASE.dll
*** ERROR: Module load completed but symbols could not be loaded for KERNELBASE.dll
DBGHELP: KERNELBASE - no symbols loaded
```
Any ideas? Are the symbols just not available on Microsoft's symbol server?
|
Are you debugging on a 32-bit or 64-bit system, and with the 32 or 64-bit version of WinDBG? You typically have to debug on the same architecture package you took the dump from:
[<http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx>](http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx)
>
> "The 32-bit version of Debugging Tools for Windows is the best choice, unless you are debugging an application on a 64-bit processor. In that case, you should use a 64-bit package."
>
>
>
Also, take a look at this article where he is debugging a 32-bit app running on a 64-bit platform:
[<http://blogs.msdn.com/alejacma/archive/2008/07/18/How-to-use-Windbg-to-debug-a-dump-of-a-32bit-.NET-app-running-on-a-x64-machine.aspx>](http://blogs.msdn.com/alejacma/archive/2008/07/18/How-to-use-Windbg-to-debug-a-dump-of-a-32bit-.NET-app-running-on-a-x64-machine.aspx)
|
265,478 |
<p>I have some HTML and jQuery that slides a <code>div</code> up and down to show or hide` it when a link is clicked:</p>
<pre class="lang-html prettyprint-override"><code><ul class="product-info">
<li>
<a href="#">YOU CLICK THIS TO SHOW/HIDE</a>
<div class="toggle">
<p>CONTENT TO SHOW/HIDE</p>
</div>
</li>
</ul>
</code></pre>
<pre class="lang-js prettyprint-override"><code>$('div.toggle').hide();
$('ul.product-info li a').click(function(event){
$(this).next('div').slideToggle(200);
}
</code></pre>
<p>My question is: How do I use <code>preventDefault()</code> to stop the link acting as a link and adding "#" to the end of my URL & jumping to the top of the page?</p>
<p>I can't figure out the right syntax, I just keep getting an error saying </p>
<blockquote>
<p>preventDefault() is not a function.</p>
</blockquote>
|
[
{
"answer_id": 265499,
"author": "Davide Gualano",
"author_id": 28582,
"author_profile": "https://Stackoverflow.com/users/28582",
"pm_score": 9,
"selected": true,
"text": "<p>Try something like:</p>\n\n<pre><code>$('div.toggle').hide();\n$('ul.product-info li a').click(function(event) {\n event.preventDefault();\n $(this).next('div').slideToggle(200);\n});\n</code></pre>\n\n<p>Here is the page about that in the <a href=\"http://learn.jquery.com/events/event-basics/#preventdefault\" rel=\"noreferrer\">jQuery documentation</a></p>\n"
},
{
"answer_id": 265583,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 4,
"selected": false,
"text": "<p>Alternatively, you could just return false from the click event: </p>\n\n<pre><code> $('div.toggle').hide();\n $('ul.product-info li a').click(function(event){\n $(this).next('div').slideToggle(200);\n+ return false; \n });\n</code></pre>\n\n<p>Which would stop the A-Href being triggered. </p>\n\n<p>Note however, for usability reasons, in an ideal world that href should still go somewhere, for the people whom want to open link in new tab ;)</p>\n"
},
{
"answer_id": 832570,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Why not just do it in css? </p>\n\n<p>Take out the 'href' attribute in your anchor tag</p>\n\n<pre><code><ul class=\"product-info\">\n <li>\n <a>YOU CLICK THIS TO SHOW/HIDE</a>\n <div class=\"toggle\">\n <p>CONTENT TO SHOW/HIDE</p>\n </div>\n </li>\n</ul>\n</code></pre>\n\n<p>In your css,</p>\n\n<pre><code> a{\n cursor: pointer;\n }\n</code></pre>\n"
},
{
"answer_id": 6188520,
"author": "sebarmeli",
"author_id": 506570,
"author_profile": "https://Stackoverflow.com/users/506570",
"pm_score": 3,
"selected": false,
"text": "<p>If stopping the propagation of the event doesn't bother you, just use </p>\n\n<pre><code>return false;\n</code></pre>\n\n<p>at the end of your handler. In jQuery it prevents the default behaviour and it stop the event bubbling.</p>\n"
},
{
"answer_id": 7061847,
"author": "Ryan Little",
"author_id": 786216,
"author_profile": "https://Stackoverflow.com/users/786216",
"pm_score": 5,
"selected": false,
"text": "<p>It's suggested that you do not use <code>return false</code>, as 3 things occur as a result:</p>\n\n<ol>\n<li>event.preventDefault();</li>\n<li>event.stopPropagation();</li>\n<li>Stops callback execution and returns immediately when called.</li>\n</ol>\n\n<p>So in this type of situation, you should really only use <code>event.preventDefault();</code></p>\n\n<p><a href=\"https://web.archive.org/web/20160603125641/http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/\" rel=\"noreferrer\">Archive of article - <strong>jQuery Events: Stop (Mis)Using Return False</strong></a></p>\n"
},
{
"answer_id": 9299864,
"author": "Jefrey Bulla",
"author_id": 1140099,
"author_profile": "https://Stackoverflow.com/users/1140099",
"pm_score": 4,
"selected": false,
"text": "<p>This is a non-JQuery solution I just tested and it works. </p>\n\n<pre><code><html lang=\"en\">\n<head>\n<script type=\"text/javascript\">\naddEventListener(\"load\",function(){\n var links= document.getElementsByTagName(\"a\");\n for (var i=0;i<links.length;i++){\n links[i].addEventListener(\"click\",function(e){\n alert(\"NOPE!, I won't take you there haha\");\n //prevent event action\n e.preventDefault();\n })\n }\n}); \n\n</script>\n</head>\n<body>\n<div>\n<ul>\n <li><a href=\"http://www.google.com\">Google</a></li>\n <li><a href=\"http://www.facebook.com\">Facebook</a></li>\n <p id=\"p1\">Paragraph</p>\n</ul>\n</div>\n<p>By Jefrey Bulla</p>\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 10478514,
"author": "Musaddiq Khan",
"author_id": 1304924,
"author_profile": "https://Stackoverflow.com/users/1304924",
"pm_score": 6,
"selected": false,
"text": "<p>Set the <strong><code>href</code></strong> attribute as <code>href=\"javascript:;\"</code> </p>\n\n<pre><code><ul class=\"product-info\">\n <li>\n <a href=\"javascript:;\">YOU CLICK THIS TO SHOW/HIDE</a>\n <div class=\"toggle\">\n <p>CONTENT TO SHOW/HIDE</p>\n </div>\n </li>\n</ul>\n</code></pre>\n"
},
{
"answer_id": 20963186,
"author": "HATCHA",
"author_id": 1510985,
"author_profile": "https://Stackoverflow.com/users/1510985",
"pm_score": 4,
"selected": false,
"text": "<pre><code><ul class=\"product-info\">\n <li>\n <a href=\"javascript:void(0);\">YOU CLICK THIS TO SHOW/HIDE</a>\n <div class=\"toggle\">\n <p>CONTENT TO SHOW/HIDE</p>\n </div>\n </li>\n</ul>\n</code></pre>\n\n<p>Use </p>\n\n<blockquote>\n <p>javascript:void(0);</p>\n</blockquote>\n"
},
{
"answer_id": 21549336,
"author": "1nstinct",
"author_id": 2467036,
"author_profile": "https://Stackoverflow.com/users/2467036",
"pm_score": 3,
"selected": false,
"text": "<p>After several operations, when the page should finally go to <code><a href"..."></code> link you can do the following:</p>\n<pre><code>jQuery("a").click(function(e){\n var self = jQuery(this);\n var href = self.attr('href');\n e.preventDefault();\n // needed operations\n\n window.location = href;\n});\n</code></pre>\n"
},
{
"answer_id": 40193846,
"author": "RPichioli",
"author_id": 5885146,
"author_profile": "https://Stackoverflow.com/users/5885146",
"pm_score": 2,
"selected": false,
"text": "<p>You can make use of <code>return false;</code> from the event call to stop the event propagation, it acts like an <code>event.preventDefault();</code> negating it. Or you can use <code>javascript:void(0)</code> in href attribute to evaluate the given expression and then return <code>undefined</code> to the element.</p>\n\n<p>Returning the event when it's called:</p>\n\n<pre><code><a href=\"\" onclick=\"return false;\"> ... </a>\n</code></pre>\n\n<p>Void case:</p>\n\n<pre><code><a href=\"javascript:void(0);\"> ... </a>\n</code></pre>\n\n<p>You can see more about in: <a href=\"https://stackoverflow.com/questions/40048143/whats-the-effect-of-adding-void0-for-href-and-return-false-on-click-event-l/40048197#40048197\">What's the effect of adding void(0) for href and 'return false' on click event listener of anchor tag?</a></p>\n"
},
{
"answer_id": 48447130,
"author": "A-Sharabiani",
"author_id": 4505446,
"author_profile": "https://Stackoverflow.com/users/4505446",
"pm_score": 5,
"selected": false,
"text": "<p>1 - Easy way:</p>\n<pre><code><a href="javascript:;">Click Me</a>\n</code></pre>\n<p>2 - using void(0):</p>\n<pre><code><a href="javascript:void(0);">Click Me</a>\n</code></pre>\n<p>3 - Using <code>preventDefault()</code>:</p>\n<pre><code><a href='#' onclick="event.preventDefault()">Click Me</a>\n</code></pre>\n<p>4 - Yet another way of doing this in Javascript using <code>inline onclick</code>, <code>IIFE</code>, <code>event</code> and <code>preventDefault()</code>:</p>\n<pre><code><a href='#' onclick="(function(e){e.preventDefault();})(event)">Click Me</a>\n</code></pre>\n"
},
{
"answer_id": 69134018,
"author": "Md Afsar Uddin",
"author_id": 7453228,
"author_profile": "https://Stackoverflow.com/users/7453228",
"pm_score": 2,
"selected": false,
"text": "<p>In <strong>Javascript</strong> you can use it</p>\n<pre><code>window.event.preventDefault();\n</code></pre>\n<p>It works in my case. write the above line into your function.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
I have some HTML and jQuery that slides a `div` up and down to show or hide` it when a link is clicked:
```html
<ul class="product-info">
<li>
<a href="#">YOU CLICK THIS TO SHOW/HIDE</a>
<div class="toggle">
<p>CONTENT TO SHOW/HIDE</p>
</div>
</li>
</ul>
```
```js
$('div.toggle').hide();
$('ul.product-info li a').click(function(event){
$(this).next('div').slideToggle(200);
}
```
My question is: How do I use `preventDefault()` to stop the link acting as a link and adding "#" to the end of my URL & jumping to the top of the page?
I can't figure out the right syntax, I just keep getting an error saying
>
> preventDefault() is not a function.
>
>
>
|
Try something like:
```
$('div.toggle').hide();
$('ul.product-info li a').click(function(event) {
event.preventDefault();
$(this).next('div').slideToggle(200);
});
```
Here is the page about that in the [jQuery documentation](http://learn.jquery.com/events/event-basics/#preventdefault)
|
265,481 |
<p>We moved our Visual C++ 2003 solution to Visual 2005 and now we have problems deploying to clean XP machines.</p>
<p>Our solution has a DLL project and a command line executable which uses this DLL. Both projects create and embed manifest files.</p>
<p>Our installer also copies the VC8 CRT runtimes from the C:\Programme\Microsoft Visual Studio 8\VC\redist\x86\Microsoft.VC80.CRT\ to the install dir.</p>
<p>When we install on a clean Windows XP, we see the error message "Application has failed to start ... application configuration is incorrect."</p>
<p>Putting the exe in Depends.exe, says:</p>
<pre><code>Error: The Side-by-Side configuration information for "c:\program files\MySoftware\vc8\BENCHMARK.EXE" contains errors. This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem (14001).
Error: The Side-by-Side configuration information for "c:\program files\MySoftware\vc8\MYLIB-VC8.DLL" contains errors. This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem (14001).
Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module.
</code></pre>
<p>Event viewer logs:</p>
<pre><code>Dependent Assembly Microsoft.VC80.CRT could not be found and Last Error was The referenced assembly is not installed on your system.
Resolve Partial Assembly failed for Microsoft.VC80.CRT. Reference error message: The referenced assembly is not installed on your system.
Generate Activation Context failed for C:\Program Files\MySoftware\vc8\Benchmark.exe. Reference error message: The operation completed successfully.
</code></pre>
<p>I've read copying the msvcp80.dll,msvcr80.dll,msvcm80.dll and Microsoft.VC80.CRT.manifest to application folder is sufficient.</p>
<p>What am I doing wrong ?</p>
|
[
{
"answer_id": 265520,
"author": "Vinay",
"author_id": 28641,
"author_profile": "https://Stackoverflow.com/users/28641",
"pm_score": 2,
"selected": false,
"text": "<p>Select Visual Studio 2005 Merge modules in the installer.\nThis can also occur if you have built the exe/dll using visual studio which has service pack installed.</p>\n"
},
{
"answer_id": 265555,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 4,
"selected": true,
"text": "<p>Copying the CRT dlls around is not recommended. As Vinay says you should use the correct merge modules.</p>\n\n<p>You can also use the redist install exe's if merge modules don't work with your installer technology:</p>\n\n<ul>\n<li><a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=32BC1BEE-A3F9-4C13-9C99-220B62A191EE&displaylang=en\" rel=\"noreferrer\">VS2005 CRT</a></li>\n<li><a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=200b2fd9-ae1a-4a14-984d-389c36f85647&displaylang=en\" rel=\"noreferrer\">VS2005 SP1 CRT</a></li>\n</ul>\n\n<p>As a last resort try copying the entire 'Microsoft.VC80.CRT' directory to your programs exe directory (not the contents, the actual directory).</p>\n"
},
{
"answer_id": 265804,
"author": "Tim",
"author_id": 10755,
"author_profile": "https://Stackoverflow.com/users/10755",
"pm_score": 2,
"selected": false,
"text": "<p>I had this problem as well. I was appalled at Microsoft for doing this to us.<br>\n(I used VC6 to build a particular project and then when I also installed 2003 and 2005 on the build machine it caused my VC6 build to have issues. (I was not checking installs on a pristine machine) Apparently the linker/compiler had no idea what it was doing so it caused problems with my distributable. I then had to add a HUGE redist install file to my 120k exe app. Freakin' microsoft.</p>\n\n<p>MS has screwed this up a few times in the past. </p>\n\n<p><a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=200B2FD9-AE1A-4A14-984D-389C36F85647&displaylang=en\" rel=\"nofollow noreferrer\">http://www.microsoft.com/downloads/details.aspx?familyid=200B2FD9-AE1A-4A14-984D-389C36F85647&displaylang=en</a></p>\n"
},
{
"answer_id": 331440,
"author": "gengmao",
"author_id": 70742,
"author_profile": "https://Stackoverflow.com/users/70742",
"pm_score": 2,
"selected": false,
"text": "<p>You don't really need the Microsoft's VC80 C Run-Time Library. It's a mess.</p>\n\n<p>Instead, relink your program with /MT option, which static links the c run-time library(libcmt.lib) or C++ Standard Library. To set this via the project properties, go to</p>\n\n<pre><code>C/C++ -> Code Generation -> Runtime Library: Multi-threaded (/MT)\n</code></pre>\n\n<p>If it doesn't compile, you may want to add this option as well (/NODEFAULTLIB:)</p>\n\n<pre><code>Linker -> Input -> Ignore Specific Library: msvcrt.lib\n</code></pre>\n\n<p>See the link options from <a href=\"http://msdn.microsoft.com/en-us/library/abx4dbyh(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/abx4dbyh(VS.80).aspx</a></p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23000/"
] |
We moved our Visual C++ 2003 solution to Visual 2005 and now we have problems deploying to clean XP machines.
Our solution has a DLL project and a command line executable which uses this DLL. Both projects create and embed manifest files.
Our installer also copies the VC8 CRT runtimes from the C:\Programme\Microsoft Visual Studio 8\VC\redist\x86\Microsoft.VC80.CRT\ to the install dir.
When we install on a clean Windows XP, we see the error message "Application has failed to start ... application configuration is incorrect."
Putting the exe in Depends.exe, says:
```
Error: The Side-by-Side configuration information for "c:\program files\MySoftware\vc8\BENCHMARK.EXE" contains errors. This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem (14001).
Error: The Side-by-Side configuration information for "c:\program files\MySoftware\vc8\MYLIB-VC8.DLL" contains errors. This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem (14001).
Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module.
```
Event viewer logs:
```
Dependent Assembly Microsoft.VC80.CRT could not be found and Last Error was The referenced assembly is not installed on your system.
Resolve Partial Assembly failed for Microsoft.VC80.CRT. Reference error message: The referenced assembly is not installed on your system.
Generate Activation Context failed for C:\Program Files\MySoftware\vc8\Benchmark.exe. Reference error message: The operation completed successfully.
```
I've read copying the msvcp80.dll,msvcr80.dll,msvcm80.dll and Microsoft.VC80.CRT.manifest to application folder is sufficient.
What am I doing wrong ?
|
Copying the CRT dlls around is not recommended. As Vinay says you should use the correct merge modules.
You can also use the redist install exe's if merge modules don't work with your installer technology:
* [VS2005 CRT](http://www.microsoft.com/downloads/details.aspx?familyid=32BC1BEE-A3F9-4C13-9C99-220B62A191EE&displaylang=en)
* [VS2005 SP1 CRT](http://www.microsoft.com/downloads/details.aspx?familyid=200b2fd9-ae1a-4a14-984d-389c36f85647&displaylang=en)
As a last resort try copying the entire 'Microsoft.VC80.CRT' directory to your programs exe directory (not the contents, the actual directory).
|
265,494 |
<p>I have a website which uses themes. Depending on the url (if it is A.something.com or B.something.com, where A and B represent clients), I will load a different theme. The intention is to use one codebase for different clients. I have an app_themes folder, several themes inside, for different clients, and different CSS files for each theme (for business reasons the CSS file is the same for each theme, but duplicated). So my code looks like this:</p>
<p>Public Overrides Property StyleSheetTheme() As String</p>
<pre><code> Get
Dim myHost As String = Request.Url.Host
Return myHost
End Get
Set(ByVal value As String)
End Set
End Property
Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
If Request.Url.Host.Contains("Savills") Then
Page.Theme = "Savills"
ElseIf Request.Url.Host.Contains("localhost") Then
Page.Theme = "localhost"
ElseIf Request.Url.Host.Contains("test.concepglobal.com") Then
Page.Theme = "test.concepglobal.com"
ElseIf Request.Url.Host.Contains("concepglobal") Then
Page.Theme = "concepglobal"
End If
End Sub
</code></pre>
<p>My app_themes folder structure:</p>
<p>App_Themes:</p>
<p>localhost:</p>
<p>Default.css</p>
<p>Savills</p>
<p>Savills.css</p>
<p>However, everytime I load the site, the css is not picked up. So I don't get the h1 style I designed in the css (it is in there), but only the graphics specified in the aspx page.</p>
<p>My source when running the site:</p>
<p> (loading the site at that url).</p>
<p>Confusingly, there is another link to the same css:</p>
<p></p>
<p>What am I doing wrong?</p>
<p>Thanks </p>
|
[
{
"answer_id": 265513,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 2,
"selected": false,
"text": "<p>Is this occurring only when you run the code from within Visual Studio? </p>\n\n<p>When running in ASP.Net Development Server, the styles in App_Themes won't be used on any unauthenticated page (such as Login.aspx or ForgotPassword.aspx). That's because the user doesn't have browse permissions on that folder yet, or the App_Themes folder lacks browsing permissions. Apparently, IIS handles this but Cassini doesn't.</p>\n\n<p>Try adding this to web.config to let Themes and styles work before authentication.</p>\n\n<pre><code><location path=\"App_Themes\">\n <system.web>\n <authorization>\n <allow users=\"?\" />\n </authorization>\n </system.web>\n </location>\n</code></pre>\n\n<p>Or, if possible, switch to running the app on IIS on your machine. </p>\n"
},
{
"answer_id": 272202,
"author": "Keltex",
"author_id": 28260,
"author_profile": "https://Stackoverflow.com/users/28260",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of doing this though code, you can specify the theme used by the application (or a folder) through your web.config:</p>\n\n<pre><code><system.web>\n <pages theme=\"concepglobal\"></pages>\n</system.web>\n</code></pre>\n\n<p>This assumes you have different web.config files for each client.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32484/"
] |
I have a website which uses themes. Depending on the url (if it is A.something.com or B.something.com, where A and B represent clients), I will load a different theme. The intention is to use one codebase for different clients. I have an app\_themes folder, several themes inside, for different clients, and different CSS files for each theme (for business reasons the CSS file is the same for each theme, but duplicated). So my code looks like this:
Public Overrides Property StyleSheetTheme() As String
```
Get
Dim myHost As String = Request.Url.Host
Return myHost
End Get
Set(ByVal value As String)
End Set
End Property
Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
If Request.Url.Host.Contains("Savills") Then
Page.Theme = "Savills"
ElseIf Request.Url.Host.Contains("localhost") Then
Page.Theme = "localhost"
ElseIf Request.Url.Host.Contains("test.concepglobal.com") Then
Page.Theme = "test.concepglobal.com"
ElseIf Request.Url.Host.Contains("concepglobal") Then
Page.Theme = "concepglobal"
End If
End Sub
```
My app\_themes folder structure:
App\_Themes:
localhost:
Default.css
Savills
Savills.css
However, everytime I load the site, the css is not picked up. So I don't get the h1 style I designed in the css (it is in there), but only the graphics specified in the aspx page.
My source when running the site:
(loading the site at that url).
Confusingly, there is another link to the same css:
What am I doing wrong?
Thanks
|
Is this occurring only when you run the code from within Visual Studio?
When running in ASP.Net Development Server, the styles in App\_Themes won't be used on any unauthenticated page (such as Login.aspx or ForgotPassword.aspx). That's because the user doesn't have browse permissions on that folder yet, or the App\_Themes folder lacks browsing permissions. Apparently, IIS handles this but Cassini doesn't.
Try adding this to web.config to let Themes and styles work before authentication.
```
<location path="App_Themes">
<system.web>
<authorization>
<allow users="?" />
</authorization>
</system.web>
</location>
```
Or, if possible, switch to running the app on IIS on your machine.
|
265,508 |
<p>I need a dropdown list on my page that will allow a user to select their state. Since this is probably a control that will be used elsewhere, I thought it would be a good idea to create an MVC View User Control that could be reused.</p>
<p>I was thinking the control would look something like this:</p>
<pre><code><select name="" id="">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>
</code></pre>
<p>And the code in my view would be something like:</p>
<pre><code><%= Html.RenderPartial("StateDropdownControl") %>
</code></pre>
<p>My question is, what's the best way to set the name and id on the control? I'd want to make sure I could have multiple instances of this control on one page, if needed. Also, I'd want to be able to send in the state that should be selected by default.</p>
<p>Would I do it with ViewData somehow?</p>
|
[
{
"answer_id": 265543,
"author": "Corey Gaudin",
"author_id": 31195,
"author_profile": "https://Stackoverflow.com/users/31195",
"pm_score": 2,
"selected": false,
"text": "<p>Well you can pass object data to the RenderPartial method in conjunction to the User Control to render, so you could easily do the following:</p>\n\n<p><Code></p>\n\n<pre><code><%= Html.RenderPartial(\"/someDirectory/SomeControl.ascx\", \"MyID\") %>\n</code></pre>\n\n<p>and in the UserControl do the following:</p>\n\n<pre><code><select name=\"<%=ViewData.Model%>\" id=\"<%=ViewData.Model%>\">\n\n....\n</code></pre>\n\n<p>Just to be sure, a better way to handle it is to make a simple DTO (data transfer object) to hold that information so you can pass more information to your user control, that you will inevitably need.</p>\n\n<p>Example:</p>\n\n<pre><code>\nclass ComboData \n{\n string ID {get;set;}\n string CssClass {get;set;}\n //Other stuff here\n}\n</code></pre>\n\n<pre><code>\n<%\nvar comboData = new ComboData {ID = \"myID\", CssClass = \"comboStyle\" }\n\n%>\n\n<%= Html.RenderPartial(\"/someDirectory/SomeControl.ascx\", comboData) %>\n</code></pre>\n\n<pre><select name=\"<%=ViewData.Model.ID%>\" id=\"<%=ViewData.Model.ID%>\" class=\"<%=ViewData.Model.CssClass%>\">\n\n....\n</code></pre>\n\n<p>Make sure you set the Code behind for the user control to be a generic of type ComboData for this example.</p>\n"
},
{
"answer_id": 265598,
"author": "CubanX",
"author_id": 27555,
"author_profile": "https://Stackoverflow.com/users/27555",
"pm_score": 4,
"selected": true,
"text": "<p>Corey is on to the right solution. I think declaring specific Model objects for your view makes the views VERY simple and as a side bonus makes them dirt easy to test.</p>\n\n<p>So instead of just passing the ID as the object, you'd probably want to create your own Model object to pass in.</p>\n\n<p>It could look something like this:</p>\n\n<pre><code>public class StateDropDownPresentationModel\n{\n public string DropDownID { get; set; }\n public string SelectedState { get; set; }\n}\n</code></pre>\n\n<p>Obviously, keep adding whatever you need to this model to make your view correct.</p>\n\n<p>Then, you could call it like this:</p>\n\n<pre><code><%= Html.RenderPartial(\"/someDirectory/SomeControl.ascx\", new StateDropDownPresentationModel { DropDownID = \"MyID\", SelectedState = \"IL\" } %>\n</code></pre>\n\n<p>Then just make sure you put in checks for things like ID being null/blank (that should probably throw an error) and SelectedState being null/blank.</p>\n"
},
{
"answer_id": 272617,
"author": "Matthew",
"author_id": 20162,
"author_profile": "https://Stackoverflow.com/users/20162",
"pm_score": 1,
"selected": false,
"text": "<p>Take a look at the Html.DropDownList helper method. It has a number of overloads that allow you to pass the list data and set the selected item. the simplest version just sets the name of the select. </p>\n\n<pre><code><%= Html.DropDownList(\"SelectStates\"); %>\n</code></pre>\n\n<p>If there is a value in the ViewData[\"SelectStates\"] that is of type MultiSelectList then the list will be automatically populated.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34720/"
] |
I need a dropdown list on my page that will allow a user to select their state. Since this is probably a control that will be used elsewhere, I thought it would be a good idea to create an MVC View User Control that could be reused.
I was thinking the control would look something like this:
```
<select name="" id="">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>
```
And the code in my view would be something like:
```
<%= Html.RenderPartial("StateDropdownControl") %>
```
My question is, what's the best way to set the name and id on the control? I'd want to make sure I could have multiple instances of this control on one page, if needed. Also, I'd want to be able to send in the state that should be selected by default.
Would I do it with ViewData somehow?
|
Corey is on to the right solution. I think declaring specific Model objects for your view makes the views VERY simple and as a side bonus makes them dirt easy to test.
So instead of just passing the ID as the object, you'd probably want to create your own Model object to pass in.
It could look something like this:
```
public class StateDropDownPresentationModel
{
public string DropDownID { get; set; }
public string SelectedState { get; set; }
}
```
Obviously, keep adding whatever you need to this model to make your view correct.
Then, you could call it like this:
```
<%= Html.RenderPartial("/someDirectory/SomeControl.ascx", new StateDropDownPresentationModel { DropDownID = "MyID", SelectedState = "IL" } %>
```
Then just make sure you put in checks for things like ID being null/blank (that should probably throw an error) and SelectedState being null/blank.
|
265,524 |
<p>We have a few applications that use the same Linq 2 SQL DataContext. One of those Apps wil do massive inserts (it's a convertor from an old system). Is it possible to change the UpdateCheck of the TimeStamp column of each table at runtime ? Only for this one app we'd like to set it to Never, all the other apps should have Always.</p>
|
[
{
"answer_id": 265582,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 1,
"selected": false,
"text": "<p>AFAIK you can not change it (at least with simple means) at runtime, because it is auto-generated as attribute in the properties of the domain classes. E.g.</p>\n\n<pre><code>[Column(Name=\"ITM_CREATE_DATE\", Storage=\"_ITM_CREATE_DATE\", DbType=\"DateTime NOT NULL\", UpdateCheck=UpdateCheck.Never)]\npublic System.DateTime CreationDate\n</code></pre>\n\n<p>A possible workaround (that I have never tried, so I don't know if it works) is to copy the <code><DataContext>.designer.cs</code> code in your single project, make the changes in the copy and use it without the designer.</p>\n"
},
{
"answer_id": 266046,
"author": "DamienG",
"author_id": 5720,
"author_profile": "https://Stackoverflow.com/users/5720",
"pm_score": 0,
"selected": false,
"text": "<p>UpdateCheck is not used for Insert operations, only for update.</p>\n"
},
{
"answer_id": 267883,
"author": "Jens",
"author_id": 34723,
"author_profile": "https://Stackoverflow.com/users/34723",
"pm_score": 0,
"selected": false,
"text": "<p>More Info about what I'm trying to do :</p>\n\n<p>I see this behaviour in the SQL Server profiler :</p>\n\n<p>exec sp_executesql N'INSERT INTO [dbo].[Test]([ID], [Data])\nVALUES (@p0, @p1)</p>\n\n<p><em>SELECT [t0].[timestamp]\nFROM [dbo].[Test] AS [t0]\nWHERE [t0].[ID] = @p2',N'@p0 uniqueidentifier,@p1 varchar(24),@p2 uniqueidentifier',@p0='EF0F12B9-825E-48A2-943A-B43E94BB00AA',@p1='tadaaa 20081106 08:41:01',@p2='EF0F12B9-825E-48A2-943A-B43E94BB00AA'</em> </p>\n\n<p>I'd like to prevent the SELECT part since this application only does INSERTS, I have a feeling that when inserting 100 000+ records, suppressing the SELECT [to].[timestamp] part might gain me a lot of performance ...</p>\n"
},
{
"answer_id": 685970,
"author": "Daniel Magliola",
"author_id": 3314,
"author_profile": "https://Stackoverflow.com/users/3314",
"pm_score": 0,
"selected": false,
"text": "<p>There's are several properties of the [Column] attribute that fire off that SELECT after the INSERT:</p>\n\n<ul>\n<li>AutoSync, which is Never by default, and is overridden by ISDBGenerated and ISDBVersion</li>\n<li>ISDBGenerated, which generates the behaviour you're describing.</li>\n<li>IsVersion, which means the field will be auto-updated every time you update/insert a record, and LINQ will also fetch the actual value after updating/inserting, resulting in the behaviour you describe.</li>\n</ul>\n\n<p>I'm not sure whether this applied to your particular situation, but is it possible to remove these attributes from the field that's troubling you, and setting it manually, instead of letting the DB set it by itself? (or at least, don't tell LINQ the DB will set it automatically, and LINQ won't SELECT after INSERT).</p>\n\n<p>This doesn't solve the actual question of fixing it for only one of the 2 projects. I'm also not sure whether LINQ stuff is done at runtime through reflection, or at compile time. If the magic is done at runtime, you <em>may</em> be able to remove the attribute with reflection and add it back, <em>maybe</em>, I don't really know.</p>\n\n<p>Disclaimer: All that I said is theoretical, I haven't tested all this stuff, and haven't had enough experience with LINQ.<br>\nJust my 2 cents.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34723/"
] |
We have a few applications that use the same Linq 2 SQL DataContext. One of those Apps wil do massive inserts (it's a convertor from an old system). Is it possible to change the UpdateCheck of the TimeStamp column of each table at runtime ? Only for this one app we'd like to set it to Never, all the other apps should have Always.
|
AFAIK you can not change it (at least with simple means) at runtime, because it is auto-generated as attribute in the properties of the domain classes. E.g.
```
[Column(Name="ITM_CREATE_DATE", Storage="_ITM_CREATE_DATE", DbType="DateTime NOT NULL", UpdateCheck=UpdateCheck.Never)]
public System.DateTime CreationDate
```
A possible workaround (that I have never tried, so I don't know if it works) is to copy the `<DataContext>.designer.cs` code in your single project, make the changes in the copy and use it without the designer.
|
265,528 |
<p>Many web sites support folksonomy tags. You may have heard of <a href="http://microformats.org/wiki/reltag" rel="nofollow noreferrer">rel-tag</a>, where it says that "The last path component of the URL is the text of the tag".</p>
<p>I am looking for a bookmarklet or greasemonkey script (javascript) to get the "last path component" for the URL currently being viewed in the browser, add that tag into another URL, and then open that page in a new tab or window.</p>
<p>For example, if I am looking at a <a href="http://delicious.com/popular/foo" rel="nofollow noreferrer">delicious.com page with the tag "foo"</a>, I may want to create <a href="http://technorati.com/tag/foo" rel="nofollow noreferrer">a new URL with the tag "foo"</a>. This should also work for multiple tags in the last path component, such as, <a href="http://delicious.com/popular/foo+bar" rel="nofollow noreferrer">foo+bar</a>.</p>
<p>Some <a href="http://microformats.org/discuss/mail/microformats-discuss/2008-June/012144.html" rel="nofollow noreferrer">regexp suggestions</a> have been offered.</p>
|
[
{
"answer_id": 321492,
"author": "Jan Goyvaerts",
"author_id": 33358,
"author_profile": "https://Stackoverflow.com/users/33358",
"pm_score": 0,
"selected": false,
"text": "<p>If you can assume both your URLs to be valid, you can get the tag from the first URL with this regex:</p>\n\n<pre><code>^[a-z]+://[^/#?]+/[^#?]*?([^#?/]+)(?:[#?]|$)\n</code></pre>\n\n<p>The first (and only) capturing group will hold the tag. This regex won't match URLs that don't have any tags.</p>\n\n<p>To append the tag to another URL, search for the regex:</p>\n\n<pre><code>^([^#?]*?)/?(?:[#?]|$)\n</code></pre>\n\n<p>and replace with:</p>\n\n<pre><code>$1/tag\n</code></pre>\n\n<p>This regex makes sure not to end up with two adjacent slashes in the URL if the path of the original URL ends with a slash.</p>\n"
},
{
"answer_id": 817324,
"author": "Peter Boughton",
"author_id": 9360,
"author_profile": "https://Stackoverflow.com/users/9360",
"pm_score": 3,
"selected": true,
"text": "<p>Since you're using JavaScript, there's no need to worry about hostnames, querystrings, etc - just use <code>location.pathname</code> to get at the important bit.</p>\n\n<p>For example:</p>\n\n<pre><code>var NewUrl = 'http://technorati.com/tag/';\nvar LastPart = location.pathname.match( /[^\\/]+\\/?$/ );\nwindow.open( NewUrl + LastPart );\n</code></pre>\n\n<p>That allows for a potential single trailing slash.</p>\n\n<p>You can use <code>/[^\\/]+\\$/</code> to disallow trailing slashes, or <code>/[^\\/]+\\/*$/</code> for any number of them.</p>\n"
},
{
"answer_id": 1701270,
"author": "kmirhfew",
"author_id": 206935,
"author_profile": "https://Stackoverflow.com/users/206935",
"pm_score": -1,
"selected": false,
"text": "<p>implementation, as in how the servers are set up, all that jazz? I'm not very knowledgeable about that stuff =\\ ahh that sounds</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31241/"
] |
Many web sites support folksonomy tags. You may have heard of [rel-tag](http://microformats.org/wiki/reltag), where it says that "The last path component of the URL is the text of the tag".
I am looking for a bookmarklet or greasemonkey script (javascript) to get the "last path component" for the URL currently being viewed in the browser, add that tag into another URL, and then open that page in a new tab or window.
For example, if I am looking at a [delicious.com page with the tag "foo"](http://delicious.com/popular/foo), I may want to create [a new URL with the tag "foo"](http://technorati.com/tag/foo). This should also work for multiple tags in the last path component, such as, [foo+bar](http://delicious.com/popular/foo+bar).
Some [regexp suggestions](http://microformats.org/discuss/mail/microformats-discuss/2008-June/012144.html) have been offered.
|
Since you're using JavaScript, there's no need to worry about hostnames, querystrings, etc - just use `location.pathname` to get at the important bit.
For example:
```
var NewUrl = 'http://technorati.com/tag/';
var LastPart = location.pathname.match( /[^\/]+\/?$/ );
window.open( NewUrl + LastPart );
```
That allows for a potential single trailing slash.
You can use `/[^\/]+\$/` to disallow trailing slashes, or `/[^\/]+\/*$/` for any number of them.
|
265,559 |
<p>When @RadioServiceGroup is set to NULL, I want to return all the records from the sbi_l_radioservicecodes table which has about 120 records. However, when I execute the following procedure and set the @RadioServiceGroup to NULL, it returns no records. Here is the stored proc:</p>
<pre><code>CREATE PROCEDURE [dbo].[GetRadioServiceCodes]
@RadioServiceGroup nvarchar(1000) = NULL
AS
BEGIN
IF(@RadioServiceGroup = NULL)
BEGIN
SELECT rsc.RadioService
FROM sbi_l_radioservicecodes rsc
END
ELSE
BEGIN
SELECT rsc.RadioService
FROM sbi_l_radioservicecodes rsc
WHERE rsc.RadioServiceGroup = @RadioServiceGroup
END
END
</code></pre>
|
[
{
"answer_id": 265565,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 5,
"selected": true,
"text": "<p>Try \"IS NULL\" instead of \"= NULL\"</p>\n"
},
{
"answer_id": 265569,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>You can cut out the <code>If</code> completely. Try this:</p>\n\n<pre><code>CREATE PROCEDURE [dbo].[GetRadioServiceCodes] \n@RadioServiceGroup nvarchar(1000) = NULL\nAS\nBEGIN \n SELECT rsc.RadioService\n FROM sbi_l_radioservicecodes rsc\n WHERE \n rsc.RadioServiceGroup = @RadioServiceGroup \n OR @RadioServiceGroup IS NULL\nEND\n</code></pre>\n\n<p>Make sure you add any necessary parentheses to group these if the where clause gets more complicated.</p>\n"
},
{
"answer_id": 265704,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Use \"IS NULL\" instead of \"= NULL\"</p>\n\n<p>Alternatively, to make \"= NULL\" work you can write \"SET ANSI_NULLS OFF\" before \"CREATE PROCEDURE\". </p>\n"
},
{
"answer_id": 266325,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Curious, is it just a syntax thing on why = does not work on nvarchar for NULL</p>\n</blockquote>\n\n<p>Some people are saying that NULL = NULL evaluates to false. This is wrong. NULL = NULL evaluates to NULL.</p>\n\n<p>The result (NULL) is not true, so the ELSE condition is run.</p>\n\n<p>See also : <a href=\"http://en.wikipedia.org/wiki/Sql_null#Three-valued_logic_.283VL.29\" rel=\"nofollow noreferrer\">ThreeValuedLogic on Wikipedia</a></p>\n\n<p>Another affect you should be aware of - Concatenation: NULL + @SomeVar evaluates to NULL. This can wipe out a computed string unexpectedly.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33690/"
] |
When @RadioServiceGroup is set to NULL, I want to return all the records from the sbi\_l\_radioservicecodes table which has about 120 records. However, when I execute the following procedure and set the @RadioServiceGroup to NULL, it returns no records. Here is the stored proc:
```
CREATE PROCEDURE [dbo].[GetRadioServiceCodes]
@RadioServiceGroup nvarchar(1000) = NULL
AS
BEGIN
IF(@RadioServiceGroup = NULL)
BEGIN
SELECT rsc.RadioService
FROM sbi_l_radioservicecodes rsc
END
ELSE
BEGIN
SELECT rsc.RadioService
FROM sbi_l_radioservicecodes rsc
WHERE rsc.RadioServiceGroup = @RadioServiceGroup
END
END
```
|
Try "IS NULL" instead of "= NULL"
|
265,563 |
<p>I'm using Windows CE Platform Builder and my code is written in C++ . For each of the folders in the project I'm creating a lib ( the code is statically linked ) . However , there are about 20 libs so far . Is there a way to reduce their number ? I was thinking of creating a lib from other libs , but I don't know if that's even possible . Is it ?</p>
<p><strong>EDIT:</strong> how could I do it ?</p>
|
[
{
"answer_id": 265580,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 3,
"selected": true,
"text": "<p>I haven't tried it in a while, but traditionally you could use the librarian tool (LIB.EXE) to do this sort of thing.</p>\n\n<pre>\n$ lib /?\nMicrosoft (R) Library Manager Version 8.00.50727.762\nCopyright (C) Microsoft Corporation. All rights reserved.\n\nusage: LIB [options] [files]\n\n options:\n\n /DEF[:filename]\n /ERRORREPORT:{NONE|PROMPT|QUEUE|SEND}\n /EXPORT:symbol\n /EXTRACT:membername\n /INCLUDE:symbol\n /LIBPATH:dir\n /LIST[:filename]\n /LTCG\n /MACHINE:{ARM|EBC|IA64|MIPS|MIPS16|MIPSFPU|MIPSFPU16|\n SH4|THUMB|X64|X86}\n /NAME:filename\n /NODEFAULTLIB[:library]\n /NOLOGO\n /OUT:filename\n /REMOVE:membername\n /SUBSYSTEM:{BOOT_APPLICATION|CONSOLE|EFI_APPLICATION|\n EFI_BOOT_SERVICE_DRIVER|EFI_ROM|EFI_RUNTIME_DRIVER|\n NATIVE|POSIX|WINDOWS|WINDOWSCE}[,#[.##]]\n /VERBOSE\n /WX[:NO]\n</pre>\n\n<p>Normally the librarian takes .OBJ files and combines them into a .LIB, but I think it will also read .LIB files as input.</p>\n"
},
{
"answer_id": 5064693,
"author": "fnz",
"author_id": 612621,
"author_profile": "https://Stackoverflow.com/users/612621",
"pm_score": 1,
"selected": false,
"text": "<p>as mentionet above, lib.exe can really merge a couple of lib files into one library, just put lib files into command line instead of obj files. few seconds ago i've tried it with a fortran lib and a c lib - everything works perfect </p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31610/"
] |
I'm using Windows CE Platform Builder and my code is written in C++ . For each of the folders in the project I'm creating a lib ( the code is statically linked ) . However , there are about 20 libs so far . Is there a way to reduce their number ? I was thinking of creating a lib from other libs , but I don't know if that's even possible . Is it ?
**EDIT:** how could I do it ?
|
I haven't tried it in a while, but traditionally you could use the librarian tool (LIB.EXE) to do this sort of thing.
```
$ lib /?
Microsoft (R) Library Manager Version 8.00.50727.762
Copyright (C) Microsoft Corporation. All rights reserved.
usage: LIB [options] [files]
options:
/DEF[:filename]
/ERRORREPORT:{NONE|PROMPT|QUEUE|SEND}
/EXPORT:symbol
/EXTRACT:membername
/INCLUDE:symbol
/LIBPATH:dir
/LIST[:filename]
/LTCG
/MACHINE:{ARM|EBC|IA64|MIPS|MIPS16|MIPSFPU|MIPSFPU16|
SH4|THUMB|X64|X86}
/NAME:filename
/NODEFAULTLIB[:library]
/NOLOGO
/OUT:filename
/REMOVE:membername
/SUBSYSTEM:{BOOT_APPLICATION|CONSOLE|EFI_APPLICATION|
EFI_BOOT_SERVICE_DRIVER|EFI_ROM|EFI_RUNTIME_DRIVER|
NATIVE|POSIX|WINDOWS|WINDOWSCE}[,#[.##]]
/VERBOSE
/WX[:NO]
```
Normally the librarian takes .OBJ files and combines them into a .LIB, but I think it will also read .LIB files as input.
|
265,585 |
<p>For example:</p>
<pre><code>public class A : A.B
{
public class B { }
}
</code></pre>
<p>Which generates this error from the compiler:</p>
<blockquote>
<p>Circular base class dependency
involving 'A' and 'A.B'</p>
</blockquote>
<p>I always figured a nested class behaved just like a regular class except with special rules concerning accessing the outer class's private members, but I guess there's some implicit inheritance occurring between the two classes?</p>
|
[
{
"answer_id": 265599,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": "<p>There's no implicit inheritance involved as far as I can tell. I would have expected this to be okay - although I can imagine weirdness if A and B were generic.</p>\n\n<p>It's specified in section 10.1.4 of the spec:</p>\n\n<blockquote>\n <p>When a class B derives from a class A,\n it is a compile-time error for A to\n depend on B. A class directly depends\n on its direct base class (if any) and\n <strong>directly depends on the class within\n which it is immediately nested</strong> (if\n any). Given this definition, the\n complete set of classes upon which a\n class depends is the transitive\n closure of the directly depends on\n relationship.</p>\n</blockquote>\n\n<p>I've highlighted the relevant section.</p>\n\n<p>That explains why the compiler is rejecting it, but not why the language prohibits it. I wonder if there's a CLI restriction...</p>\n\n<p>EDIT: Okay, I've had a response from Eric Lippert. Basically, it would be technically possible (there's nothing in the CLI to prohibit it), but:</p>\n\n<ul>\n<li>Allowing it would be difficult in the compiler, invalidating various current assumptions around ordering and cycles</li>\n<li>It's a pretty odd design decision which is easier to prohibit than to support</li>\n</ul>\n\n<p>It was also noted on the email thread that it would make this kind of thing valid:</p>\n\n<pre><code>A.B x = new A.B.B.B.B.B.B.B.B.B.B.B.B();\n</code></pre>\n\n<p>... but that would already (as noted by Tinister) be valid if B derived from A.</p>\n\n<p>Nesting + inheritance = oddness...</p>\n"
},
{
"answer_id": 265658,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": -1,
"selected": false,
"text": "<p>This makes no sense to me... You are trying to extend something that doesn't exist !!! Class B only exists in the scope of class A and because of this I think there is some kind of inheritance.</p>\n"
},
{
"answer_id": 265670,
"author": "Jeff Kotula",
"author_id": 1382162,
"author_profile": "https://Stackoverflow.com/users/1382162",
"pm_score": 0,
"selected": false,
"text": "<p>I think the nesting is meant to represent that the nested type is <em>part of the definition</em> of the nesting type. With that interpretation, the limitation makes sense because at the time the compiler hits the definition of A, A.B is not yet defined, and even at the end of A, it is already defined in terms of A.B.</p>\n"
},
{
"answer_id": 265672,
"author": "Whaledawg",
"author_id": 23829,
"author_profile": "https://Stackoverflow.com/users/23829",
"pm_score": 4,
"selected": false,
"text": "<p>This is not a C# thing as much as it is a compiler thing. One of the jobs of a compiler is to lay out a class in memory, that is a bunch of basic data types, pointers, function pointers and other classes. </p>\n\n<p>It can't construct the layout for class A until it knows what the layout of class B is. It can't know what the layout of class B is until it finished with the layout of class A. Circular dependency.</p>\n"
},
{
"answer_id": 265838,
"author": "Tinister",
"author_id": 34715,
"author_profile": "https://Stackoverflow.com/users/34715",
"pm_score": 1,
"selected": false,
"text": "<p>Regarding questions about what I was attempting to do:</p>\n\n<p>Basically, I wanted to create a class that had a composition relationship with itself, but I didn't want to have the contained object to contain other objects and therefore create a chain with many \"A has-a A has-a A has-a A has-a...\" relationships. So my thought at the time was do something like this:</p>\n\n<pre><code>public class A : A.AA\n{\n public class AA\n {\n // All of the class's logic\n }\n\n private AA _containedObject;\n}\n</code></pre>\n\n<p>Which at the time seemed pretty slick but in retrospect I'm not so sure...</p>\n\n<p>I had rummaged through Google and didn't find any good discussion on it so I thought I'd post it here.</p>\n\n<p>However, within the comments of a <a href=\"http://blogs.msdn.com/ericlippert/archive/2008/09/26/preventing-third-party-derivation-part-one.aspx\" rel=\"nofollow noreferrer\">post at Eric Lippert's Blog</a> he gives examples of a class implementing a nested interface as well as a class implementing a generic interface with a nested class as the type argument (which doesn't compile and he calls a \"bug\" in the current compiler). Both of those examples concern interfaces so I was wondering if there was some special rules with nested classes. And it seems there are.</p>\n"
},
{
"answer_id": 39197714,
"author": "Dave Cousineau",
"author_id": 621316,
"author_profile": "https://Stackoverflow.com/users/621316",
"pm_score": 0,
"selected": false,
"text": "<p>I was able to avoid this (at least with interfaces) by inheriting from a separate class containing the nested interfaces. (In my scenario I am also returning references to these interfaces.)</p>\n\n<p>Instead of:</p>\n\n<pre><code>public class MyClass<T1, T2, T3> :\n MyClass<T1, T2, T3>.Interface\nwhere T1 : ...\nwhere T2 : ... \nwhere T3 : ... {\n public interface Interface { Interface SomeMethod(); }\n\n Interface Interface.SomeMethod() {\n ...\n }\n}\n\n// compile error: Circular base class dependency\n</code></pre>\n\n<p>Do something like this:</p>\n\n<pre><code>public sealed class MyClassInterfaces<T1, T2, T3>\nwhere T1 : ...\nwhere T2 : ... \nwhere T3 : ... {\n public interface Interface { Interface SomeMethod(); }\n}\n\nsealed class MyClass<T1, T2, T3> :\n MyClassInterfaces<T1, T2, T3>.Interface\nwhere T1 : ...\nwhere T2 : ... \nwhere T3 : ... {\n MyClassInterfaces<T1, T2, T3>.Interface\n MyClassInterfaces<T1, T2, T3>.Interface.SomeMethod() {\n ...\n }\n}\n</code></pre>\n\n<p>To avoid the ugliness with explicit interface implementations, you can also inherit from the other class, though that wouldn't work if you were trying to inherit from a nested class, since you can't inherit from both classes.</p>\n\n<pre><code>public abstract class MyClassInterfaces<T1, T2, T3>\nwhere T1 : ...\nwhere T2 : ... \nwhere T3 : ... {\n public interface Interface { Interface SomeMethod(); }\n}\n\nsealed class MyClass<T1, T2, T3> :\n MyClassInterfaces<T1, T2, T3>,\n MyClassInterfaces<T1, T2, T3>.Interface\nwhere T1 : ...\nwhere T2 : ... \nwhere T3 : ... {\n Interface Interface.SomeMethod() {\n ...\n }\n}\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34715/"
] |
For example:
```
public class A : A.B
{
public class B { }
}
```
Which generates this error from the compiler:
>
> Circular base class dependency
> involving 'A' and 'A.B'
>
>
>
I always figured a nested class behaved just like a regular class except with special rules concerning accessing the outer class's private members, but I guess there's some implicit inheritance occurring between the two classes?
|
There's no implicit inheritance involved as far as I can tell. I would have expected this to be okay - although I can imagine weirdness if A and B were generic.
It's specified in section 10.1.4 of the spec:
>
> When a class B derives from a class A,
> it is a compile-time error for A to
> depend on B. A class directly depends
> on its direct base class (if any) and
> **directly depends on the class within
> which it is immediately nested** (if
> any). Given this definition, the
> complete set of classes upon which a
> class depends is the transitive
> closure of the directly depends on
> relationship.
>
>
>
I've highlighted the relevant section.
That explains why the compiler is rejecting it, but not why the language prohibits it. I wonder if there's a CLI restriction...
EDIT: Okay, I've had a response from Eric Lippert. Basically, it would be technically possible (there's nothing in the CLI to prohibit it), but:
* Allowing it would be difficult in the compiler, invalidating various current assumptions around ordering and cycles
* It's a pretty odd design decision which is easier to prohibit than to support
It was also noted on the email thread that it would make this kind of thing valid:
```
A.B x = new A.B.B.B.B.B.B.B.B.B.B.B.B();
```
... but that would already (as noted by Tinister) be valid if B derived from A.
Nesting + inheritance = oddness...
|
265,602 |
<p>I'm trying to create a simple Java application that displays a frame containing a JButton. I'm using JNI to add transparency to the window. The window is transparent but the button is not. Also, when I move the window the button doesn't move with the window. The same thing happens with a JLabel. If I use a Button instead of a JButton it works just fine.</p>
<p>Native code:</p>
<pre><code>#include <windows.h>
#include <jawt_md.h>
#include <jawt.h>
#include <jni.h>
// Don't mangle names for the JVM
extern "C" {
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
/**
* Gets the window handle for the Java window.
* Procedure for obtaining the handle:
* 1. Get the structure (JAWT) that contains the native methods.
* 2. Get the drawing surface (JAWT_DrawingSurface).
* 3. Using the drawing surface, get the drawing surface info (JAWT_DrawingSurfaceInfo).
* 4. Get the drawing info that's specific to Win32 (JAWT_Win32DrawingSurfaceInfo).
* 5. Using the drawing surface info, get the hwnd.
*/
/*
* Class: test_Transparency
* Method: getWindowHandle
* Signature: (Ljava/awt/Component;)J
*/
JNIEXPORT jlong JNICALL Java_test_Transparency_getWindowHandle
(JNIEnv * env, jclass cls, jobject component)
{
JAWT awt;
JAWT_DrawingSurface* ds;
JAWT_DrawingSurfaceInfo* dsi;
JAWT_Win32DrawingSurfaceInfo* dsi_win;
jint dsLock;
jboolean result = JNI_FALSE;
// Get the AWT
awt.version = JAWT_VERSION_1_4;
result = JAWT_GetAWT(env, &awt);
if ( result == JNI_FALSE )
{
printf( "%s:%i - JAWT_GetAWT() failed.\n", __FILE__, __LINE__ );
return 0;
}
// Get the drawing surface
ds = awt.GetDrawingSurface(env, component);
if ( ds == NULL )
{
printf( "%s:%i - GetDrawingSurface() failed.\n", __FILE__, __LINE__ );
return 0;
}
dsLock = ds->Lock(ds);
// Get the drawing surface info
dsi = ds->GetDrawingSurfaceInfo(ds);
// Get the platform-specific drawing info
dsi_win = (JAWT_Win32DrawingSurfaceInfo*)dsi->platformInfo;
HWND handle = dsi_win->hwnd;
ds->FreeDrawingSurfaceInfo(dsi);
ds->Unlock(ds);
awt.FreeDrawingSurface(ds);
return (jlong)handle;
}
void printLastError()
{
LPTSTR pszMessage;
DWORD dwLastError = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dwLastError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&pszMessage,
0, NULL );
// Display the error message
wprintf(L"failed with error %d: %s\n", dwLastError, pszMessage);
LocalFree(pszMessage);
}
/*
* Class: test_Transparency
* Method: setTransparency
* Signature: (JF)V
*/
JNIEXPORT void JNICALL Java_test_Transparency_setTransparency
(JNIEnv * env, jclass cls, jlong windowHandle, jfloat alpha)
{
HWND hwnd = (HWND)windowHandle;
// Get the current window style
LONG currentStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
if ( currentStyle == 0 )
{
printf( "Error calling GetWindowLong() ");
printLastError();
}
if ( alpha == 0 )
{
// No transparency.
// Remove WS_EX_LAYERED from this window style
SetWindowLong(hwnd, GWL_EXSTYLE, currentStyle & ~WS_EX_LAYERED);
}
else
{
// Calculate the transparency value. Should be in the range 0-255
unsigned char transparency = (unsigned char)(255 * alpha);
// Set window style to WS_EX_LAYERED. This is required for windows to be transparent.
SetWindowLong(hwnd, GWL_EXSTYLE, currentStyle | WS_EX_LAYERED );
// set the transparency level
SetLayeredWindowAttributes(hwnd, 0, transparency, LWA_ALPHA);
}
}
} // extern "C"
</code></pre>
<p>MyFrame.java</p>
<pre><code>package test;
import javax.swing.*;
import javax.swing.SwingUtilities;
import java.awt.event.*;
public class MyFrame implements ActionListener
{
private JFrame frame;
private Transparency trans; // = new Transparency();
private float t = 1.0f;
public MyFrame()
{
frame = new JFrame("My transparent window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds( 10, 10, 200, 200 );
JButton button = new JButton("My button");
button.setBounds( 20, 20, 50, 10 );
button.addActionListener( this );
JPanel panel = new JPanel();
panel.add( button );
frame.setContentPane( panel );
//Display the window.
frame.setVisible(true);
trans = new Transparency();
}
/**
* @param args
*/
public static void main( String[] args )
{
MyFrame f = new MyFrame();
}
public void actionPerformed(ActionEvent e)
{
t -= 0.05f;
trans.setWindowOpacity( frame, t );
}
}
</code></pre>
<p>Transparency.java</p>
<pre><code>package test;
import java.awt.Window;
import java.awt.Component;
public class Transparency
{
static boolean libLoaded = false;
/**
* Sets the transparency for a window.
* @param hwnd Handle for the window.
* @param opacity Transparency level, from 0.0 to 1.0.
* 1.0 is completely transparent. 0.0 is completely opaque.
*/
private static native void setTransparency( long hwnd, float opacity );
/**
* Get the window handle for the component.
* @param component
* @return HWND value obtained from the OS.
*/
private static native long getWindowHandle( Component component );
static
{
try
{
System.loadLibrary("transJNI");
libLoaded = true;
}
catch ( Exception e )
{
e.printStackTrace();
libLoaded = false;
}
}
/**
* @param window The window whose opacity will be adjusted.
* @param opacity The opacity level, from 0.0 (opaque) to 1.0 (completely transparent).
*/
public void setWindowOpacity(Window window, float opacity)
{
if ( !libLoaded )
{
return;
}
if ( !window.isVisible() )
{
return;
}
long hwnd = getWindowHandle( window );
setTransparency(hwnd, opacity);
}
}
</code></pre>
|
[
{
"answer_id": 265630,
"author": "johnstok",
"author_id": 27929,
"author_profile": "https://Stackoverflow.com/users/27929",
"pm_score": 0,
"selected": false,
"text": "<p>You may have more success with <a href=\"https://github.com/twall/jna/\" rel=\"nofollow noreferrer\">JNA</a>, and in particular their <a href=\"https://github.com/twall/jna/javadoc/com/sun/jna/examples/WindowUtils.html\" rel=\"nofollow noreferrer\">Window utils</a>.</p>\n"
},
{
"answer_id": 266081,
"author": "Swapnonil Mukherjee",
"author_id": 11602,
"author_profile": "https://Stackoverflow.com/users/11602",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.teamdev.com/winpack/features.jsf\" rel=\"nofollow noreferrer\">Team Dev's Winpack.</a></p>\n\n<p>Try it out. Looks interesting to me.</p>\n"
},
{
"answer_id": 266102,
"author": "Davide",
"author_id": 25891,
"author_profile": "https://Stackoverflow.com/users/25891",
"pm_score": 0,
"selected": false,
"text": "<p>SwingX has many transparent features, I'm not 100% sure that it will fit your needs, but give it a try! swinglabs.org</p>\n"
},
{
"answer_id": 269369,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "<p>6u10 supports <a href=\"http://java.sun.com/developer/technicalArticles/GUI/translucent_shaped_windows/\" rel=\"nofollow noreferrer\">transparent windows</a> through an unofficial API. 6u10 is available for download through java.com and previous JDK versions will update to it or a later update soon.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22386/"
] |
I'm trying to create a simple Java application that displays a frame containing a JButton. I'm using JNI to add transparency to the window. The window is transparent but the button is not. Also, when I move the window the button doesn't move with the window. The same thing happens with a JLabel. If I use a Button instead of a JButton it works just fine.
Native code:
```
#include <windows.h>
#include <jawt_md.h>
#include <jawt.h>
#include <jni.h>
// Don't mangle names for the JVM
extern "C" {
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
/**
* Gets the window handle for the Java window.
* Procedure for obtaining the handle:
* 1. Get the structure (JAWT) that contains the native methods.
* 2. Get the drawing surface (JAWT_DrawingSurface).
* 3. Using the drawing surface, get the drawing surface info (JAWT_DrawingSurfaceInfo).
* 4. Get the drawing info that's specific to Win32 (JAWT_Win32DrawingSurfaceInfo).
* 5. Using the drawing surface info, get the hwnd.
*/
/*
* Class: test_Transparency
* Method: getWindowHandle
* Signature: (Ljava/awt/Component;)J
*/
JNIEXPORT jlong JNICALL Java_test_Transparency_getWindowHandle
(JNIEnv * env, jclass cls, jobject component)
{
JAWT awt;
JAWT_DrawingSurface* ds;
JAWT_DrawingSurfaceInfo* dsi;
JAWT_Win32DrawingSurfaceInfo* dsi_win;
jint dsLock;
jboolean result = JNI_FALSE;
// Get the AWT
awt.version = JAWT_VERSION_1_4;
result = JAWT_GetAWT(env, &awt);
if ( result == JNI_FALSE )
{
printf( "%s:%i - JAWT_GetAWT() failed.\n", __FILE__, __LINE__ );
return 0;
}
// Get the drawing surface
ds = awt.GetDrawingSurface(env, component);
if ( ds == NULL )
{
printf( "%s:%i - GetDrawingSurface() failed.\n", __FILE__, __LINE__ );
return 0;
}
dsLock = ds->Lock(ds);
// Get the drawing surface info
dsi = ds->GetDrawingSurfaceInfo(ds);
// Get the platform-specific drawing info
dsi_win = (JAWT_Win32DrawingSurfaceInfo*)dsi->platformInfo;
HWND handle = dsi_win->hwnd;
ds->FreeDrawingSurfaceInfo(dsi);
ds->Unlock(ds);
awt.FreeDrawingSurface(ds);
return (jlong)handle;
}
void printLastError()
{
LPTSTR pszMessage;
DWORD dwLastError = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dwLastError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&pszMessage,
0, NULL );
// Display the error message
wprintf(L"failed with error %d: %s\n", dwLastError, pszMessage);
LocalFree(pszMessage);
}
/*
* Class: test_Transparency
* Method: setTransparency
* Signature: (JF)V
*/
JNIEXPORT void JNICALL Java_test_Transparency_setTransparency
(JNIEnv * env, jclass cls, jlong windowHandle, jfloat alpha)
{
HWND hwnd = (HWND)windowHandle;
// Get the current window style
LONG currentStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
if ( currentStyle == 0 )
{
printf( "Error calling GetWindowLong() ");
printLastError();
}
if ( alpha == 0 )
{
// No transparency.
// Remove WS_EX_LAYERED from this window style
SetWindowLong(hwnd, GWL_EXSTYLE, currentStyle & ~WS_EX_LAYERED);
}
else
{
// Calculate the transparency value. Should be in the range 0-255
unsigned char transparency = (unsigned char)(255 * alpha);
// Set window style to WS_EX_LAYERED. This is required for windows to be transparent.
SetWindowLong(hwnd, GWL_EXSTYLE, currentStyle | WS_EX_LAYERED );
// set the transparency level
SetLayeredWindowAttributes(hwnd, 0, transparency, LWA_ALPHA);
}
}
} // extern "C"
```
MyFrame.java
```
package test;
import javax.swing.*;
import javax.swing.SwingUtilities;
import java.awt.event.*;
public class MyFrame implements ActionListener
{
private JFrame frame;
private Transparency trans; // = new Transparency();
private float t = 1.0f;
public MyFrame()
{
frame = new JFrame("My transparent window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds( 10, 10, 200, 200 );
JButton button = new JButton("My button");
button.setBounds( 20, 20, 50, 10 );
button.addActionListener( this );
JPanel panel = new JPanel();
panel.add( button );
frame.setContentPane( panel );
//Display the window.
frame.setVisible(true);
trans = new Transparency();
}
/**
* @param args
*/
public static void main( String[] args )
{
MyFrame f = new MyFrame();
}
public void actionPerformed(ActionEvent e)
{
t -= 0.05f;
trans.setWindowOpacity( frame, t );
}
}
```
Transparency.java
```
package test;
import java.awt.Window;
import java.awt.Component;
public class Transparency
{
static boolean libLoaded = false;
/**
* Sets the transparency for a window.
* @param hwnd Handle for the window.
* @param opacity Transparency level, from 0.0 to 1.0.
* 1.0 is completely transparent. 0.0 is completely opaque.
*/
private static native void setTransparency( long hwnd, float opacity );
/**
* Get the window handle for the component.
* @param component
* @return HWND value obtained from the OS.
*/
private static native long getWindowHandle( Component component );
static
{
try
{
System.loadLibrary("transJNI");
libLoaded = true;
}
catch ( Exception e )
{
e.printStackTrace();
libLoaded = false;
}
}
/**
* @param window The window whose opacity will be adjusted.
* @param opacity The opacity level, from 0.0 (opaque) to 1.0 (completely transparent).
*/
public void setWindowOpacity(Window window, float opacity)
{
if ( !libLoaded )
{
return;
}
if ( !window.isVisible() )
{
return;
}
long hwnd = getWindowHandle( window );
setTransparency(hwnd, opacity);
}
}
```
|
6u10 supports [transparent windows](http://java.sun.com/developer/technicalArticles/GUI/translucent_shaped_windows/) through an unofficial API. 6u10 is available for download through java.com and previous JDK versions will update to it or a later update soon.
|
265,605 |
<p>I have a stored procedure that creates and opens some cursors. It closes them at the end, but if it hits an error those cursors are left open! Then subsequent runs fail when it tries to create cursors since a cursor with the name already exists.</p>
<p>Is there a way I can query which cursors exists and if they are open or not so I can close and deallocate them? I feel like this is better than blindly trying to close and swallow errors.</p>
|
[
{
"answer_id": 265634,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/aa172595(SQL.80).aspx\" rel=\"nofollow noreferrer\">Look here</a> for info on how to find cursors. I have never used any of them because I could figure out a way to get it done without going Row By Agonizing Row. </p>\n\n<p>You should rebuild the sp to either </p>\n\n<ul>\n<li><p>not use cursors ( we can help -\nthere is almost always a way to\navoid RBAR)</p></li>\n<li><p>build it in a transaction and roll it back if there is a failure or if you detect an error. Here are some excellent articles on this. <a href=\"http://www.sommarskog.se/error-handling-I.html\" rel=\"nofollow noreferrer\">part 1</a> and <a href=\"http://www.sommarskog.se/error-handling-II.html\" rel=\"nofollow noreferrer\">part 2</a></p></li>\n</ul>\n\n<p>If you have SQL2005, you can also use <a href=\"http://technet.microsoft.com/en-us/library/ms175976.aspx\" rel=\"nofollow noreferrer\">try catch</a></p>\n\n<p>EDIT (in response to your post):Ideally, data generation is best handled at the application level as they are better suited for non set based operations.</p>\n\n<p>Red Gate has a <a href=\"http://www.red-gate.com/products/SQL_Data_Generator/index.htm\" rel=\"nofollow noreferrer\">SQL Data generator</a> that I have used before (its great for single tables, but takes some configuring if you have lots of FK or a wide [normalized] database). </p>\n"
},
{
"answer_id": 278120,
"author": "Aaron Silverman",
"author_id": 26197,
"author_profile": "https://Stackoverflow.com/users/26197",
"pm_score": 3,
"selected": true,
"text": "<p>This seems to work for me:</p>\n\n<pre><code>CREATE PROCEDURE dbo.p_cleanUpCursor @cursorName varchar(255) AS\nBEGIN\n\n DECLARE @cursorStatus int\n SET @cursorStatus = (SELECT cursor_status('global',@cursorName))\n\n DECLARE @sql varchar(255)\n SET @sql = ''\n\n IF @cursorStatus > 0\n SET @sql = 'CLOSE '+@cursorName\n\n IF @cursorStatus > -3\n SET @sql = @sql+' DEALLOCATE '+@cursorName\n\n IF @sql <> ''\n exec(@sql)\n\nEND\n</code></pre>\n"
},
{
"answer_id": 14338377,
"author": "riofly",
"author_id": 1387407,
"author_profile": "https://Stackoverflow.com/users/1387407",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>You can use the <strong>sp_cursor_list</strong> system stored procedure to get a list\n of cursors visible to the current connection, and\n <strong>sp_describe_cursor</strong>, <strong>sp_describe_cursor_columns</strong>, and\n <strong>sp_describe_cursor_tables</strong> to determine the characteristics of a\n cursor.</p>\n</blockquote>\n\n<p>(from <a href=\"http://msdn.microsoft.com/it-it/library/aa172595(v=sql.80).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/it-it/library/aa172595(v=sql.80).aspx</a> )</p>\n"
},
{
"answer_id": 16177583,
"author": "BlackICE",
"author_id": 264607,
"author_profile": "https://Stackoverflow.com/users/264607",
"pm_score": 2,
"selected": false,
"text": "<p>This works on 2008R2, haven't tested on anything earlier than that:</p>\n\n<pre><code>USE MASTER\nGO\nselect s.session_id, s.host_name, s.program_name, s.client_interface_name, s.login_name\n, c.cursor_id, c.properties, c.creation_time, c.is_open, con.text,\nl.resource_type, d.name, l.request_type, l.request_Status, l.request_reference_count, l.request_lifetime, l.request_owner_type\nfrom sys.dm_exec_cursors(0) c\nleft outer join (select * from sys.dm_exec_connections c cross apply sys.dm_exec_sql_text(c.most_recent_sql_handle) mr) con on c.session_id = con.session_id\nleft outer join sys.dm_exec_sessions s on s.session_id = c.session_id\nleft outer join sys.dm_tran_locks l on l.request_session_id = c.session_id\nleft outer join sys.databases d on d.database_id = l.resource_database_id\n</code></pre>\n"
},
{
"answer_id": 51745031,
"author": "nzrytmn",
"author_id": 3193030,
"author_profile": "https://Stackoverflow.com/users/3193030",
"pm_score": 0,
"selected": false,
"text": "<p>You can use </p>\n\n<blockquote>\n <p>sys.dm_exec_cursors</p>\n</blockquote>\n\n<p>as described <a href=\"https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-exec-cursors-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\">here</a> </p>\n\n<p>Basically you can run this sample query and get information about the cursors that are open in various databases </p>\n\n<blockquote>\n <p>sys.dm_exec_cursors(0)</p>\n</blockquote>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26197/"
] |
I have a stored procedure that creates and opens some cursors. It closes them at the end, but if it hits an error those cursors are left open! Then subsequent runs fail when it tries to create cursors since a cursor with the name already exists.
Is there a way I can query which cursors exists and if they are open or not so I can close and deallocate them? I feel like this is better than blindly trying to close and swallow errors.
|
This seems to work for me:
```
CREATE PROCEDURE dbo.p_cleanUpCursor @cursorName varchar(255) AS
BEGIN
DECLARE @cursorStatus int
SET @cursorStatus = (SELECT cursor_status('global',@cursorName))
DECLARE @sql varchar(255)
SET @sql = ''
IF @cursorStatus > 0
SET @sql = 'CLOSE '+@cursorName
IF @cursorStatus > -3
SET @sql = @sql+' DEALLOCATE '+@cursorName
IF @sql <> ''
exec(@sql)
END
```
|
265,628 |
<p>I added the columns in the select list to the order by list, but it is still giving me the error:</p>
<p>ORDER BY items must appear in the select list if SELECT DISTINCT is specified.</p>
<p>Here is the stored proc:</p>
<pre><code>CREATE PROCEDURE [dbo].[GetRadioServiceCodesINGroup]
@RadioServiceGroup nvarchar(1000) = NULL
AS
BEGIN
SET NOCOUNT ON;
SELECT DISTINCT rsc.RadioServiceCodeId,
rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService
FROM sbi_l_radioservicecodes rsc
INNER JOIN sbi_l_radioservicecodegroups rscg
ON rsc.radioservicecodeid = rscg.radioservicecodeid
WHERE rscg.radioservicegroupid IN
(select val from dbo.fnParseArray(@RadioServiceGroup,','))
OR @RadioServiceGroup IS NULL
ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService
END
</code></pre>
|
[
{
"answer_id": 265637,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 6,
"selected": false,
"text": "<p>While they are not the same thing, in one sense <code>DISTINCT</code> implies a <code>GROUP BY</code>, because every <code>DISTINCT</code> could be re-written using <code>GROUP BY</code> instead. With that in mind, it doesn't make sense to order by something that's not in the aggregate group. </p>\n\n<p>For example, if you have a table like this:</p>\n\n<pre>\ncol1 col2\n---- ----\n 1 1\n 1 2\n 2 1\n 2 2\n 2 3\n 3 1\n</pre>\n\n<p>and then try to query it like this:</p>\n\n<pre><code>SELECT DISTINCT col1 FROM [table] WHERE col2 > 2 ORDER BY col1, col2\n</code></pre>\n\n<p>That would make no sense, because there <em>could</em> end up being multiple <code>col2</code> values per row. Which one should it use for the order? Of course, in this query you know the results wouldn't be that way, but the database server can't know that in advance.</p>\n\n<p>Now, your case is a little different. You included all the columns from the <code>order by</code> clause in the <code>select</code> clause, and therefore it would seem at first glance that they were all grouped. However, some of those columns were included in a calculated field. When you do that in combination with distinct, the <code>distinct</code> directive can <em>only</em> be applied to the <em>final results</em> of the calculation: it doesn't know anything about the source of the calculation any more.</p>\n\n<p>This means the server doesn't really know it can count on those columns any more. It knows that they were used, but it doesn't know if the calculation operation might cause an effect similar to my first simple example above.</p>\n\n<p>So now you need to do something else to tell the server that the columns are okay to use for ordering. There are several ways to do that, but this approach should work okay:</p>\n\n<pre><code>SELECT rsc.RadioServiceCodeId,\n rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService\nFROM sbi_l_radioservicecodes rsc\nINNER JOIN sbi_l_radioservicecodegroups rscg \n ON rsc.radioservicecodeid = rscg.radioservicecodeid\nWHERE rscg.radioservicegroupid IN \n (SELECT val FROM dbo.fnParseArray(@RadioServiceGroup,','))\n OR @RadioServiceGroup IS NULL \nGROUP BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService\nORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService\n</code></pre>\n"
},
{
"answer_id": 265641,
"author": "Chris Van Opstal",
"author_id": 7264,
"author_profile": "https://Stackoverflow.com/users/7264",
"pm_score": 7,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre><code>ORDER BY 1, 2\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>ORDER BY rsc.RadioServiceCodeId, rsc.RadioServiceCode + ' - ' + rsc.RadioService\n</code></pre>\n"
},
{
"answer_id": 265649,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 4,
"selected": false,
"text": "<p>Try one of these:</p>\n\n<ol>\n<li><p>Use column alias:</p>\n\n<p>ORDER BY RadioServiceCodeId,RadioService</p></li>\n<li><p>Use column position:</p>\n\n<p>ORDER BY 1,2</p></li>\n</ol>\n\n<p>You can only order by columns that actually appear in the result of the DISTINCT query - the underlying data isn't available for ordering on. </p>\n"
},
{
"answer_id": 265907,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 3,
"selected": false,
"text": "<p>Distinct and Group By generally do the same kind of thing, for different purposes... They both create a 'working\" table in memory based on the columns being Grouped on, (or selected in the Select Distinct clause) - and then populate that working table as the query reads data, adding a new \"row\" only when the values indicate the need to do so... </p>\n\n<p>The only difference is that in the Group By there are additional \"columns\" in the working table for any calculated aggregate fields, like Sum(), Count(), Avg(), etc. that need to updated for each original row read. Distinct doesn't have to do this... In the special case where you Group By only to get distinct values, (And there are no aggregate columns in output), then it is probably exactly the same query plan.... It would be interesting to review the query execution plan for the two options and see what it did... </p>\n\n<p>Certainly Distinct is the way to go for readability if that is what you are doing (When your purpose is to eliminate duplicate rows, and you are not calculating any aggregate columns) </p>\n"
},
{
"answer_id": 11292320,
"author": "rio",
"author_id": 313881,
"author_profile": "https://Stackoverflow.com/users/313881",
"pm_score": 2,
"selected": false,
"text": "<p>When you define concatenation you need to use an ALIAS for the new column if you want to order on it combined with DISTINCT\n<strong>Some Ex with sql 2008</strong></p>\n\n<pre><code>--this works \n\n SELECT DISTINCT (c.FirstName + ' ' + c.LastName) as FullName \n from SalesLT.Customer c \n order by FullName\n\n--this works too\n\n SELECT DISTINCT (c.FirstName + ' ' + c.LastName) \n from SalesLT.Customer c \n order by 1\n\n-- this doesn't \n\n SELECT DISTINCT (c.FirstName + ' ' + c.LastName) as FullName \n from SalesLT.Customer c \n order by c.FirstName, c.LastName\n\n-- the problem the DISTINCT needs an order on the new concatenated column, here I order on the singular column\n-- this works\n\n SELECT DISTINCT (c.FirstName + ' ' + c.LastName) \n as FullName, CustomerID \n from SalesLT.Customer c \n\norder by 1, CustomerID\n\n-- this doesn't\n\n SELECT DISTINCT (c.FirstName + ' ' + c.LastName) as FullName \n from SalesLT.Customer c \n order by 1, CustomerID\n</code></pre>\n"
},
{
"answer_id": 33627742,
"author": "HenryS",
"author_id": 4428815,
"author_profile": "https://Stackoverflow.com/users/4428815",
"pm_score": -1,
"selected": false,
"text": "<p>You could try a subquery:</p>\n\n<pre><code>SELECT DISTINCT TEST.* FROM (\n SELECT rsc.RadioServiceCodeId,\n rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService\n FROM sbi_l_radioservicecodes rsc\n INNER JOIN sbi_l_radioservicecodegroups rscg ON rsc.radioservicecodeid = rscg.radioservicecodeid\n WHERE rscg.radioservicegroupid IN \n (select val from dbo.fnParseArray(@RadioServiceGroup,','))\n OR @RadioServiceGroup IS NULL \n ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService\n) as TEST\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33690/"
] |
I added the columns in the select list to the order by list, but it is still giving me the error:
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
Here is the stored proc:
```
CREATE PROCEDURE [dbo].[GetRadioServiceCodesINGroup]
@RadioServiceGroup nvarchar(1000) = NULL
AS
BEGIN
SET NOCOUNT ON;
SELECT DISTINCT rsc.RadioServiceCodeId,
rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService
FROM sbi_l_radioservicecodes rsc
INNER JOIN sbi_l_radioservicecodegroups rscg
ON rsc.radioservicecodeid = rscg.radioservicecodeid
WHERE rscg.radioservicegroupid IN
(select val from dbo.fnParseArray(@RadioServiceGroup,','))
OR @RadioServiceGroup IS NULL
ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService
END
```
|
Try this:
```
ORDER BY 1, 2
```
OR
```
ORDER BY rsc.RadioServiceCodeId, rsc.RadioServiceCode + ' - ' + rsc.RadioService
```
|
265,639 |
<p>I've got a text file that contains several 'records' inside of it. Each record contains a name and a collection of numbers as data. </p>
<p>I'm trying to build a class that will read through the file, present only the names of all the records, and then allow the user to select which record data he/she wants. </p>
<p>The first time I go through the file, I only read header names, but I can keep track of the 'position' in the file where the header is. I need random access to the text file to seek to the beginning of each record after a user asks for it.</p>
<p>I have to do it this way because the file is too large to be read in completely in memory (1GB+) with the other memory demands of the application.</p>
<p>I've tried using the .NET StreamReader class to accomplish this (which provides very easy to use 'ReadLine' functionality, but there is no way to capture the true position of the file (the position in the BaseStream property is skewed due to the buffer the class uses).</p>
<p>Is there no easy way to do this in .NET? </p>
|
[
{
"answer_id": 265654,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 3,
"selected": false,
"text": "<p>You can use a System.IO.FileStream instead of StreamReader. If you know exactly, what file contains ( the encoding for example ), you can do all operation like with StreamReader.</p>\n"
},
{
"answer_id": 265655,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p>Are you sure that the file is \"too large\"? Have you tried it that way and has it caused a problem? </p>\n\n<p>If you allocate a large amount of memory, and you aren't using it right now, Windows will just swap it out to disk. Hence, by accessing it from \"memory\", you will have accomplished what you want -- random access to the file on disk.</p>\n"
},
{
"answer_id": 265656,
"author": "LeppyR64",
"author_id": 16592,
"author_profile": "https://Stackoverflow.com/users/16592",
"pm_score": 3,
"selected": false,
"text": "<p>FileStream has the seek() method.</p>\n"
},
{
"answer_id": 265661,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>Is the encoding a fixed-size one (e.g. ASCII or UCS-2)? If so, you could keep track of the character index (based on the number of characters you've seen) and find the binary index based on that.</p>\n\n<p>Otherwise, no - you'd basically need to write your own StreamReader implementation which lets you peek at the binary index. It's a shame that StreamReader doesn't implement this, I agree.</p>\n"
},
{
"answer_id": 265863,
"author": "reshefm",
"author_id": 30717,
"author_profile": "https://Stackoverflow.com/users/30717",
"pm_score": 1,
"selected": false,
"text": "<p>I think that the FileHelpers library runtime records feature might help u. <a href=\"http://filehelpers.sourceforge.net/runtime_classes.html\" rel=\"nofollow noreferrer\">http://filehelpers.sourceforge.net/runtime_classes.html</a></p>\n"
},
{
"answer_id": 266011,
"author": "Mike Blandford",
"author_id": 28643,
"author_profile": "https://Stackoverflow.com/users/28643",
"pm_score": 0,
"selected": false,
"text": "<p>This exact question was asked in 2006 here: <a href=\"http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic40275.aspx\" rel=\"nofollow noreferrer\">http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic40275.aspx</a></p>\n\n<p>Summary:</p>\n\n<p>\"The problem is that the StreamReader buffers data, so the value returned in \nBaseStream.Position property is always ahead of the actual processed line.\"</p>\n\n<p>However, \"if the file is encoded in a text encoding which is fixed-width, you could keep track of how much text has been read and multiply that by the width\"</p>\n\n<p>and if not, you can just use the FileStream and read a char at a time and then the BaseStream.Position property should be correct</p>\n"
},
{
"answer_id": 267056,
"author": "Corbin March",
"author_id": 7625,
"author_profile": "https://Stackoverflow.com/users/7625",
"pm_score": 3,
"selected": false,
"text": "<p>If you're flexible with how the data file is written and don't mind it being a little less text editor-friendly, you could write your records with a BinaryWriter:</p>\n\n<pre><code>using (BinaryWriter writer = \n new BinaryWriter(File.Open(\"data.txt\", FileMode.Create)))\n{\n writer.Write(\"one,1,1,1,1\");\n writer.Write(\"two,2,2,2,2\");\n writer.Write(\"three,3,3,3,3\");\n}\n</code></pre>\n\n<p>Then, initially reading each record is simple because you can use the BinaryReader's ReadString method:</p>\n\n<pre><code>using (BinaryReader reader = new BinaryReader(File.OpenRead(\"data.txt\")))\n{\n string line = null;\n long position = reader.BaseStream.Position;\n while (reader.PeekChar() > -1)\n {\n line = reader.ReadString();\n\n //parse the name out of the line here...\n\n Console.WriteLine(\"{0},{1}\", position, line);\n position = reader.BaseStream.Position;\n }\n}\n</code></pre>\n\n<p>The BinaryReader isn't buffered so you get the proper position to store and use later. The only hassle is parsing the name out of the line, which you may have to do with a StreamReader anyway.</p>\n"
},
{
"answer_id": 921524,
"author": "Jimmy",
"author_id": 68936,
"author_profile": "https://Stackoverflow.com/users/68936",
"pm_score": 4,
"selected": false,
"text": "<p>There are some good answers provided, but I couldn't find some source code that would work in my very simplistic case. Here it is, with the hope that it'll save someone else the hour that I spent searching around. </p>\n\n<p>The \"very simplistic case\" that I refer to is: the text encoding is fixed-width, and the line ending characters are the same throughout the file. This code works well in my case (where I'm parsing a log file, and I sometime have to seek ahead in the file, and then come back. I implemented just enough to do what I needed to do (ex: only one constructor, and only override ReadLine()), so most likely you'll need to add code... but I think it's a reasonable starting point.</p>\n\n<pre><code>public class PositionableStreamReader : StreamReader\n{\n public PositionableStreamReader(string path)\n :base(path)\n {}\n\n private int myLineEndingCharacterLength = Environment.NewLine.Length;\n public int LineEndingCharacterLength\n {\n get { return myLineEndingCharacterLength; }\n set { myLineEndingCharacterLength = value; }\n }\n\n public override string ReadLine()\n {\n string line = base.ReadLine();\n if (null != line)\n myStreamPosition += line.Length + myLineEndingCharacterLength;\n return line;\n }\n\n private long myStreamPosition = 0;\n public long Position\n {\n get { return myStreamPosition; }\n set\n {\n myStreamPosition = value;\n this.BaseStream.Position = value;\n this.DiscardBufferedData();\n }\n }\n}\n</code></pre>\n\n<p>Here's an example of how to use the PositionableStreamReader:</p>\n\n<pre><code>PositionableStreamReader sr = new PositionableStreamReader(\"somepath.txt\");\n\n// read some lines\nwhile (something)\n sr.ReadLine();\n\n// bookmark the current position\nlong streamPosition = sr.Position;\n\n// read some lines\nwhile (something)\n sr.ReadLine();\n\n// go back to the bookmarked position\nsr.Position = streamPosition;\n\n// read some lines\nwhile (something)\n sr.ReadLine();\n</code></pre>\n"
},
{
"answer_id": 2538385,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>A couple of items that may be of interest.</p>\n\n<p>1) If the lines are a fixed set of characters in length, that is not of necessity useful information if the character set has variable sizes (like UTF-8). So check your character set.</p>\n\n<p>2) You can ascertain the exact position of the file cursor from StreamReader by using the BaseStream.Position value <strong>IF</strong> you Flush() the buffers first (which will force the current position to be where the next read will begin - one byte after the last byte read).</p>\n\n<p>3) If you know in advance that the exact length of each record will be the same number of characters, and the character set uses fixed-width characters (so each line is the same number of bytes long) the you can use FileStream with a fixed buffer size to match the size of a line and the position of the cursor at the end of each read will be, perforce, the beginning of the next line.</p>\n\n<p>4) Is there any particular reason why, if the lines are the same length (assuming in bytes here) that you don't simply use line numbers and calculate the byte-offset in the file based on line size x line number?</p>\n"
},
{
"answer_id": 72898255,
"author": "Theodore Tsirpanis",
"author_id": 4964734,
"author_profile": "https://Stackoverflow.com/users/4964734",
"pm_score": 0,
"selected": false,
"text": "<p>Starting with .NET 6, the methods in the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.io.randomaccess\" rel=\"nofollow noreferrer\"><code>System.IO.RandomAccess</code></a> class is the official and supported way to randomly read and write to a file. These APIs work with <code>Microsoft.Win32.SafeHandles.SafeFileHandle</code>s which can be obtained with the new <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.io.file.openhandle\" rel=\"nofollow noreferrer\"><code>System.IO.File.OpenHandle</code></a> function, also introduced in .NET 6.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I've got a text file that contains several 'records' inside of it. Each record contains a name and a collection of numbers as data.
I'm trying to build a class that will read through the file, present only the names of all the records, and then allow the user to select which record data he/she wants.
The first time I go through the file, I only read header names, but I can keep track of the 'position' in the file where the header is. I need random access to the text file to seek to the beginning of each record after a user asks for it.
I have to do it this way because the file is too large to be read in completely in memory (1GB+) with the other memory demands of the application.
I've tried using the .NET StreamReader class to accomplish this (which provides very easy to use 'ReadLine' functionality, but there is no way to capture the true position of the file (the position in the BaseStream property is skewed due to the buffer the class uses).
Is there no easy way to do this in .NET?
|
There are some good answers provided, but I couldn't find some source code that would work in my very simplistic case. Here it is, with the hope that it'll save someone else the hour that I spent searching around.
The "very simplistic case" that I refer to is: the text encoding is fixed-width, and the line ending characters are the same throughout the file. This code works well in my case (where I'm parsing a log file, and I sometime have to seek ahead in the file, and then come back. I implemented just enough to do what I needed to do (ex: only one constructor, and only override ReadLine()), so most likely you'll need to add code... but I think it's a reasonable starting point.
```
public class PositionableStreamReader : StreamReader
{
public PositionableStreamReader(string path)
:base(path)
{}
private int myLineEndingCharacterLength = Environment.NewLine.Length;
public int LineEndingCharacterLength
{
get { return myLineEndingCharacterLength; }
set { myLineEndingCharacterLength = value; }
}
public override string ReadLine()
{
string line = base.ReadLine();
if (null != line)
myStreamPosition += line.Length + myLineEndingCharacterLength;
return line;
}
private long myStreamPosition = 0;
public long Position
{
get { return myStreamPosition; }
set
{
myStreamPosition = value;
this.BaseStream.Position = value;
this.DiscardBufferedData();
}
}
}
```
Here's an example of how to use the PositionableStreamReader:
```
PositionableStreamReader sr = new PositionableStreamReader("somepath.txt");
// read some lines
while (something)
sr.ReadLine();
// bookmark the current position
long streamPosition = sr.Position;
// read some lines
while (something)
sr.ReadLine();
// go back to the bookmarked position
sr.Position = streamPosition;
// read some lines
while (something)
sr.ReadLine();
```
|
265,650 |
<p>I have a question regarding a symptom of my misuse of CreateProcess. I'm using the lpcommandline parameter to feed the path to my executable and parameters. My misuse is that I have not surrounded the path to the exe with quotes. </p>
<p>My question is, why does the CreateProcess work just fine on most computers and not others? I know that the path will have a space in most of the time, yet on 90% of XP machines it works. I of course found out my issue on those 10% where it did not. But I'm wondering what is different on the machines where it does not work? Is there a setting or a policy that any of you folks know about. And yes, I am going to fix the quote issue. Just curious about why something like this would not have just failed off the bat. </p>
<p>So the code would look something like below and the szCommandLine Parameter would be something like below. Notice no quotes around the path to the exe.</p>
<p>"C:\Program Files\My Company\doit.exe parameter1 parameter2"</p>
<pre><code>CreateProcess(
NULL,
szCommandLine,
NULL,
NULL,
FALSE,
NULL,
NULL,
NULL,
&si,
&pi )
</code></pre>
|
[
{
"answer_id": 265847,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "<p>You should read this page:<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/ms682425.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms682425.aspx</a></p>\n\n<ul>\n<li>If the application name is NULL (first parameter).<br></li>\n<li>It uses the first space separated word in the command line (second parameter) as the application name.<br></li>\n<li>If the application name contains a space it must be quoted.</li>\n</ul>\n\n<p>Again code is worth a million words:<br>\nDoes it look like this:</p>\n\n<pre><code>char commandline[] = \"C:\\Program Files\\My Company\\doit.exe parameter1 parameter2\";\nCreateProcess(NULL,commandline, .... );\n</code></pre>\n\n<p>Or are you generating the path name somwhere?<br>\nRemember generic questions will only get you generic answers.<br>\nYou have to be specific before you get a specific answer on why there is just too much speculation otherwise.</p>\n"
},
{
"answer_id": 270478,
"author": "Klathzazt",
"author_id": 35223,
"author_profile": "https://Stackoverflow.com/users/35223",
"pm_score": 0,
"selected": false,
"text": "<p>A good way to diagnose something like that is to build in to your application error and reporting mechanism. This helps for so many purposes- mainly for bugs that you may never see yourself and which some users may just ignore and not report to you. This way you can diagnose what these parameters were when the command was called and the failure occurred.</p>\n\n<p>Additionally, you can try exploring further the MSDN site and the advanced features associated with this method. You left most of them NULL. By exploring these extended features you will learn and maybe able to find out yourself why there may be that discrepency.</p>\n\n<p>Another generic answer but I hope this helps you to evaluate your particular situation.</p>\n"
},
{
"answer_id": 308119,
"author": "Simon Buchan",
"author_id": 20135,
"author_profile": "https://Stackoverflow.com/users/20135",
"pm_score": 3,
"selected": false,
"text": "<p>As the document Martin York linked to hinted, CreateProcess() has some behaviour for back-compat with pre-long-name programs.</p>\n\n<p>\"c:\\program files\\sub dir\\program name arg1 arg2\" will look for:</p>\n\n<blockquote>\n<pre><code>\"c:\\program.exe\" files\\sub dir\\program name arg1 arg2\n\"c:\\program files\\sub.exe\" dir\\program name arg1 arg2\n\"c:\\program files\\sub dir\\program.exe\" name arg1 arg2\n\"c:\\program files\\sub dir\\program name.exe\" arg1 arg2\n</code></pre>\n</blockquote>\n\n<p>So if any of these files exist, Windows will to call them, not your program. Also, I would assume if you did not have read access to any of the folders these possible matches are in, CreateProcess() may fail out immediatly, instead of checking if you have read to the later possible matches. (Windows by default checks read access only the final folder.)</p>\n"
},
{
"answer_id": 1922171,
"author": "nopopem",
"author_id": 233823,
"author_profile": "https://Stackoverflow.com/users/233823",
"pm_score": 2,
"selected": false,
"text": "<p>I just struggled with the same problem for quite some time. So even if this question was raised a long time ago, just for the record, here is what the problem was in my case:</p>\n\n<p>If the command line is not quoted and contains spaces, CreateProcess will try to resolve the ambiguity as described in Simon's answer. \nIf any of the tested parts up to a space character also resolves to an existing file with no or a .exe extension, this file will be used instead of the intended complete path.</p>\n\n<p>Example:</p>\n\n<pre><code>char cmdline[] = \"C:\\Program Files\\App One\\bin\\app.exe param1 param2\";\nCreateProcess(NULL, cmdline, ...);\n</code></pre>\n\n<p>Unfortunately there actually was an existing file called \"C:\\Program Files\\App\" (no extension) in my case.\nCreateProcess found this file, assumed it was an executable with no .exe extension and tried to execute it. Result: error 193 \"%1 is not a valid Win32 application\".</p>\n\n<p>Bottom line: use quotes or even better, the first argument to CreateProcess, or go looking for any other file which might match part of the offending path.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24979/"
] |
I have a question regarding a symptom of my misuse of CreateProcess. I'm using the lpcommandline parameter to feed the path to my executable and parameters. My misuse is that I have not surrounded the path to the exe with quotes.
My question is, why does the CreateProcess work just fine on most computers and not others? I know that the path will have a space in most of the time, yet on 90% of XP machines it works. I of course found out my issue on those 10% where it did not. But I'm wondering what is different on the machines where it does not work? Is there a setting or a policy that any of you folks know about. And yes, I am going to fix the quote issue. Just curious about why something like this would not have just failed off the bat.
So the code would look something like below and the szCommandLine Parameter would be something like below. Notice no quotes around the path to the exe.
"C:\Program Files\My Company\doit.exe parameter1 parameter2"
```
CreateProcess(
NULL,
szCommandLine,
NULL,
NULL,
FALSE,
NULL,
NULL,
NULL,
&si,
&pi )
```
|
As the document Martin York linked to hinted, CreateProcess() has some behaviour for back-compat with pre-long-name programs.
"c:\program files\sub dir\program name arg1 arg2" will look for:
>
>
> ```
> "c:\program.exe" files\sub dir\program name arg1 arg2
> "c:\program files\sub.exe" dir\program name arg1 arg2
> "c:\program files\sub dir\program.exe" name arg1 arg2
> "c:\program files\sub dir\program name.exe" arg1 arg2
>
> ```
>
>
So if any of these files exist, Windows will to call them, not your program. Also, I would assume if you did not have read access to any of the folders these possible matches are in, CreateProcess() may fail out immediatly, instead of checking if you have read to the later possible matches. (Windows by default checks read access only the final folder.)
|
265,669 |
<p>I have some code that opens a word document using VBScript on an ASP.net page:</p>
<pre><code>set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "c:\inetpub\wwwroot\JSWordTest\test.doc", False, False, False
</code></pre>
<p>This works great but opens the word doc in another window. Ideally I would like to make this look as if it is contained in the current page perhaps in an IFrame. I have some other buttons which paste text into the word document when clicked. </p>
<p>I cannot just set the src of the iframe to the word document as need a reference to the word document (objWord) to allow me to paste text into it in real time again using Vbscript to do this.</p>
<p>Not sure if this is possible but any ideas/alternatives welcome?</p>
<p>Requirements:
The word doc needs to be displayed from web browser</p>
<p>At the side of the word document will be some buttons which when clicked paste text into it</p>
|
[
{
"answer_id": 267116,
"author": "unrealtrip",
"author_id": 11130,
"author_profile": "https://Stackoverflow.com/users/11130",
"pm_score": 2,
"selected": false,
"text": "<p>You can use this technique to get the contents of the Word document without displaying any windows at all. </p>\n\n<pre><code>' Declare an object for the word application '\nSet objWord = CreateObject(\"Word.Application\")\n\nobjWord.Visible = False ' Don''t show word '\nobjWord.Documents.open(\"C:\\test.doc\") ' Open document '\nobjWord.Selection.WholeStory ' Select everything in the doc '\nstrText = objWord.Selection.Text ' Assign document contents to var'\nobjWord.Quit False ' Close Word, don't save ' \n</code></pre>\n\n<p>Once you've got the contents of the document in the variable you can do what you want with it as far as writing it out with a document.write or whatever method you want to use.</p>\n\n<p>You can find more detail on the MS Word application object and its methods here: <a href=\"http://msdn.microsoft.com/en-us/library/aa221371(office.11).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa221371(office.11).aspx</a></p>\n"
},
{
"answer_id": 5027694,
"author": "Tarnschaf",
"author_id": 50777,
"author_profile": "https://Stackoverflow.com/users/50777",
"pm_score": 0,
"selected": false,
"text": "<p>If it is an option to install an ActiveX component at the client machines, you can try <a href=\"http://www.officeocx.com/\" rel=\"nofollow\">EDraw Office Viewer component</a> or the cheapter <a href=\"http://www.ultrashareware.com/Ultra-Office-Control.htm\" rel=\"nofollow\">Ultra Office Control</a>. Both are based on the DSOFramer example by Microsoft and provider similar methods to interface with the documents.</p>\n\n<p>Sample code is given and shows how to trigger dialogs, insert text, etc.</p>\n"
},
{
"answer_id": 17020060,
"author": "alisabzevari",
"author_id": 692422,
"author_profile": "https://Stackoverflow.com/users/692422",
"pm_score": 0,
"selected": false,
"text": "<p>You can get inspirations from <a href=\"https://excelviewer.codeplex.com/\" rel=\"nofollow\">Excel Viewer</a> component. It is like EDraw Office Viewer but free and open source. Currently, it opens office documents only but you can easily change it to work with Word.</p>\n"
},
{
"answer_id": 18613564,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You <em>could</em> try saving to HTML format</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Const wdFormatHTML = 8\n\ndim doc\nset doc = objWord.Documents.open(\"C:\\test.doc\")\ndoc.SaveAs \"doc.htm\", wdFormatHTML \n\n' etc ...\n</code></pre>\n\n<p>and then use that as the source of your iframe document. Bear in mind that when saving to HTML format, Word creates a corresponding resources folder (for images etc), so you might need to take that into account.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23066/"
] |
I have some code that opens a word document using VBScript on an ASP.net page:
```
set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "c:\inetpub\wwwroot\JSWordTest\test.doc", False, False, False
```
This works great but opens the word doc in another window. Ideally I would like to make this look as if it is contained in the current page perhaps in an IFrame. I have some other buttons which paste text into the word document when clicked.
I cannot just set the src of the iframe to the word document as need a reference to the word document (objWord) to allow me to paste text into it in real time again using Vbscript to do this.
Not sure if this is possible but any ideas/alternatives welcome?
Requirements:
The word doc needs to be displayed from web browser
At the side of the word document will be some buttons which when clicked paste text into it
|
You can use this technique to get the contents of the Word document without displaying any windows at all.
```
' Declare an object for the word application '
Set objWord = CreateObject("Word.Application")
objWord.Visible = False ' Don''t show word '
objWord.Documents.open("C:\test.doc") ' Open document '
objWord.Selection.WholeStory ' Select everything in the doc '
strText = objWord.Selection.Text ' Assign document contents to var'
objWord.Quit False ' Close Word, don't save '
```
Once you've got the contents of the document in the variable you can do what you want with it as far as writing it out with a document.write or whatever method you want to use.
You can find more detail on the MS Word application object and its methods here: <http://msdn.microsoft.com/en-us/library/aa221371(office.11).aspx>
|
265,679 |
<p>I want to do something like this from within Eclipse: <a href="http://svn.collab.net/viewvc/svn?view=rev&revision=33845" rel="nofollow noreferrer">http://svn.collab.net/viewvc/svn?view=rev&revision=33845</a></p>
<p>I use Subversive 0.7.5 with the Native JavaHL 1.5.3 (r33570) Connector.</p>
<p>I tried to change something in a my working copy of a branch i'd like to tag and creating a Tag with Team -> Tag... But I got the error message:</p>
<blockquote>
<p>Tag operation for some of selected resources failed.</p>
<p>A path under version control is needed for this operation</p>
</blockquote>
<p>I tried only a tag name and one with full repository path. Both resulted in the same error.
This is the error I get:</p>
<pre><code>*** Tag
svn copy "C:/workspace/some_branch" "http://server:8080/svn/project/tags/TagWithChange" -r WORKING -m "TagWithChange" --username "masi"
A path under version control is needed for this operation
</code></pre>
<p>Is it possible from within Eclipse?</p>
<p>How would you do something like this from the command line? See my own answer.</p>
<p>Though if I use the following at the command line I get an error:</p>
<pre><code>svn copy "C:/workspace/some_branch" "http://server:8080/svn/project/tags/TagWithChange" -r WORKING -m "TagWithChange" --username "masi"
</code></pre>
<p>Error:</p>
<blockquote>
<p>svn: Syntax error in revision argument 'WORKING'</p>
</blockquote>
<p>I'm using the svn client 1.5.4.</p>
|
[
{
"answer_id": 265697,
"author": "masi",
"author_id": 12398,
"author_profile": "https://Stackoverflow.com/users/12398",
"pm_score": 2,
"selected": false,
"text": "<p>Found the command line answer myself: \n<a href=\"http://svnbook.red-bean.com/en/1.4/svn.branchmerge.tags.html\" rel=\"nofollow noreferrer\">http://svnbook.red-bean.com/en/1.4/svn.branchmerge.tags.html</a></p>\n\n<pre><code>svn copy some_branch http://server:8080/svn/tags/TagWithChange -m\"TagWithChange\"\n</code></pre>\n"
},
{
"answer_id": 265707,
"author": "Mario",
"author_id": 8426,
"author_profile": "https://Stackoverflow.com/users/8426",
"pm_score": 0,
"selected": false,
"text": "<p>I have always used Subclipse <a href=\"http://subclipse.tigris.org/\" rel=\"nofollow noreferrer\">http://subclipse.tigris.org/</a> with eclipse - it is excellent and I think what all other plugins benchmark from.</p>\n\n<p>It has been awhile since i used that particular setup, but subclipse will automatically add a new (non versioned file - one that hasn't been 'versioned', or put in the repository yet) meaning you shouldn't get your error.</p>\n"
},
{
"answer_id": 563390,
"author": "TJR",
"author_id": 728,
"author_profile": "https://Stackoverflow.com/users/728",
"pm_score": 1,
"selected": false,
"text": "<p>I've found this same error when I used the Native JavaHL. You can do two things to make your tag.</p>\n\n<h2>A. Tag From SVN Respository Exploring Perspective</h2>\n\n<p><strong>SVN Repositories View</strong></p>\n\n<ol>\n<li>Right click on the trunk you'd like to tag, New -> Tag.</li>\n</ol>\n\n<hr>\n\n<h2>B. Update SVN Connector</h2>\n\n<p><strong>SVN Kit (SVN/1.5.5 SVNKit/1.2.2 (<a href=\"http://svnkit.com/\" rel=\"nofollow noreferrer\">http://svnkit.com/</a>) r5428)</strong></p>\n\n<ol>\n<li><p>Install SVN Kit through software updates.</p></li>\n<li><p>Window -> Prefs -> Team -> SVN -> SVN Connector -> SVN Connector</p></li>\n</ol>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12398/"
] |
I want to do something like this from within Eclipse: <http://svn.collab.net/viewvc/svn?view=rev&revision=33845>
I use Subversive 0.7.5 with the Native JavaHL 1.5.3 (r33570) Connector.
I tried to change something in a my working copy of a branch i'd like to tag and creating a Tag with Team -> Tag... But I got the error message:
>
> Tag operation for some of selected resources failed.
>
>
> A path under version control is needed for this operation
>
>
>
I tried only a tag name and one with full repository path. Both resulted in the same error.
This is the error I get:
```
*** Tag
svn copy "C:/workspace/some_branch" "http://server:8080/svn/project/tags/TagWithChange" -r WORKING -m "TagWithChange" --username "masi"
A path under version control is needed for this operation
```
Is it possible from within Eclipse?
How would you do something like this from the command line? See my own answer.
Though if I use the following at the command line I get an error:
```
svn copy "C:/workspace/some_branch" "http://server:8080/svn/project/tags/TagWithChange" -r WORKING -m "TagWithChange" --username "masi"
```
Error:
>
> svn: Syntax error in revision argument 'WORKING'
>
>
>
I'm using the svn client 1.5.4.
|
Found the command line answer myself:
<http://svnbook.red-bean.com/en/1.4/svn.branchmerge.tags.html>
```
svn copy some_branch http://server:8080/svn/tags/TagWithChange -m"TagWithChange"
```
|
265,680 |
<p>I'm using AspectJ to advice all the public methods which do have an argument of a chosen class. I tried the following:</p>
<pre><code>pointcut permissionCheckMethods(Session sess) :
(execution(public * *(.., Session)) && args(*, sess));
</code></pre>
<p>This is working wonderfully for methods with at least 2 arguments:</p>
<pre><code>public void delete(Object item, Session currentSession);
</code></pre>
<p>but it does not work with methods like:</p>
<pre><code>public List listAll(Session currentSession);
</code></pre>
<p>How may I change my pointcut to advice both methods executions? In other words: I expected the ".." wildcard to represent "zero or more arguments", but it looks like it means instead "one or more"...</p>
|
[
{
"answer_id": 320404,
"author": "Manrico Corazzi",
"author_id": 4690,
"author_profile": "https://Stackoverflow.com/users/4690",
"pm_score": 4,
"selected": true,
"text": "<p>Oh well... I worked that around with this nasty trick. Still waiting for someone to show up with an \"official\" pointcut definition.</p>\n\n<pre><code>pointcut permissionCheckMethods(EhealthSession eheSess) : \n (execution(public * *(.., EhealthSession)) && args(*, eheSess))\n && !within(it.___.security.PermissionsCheck);\n\npointcut permissionCheckMethods2(EhealthSession eheSess) : \n (execution(public * *(EhealthSession)) && args(eheSess))\n && !within(it.___.security.PermissionsCheck)\n && !within(it.___.app.impl.EhealthApplicationImpl);\n\nbefore(EhealthSession eheSess) throws AuthorizationException : permissionCheckMethods(eheSess)\n{\n Signature sig = thisJoinPointStaticPart.getSignature(); \n check(eheSess, sig);\n}\n\nbefore(EhealthSession eheSess) throws AuthorizationException : permissionCheckMethods2(eheSess)\n{\n Signature sig = thisJoinPointStaticPart.getSignature(); \n check(eheSess, sig);\n}\n</code></pre>\n"
},
{
"answer_id": 974466,
"author": "Tahir Akhtar",
"author_id": 18027,
"author_profile": "https://Stackoverflow.com/users/18027",
"pm_score": 2,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code>pointcut permissionCheckMethods(Session sess) : \n(execution(public * *(..)) && args(.., sess));\n</code></pre>\n\n<p>I guess this will match if last (or only) argument is of type Session. By swapping the positions of args you can also match first-or-only. But i don't know if matching any arbitrary position is possible. </p>\n"
},
{
"answer_id": 11882677,
"author": "kriegaex",
"author_id": 1082681,
"author_profile": "https://Stackoverflow.com/users/1082681",
"pm_score": 2,
"selected": false,
"text": "<p>I cannot extend AspectJ syntax for you, but I can offer a workaround. But first let me explain why it is not possible to do what you want with an <code>args</code> definition in a pointcut: because if you would match your <code>EhealthSession</code> parameter anyplace within the method signature, how should AspectJ handle the case that the signature contains multiple parameters of that class? The meaning of <code>eheSess</code> would be ambiguous.</p>\n\n<p>Now the workaround: It might be slower - how much depends on your environment, just test it - but you could just have the pointcut match all potential methods regardless of their parameter list and then let the advice find the parameter you need by inspecting the parameter list:</p>\n\n<pre><code>pointcut permissionCheckMethods() : execution(public * *(..));\n\nbefore() throws AuthorizationException : permissionCheckMethods() {\n for (Object arg : thisJoinPoint.getArgs()) {\n if (arg instanceof EhealthSession)\n check(arg, thisJoinPointStaticPart.getSignature());\n }\n}\n</code></pre>\n\n<p>P.S.: Maybe you can narrow the focus via <code>within(SomeBaseClass+)</code> or <code>within(*Postfix)</code> or <code>within(com.company.package..*)</code> so as not to apply the advice to the whole universe.</p>\n"
},
{
"answer_id": 43723129,
"author": "Iomanip",
"author_id": 1945856,
"author_profile": "https://Stackoverflow.com/users/1945856",
"pm_score": 2,
"selected": false,
"text": "<p>You have to use .. (double points) at the end and the beginning as follows:</p>\n\n<pre><code>pointcut permissionCheckMethods(Session sess) : \n (execution(public * *(.., Session , ..)) );\n</code></pre>\n\n<p>Also get rid off <code>&& args(*, sess)</code> because that means that you expect to catch only those methods with whatever type for first param but <code>sess</code> as second param and no more than 2 params as well..</p>\n"
},
{
"answer_id": 61189787,
"author": "Chirag Thakkar",
"author_id": 5690380,
"author_profile": "https://Stackoverflow.com/users/5690380",
"pm_score": 0,
"selected": false,
"text": "<pre><code>@Before(value = \"execution(public * *(.., org.springframework.data.domain.Pageable , ..))\")\nprivate void isMethodPageable () {\n log.info(\"in a Aspect point cut isPageableParameterAvailable()\");\n}\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4690/"
] |
I'm using AspectJ to advice all the public methods which do have an argument of a chosen class. I tried the following:
```
pointcut permissionCheckMethods(Session sess) :
(execution(public * *(.., Session)) && args(*, sess));
```
This is working wonderfully for methods with at least 2 arguments:
```
public void delete(Object item, Session currentSession);
```
but it does not work with methods like:
```
public List listAll(Session currentSession);
```
How may I change my pointcut to advice both methods executions? In other words: I expected the ".." wildcard to represent "zero or more arguments", but it looks like it means instead "one or more"...
|
Oh well... I worked that around with this nasty trick. Still waiting for someone to show up with an "official" pointcut definition.
```
pointcut permissionCheckMethods(EhealthSession eheSess) :
(execution(public * *(.., EhealthSession)) && args(*, eheSess))
&& !within(it.___.security.PermissionsCheck);
pointcut permissionCheckMethods2(EhealthSession eheSess) :
(execution(public * *(EhealthSession)) && args(eheSess))
&& !within(it.___.security.PermissionsCheck)
&& !within(it.___.app.impl.EhealthApplicationImpl);
before(EhealthSession eheSess) throws AuthorizationException : permissionCheckMethods(eheSess)
{
Signature sig = thisJoinPointStaticPart.getSignature();
check(eheSess, sig);
}
before(EhealthSession eheSess) throws AuthorizationException : permissionCheckMethods2(eheSess)
{
Signature sig = thisJoinPointStaticPart.getSignature();
check(eheSess, sig);
}
```
|
265,708 |
<p>A fairly basic question, but I don't see it asked anywhere.</p>
<p>Let's say we have a global struct (in C) like so:</p>
<pre><code>struct foo {
int written_frequently1;
int read_only;
int written_frequently2;
};
</code></pre>
<p>It seems clear to me that if we have lots of threads reading and writing, we need a semaphore (or other lock) on the <code>written_frequently</code> members, even for reading, since we can't be 100% sure that assignments to this struct will be atomic.</p>
<p>If we want lots of threads to read the <code>read_only</code> member, and none to write, to we need a semaphore on the struct access just for reading?</p>
<p>(I'm inclined to say no, because the fact that the locations immediately before and after are constantly changed shouldn't affect the <code>read_only</code> member, and multiple threads reading the value shouldn't interfere with each other. But I'm not sure.)</p>
<hr>
<p>[Edit: I realize now I should have asked this question much better, in order to clarify <em>very specifically</em> what I meant. Naturally, I didn't really grok all of the issues involved when I first asked the question. Of course, if I comprehensively edit the question now, I will ruin all of these great answers. What I meant is more like:</p>
<pre><code>struct bar {
char written_frequently1[LONGISH_LEN];
char read_only[LONGISH_LEN];
char written_frequently2[LONGISH_LEN];
};
</code></pre>
<p>The major issue I asked about is, since this data is part of a struct, is it at all influenced by the other struct members, and might it influence them in return?</p>
<p>The fact that the members were ints, and therefore writes are likely atomic, is really just a red herring in this case.]</p>
|
[
{
"answer_id": 265721,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 1,
"selected": false,
"text": "<p>If all the threads are only reading, you don't need a semaphore.</p>\n"
},
{
"answer_id": 265723,
"author": "Jonathan Adelson",
"author_id": 8092,
"author_profile": "https://Stackoverflow.com/users/8092",
"pm_score": 3,
"selected": false,
"text": "<p>If the read_only member is actually read only, then there is no danger of the data being changed and therefore no need for synchronization. This could be data that is set up before the threads are started.</p>\n\n<p>You will want synchronization for any data that can be written, regardless of the frequency.</p>\n"
},
{
"answer_id": 265727,
"author": "Robert Deml",
"author_id": 9516,
"author_profile": "https://Stackoverflow.com/users/9516",
"pm_score": 0,
"selected": false,
"text": "<p>I would hide each field behind behind a function call. The write-only fields would have a semaphore. The read-only just returns the value.</p>\n"
},
{
"answer_id": 265748,
"author": "Yogi",
"author_id": 32801,
"author_profile": "https://Stackoverflow.com/users/32801",
"pm_score": 2,
"selected": false,
"text": "<p>No.</p>\n\n<p>In general you need semaphores to prevent concurrent access to resources (an <code>int</code> in this case). However, since the <code>read_only</code> member is read only, it won't change between/during accesses. Note that it doesn't even have to be an atomic read — if nothing changes, you're always safe.</p>\n\n<p>How are you setting <code>read_only</code> initially?</p>\n"
},
{
"answer_id": 265813,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 0,
"selected": false,
"text": "<p>Adding to previous answers:</p>\n\n<ol>\n<li>In this case the natural synchronization paradigm is mutual exclusion, not semaphores.</li>\n<li>I agree that you don't need any mutex on readonly variables.</li>\n<li>If the read-write part of the structure has consistency constraints, in general you will need <em>one</em> mutex for <em>all</em> of them, in order to keep the operations atomic.</li>\n</ol>\n"
},
{
"answer_id": 265904,
"author": "sk.",
"author_id": 16399,
"author_profile": "https://Stackoverflow.com/users/16399",
"pm_score": 2,
"selected": false,
"text": "<p>\"Read only\" is a bit misleading, since the variable is written to at least once when it's initialized. In that case you still need a memory barrier between the initial write and subsequent reads if they're in different threads, or else they could see the uninitialized value.</p>\n"
},
{
"answer_id": 266008,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 3,
"selected": false,
"text": "<p>You need a mutex to guarantee that an operation is atomic. So in this particular case, you <em>may not need a mutex at all.</em> Specifically, if each thread writes to <em>one</em> element <em>and</em> the write is atomic <em>and</em> the new value is independent of the current value of <em>any</em> element (including itself), there is no problem.</p>\n\n<p><strong>Example:</strong> each of several threads updates a \"last_updated_by\" variable that simply records the last thread that updated it. Clearly, as long as the variable itself is updated atomically, no errors will occur.</p>\n\n<hr>\n\n<p>However, you <em>do</em> need a mutex to guarantee consistency if a thread <em>reads or writes</em> more than one element at a time, particularly because you mention locking an <em>element</em> rather than the <em>entire structure</em>.</p>\n\n<p><strong>Example:</strong> a thread updates the \"day\", \"month\" and \"year\" elements of a structure. This must happen atomically, lest another thread read the structure after the \"month\" increments but before the \"day\" wraps to 1, to avoid dates such as February 31. Note that you must <em>honor</em> the mutex when reading; otherwise you may read an erroneous, half-updated value.</p>\n"
},
{
"answer_id": 267617,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 2,
"selected": false,
"text": "<h2>Readers need mutexes, too!</h2>\n\n<p>There seems to be a common misconception that mutexes are for writers only, and that readers don't need them. <strong>This is wrong,</strong> and this misconception is responsible for bugs that are <strong>extremely difficult to diagnose.</strong></p>\n\n<h2>Here's why, in the form of an example.</h2>\n\n<p>Imagine a clock that updates every second with the code:</p>\n\n<pre><code>if (++seconds > 59) { // Was the time hh:mm:59?\n seconds = 0; // Wrap seconds..\n if (++minutes > 59) { // ..and increment minutes. Was it hh:59:59?\n minutes = 0; // Wrap minutes..\n if (++hours > 23) // ..and increment hours. Was it 23:59:59?\n hours = 0; // Wrap hours.\n }\n}\n</code></pre>\n\n<p>If the code is not protected by a mutex, another thread can read the <code>hours</code>, <code>minutes</code>, and <code>seconds</code> variables while an update is in progress. Following the code above:</p>\n\n<pre>\n[Start just before midnight] 23:59:59\n[WRITER increments seconds] 23:59:60\n[WRITER wraps seconds] 23:59:00\n[WRITER increments minutes] 23:60:00\n[WRITER wraps minutes] 23:00:00\n[WRITER increments hours] 24:00:00\n[WRITER wraps hours] 00:00:00\n</pre>\n\n<p>The time is invalid from the first increment until the final operation <em>six steps later</em>. If a reader checks the clock during this period, it will see a value that may be not only incorrect but <em>illegal</em>. And since your code is likely to <em>depend</em> on the clock without <em>displaying</em> the time directly, this is a classic source of \"ricochet\" errors that are notoriously difficult to track down.</p>\n\n<h2>The fix is simple.</h2>\n\n<p>Surround the clock-update code with a mutex, and <em>create a reader function</em> that <em>also locks the mutex</em> while it executes. Now the reader will wait until the update is complete, and the writer won't change the values mid-read.</p>\n"
},
{
"answer_id": 653952,
"author": "Tim Post",
"author_id": 50049,
"author_profile": "https://Stackoverflow.com/users/50049",
"pm_score": 1,
"selected": false,
"text": "<p>You might enjoy reading any one of these papers on <a href=\"http://www.cl.cam.ac.uk/research/srg/netos/lock-free/\" rel=\"nofollow noreferrer\">practical lock free programming</a>, or just dissecting and understanding the provided snippets.</p>\n"
},
{
"answer_id": 1630064,
"author": "JXG",
"author_id": 15456,
"author_profile": "https://Stackoverflow.com/users/15456",
"pm_score": 1,
"selected": true,
"text": "<p>Many thanks to all the great answerers (and for all the great answers).</p>\n\n<p>To sum up: </p>\n\n<p>If there is a read-only member of a struct (in our case, if the value is set once, long before any thread might want to read it), then threads reading this member do not need locks, mutexes, semaphores, or any other concurrency protection.</p>\n\n<p>This is true even if the other members are written to frequently. The fact that the different variables are all part of the same struct makes no difference.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15456/"
] |
A fairly basic question, but I don't see it asked anywhere.
Let's say we have a global struct (in C) like so:
```
struct foo {
int written_frequently1;
int read_only;
int written_frequently2;
};
```
It seems clear to me that if we have lots of threads reading and writing, we need a semaphore (or other lock) on the `written_frequently` members, even for reading, since we can't be 100% sure that assignments to this struct will be atomic.
If we want lots of threads to read the `read_only` member, and none to write, to we need a semaphore on the struct access just for reading?
(I'm inclined to say no, because the fact that the locations immediately before and after are constantly changed shouldn't affect the `read_only` member, and multiple threads reading the value shouldn't interfere with each other. But I'm not sure.)
---
[Edit: I realize now I should have asked this question much better, in order to clarify *very specifically* what I meant. Naturally, I didn't really grok all of the issues involved when I first asked the question. Of course, if I comprehensively edit the question now, I will ruin all of these great answers. What I meant is more like:
```
struct bar {
char written_frequently1[LONGISH_LEN];
char read_only[LONGISH_LEN];
char written_frequently2[LONGISH_LEN];
};
```
The major issue I asked about is, since this data is part of a struct, is it at all influenced by the other struct members, and might it influence them in return?
The fact that the members were ints, and therefore writes are likely atomic, is really just a red herring in this case.]
|
Many thanks to all the great answerers (and for all the great answers).
To sum up:
If there is a read-only member of a struct (in our case, if the value is set once, long before any thread might want to read it), then threads reading this member do not need locks, mutexes, semaphores, or any other concurrency protection.
This is true even if the other members are written to frequently. The fact that the different variables are all part of the same struct makes no difference.
|
265,720 |
<p>In Python 2.6, a new "timeout" parameter was added to the httplib.HTTPConnection class:
<a href="http://docs.python.org/library/httplib.html#httplib.HTTPConnection" rel="nofollow noreferrer">http://docs.python.org/library/httplib.html#httplib.HTTPConnection</a></p>
<p>However, this is only a timeout for the connection to a server. I am looking to set a timeout value for the <b>request</b>, not the connection. This doesn't seem to be supported by httplib.</p>
<p>Is there any way to emulate this behavior?</p>
|
[
{
"answer_id": 265741,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": true,
"text": "<p>You can set a global socket timeout <sup>(*)</sup>:</p>\n\n<pre><code>import socket\n\ntimeout = 10\nsocket.setdefaulttimeout(timeout)\n</code></pre>\n\n<hr>\n\n<p><sup>(*)</sup> <strong>EDIT</strong>: As people in the comments correctly point out: This is technically true, but it only has predictable results for tasks that involve a single socket operation. An HTTP request consists of multiple socket operations (e.g. DNS requests or other things that might be abstracted away from an HTTP client). The timeout of the overall operation becomes unpredictable because of that.</p>\n"
},
{
"answer_id": 268174,
"author": "mkoeller",
"author_id": 33433,
"author_profile": "https://Stackoverflow.com/users/33433",
"pm_score": 3,
"selected": false,
"text": "<p>No, there isn't.</p>\n\n<p>It's because the <a href=\"http://www.greenbytes.de/tech/webdav/rfc2616.html\" rel=\"noreferrer\">HTTP spec</a> does not provide anything for the client to specify time-to-live information with a HTTP request. You can do this only on TCP level, as you mentioned.</p>\n\n<p>On the other hand, the server may inform the client about timeout situations with HTTP status codes <a href=\"http://www.greenbytes.de/tech/webdav/rfc2616.html#status.408\" rel=\"noreferrer\">408 Request Timeout</a> resp. <a href=\"http://www.greenbytes.de/tech/webdav/rfc2616.html#status.504\" rel=\"noreferrer\">504 Gateway Timeout</a>.</p>\n"
},
{
"answer_id": 4453301,
"author": "Pankrat",
"author_id": 63392,
"author_profile": "https://Stackoverflow.com/users/63392",
"pm_score": 3,
"selected": false,
"text": "<p>You could also use <code>settimeout</code> on the socket of the connection (works with Python 2.5):</p>\n\n<pre><code>connection = HTTPConnection('slow.service.com')\nconnection.request(...)\nconnection.sock.settimeout(5.0)\nresponse = connection.getresponse()\nresponse.read()\nconnection.close()\n</code></pre>\n\n<p>If the server cannot send the response within 5 seconds, a <code>socket.error</code> will be raised.</p>\n"
},
{
"answer_id": 51402077,
"author": "Bob Baeck",
"author_id": 4042961,
"author_profile": "https://Stackoverflow.com/users/4042961",
"pm_score": 0,
"selected": false,
"text": "<p>When you initiate the connection, it is posible to give as third argument the timout value.</p>\n\n<pre><code>connection = HTTPConnection(<IP of URL>, <port or None>, <timeout>)\n...\n</code></pre>\n\n<p> is a float in seconds.</p>\n\n<pre><code>connection = HTTPConnection('slow.service.com', None, 20.0)\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16148/"
] |
In Python 2.6, a new "timeout" parameter was added to the httplib.HTTPConnection class:
<http://docs.python.org/library/httplib.html#httplib.HTTPConnection>
However, this is only a timeout for the connection to a server. I am looking to set a timeout value for the **request**, not the connection. This doesn't seem to be supported by httplib.
Is there any way to emulate this behavior?
|
You can set a global socket timeout (\*):
```
import socket
timeout = 10
socket.setdefaulttimeout(timeout)
```
---
(\*) **EDIT**: As people in the comments correctly point out: This is technically true, but it only has predictable results for tasks that involve a single socket operation. An HTTP request consists of multiple socket operations (e.g. DNS requests or other things that might be abstracted away from an HTTP client). The timeout of the overall operation becomes unpredictable because of that.
|
265,725 |
<p>I have some constants that represent the valid options in one of my model's fields. What's the best way to handle these constants in Ruby?</p>
|
[
{
"answer_id": 265767,
"author": "Micah",
"author_id": 19964,
"author_profile": "https://Stackoverflow.com/users/19964",
"pm_score": 4,
"selected": false,
"text": "<p>I put them directly in the model class, like so:</p>\n\n<pre><code>class MyClass < ActiveRecord::Base\n ACTIVE_STATUS = \"active\"\n INACTIVE_STATUS = \"inactive\"\n PENDING_STATUS = \"pending\"\nend\n</code></pre>\n\n<p>Then, when using the model from another class, I reference the constants</p>\n\n<pre><code>@model.status = MyClass::ACTIVE_STATUS\[email protected]\n</code></pre>\n"
},
{
"answer_id": 265783,
"author": "Codebeef",
"author_id": 12037,
"author_profile": "https://Stackoverflow.com/users/12037",
"pm_score": 6,
"selected": true,
"text": "<p>You can use an array or hash for this purpose (in your environment.rb):</p>\n\n<pre><code>OPTIONS = ['one', 'two', 'three']\nOPTIONS = {:one => 1, :two => 2, :three => 3}\n</code></pre>\n\n<p>or alternatively an enumeration class, which allows you to enumerate over your constants as well as the keys used to associate them:</p>\n\n<pre><code>class Enumeration\n def Enumeration.add_item(key,value)\n @hash ||= {}\n @hash[key]=value\n end\n\n def Enumeration.const_missing(key)\n @hash[key]\n end \n\n def Enumeration.each\n @hash.each {|key,value| yield(key,value)}\n end\n\n def Enumeration.values\n @hash.values || []\n end\n\n def Enumeration.keys\n @hash.keys || []\n end\n\n def Enumeration.[](key)\n @hash[key]\n end\nend\n</code></pre>\n\n<p>which you can then derive from:</p>\n\n<pre><code>class Values < Enumeration\n self.add_item(:RED, '#f00')\n self.add_item(:GREEN, '#0f0')\n self.add_item(:BLUE, '#00f')\nend\n</code></pre>\n\n<p>and use like this:</p>\n\n<pre><code>Values::RED => '#f00'\nValues::GREEN => '#0f0'\nValues::BLUE => '#00f'\n\nValues.keys => [:RED, :GREEN, :BLUE]\nValues.values => ['#f00', '#0f0', '#00f']\n</code></pre>\n"
},
{
"answer_id": 266003,
"author": "Dema",
"author_id": 407003,
"author_profile": "https://Stackoverflow.com/users/407003",
"pm_score": 3,
"selected": false,
"text": "<p>You can also use it within your model inside a hash like this:</p>\n\n<pre><code>\nclass MyModel\n\n SOME_ATTR_OPTIONS = {\n :first_option => 1,\n :second_option => 2, \n :third_option => 3\n }\nend\n</code></pre>\n\n<p>And use it like this:</p>\n\n<pre><code>\n\nif x == MyModel::SOME_ATTR_OPTIONS[:first_option]\n do this\nend\n\n</code></pre>\n"
},
{
"answer_id": 266747,
"author": "Dave",
"author_id": 34841,
"author_profile": "https://Stackoverflow.com/users/34841",
"pm_score": 3,
"selected": false,
"text": "<p>If it is driving model behavior, then the constants should be part of the model:</p>\n\n<pre><code>class Model < ActiveRecord::Base\n ONE = 1\n TWO = 2\n\n validates_inclusion_of :value, :in => [ONE, TWO]\nend\n</code></pre>\n\n<p>This will allow you to use the built-in Rails functionality:</p>\n\n<pre><code>>> m=Model.new\n=> #<Model id: nil, value: nil, created_at: nil, updated_at: nil>\n>> m.valid?\n=> false\n>> m.value = 1\n=> 1\n>> m.valid?\n=> true\n</code></pre>\n\n<p>Alternatively, if your database supports enumerations, then you can use something like the <a href=\"http://wiki.rubyonrails.org/rails/pages/Enum+Column+in+MySql\" rel=\"nofollow noreferrer\">Enum Column</a> plugin.</p>\n"
},
{
"answer_id": 21023503,
"author": "Simone Carletti",
"author_id": 123527,
"author_profile": "https://Stackoverflow.com/users/123527",
"pm_score": 3,
"selected": false,
"text": "<p>Rails 4.1 added <a href=\"http://edgeguides.rubyonrails.org/4_1_release_notes.html#active-record-enums\" rel=\"noreferrer\">support for ActiveRecord enums</a>.</p>\n\n<p>Declare an enum attribute where the values map to integers in the database, but can be queried by name.</p>\n\n<pre><code>class Conversation < ActiveRecord::Base\n enum status: [ :active, :archived ]\nend\n\nconversation.archived!\nconversation.active? # => false\nconversation.status # => \"archived\"\n\nConversation.archived # => Relation for all archived Conversations\n</code></pre>\n\n<p>See <a href=\"http://api.rubyonrails.org/v4.1.0/classes/ActiveRecord/Enum.html\" rel=\"noreferrer\">its documentation</a> for a detailed write up.</p>\n"
},
{
"answer_id": 41910047,
"author": "Ady Rosen",
"author_id": 2200274,
"author_profile": "https://Stackoverflow.com/users/2200274",
"pm_score": 0,
"selected": false,
"text": "<p>You can also group constants into subjects, using a module -- </p>\n\n<pre><code>class Runner < ApplicationRecord\n module RUN_TYPES\n SYNC = 0\n ASYNC = 1\n end\nend\n</code></pre>\n\n<p>And then have,</p>\n\n<pre><code>> Runner::RUN_TYPES::SYNC\n => 0\n> Runner::RUN_TYPES::ASYNC\n => 1\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/265725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34746/"
] |
I have some constants that represent the valid options in one of my model's fields. What's the best way to handle these constants in Ruby?
|
You can use an array or hash for this purpose (in your environment.rb):
```
OPTIONS = ['one', 'two', 'three']
OPTIONS = {:one => 1, :two => 2, :three => 3}
```
or alternatively an enumeration class, which allows you to enumerate over your constants as well as the keys used to associate them:
```
class Enumeration
def Enumeration.add_item(key,value)
@hash ||= {}
@hash[key]=value
end
def Enumeration.const_missing(key)
@hash[key]
end
def Enumeration.each
@hash.each {|key,value| yield(key,value)}
end
def Enumeration.values
@hash.values || []
end
def Enumeration.keys
@hash.keys || []
end
def Enumeration.[](key)
@hash[key]
end
end
```
which you can then derive from:
```
class Values < Enumeration
self.add_item(:RED, '#f00')
self.add_item(:GREEN, '#0f0')
self.add_item(:BLUE, '#00f')
end
```
and use like this:
```
Values::RED => '#f00'
Values::GREEN => '#0f0'
Values::BLUE => '#00f'
Values.keys => [:RED, :GREEN, :BLUE]
Values.values => ['#f00', '#0f0', '#00f']
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.