qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
37,011 |
<p>Should you ever use protected member variables? What are the the advantages and what issues can this cause?</p>
|
[
{
"answer_id": 194655,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 2,
"selected": false,
"text": "template <typename T, typename TContainer>\nclass Base\n{\n // etc.\n protected\n TContainer container ;\n}\n\ntemplate <typename Key, typename T>\nclass DerivedMap : public Base<T, std::map<Key, T> > { /* etc. */ }\n\ntemplate <typename Key, typename T>\nclass DerivedHashMap : public Base<T, std::hash_map<Key, T> > { /* etc. */ }\n\ntemplate <typename T>\nclass DerivedVector : public Base<T, std::vector<T> > { /* etc. */ }\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3305/"
] |
37,026 |
<p>If one Googles for "difference between <code>notify()</code> and <code>notifyAll()</code>" then a lot of explanations will pop up (leaving apart the javadoc paragraphs). It all boils down to the number of waiting threads being waken up: one in <code>notify()</code> and all in <code>notifyAll()</code>.</p>
<p>However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition; in the first case the one selected by the VM, in the second case the one selected by the system thread scheduler. The exact selection procedures for both of them (in the general case) are not known to the programmer.</p>
<p>What's the <strong>useful</strong> difference between <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notify%28%29" rel="noreferrer">notify()</a> and <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notifyAll%28%29" rel="noreferrer">notifyAll()</a> then? Am I missing something?</p>
|
[
{
"answer_id": 37038,
"author": "Spoike",
"author_id": 3713,
"author_profile": "https://Stackoverflow.com/users/3713",
"pm_score": 2,
"selected": false,
"text": "notify() notifyAll() notify() notifyAll()"
},
{
"answer_id": 37046,
"author": "Liedman",
"author_id": 890,
"author_profile": "https://Stackoverflow.com/users/890",
"pm_score": 9,
"selected": true,
"text": "o.notifyAll() o.wait() o.wait() synchronized(o) {\n while (! IsConditionTrue()) {\n o.wait();\n }\n DoSomethingThatOnlyMakesSenseWhenConditionIsTrue_and_MaybeMakeConditionFalseAgain();\n}\n o.notifyAll() o.wait()"
},
{
"answer_id": 1006498,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "signal() signalAll() java.util.concurrent notify() Thread.interrupt() notifyAll()"
},
{
"answer_id": 2879412,
"author": "Erik",
"author_id": 346719,
"author_profile": "https://Stackoverflow.com/users/346719",
"pm_score": 3,
"selected": false,
"text": "public class ProducerConsumerExample {\n\n private static boolean Even = true;\n private static boolean Odd = false;\n\n public static void main(String[] args) {\n Dropbox dropbox = new Dropbox();\n (new Thread(new Consumer(Even, dropbox))).start();\n (new Thread(new Consumer(Odd, dropbox))).start();\n (new Thread(new Producer(dropbox))).start();\n }\n}\n public class Dropbox {\n\n private int number;\n private boolean empty = true;\n private boolean evenNumber = false;\n\n public synchronized int take(final boolean even) {\n while (empty || evenNumber != even) {\n try {\n System.out.format(\"%s is waiting ... %n\", even ? \"Even\" : \"Odd\");\n wait();\n } catch (InterruptedException e) { }\n }\n System.out.format(\"%s took %d.%n\", even ? \"Even\" : \"Odd\", number);\n empty = true;\n notifyAll();\n\n return number;\n }\n\n public synchronized void put(int number) {\n while (!empty) {\n try {\n System.out.println(\"Producer is waiting ...\");\n wait();\n } catch (InterruptedException e) { }\n }\n this.number = number;\n evenNumber = number % 2 == 0;\n System.out.format(\"Producer put %d.%n\", number);\n empty = false;\n notifyAll();\n }\n}\n import java.util.Random;\n\npublic class Consumer implements Runnable {\n\n private final Dropbox dropbox;\n private final boolean even;\n\n public Consumer(boolean even, Dropbox dropbox) {\n this.even = even;\n this.dropbox = dropbox;\n }\n\n public void run() {\n Random random = new Random();\n while (true) {\n dropbox.take(even);\n try {\n Thread.sleep(random.nextInt(100));\n } catch (InterruptedException e) { }\n }\n }\n}\n import java.util.Random;\n\npublic class Producer implements Runnable {\n\n private Dropbox dropbox;\n\n public Producer(Dropbox dropbox) {\n this.dropbox = dropbox;\n }\n\n public void run() {\n Random random = new Random();\n while (true) {\n int number = random.nextInt(10);\n try {\n Thread.sleep(random.nextInt(100));\n dropbox.put(number);\n } catch (InterruptedException e) { }\n }\n }\n}\n"
},
{
"answer_id": 3186336,
"author": "xagyg",
"author_id": 384464,
"author_profile": "https://Stackoverflow.com/users/384464",
"pm_score": 9,
"selected": false,
"text": "notify notifyAll notifyAll notifyAll notify public synchronized void put(Object o) {\n while (buf.size()==MAX_SIZE) {\n wait(); // called if the buffer is full (try/catch removed for brevity)\n }\n buf.add(o);\n notify(); // called in case there are any getters or putters waiting\n}\n\npublic synchronized Object get() {\n // Y: this is where C2 tries to acquire the lock (i.e. at the beginning of the method)\n while (buf.size()==0) {\n wait(); // called if the buffer is empty (try/catch removed for brevity)\n // X: this is where C1 tries to re-acquire the lock (see below)\n }\n Object o = buf.remove(0);\n notify(); // called if there are any getters or putters waiting\n return o;\n}\n while wait notify while while IndexArrayOutOfBoundsException notify put get buf.size() == 0 AND buf.size() == MAX_SIZE notifyAll put put get get get notify notify put notify notifyAll"
},
{
"answer_id": 8390277,
"author": "Kshitij Banerjee",
"author_id": 985306,
"author_profile": "https://Stackoverflow.com/users/985306",
"pm_score": 0,
"selected": false,
"text": "notify() wait() notifyAll() wait()"
},
{
"answer_id": 9880331,
"author": "alxlevin",
"author_id": 1294054,
"author_profile": "https://Stackoverflow.com/users/1294054",
"pm_score": 2,
"selected": false,
"text": "buf.size() != MAX_SIZE buf.size() != 0 buf.size() notify() notifyAll() buf.size() MAX_SIZE get()"
},
{
"answer_id": 17158435,
"author": "Alexander Ryzhov",
"author_id": 1713695,
"author_profile": "https://Stackoverflow.com/users/1713695",
"pm_score": 2,
"selected": false,
"text": "notify() notifyAll() synchronized(this) {\n while(busy) // a loop is necessary here\n wait();\n busy = true;\n}\n...\nsynchronized(this) {\n busy = false;\n notifyAll();\n}\n notify() synchronized(this) {\n if(busy) // replaced the loop with a condition which is evaluated only once\n wait();\n busy = true;\n}\n...\nsynchronized(this) {\n busy = false;\n notify();\n}\n notify() notifyAll() notifyAll() notify() notifyAll() synchronized(this) {\n while(idx != last+1) // wait until it's my turn\n wait();\n}\n...\nsynchronized(this) {\n last = idx;\n notifyAll();\n}\n notifyAll() synchronized notifyAll() while true wait() while"
},
{
"answer_id": 18650599,
"author": "AKS",
"author_id": 1669747,
"author_profile": "https://Stackoverflow.com/users/1669747",
"pm_score": 2,
"selected": false,
"text": "It will be NotifyAll, and reason is that it will save from signall hijacking.\n"
},
{
"answer_id": 33329952,
"author": "fireboy91",
"author_id": 4673384,
"author_profile": "https://Stackoverflow.com/users/4673384",
"pm_score": 2,
"selected": false,
"text": "notify() BLOCKED WAITING notifyAll() BLOCKED notifyAll() BLOCKED WAITING BLOCKED WAITING"
},
{
"answer_id": 44175631,
"author": "Marco",
"author_id": 3721542,
"author_profile": "https://Stackoverflow.com/users/3721542",
"pm_score": 3,
"selected": false,
"text": "while (!empty) {\n wait() // on full\n}\nput()\nnotify()\n while (empty) {\n wait() // on empty\n}\ntake()\nnotify()\n"
},
{
"answer_id": 46414690,
"author": "rajya vardhan",
"author_id": 161243,
"author_profile": "https://Stackoverflow.com/users/161243",
"pm_score": 2,
"selected": false,
"text": "The notifyAll method should generally be used in preference to notify. \n\nIf notify is used, great care must be taken to ensure liveness.\n"
},
{
"answer_id": 64409492,
"author": "haoyu wang",
"author_id": 12824504,
"author_profile": "https://Stackoverflow.com/users/12824504",
"pm_score": 0,
"selected": false,
"text": "Object.wait notify notifyAll notifyAll notifyAll notify notify notify notifyALl"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3894/"
] |
37,029 |
<p>It is generally accepted that the use of cursors in stored procedures should be avoided where possible (replaced with set based logic etc). If you take the cases where you need to iterate over some data, and can do in a read only manner, are fast forward (read only forward) cursor more or less inefficient than say while loops? From my investigations it looks as though the cursor option is generally faster and uses less reads and cpu time. I haven't done any extensive testing, but is this what others find? Do cursors of this type (fast forward) carry additional overhead or resource that could be expensive that I don't know about.</p>
<p>Is all the talk about not using cursors really about avoiding the use of cursors when set-based approaches are available, and the use of updatable cursors etc.</p>
|
[
{
"answer_id": 461370,
"author": "Miles D",
"author_id": 3898,
"author_profile": "https://Stackoverflow.com/users/3898",
"pm_score": 2,
"selected": false,
"text": "SELECT INSERT UPDATE DELETE FROM FAST FORWARD"
},
{
"answer_id": 27359172,
"author": "Fabiano Novaes Ferreira",
"author_id": 4337447,
"author_profile": "https://Stackoverflow.com/users/4337447",
"pm_score": 2,
"selected": false,
"text": "IF OBJECT_ID('Funcionarios') IS NOT NULL\nDROP TABLE Funcionarios\nGO\n\nCREATE TABLE Funcionarios(ID Int IDENTITY(1,1) PRIMARY KEY,\n ContactName Char(7000),\n Salario Numeric(18,2));\nGO\n\nINSERT INTO Funcionarios(ContactName, Salario) VALUES('Fabiano', 1900)\nINSERT INTO Funcionarios(ContactName, Salario) VALUES('Luciano',2050)\nINSERT INTO Funcionarios(ContactName, Salario) VALUES('Gilberto', 2070)\nINSERT INTO Funcionarios(ContactName, Salario) VALUES('Ivan', 2090)\nGO\n\nCREATE NONCLUSTERED INDEX ix_Salario ON Funcionarios(Salario)\nGO\n\n-- Halloween problem, will update all rows until then reach 3000 !!!\nUPDATE Funcionarios SET Salario = Salario * 1.1\n FROM Funcionarios WITH(index=ix_Salario)\n WHERE Salario < 3000\nGO\n\n-- Simulate here with all different CURSOR declarations\n-- DYNAMIC update the rows until all of then reach 3000\n-- FAST_FORWARD update the rows until all of then reach 3000\n-- STATIC update the rows only one time. \n\nBEGIN TRAN\nDECLARE @ID INT\nDECLARE TMP_Cursor CURSOR DYNAMIC \n--DECLARE TMP_Cursor CURSOR FAST_FORWARD\n--DECLARE TMP_Cursor CURSOR STATIC READ_ONLY FORWARD_ONLY\n FOR SELECT ID \n FROM Funcionarios WITH(index=ix_Salario)\n WHERE Salario < 3000\n\nOPEN TMP_Cursor\n\nFETCH NEXT FROM TMP_Cursor INTO @ID\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n SELECT * FROM Funcionarios WITH(index=ix_Salario)\n\n UPDATE Funcionarios SET Salario = Salario * 1.1 \n WHERE ID = @ID\n\n FETCH NEXT FROM TMP_Cursor INTO @ID\nEND\n\nCLOSE TMP_Cursor\nDEALLOCATE TMP_Cursor\n\nSELECT * FROM Funcionarios\n\nROLLBACK TRAN\nGO\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3898/"
] |
37,041 |
<p>I have a question on the best way of exposing an asynchronous remote interface.</p>
<p>The conditions are as follows:</p>
<ul>
<li>The protocol is asynchronous</li>
<li>A third party can modify the data at any time</li>
<li>The command round-trip can be significant</li>
<li>The model should be well suited for UI interaction</li>
<li>The protocol supports queries over certain objects, and so must the model</li>
</ul>
<p>As a means of improving my lacking skills in this area (and brush up my Java in general), I have started a <a href="http://Telharmonium.devjavu.com/" rel="nofollow noreferrer">project</a> to create an Eclipse-based front-end for <a href="http://xmms2.xmms.se" rel="nofollow noreferrer">xmms2</a> (described below).</p>
<p>So, the question is; how should I expose the remote interface as a neat data model (In this case, track management and event handling)?</p>
<p>I welcome anything from generic discussions to pattern name-dropping or concrete examples and patches :)</p>
<hr>
<p>My primary goal here is learning about this class of problems in general. If my project can gain from it, fine, but I present it strictly to have something to start a discussion around.</p>
<p>I've implemented a protocol abstraction which I call <a href="http://telharmonium.devjavu.com/browser/trunk/xmms2-client" rel="nofollow noreferrer">'client'</a> (for legacy reasons) which allows me to access most exposed features using method calls which I am happy with even if it's far from perfect.</p>
<p>The features provided by the xmms2 daemon are things like track searching, meta-data retrieval and manipulation, change playback state, load playlists and so on and so forth.</p>
<p>I'm in the middle of updating to the latest stable release of xmms2, and I figured I might as well fix some of the glaring weaknesses of my current implementation.</p>
<p>My plan is to build a better abstraction on top of the protocol interface, one that allows a more natural interaction with the daemon. The current <a href="http://telharmonium.devjavu.com/browser/trunk/xmms2-model" rel="nofollow noreferrer">'model'</a> implementation is hard to use and is frankly quite ugly (not to mention the UI-code which is truly horrible atm).</p>
<p>Today I have the <a href="http://telharmonium.devjavu.com/browser/trunk/xmms2-model/src/se/fnord/xmms2/model/Tracks.java" rel="nofollow noreferrer">Tracks</a> interface which I can use to get instances of <a href="http://telharmonium.devjavu.com/browser/trunk/xmms2-model/src/se/fnord/xmms2/model/Track.java" rel="nofollow noreferrer">Track</a> classes based on their id. Searching is performed through the <a href="http://telharmonium.devjavu.com/browser/trunk/xmms2-model/src/se/fnord/xmms2/model/Collections.java" rel="nofollow noreferrer">Collections</a> interface (unfortunate namespace clash) which I'd rather move to Tracks, I think.</p>
<p>Any data can be modified by a third party at any time, and this should be properly reflected in the model and change-notifications distributed</p>
<p>These interfaces are exposed when connecting, by returning an object hierarchy that looks like this:</p>
<ul>
<li>Connection
<ul>
<li>Playback getPlayback()
<ul>
<li>Play, pause, jump, current track etc</li>
<li>Expose playback state changes</li>
</ul></li>
<li>Tracks getTracks()
<ul>
<li>Track getTrack(id) etc</li>
<li>Expose track updates</li>
</ul></li>
<li>Collections getCollection()
<ul>
<li>Load and manipulate playlists or named collections</li>
<li>Query media library</li>
<li>Expose collection updates</li>
</ul></li>
</ul></li>
</ul>
|
[
{
"answer_id": 37093,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 3,
"selected": true,
"text": "java.util.concurrent Future<T> Iterable QuerySet Iterable<Song> allSongs() allSongs().artist(\"Beatles\") allSongs().artist(\"Beatles\").years(1965,1967)"
},
{
"answer_id": 37123,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 0,
"selected": false,
"text": "somehandlername(int changes, Track old_track, Track new_track)\n Tracks.allSongs().artist(\"Beatles\").years(1965,1967).execute()\n"
},
{
"answer_id": 37933,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 0,
"selected": false,
"text": "class Track {\n public final String album;\n public final String artist;\n public final String title;\n public final String genre;\n public final String comment;\n\n public final String cover_id;\n\n public final long duration;\n public final long bitrate;\n public final long samplerate;\n public final long id;\n public final Date date;\n\n /* Some more stuff here */\n}\n interface TrackUpdateListener {\n void trackUpdate(Track oldTrack, Track newTrack);\n}\n interface TrackQuery extends Iterable<Track> {\n TrackQuery years(int from, int to);\n TrackQuery artist(String name);\n TrackQuery album(String name);\n TrackQuery id(long id);\n TrackQuery ids(long id[]);\n\n Future<Track[]> get();\n}\n tracks.allTracks();\ntracks.allTracks().artist(\"Front 242\").album(\"Tyranny (For You)\");\n interface Tracks {\n TrackQuery allTracks();\n\n void addUpdateListener(TrackUpdateListener listener);\n void removeUpdateListener(TrackUpdateListener listener);\n}\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2010/"
] |
37,048 |
<p>Can anyone advise on how to crop an image, let's say jpeg, without using any .NET framework constructs, just raw bytes? Since this is the only* way in Silverlight...</p>
<p>Or point to a library?</p>
<p>I'm not concerned with rendering i'm wanting to manipulate a jpg before uploading.</p>
<p>*There are no GDI+(System.Drawing) or WPF(System.Windows.Media.Imaging) libraries available in Silverlight.</p>
<p>Lockbits requires GDI+, clarified question</p>
<p>Using fjcore: <a href="http://code.google.com/p/fjcore/" rel="nofollow noreferrer">http://code.google.com/p/fjcore/</a> to resize but no way to crop :(</p>
|
[
{
"answer_id": 97669,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "for (int y = 0; y < _newHeight; y++)\n{\n i_sY = (int)sY; sX = 0;\n\n UpdateProgress((double)y / _newHeight);\n\n for (int x = 0; x < _newWidth; x++)\n {\n i_sX = (int)sX;\n\n _destinationData[0][x, y] = _sourceData[0][i_sX, i_sY];\n\n if (_color) {\n\n _destinationData[1][x, y] = _sourceData[1][i_sX, i_sY];\n _destinationData[2][x, y] = _sourceData[2][i_sX, i_sY];\n }\n\n sX += xStep;\n }\n sY += yStep;\n}\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
] |
37,053 |
<p>I'm trying to find out the 'correct' windows API for finding out the localized name of 'special' folders, specifically the Recycle Bin. I want to be able to prompt the user with a suitably localized dialog box asking them if they want to send files to the recycle bin or delete them directly.</p>
<p>I've found lots on the internet (and on Stackoverflow) about how to do the actual deletion, and it seems simple enough, I just really want to be able to have the text localized.</p>
|
[
{
"answer_id": 7417694,
"author": "ladenedge",
"author_id": 222481,
"author_profile": "https://Stackoverflow.com/users/222481",
"pm_score": 0,
"selected": false,
"text": "public static string GetLocalizedRecycleBinName()\n{\n IntPtr relative_pidl, parent_ptr, absolute_pidl;\n\n PInvoke.SHGetFolderLocation(IntPtr.Zero, PInvoke.CSIDL.BitBucket,\n IntPtr.Zero, 0, out absolute_pidl);\n try\n {\n PInvoke.SHBindToParent(absolute_pidl,\n ref PInvoke.Guids.IID_IShellFolder,\n out parent_ptr, out relative_pidl);\n PInvoke.IShellFolder shell_folder =\n Marshal.GetObjectForIUnknown(parent_ptr)\n as PInvoke.IShellFolder;\n // Release() for this object is called at finalization\n if (shell_folder == null)\n return Strings.RecycleBin;\n\n PInvoke.STRRET strret = new PInvoke.STRRET();\n StringBuilder sb = new StringBuilder(260);\n shell_folder.GetDisplayNameOf(relative_pidl, PInvoke.SHGNO.Normal,\n out strret);\n PInvoke.StrRetToBuf(ref strret, relative_pidl, sb, 260);\n string name = sb.ToString();\n\n return String.IsNullOrEmpty(name) ? Strings.RecycleBin : name;\n }\n finally { PInvoke.ILFree(absolute_pidl); }\n}\n\nstatic class PInvoke\n{\n [DllImport(\"shell32.dll\")]\n public static extern int SHGetFolderLocation(IntPtr hwndOwner,\n CSIDL nFolder, IntPtr hToken, uint dwReserved, out IntPtr ppidl);\n\n [DllImport(\"shell32.dll\")]\n public static extern int SHBindToParent(IntPtr lpifq, [In] ref Guid riid,\n out IntPtr ppv, out IntPtr pidlLast);\n\n [DllImport(\"shlwapi.dll\")]\n public static extern Int32 StrRetToBuf(ref STRRET pstr, IntPtr pidl,\n StringBuilder pszBuf, uint cchBuf);\n\n [DllImport(\"shell32.dll\")]\n public static extern void ILFree([In] IntPtr pidl);\n\n [ComImport]\n [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n [Guid(\"000214E6-0000-0000-C000-000000000046\")]\n public interface IShellFolder\n {\n [PreserveSig]\n Int32 CompareIDs(Int32 lParam, IntPtr pidl1, IntPtr pidl2);\n void ParseDisplayName(IntPtr hwnd, IntPtr pbc, String pszDisplayName,\n UInt32 pchEaten, out IntPtr ppidl, UInt32 pdwAttributes);\n void EnumObjects(IntPtr hwnd, int grfFlags,\n out IntPtr ppenumIDList);\n void BindToObject(IntPtr pidl, IntPtr pbc, [In] ref Guid riid,\n out IntPtr ppv);\n void BindToStorage(IntPtr pidl, IntPtr pbc, [In] ref Guid riid,\n out IntPtr ppv);\n void CreateViewObject(IntPtr hwndOwner, [In] ref Guid riid,\n out IntPtr ppv);\n void GetAttributesOf(UInt32 cidl,\n [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]\n IntPtr[] apidl, ref uint rgfInOut);\n void GetUIObjectOf(IntPtr hwndOwner, UInt32 cidl,\n [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]\n IntPtr[] apidl, [In] ref Guid riid, UInt32 rgfReserved,\n out IntPtr ppv);\n void GetDisplayNameOf(IntPtr pidl, SHGNO uFlags, out STRRET pName);\n void SetNameOf(IntPtr hwnd, IntPtr pidl, string pszName,\n int uFlags, out IntPtr ppidlOut);\n }\n\n public enum CSIDL\n {\n BitBucket = 0x000a,\n }\n\n public enum SHGNO\n {\n Normal = 0x0000, ForParsing = 0x8000,\n }\n\n [StructLayout(LayoutKind.Explicit, Size = 520)]\n public struct STRRETinternal\n {\n [FieldOffset(0)] public IntPtr pOleStr;\n [FieldOffset(0)] public IntPtr pStr;\n [FieldOffset(0)] public uint uOffset;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n public struct STRRET\n {\n public uint uType;\n public STRRETinternal data;\n }\n\n public class Guids\n {\n public static Guid IID_IShellFolder =\n new Guid(\"{000214E6-0000-0000-C000-000000000046}\");\n }\n}\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1849/"
] |
37,056 |
<p>I'm setting up a web application with a FreeBSD PostgreSQL back-end. I'm looking for some database performance optimization tool/technique.</p>
|
[
{
"answer_id": 65180,
"author": "brianestes",
"author_id": 8993,
"author_profile": "https://Stackoverflow.com/users/8993",
"pm_score": 2,
"selected": false,
"text": "#log_min_duration_statement = -1 # -1 is disabled, 0 logs all statements\n # and their durations, > 0 logs only\n # statements running at least this time.\n"
},
{
"answer_id": 20422573,
"author": "Michael Renner",
"author_id": 183622,
"author_profile": "https://Stackoverflow.com/users/183622",
"pm_score": 3,
"selected": false,
"text": "pgfouine pgbadger pgfouine pgbadger pg_stat_statements pg_stat_plans pg_statsinfo pg_stats_reporter pg_stat_statements pg_stat_plans pganalyze"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2313/"
] |
37,069 |
<p>On Mac OS X 10.5 I downloaded the latest version of Apache 2.2.9. After the usual configure, make, make install dance I had a build of apache without mod_rewrite. This wasn't statically linked and the module was not built in the /modules folder either.</p>
<p>I had to do the following to build Apache and mod_rewrite:</p>
<pre><code>./configure --prefix=/usr/local/apache2 --enable-rewrite=shared
</code></pre>
<ul>
<li>Is there a way to tell Apache to build all modules as Shared Modules (DSOs) so I can control loading from the Apache config?</li>
<li>Now that I have built Apache and the mod_rewrite DSO, how can I build another shared module without building all of Apache?</li>
</ul>
<p>(The last time I built Apache (2.2.8) on Solaris, by default it built everything as a shared module.)</p>
|
[
{
"answer_id": 37111,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 5,
"selected": true,
"text": "./configure --enable-mods-shared=\"all\" --enable-mods-shared=\"<list of modules>\" --enable-so"
},
{
"answer_id": 9094896,
"author": "so_mv",
"author_id": 186858,
"author_profile": "https://Stackoverflow.com/users/186858",
"pm_score": 1,
"selected": false,
"text": "./configure --prefix=/usr/local/apache2 --enable-mods-shared=\"all\" --enable-proxy=shared\n v2.2.22"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
] |
37,070 |
<p>This is a somewhat low-level question. In x86 assembly there are two SSE instructions: </p>
<blockquote>
<p><code>MOVDQA <i><em>xmmi, m128</em></i></code></p>
</blockquote>
<p>and </p>
<blockquote>
<p><code>MOVNTDQA <i><em>xmmi, m128</em></i></code></p>
</blockquote>
<p>The IA-32 Software Developer's Manual says that the <em>NT</em> in MOVNTDQA stands for <em>Non-Temporal</em>, and that otherwise it's the same as MOVDQA.</p>
<p>My question is, what does <em>Non-Temporal</em> mean? </p>
|
[
{
"answer_id": 53199688,
"author": "chus",
"author_id": 1037634,
"author_profile": "https://Stackoverflow.com/users/1037634",
"pm_score": 4,
"selected": false,
"text": "prefetchnta"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
] |
37,073 |
<p>What is currently the best way to get a favicon to display in all browsers that currently support it?</p>
<p>Please include:</p>
<ol>
<li><p>Which image formats are supported by which browsers.</p></li>
<li><p>Which lines are needed in what places for the various browsers.</p></li>
</ol>
|
[
{
"answer_id": 37076,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 2,
"selected": false,
"text": "favicon.* <link rel=\"icon\" type=\"image/png\" href=\"/path/image.png\" />\n"
},
{
"answer_id": 37091,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 3,
"selected": false,
"text": "<head> <link rel=\"icon\" href=\"/favicon.ico\" type=\"image/x-icon\" />\n<link rel=\"shortcut icon\" href=\"/favicon.ico\" type=\"image/x-icon\" />\n"
},
{
"answer_id": 37321,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 8,
"selected": true,
"text": ".ico .png favicon.ico favicon.png favicon.ico <head> .ico type"
},
{
"answer_id": 15543670,
"author": "Willem de Wit",
"author_id": 1474739,
"author_profile": "https://Stackoverflow.com/users/1474739",
"pm_score": 3,
"selected": false,
"text": "(57px*57px) HiDPI (32x32px)"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177/"
] |
37,089 |
<p>When launching a thread or a process in .NET or Java, is there a way to choose which processor or core it is launched on? How does the shared memory model work in such cases?</p>
|
[
{
"answer_id": 37117,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "Processes Set Affinity..."
},
{
"answer_id": 37127,
"author": "sieben",
"author_id": 1147,
"author_profile": "https://Stackoverflow.com/users/1147",
"pm_score": 0,
"selected": false,
"text": "// Programmatically set process affinity\nvar process = System.Diagnostics.Process.GetCurrentProcess();\n\n// Set Core 0\nprocess.ProcessorAffinity = new IntPtr(0x0001);\n // Set Core 1\nprocess.ProcessorAffinity = new IntPtr(0x0002);\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/646/"
] |
37,095 |
<p>How do I avoid read locks in my database?</p>
<p>Answers for multiple databases welcome!</p>
|
[
{
"answer_id": 37099,
"author": "Joe Barone",
"author_id": 3452,
"author_profile": "https://Stackoverflow.com/users/3452",
"pm_score": 2,
"selected": false,
"text": "Select table1.columna, table2.columna\nfrom table1 with(nolock), table2 with(nolock)\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] |
37,101 |
<p>Is there a way clear or reset the outputcache for an entire website without a restart?</p>
<p>I'm just starting to use outputcache on a site and when I make a mistake in setting it up I need a page I can browse to that will reset it.</p>
|
[
{
"answer_id": 37167,
"author": "Ethan Gunderson",
"author_id": 2066,
"author_profile": "https://Stackoverflow.com/users/2066",
"pm_score": 4,
"selected": true,
"text": "Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)\n\n Dim path As String\n path=\"/AbosoluteVirtualPath/OutputCached.aspx\"\n HttpResponse.RemoveOutputCacheItem(path)\n\nEnd Sub\n"
},
{
"answer_id": 12877327,
"author": "Andrus",
"author_id": 742402,
"author_profile": "https://Stackoverflow.com/users/742402",
"pm_score": 0,
"selected": false,
"text": "HttpContext.Cache.Insert(\"Page\", 1);\nResponse.AddCacheItemDependency(\"Page\");\n HttpContext.Cache.Remove(\"Page\");\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] |
37,103 |
<p>I have a container div with a fixed <code>width</code> and <code>height</code>, with <code>overflow: hidden</code>.</p>
<p>I want a horizontal row of float: left divs within this container. Divs which are floated left will naturally push onto the 'line' below after they read the right bound of their parent. This will happen even if the <code>height</code> of the parent should not allow this. This is how this looks:</p>
<p><img src="https://i.stack.imgur.com/v2x7d.png" alt="Wrong" /></p>
<p>How I would like it to look:</p>
<p>![Right][2] - <em>removed image shack image that had been replaced by an advert</em></p>
<p>Note: the effect I want can be achieved by using inline elements & <code>white-space: no-wrap</code> (that is how I did it in the image shown). This, however, is no good to me (for reasons too lengthy to explain here), as the child divs need to be floated block level elements.</p>
|
[
{
"answer_id": 37125,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 3,
"selected": false,
"text": "#foo {\n background: red;\n max-height: 100px;\n overflow-y: hidden;\n}\n\n.bar {\n background: blue;\n width: 100px;\n height: 100px;\n float: left;\n margin: 1em;\n} <div id=\"foo\">\n <div class=\"bar\"></div>\n <div class=\"bar\"></div>\n <div class=\"bar\"></div>\n <div class=\"bar\"></div>\n <div class=\"bar\"></div>\n <div class=\"bar\"></div>\n</div>"
},
{
"answer_id": 37129,
"author": "fcurella",
"author_id": 3914,
"author_profile": "https://Stackoverflow.com/users/3914",
"pm_score": 2,
"selected": false,
"text": "clip #container {\n position: absolute;\n clip: rect(0px,200px,100px,0px);\n overflow: hidden;\n background: red;\n}\n position: absolute overflow: hidden clip"
},
{
"answer_id": 37131,
"author": "LucaM",
"author_id": 3511,
"author_profile": "https://Stackoverflow.com/users/3511",
"pm_score": 8,
"selected": true,
"text": "#container {\n background-color: red;\n overflow: hidden;\n width: 200px;\n}\n\n#inner {\n overflow: hidden;\n width: 2000px;\n}\n\n.child {\n float: left;\n background-color: blue;\n width: 50px;\n height: 50px;\n} <div id=\"container\">\n <div id=\"inner\">\n <div class=\"child\"></div>\n <div class=\"child\"></div>\n <div class=\"child\"></div>\n </div>\n</div>"
},
{
"answer_id": 5648296,
"author": "Kwex",
"author_id": 705902,
"author_profile": "https://Stackoverflow.com/users/705902",
"pm_score": 5,
"selected": false,
"text": "style=\"overflow:hidden\" div style=\"float: left\" divs divs style=\"display: table-cell\" divs"
},
{
"answer_id": 11717454,
"author": "Wolfpack'08",
"author_id": 445651,
"author_profile": "https://Stackoverflow.com/users/445651",
"pm_score": 0,
"selected": false,
"text": "id=\"container\""
},
{
"answer_id": 32277117,
"author": "William B",
"author_id": 5046541,
"author_profile": "https://Stackoverflow.com/users/5046541",
"pm_score": 2,
"selected": false,
"text": "white-space: nowrap"
},
{
"answer_id": 38420482,
"author": "sriram hegde",
"author_id": 5065439,
"author_profile": "https://Stackoverflow.com/users/5065439",
"pm_score": 3,
"selected": false,
"text": "parent-div {\n display: flex;\n flex-wrap: wrap;\n /* for horizontal aligning of child divs */\n justify-content: center;\n /* for vertical aligning */\n align-items: center;\n}\n\nchild-div {\n width: /* yoursize for each div */\n ;\n}\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1349865/"
] |
37,104 |
<p>What's are the best practices for versioning web sites?</p>
<ul>
<li>Which revision control systems are well suited for such a job?</li>
<li>What special-purpose tools exist?</li>
<li>What other questions should I be asking?</li>
</ul>
|
[
{
"answer_id": 37147,
"author": "Christian Lescuyer",
"author_id": 341,
"author_profile": "https://Stackoverflow.com/users/341",
"pm_score": 2,
"selected": false,
"text": "<?php print(\"$Revision: 1 $\"); ?>\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] |
37,122 |
<p>How do I make a user's browser blink/flash/highlight in the task bar using JavaScript? For example, if I make an AJAX request every 10 seconds to see if the user has any new messages on the server, I want the user to know it right away, even if he is using another application at the time.</p>
<p><em>Edit: These users do want to be distracted when a new message arrives.</em></p>
|
[
{
"answer_id": 37283,
"author": "Toran Billups",
"author_id": 2701,
"author_profile": "https://Stackoverflow.com/users/2701",
"pm_score": 1,
"selected": false,
"text": "document.title = \"[user] hello world\";\n"
},
{
"answer_id": 156274,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 7,
"selected": true,
"text": "newExcitingAlerts = (function () {\n var oldTitle = document.title;\n var msg = \"New!\";\n var timeoutId;\n var blink = function() { document.title = document.title == msg ? ' ' : msg; };\n var clear = function() {\n clearInterval(timeoutId);\n document.title = oldTitle;\n window.onmousemove = null;\n timeoutId = null;\n };\n return function () {\n if (!timeoutId) {\n timeoutId = setInterval(blink, 1000);\n window.onmousemove = clear;\n }\n };\n}());\n"
},
{
"answer_id": 3886467,
"author": "heyman",
"author_id": 27406,
"author_profile": "https://Stackoverflow.com/users/27406",
"pm_score": 6,
"selected": false,
"text": "$.titleAlert(\"New mail!\", {\n requireBlur:true,\n stopOnFocus:true,\n interval:600\n});\n"
},
{
"answer_id": 31615360,
"author": "Rikki Goswami",
"author_id": 5153189,
"author_profile": "https://Stackoverflow.com/users/5153189",
"pm_score": 3,
"selected": false,
"text": " var oldTitle = document.title;\n var msg = \"New Popup!\";\n var timeoutId = false;\n\n var blink = function() {\n document.title = document.title == msg ? oldTitle : msg;//Modify Title in case a popup\n\n if(document.hasFocus())//Stop blinking and restore the Application Title\n {\n document.title = oldTitle;\n clearInterval(timeoutId);\n } \n };\n\n if (!timeoutId) {\n timeoutId = setInterval(blink, 500);//Initiate the Blink Call\n };//Blink logic \n"
},
{
"answer_id": 57670498,
"author": "prashantsahni",
"author_id": 1076982,
"author_profile": "https://Stackoverflow.com/users/1076982",
"pm_score": 0,
"selected": false,
"text": "function blinkTab() {\n const browserTitle = document.title;\n let timeoutId;\n let message = 'My New Title';\n\n const stopBlinking = () => {\n document.title = browserTitle;\n clearInterval(timeoutId);\n };\n\n const startBlinking = () => {\n document.title = document.title === message ? browserTitle : message;\n };\n\n function registerEvents() {\n window.addEventListener(\"focus\", function(event) { \n stopBlinking();\n });\n\n window.addEventListener(\"blur\", function(event) {\n const timeoutId = setInterval(startBlinking, 500);\n });\n };\n\n registerEvents();\n };\n\n\n blinkTab();\n"
},
{
"answer_id": 66188187,
"author": "Ingo",
"author_id": 2278668,
"author_profile": "https://Stackoverflow.com/users/2278668",
"pm_score": -1,
"selected": false,
"text": "via Javascript \n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191/"
] |
37,142 |
<p>Even though <a href="http://twistedmatrix.com/pipermail/twisted-python/2004-May/007896.html" rel="noreferrer">Python</a> and <a href="http://www.reddit.com/comments/6wmum/thread_safe_ruby_on_rails_in_22_release/" rel="noreferrer">Ruby</a> have one kernel thread per interpreter thread, they have a global interpreter lock (GIL) that is used to protect potentially shared data structures, so this inhibits multi-processor execution. Even though the portions in those languajes that are written in C or C++ can be free-threaded, that's not possible with pure interpreted code unless you use multiple processes. What's the best way to achieve this? <a href="http://blogs.codehaus.org/people/tirsen/archives/001041_ruby_on_rails_and_fastcgi_scaling_using_processes_instead_of_threads.html" rel="noreferrer">Using FastCGI</a>? Creating a <a href="http://blog.innerewut.de/files/images/stage_2.png" rel="noreferrer">cluster or a farm</a> of virtualized servers? Using their Java equivalents, JRuby and Jython?</p>
|
[
{
"answer_id": 37146,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 1,
"selected": false,
"text": "mod_wsgi mod_wsgi"
},
{
"answer_id": 191257,
"author": "David Eyk",
"author_id": 18950,
"author_profile": "https://Stackoverflow.com/users/18950",
"pm_score": 0,
"selected": false,
"text": "multiprocessing"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3855/"
] |
37,162 |
<p>We generate web pages that should always be printed in landscape mode. Web browser print dialogs default to portrait, so for every print job the user has to manually select landscape. It's minor, but would be nice for the user if we can remove this unnecessary step. </p>
<p>Thanks in advance to all respondents.</p>
|
[
{
"answer_id": 37168,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 1,
"selected": false,
"text": "@page"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3915/"
] |
37,198 |
<ol>
<li>Specifically getting on Windows the "..\Documents & Settings\All Users, basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on. <strong>(Now I need the answer to this)</strong></li>
<li>the current users My Documents dirctory <strong>(okay this has been answered)</strong>
and basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on.</li>
</ol>
|
[
{
"answer_id": 37240,
"author": "nimish",
"author_id": 3926,
"author_profile": "https://Stackoverflow.com/users/3926",
"pm_score": 3,
"selected": false,
"text": "System.getProperty(\"user.home\");\n"
},
{
"answer_id": 37693,
"author": "Lee Theobald",
"author_id": 1900,
"author_profile": "https://Stackoverflow.com/users/1900",
"pm_score": 2,
"selected": false,
"text": "System.getProperty(\"...\");\n System.getProperty(\"os.name\");\n System.getProperty(\"user.home\");\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3576/"
] |
37,219 |
<p>Suppose your git history looks like this:</p>
<p>1
2
3
4
5</p>
<p>1–5 are separate revisions. You need to remove 3 while still keeping 1, 2, 4 and 5. How can this be done?</p>
<p>Is there an efficient method when there are hundreds of revisions after the one to be deleted?</p>
|
[
{
"answer_id": 37267,
"author": "garethm",
"author_id": 2219,
"author_profile": "https://Stackoverflow.com/users/2219",
"pm_score": 7,
"selected": true,
"text": "git rebase -i <after-this-commit>"
},
{
"answer_id": 3705310,
"author": "rado",
"author_id": 127388,
"author_profile": "https://Stackoverflow.com/users/127388",
"pm_score": 7,
"selected": false,
"text": "<commit-id> <commit-id> git rebase --onto <commit-id>^ <commit-id> HEAD\n"
},
{
"answer_id": 4110978,
"author": "rvernica",
"author_id": 418730,
"author_profile": "https://Stackoverflow.com/users/418730",
"pm_score": 6,
"selected": false,
"text": "master git rebase --onto master~3 master~2 master\n 1---2---3---4---5 master\n 1---2---4'---5' master\n E---F---G---H---I---J topicA\n git rebase --onto topicA~5 topicA~3 topicA\n E---H'---I'---J' topicA\n"
},
{
"answer_id": 12567860,
"author": "jdsumsion",
"author_id": 1667497,
"author_profile": "https://Stackoverflow.com/users/1667497",
"pm_score": 4,
"selected": false,
"text": "[master] -> [hundreds-of-commits-including-merges] -> [C] -> [R] -> [B]\n git branch base B git branch remove-me R git branch save git rebase --preserve-merges --onto base remove-me rebase --continue rebase --abort master save stash reset --hard cherry-pick base remove-me save"
},
{
"answer_id": 13389977,
"author": "kareem",
"author_id": 62251,
"author_profile": "https://Stackoverflow.com/users/62251",
"pm_score": 7,
"selected": false,
"text": "HEAD <commit-id> git rebase --onto <commit-id>^ <commit-id>\n"
},
{
"answer_id": 26753212,
"author": "Gautam",
"author_id": 492561,
"author_profile": "https://Stackoverflow.com/users/492561",
"pm_score": 2,
"selected": false,
"text": "[branch-a]\n\n[Hundreds of commits] -> [R] -> [I]\n R I R git revert [commit id of R]\ngit rebase -i HEAD~3\n"
},
{
"answer_id": 39358948,
"author": "Sankalp",
"author_id": 1883278,
"author_profile": "https://Stackoverflow.com/users/1883278",
"pm_score": 2,
"selected": false,
"text": "git rebase -i remote/branch\n"
},
{
"answer_id": 46213462,
"author": "fdermishin",
"author_id": 502144,
"author_profile": "https://Stackoverflow.com/users/502144",
"pm_score": 0,
"selected": false,
"text": "git rebase --onto <commit-id>^ <commit-id>\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146/"
] |
37,248 |
<p>While the C# spec does include a pre-processor and basic directives (#define, #if, etc), the language does not have the same flexible pre-processor found in languages such as C/C++. I believe the lack of such a flexible pre-processor was a design decision made by Anders Hejlsberg (although, unfortunately, I can't find reference to this now). From experience, this is certainly a good decision, as there were some really terrible un-maintainable macros created back when I was doing a lot of C/C++. </p>
<p>That said, there are a number of scenarios where I could find a slightly more flexible pre-processor to be useful. Code such as the following could be improved by some simple pre-processor directives:</p>
<pre><code>public string MyProperty
{
get { return _myProperty; }
set
{
if (value != _myProperty)
{
_myProperty = value;
NotifyPropertyChanged("MyProperty");
// This line above could be improved by replacing the literal string with
// a pre-processor directive like "#Property", which could be translated
// to the string value "MyProperty" This new notify call would be as follows:
// NotifyPropertyChanged(#Property);
}
}
}
</code></pre>
<p>Would it be a good idea to write a pre-processor to handle extremely simple cases like this? Steve McConnell wrote in <a href="https://rads.stackoverflow.com/amzn/click/com/0735619670" rel="nofollow noreferrer" rel="nofollow noreferrer">Code Complete</a> (p208):</p>
<blockquote>
<p><em>Write your own preprocessor</em> If a language doesn't include a preprocessor, it's fairly easy to write one...</p>
</blockquote>
<p>I am torn. It was a design decision to leave such a flexible pre-processor out of C#. However, an author I highly respect mentions it may be ok in some circumstances.</p>
<p><strong>Should I build a C# pre-processor? Is there one available that does the simple things I want to do?</strong></p>
|
[
{
"answer_id": 37941,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 1,
"selected": false,
"text": "public static string GetNameOfCurrentMethod()\n{\n // Skip 1 frame (this method call)\n var trace = new System.Diagnostics.StackTrace( 1 );\n var frame = trace.GetFrame( 0 );\n return frame.GetMethod().Name;\n}\n"
},
{
"answer_id": 1338420,
"author": "Brett Ryan",
"author_id": 140037,
"author_profile": "https://Stackoverflow.com/users/140037",
"pm_score": 1,
"selected": false,
"text": "public static string MyPropertyPropertyName\npublic string MyProperty {\n get { return _myProperty; }\n set {\n if (!String.Equals(value, _myProperty)) {\n _myProperty = value;\n NotifyPropertyChanged(MyPropertyPropertyName);\n }\n }\n}\n\n// in the consumer.\nprivate void MyPropertyChangedHandler(object sender,\n PropertyChangedEventArgs args) {\n switch (e.PropertyName) {\n case MyClass.MyPropertyPropertyName:\n // Handle property change.\n break;\n }\n}\n"
},
{
"answer_id": 19001173,
"author": "Marcus Hansson",
"author_id": 512929,
"author_profile": "https://Stackoverflow.com/users/512929",
"pm_score": 0,
"selected": false,
"text": "public static class ObjectExtensions \n{\n public static string PropertyName<TModel, TProperty>( this TModel @this, Expression<Func<TModel, TProperty>> expr )\n {\n Type source = typeof(TModel);\n MemberExpression member = expr.Body as MemberExpression;\n\n if (member == null)\n throw new ArgumentException(String.Format(\n \"Expression '{0}' refers to a method, not a property\",\n expr.ToString( )));\n\n PropertyInfo property = member.Member as PropertyInfo;\n\n if (property == null)\n throw new ArgumentException(String.Format(\n \"Expression '{0}' refers to a field, not a property\",\n expr.ToString( )));\n\n if (source != property.ReflectedType ||\n !source.IsSubclassOf(property.ReflectedType) ||\n !property.ReflectedType.IsAssignableFrom(source))\n throw new ArgumentException(String.Format(\n \"Expression '{0}' refers to a property that is not a member of type '{1}'.\",\n expr.ToString( ),\n source));\n\n return property.Name;\n }\n}\n PropertyInfo Extension method"
},
{
"answer_id": 19099390,
"author": "user2831877",
"author_id": 2831877,
"author_profile": "https://Stackoverflow.com/users/2831877",
"pm_score": 2,
"selected": false,
"text": " OBSERVABLE_PROPERTY(string, MyProperty)\n #define OBSERVABLE_PROPERTY(propType, propName) \\\nprivate propType _##propName; \\\npublic propType propName \\\n{ \\\n get { return _##propName; } \\\n set \\\n { \\\n if (value != _##propName) \\\n { \\\n _##propName = value; \\\n NotifyPropertyChanged(#propName); \\\n } \\\n } \\\n}\n"
},
{
"answer_id": 67684070,
"author": "Wolfgang Grinfeld",
"author_id": 6522669,
"author_profile": "https://Stackoverflow.com/users/6522669",
"pm_score": 0,
"selected": false,
"text": "#if Precompiled || DEBUG\n #if Precompiled\n §RegexReplace(\"((private|internal|public|protected)( static)?) readonly\",\"$1\")\n #endif\n #if !Precompiled && DEBUG\n namespace NotPrecompiled\n {\n #endif\n\n ... // your code\n\n #if !Precompiled && DEBUG\n }\n #endif\n#endif // Precompiled || DEBUG\n #define Precompiled\n"
},
{
"answer_id": 67684319,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "public static class Code\n{\n [MethodImplAttribute(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]\n public static string MemberName([CallerMemberName] string name = null) => name;\n \n [MethodImplAttribute(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]\n public static string FilePath([CallerFilePathAttribute] string filePath = null) => filePath;\n \n [MethodImplAttribute(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]\n public static int LineNumber([CallerLineNumberAttribute] int lineNumber = 0) => lineNumber;\n}\n public class Test : INotifyPropertyChanged\n{\n private string _myProperty;\n public string MyProperty\n {\n get => _myProperty;\n set\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Code.MemberName()));\n _myProperty = value;\n }\n }\n \n public event PropertyChangedEventHandler PropertyChanged;\n}\n void Main()\n{\n var t = new Test();\n t.PropertyChanged += (s, e) => Console.WriteLine(e.PropertyName);\n \n t.MyProperty = \"Test\";\n}\n MyProperty\n IL_0000 ldarg.0 \nIL_0001 ldfld Test.PropertyChanged\nIL_0006 dup \nIL_0007 brtrue.s IL_000C\nIL_0009 pop \nIL_000A br.s IL_0021\nIL_000C ldarg.0 \n\n// important bit here\nIL_000D ldstr \"MyProperty\"\nIL_0012 call Code.MemberName (String)\n// important bit here\n\nIL_0017 newobj PropertyChangedEventArgs..ctor\nIL_001C callvirt PropertyChangedEventHandler.Invoke (Object, PropertyChangedEventArgs)\nIL_0021 ldarg.0 \nIL_0022 ldarg.1 \nIL_0023 stfld Test._myProperty\nIL_0028 ret\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
] |
37,275 |
<p>What is the SQL query to select all of the MSSQL Server's logins?</p>
<p>Thank you. More than one of you had the answer I was looking for:</p>
<pre><code>SELECT * FROM syslogins
</code></pre>
|
[
{
"answer_id": 37280,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 4,
"selected": false,
"text": "EXEC sp_helplogins\n EXEC sp_helplogins @LoginNamePattern='fred'\n"
},
{
"answer_id": 37284,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 2,
"selected": false,
"text": "Select * From Master..SysUsers Where IsSqlUser = 1\n"
},
{
"answer_id": 37286,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "SELECT name FROM master..sysxlogins WHERE sid IS NOT NULL\n"
},
{
"answer_id": 37290,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 7,
"selected": true,
"text": "select * from master.syslogins\n"
},
{
"answer_id": 13436833,
"author": "DeepSpace101",
"author_id": 862563,
"author_profile": "https://Stackoverflow.com/users/862563",
"pm_score": 5,
"selected": false,
"text": " --connecct to master\n\n --logins\n SELECT * from sys.sql_logins\n --users\n SELECT * from sys.sysusers\n --connect to database\n SELECT * from sys.sysusers\n"
},
{
"answer_id": 42567127,
"author": "BradC",
"author_id": 21398,
"author_profile": "https://Stackoverflow.com/users/21398",
"pm_score": 3,
"selected": false,
"text": "sys.server_principals sys.syslogins"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/37275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1208/"
] |
37,299 |
<p>What's the instruction to cause a hard-break in Xcode? For example under Visual Studio I could do '_asm int 3' or 'DebugBreak()'. Under some GCC implementations it's asm("break 0") or asm("trap").</p>
<p>I've tried various combos under Xcode without any luck. (inline assembler works fine so it's not a syntax issue).</p>
<p>For reference this is for an assert macro. I don't want to use the definitions in assert.h both for portability, and because they appear to do an abort() in the version XCode provides.</p>
<hr>
<p>John - Super, cheers. For reference the int 3 syntax is the one required for Intel Macs and iPhone.</p>
<hr>
<p>Chris - Thanks for your comment but there are many reasons to avoid the standard assert() function for codebases ported to different platforms. If you've gone to the trouble of rolling your own assert it's usually because you have additional functionality (logging, stack unwinding, user-interaction) that you wish to retain.</p>
<p>Your suggestion of attempting to replace the hander via an implementation of '__assert" or similar is not going to be portable. The standard 'assert' is usually a macro and while it may map to __assert on the Mac it doesn't on other platforms.</p>
|
[
{
"answer_id": 37304,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 6,
"selected": true,
"text": "asm {trap} ; Halts a program running on PPC32 or PPC64.\n\n__asm {int 3} ; Halts a program running on IA-32.\n"
},
{
"answer_id": 38546,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 4,
"selected": false,
"text": "Debugger() assert() abort() void __assert(const char *expression, const char *file, int line);\n assert() printf() abort()"
},
{
"answer_id": 720381,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "#include <stdlib.h>\n\nvoid abort(void);\n"
},
{
"answer_id": 6205564,
"author": "Sonny Saluja",
"author_id": 539115,
"author_profile": "https://Stackoverflow.com/users/539115",
"pm_score": 2,
"selected": false,
"text": "kill(getpid(), SIGINT);\n"
},
{
"answer_id": 12321843,
"author": "Tod",
"author_id": 16679,
"author_profile": "https://Stackoverflow.com/users/16679",
"pm_score": 3,
"selected": false,
"text": "__builtin_trap();\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043/"
] |
37,310 |
<p>I have developed some classes with similar behavior, they all implement the same interface. I implemented a factory that creates the appropriate object and returns the interface. I am writing a unit test for the factory. All you get back is an interface to the object.
What is the best way to test that the factory has worked correctly?</p>
<p>I would like to know the answer in Java, but if there is a solution that crosses languages I would like to know it.</p>
<p>Number 2. in the answer, would be done like the other answer? If so I will mark the other answer accepted as well and reword my question to adress both a factory where an interface is returned and you have no clue what type of concrete class implemented the interface, and the case where you do know what concrete class was used.</p>
|
[
{
"answer_id": 37316,
"author": "Cem Catikkas",
"author_id": 3087,
"author_profile": "https://Stackoverflow.com/users/3087",
"pm_score": 6,
"selected": true,
"text": "IMyInterface fromFactory = factory.create(...); \nAssert.assertTrue(fromFactory instanceof MyInterfaceImpl1);\n"
},
{
"answer_id": 37318,
"author": "izb",
"author_id": 974,
"author_profile": "https://Stackoverflow.com/users/974",
"pm_score": 0,
"selected": false,
"text": "if (myNewObject instanceof CorrectClass)\n{\n /* pass test */\n}\n public void doTest()\n{\n MyInterface inst = MyFactory.createAppropriateObject();\n if (! inst instanceof ExpectedConcreteClass)\n {\n /* FAIL */\n }\n}\n"
},
{
"answer_id": 39369,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 0,
"selected": false,
"text": "IMyInterface fromFactory = factory.create(...); \nAssert.assertEquals(fromFactory.getClass().getName(), MyInterfaceImpl1.class.getName());\n"
},
{
"answer_id": 34199097,
"author": "Undreren",
"author_id": 1264675,
"author_profile": "https://Stackoverflow.com/users/1264675",
"pm_score": 6,
"selected": false,
"text": "null instanceof"
},
{
"answer_id": 51817768,
"author": "Federico Gatti",
"author_id": 8615621,
"author_profile": "https://Stackoverflow.com/users/8615621",
"pm_score": 0,
"selected": false,
"text": "package it.sorintlab.pxrm.proposition.model.factory.task;\n\nimport org.junit.Test;\n\nimport java.util.Arrays;\nimport java.util.Collection;\n\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.junit.runners.Parameterized.Parameters;\n\nimport static org.junit.Assert.*;\n\n@RunWith(Parameterized.class)\npublic class TaskFactoryTest {\n\n @Parameters\n public static Collection<Object[]> data() {\n return Arrays.asList(new Object[][] {\n { \"sas:wp|repe\" , WorkPackageAvailabilityFactory.class},\n { \"sas:wp|people\", WorkPackagePeopleFactory.class},\n { \"edu:wp|course\", WorkPackageCourseFactory.class},\n { \"edu:wp|module\", WorkPackageModuleFactory.class},\n { \"else\", AttachmentTaskDetailFactory.class}\n });\n }\n\n private String fInput;\n private Class<? extends TaskFactory> fExpected;\n\n public TaskFactoryTest(String input, Class<? extends TaskFactory> expected) {\n this.fInput = input;\n this.fExpected = expected;\n }\n\n @Test\n public void getFactory() {\n assertEquals(fExpected, TaskFactory.getFactory(fInput).getClass());\n }\n}\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3576/"
] |
37,317 |
<p>I'm working on a windows forms application (C#) where a user is entering data in a form. At any point while editing the data in the form the user can click one of the buttons on the form to perform certain actions. By default the focus goes to the clicked button so the user has to click back on to the control they want to edit in order to continue modifying the data on the form. What I need to be able to do is return the focus to the last edited control after the button click event has been processed. Here's a sample screenshot that illustrates what I'm talking about:</p>
<p><img src="https://lh6.ggpht.com/joe.r.barone/SLs4KZMBqfI/AAAAAAAABNw/P6xtqhCo8Y4/s800/SampleApp1.jpg" alt="Sample App Screen Shot"></p>
<p>The user can be entering data in textbox1, textbox2, textbox3, etc and click the button. I need the button to return the focus back to the control that most recently had the focus before the button was clicked.</p>
<p>I'm wondering if anyone has a better way of implementing this functionality than what I've come up with. Here's what I'm doing right now:</p>
<pre><code> public partial class Form1 : Form
{
Control _lastEnteredControl;
private void textBox_Enter(object sender, EventArgs e)
{
_lastEnteredControl = (Control)sender;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Do something here");
_lastEnteredControl.Focus();
}
}
</code></pre>
<p>So basically what we have here is a class variable that points to the last entered control. Each textbox on the form is setup so the textBox_Enter method is fired when the control receives the focus. Then, when the button is clicked focus is returned to the control that had the focus before the button was clicked. Anybody have any more elegant solutions for this?</p>
|
[
{
"answer_id": 37331,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 1,
"selected": false,
"text": "private void Form_OnLoad(object obj, EventArgs e)\n{\n AddGotFocusListener(this);\n}\n\nprivate void AddGotFocusListener(Control ctrl)\n{\n foreach(Control c in ctrl.Controls)\n {\n c.GotFocus += new EventHandler(Control_GotFocus);\n if(c.Controls.Count > 0)\n {\n AddGotFocusListener(c);\n }\n }\n}\n\nprivate void Control_GotFocus(object obj, EventArgs e)\n{\n // Set focused control here\n}\n"
},
{
"answer_id": 37336,
"author": "Joshua Turner",
"author_id": 820,
"author_profile": "https://Stackoverflow.com/users/820",
"pm_score": 5,
"selected": true,
"text": "public Form1()\n {\n InitializeComponent();\n\n foreach (Control ctrl in Controls)\n {\n if (ctrl is TextBox)\n {\n ctrl.Enter += delegate(object sender, EventArgs e)\n {\n _lastEnteredControl = (Control)sender;\n };\n }\n }\n }\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3452/"
] |
37,324 |
<p>I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an <code>ON</code> clause in C#.</p>
<p>How do you represent the following in LINQ to SQL:</p>
<pre><code>select DealerContact.*
from Dealer
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID
</code></pre>
|
[
{
"answer_id": 37332,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 10,
"selected": true,
"text": "from t1 in db.Table1\njoin t2 in db.Table2 on t1.field equals t2.field\nselect new { t1.field2, t2.field3}\n var dealercontacts = from contact in DealerContact\n join dealer in Dealer on contact.DealerId equals dealer.ID\n select contact;\n"
},
{
"answer_id": 37333,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 5,
"selected": false,
"text": "var q = from d in Dealer\n join dc in DealerConact on d.DealerID equals dc.DealerID\n select dc;\n"
},
{
"answer_id": 1824432,
"author": "herste",
"author_id": 221890,
"author_profile": "https://Stackoverflow.com/users/221890",
"pm_score": 6,
"selected": false,
"text": "var results = from c in db.Companies\n join cn in db.Countries on c.CountryID equals cn.ID\n join ct in db.Cities on c.CityID equals ct.ID\n join sect in db.Sectors on c.SectorID equals sect.ID\n where (c.CountryID == cn.ID) && (c.CityID == ct.ID) && (c.SectorID == company.SectorID) && (company.SectorID == sect.ID)\n select new { country = cn.Name, city = ct.Name, c.ID, c.Name, c.Address1, c.Address2, c.Address3, c.CountryID, c.CityID, c.Region, c.PostCode, c.Telephone, c.Website, c.SectorID, Status = (ContactStatus)c.StatusID, sector = sect.Name };\n\n\nreturn results.ToList();\n"
},
{
"answer_id": 3851487,
"author": "CleverPatrick",
"author_id": 22399,
"author_profile": "https://Stackoverflow.com/users/22399",
"pm_score": 8,
"selected": false,
"text": "var dealerContracts = DealerContact.Join(Dealer, \n contact => contact.DealerId,\n dealer => dealer.DealerId,\n (contact, dealer) => contact);\n"
},
{
"answer_id": 5170765,
"author": "the_joric",
"author_id": 229949,
"author_profile": "https://Stackoverflow.com/users/229949",
"pm_score": 5,
"selected": false,
"text": "var r = from dealer in db.Dealers\n from contact in db.DealerContact\n where dealer.DealerID == contact.DealerID\n select dealerContact;\n from contact in db.DealerContact \n"
},
{
"answer_id": 8251984,
"author": "Kirk Broadhurst",
"author_id": 146077,
"author_profile": "https://Stackoverflow.com/users/146077",
"pm_score": 5,
"selected": false,
"text": "Dealer DealerContacts from contact in dealer.DealerContacts select contact\n context.Dealers.Select(d => d.DealerContacts)\n"
},
{
"answer_id": 11334923,
"author": "Gert Arnold",
"author_id": 861716,
"author_profile": "https://Stackoverflow.com/users/861716",
"pm_score": 4,
"selected": false,
"text": "from dealer in db.Dealers\nfrom contact in dealer.DealerContacts\nselect new { whatever you need from dealer or contact }\n SELECT <columns>\nFROM Dealer, DealerContact\nWHERE Dealer.DealerID = DealerContact.DealerID\n"
},
{
"answer_id": 13096990,
"author": "Sandeep Shekhawat",
"author_id": 1390850,
"author_profile": "https://Stackoverflow.com/users/1390850",
"pm_score": 2,
"selected": false,
"text": "OperationDataContext odDataContext = new OperationDataContext(); \n var studentInfo = from student in odDataContext.STUDENTs\n join course in odDataContext.COURSEs\n on student.course_id equals course.course_id\n select new { student.student_name, student.student_city, course.course_name, course.course_desc };\n"
},
{
"answer_id": 16356390,
"author": "Prasad KM",
"author_id": 2346395,
"author_profile": "https://Stackoverflow.com/users/2346395",
"pm_score": -1,
"selected": false,
"text": "TBL_Emp TBL_Dep var result = from emp in TBL_Emp join dep in TBL_Dep on emp.id=dep.id\nselect new\n{\n emp.Name;\n emp.Address\n dep.Department_Name\n}\n\n\nforeach(char item in result)\n { // to do}\n"
},
{
"answer_id": 23510671,
"author": "Uthaiah",
"author_id": 1488323,
"author_profile": "https://Stackoverflow.com/users/1488323",
"pm_score": 2,
"selected": false,
"text": "var employeeInfo = from emp in db.Employees\n join dept in db.Departments\n on emp.Eid equals dept.Eid \n select new\n {\n emp.Ename,\n dept.Dname,\n emp.Elocation\n };\n"
},
{
"answer_id": 26339802,
"author": "Milan",
"author_id": 3804209,
"author_profile": "https://Stackoverflow.com/users/3804209",
"pm_score": 2,
"selected": false,
"text": "var dealer = from d in Dealer\n join dc in DealerContact on d.DealerID equals dc.DealerID\n select d;\n"
},
{
"answer_id": 28985025,
"author": "Ajay",
"author_id": 6998210,
"author_profile": "https://Stackoverflow.com/users/6998210",
"pm_score": 2,
"selected": false,
"text": " var data =(from t1 in dataContext.Table1 join \n t2 in dataContext.Table2 on \n t1.field equals t2.field \n orderby t1.Id select t1).ToList(); \n"
},
{
"answer_id": 29310640,
"author": "Jon Schneider",
"author_id": 12484,
"author_profile": "https://Stackoverflow.com/users/12484",
"pm_score": 6,
"selected": false,
"text": "var dealerInfo = DealerContact.Join(Dealer, \n dc => dc.DealerId,\n d => d.DealerId,\n (dc, d) => new { DealerContact = dc, Dealer = d })\n .Where(dc_d => dc_d.Dealer.FirstName == \"Glenn\" \n && dc_d.DealerContact.City == \"Chicago\")\n .Select(dc_d => new {\n dc_d.Dealer.DealerID,\n dc_d.Dealer.FirstName,\n dc_d.Dealer.LastName,\n dc_d.DealerContact.City,\n dc_d.DealerContact.State });\n (dc, d) => new { DealerContact = dc, Dealer = d }\n dc_d"
},
{
"answer_id": 43161807,
"author": "Md Shahriar",
"author_id": 4211947,
"author_profile": "https://Stackoverflow.com/users/4211947",
"pm_score": 2,
"selected": false,
"text": "var result = from q1 in table1\n join q2 in table2\n on q1.Customer_Id equals q2.Customer_Id\n select new { q1.Name, q1.Mobile, q2.Purchase, q2.Dates }\n"
},
{
"answer_id": 43177753,
"author": "Ankita_systematix",
"author_id": 7348760,
"author_profile": "https://Stackoverflow.com/users/7348760",
"pm_score": 1,
"selected": false,
"text": "var Data= (from dealer in Dealer join dealercontact in DealerContact on dealer.ID equals dealercontact.DealerID\nselect new{\ndealer.Id,\ndealercontact.ContactName\n\n}).ToList();\n"
},
{
"answer_id": 47390465,
"author": "sanket parikh",
"author_id": 5414397,
"author_profile": "https://Stackoverflow.com/users/5414397",
"pm_score": 1,
"selected": false,
"text": "var data=(from t in db.your tableName(t1) \n join s in db.yourothertablename(t2) on t1.fieldname equals t2.feldname\n (where condtion)).tolist();\n"
},
{
"answer_id": 47950778,
"author": "Sarfraj Sutar",
"author_id": 8676193,
"author_profile": "https://Stackoverflow.com/users/8676193",
"pm_score": 1,
"selected": false,
"text": "var list = (from u in db.Users join c in db.Customers on u.CustomerId equals c.CustomerId where u.Username == username\n select new {u.UserId, u.CustomerId, u.ClientId, u.RoleId, u.Username, u.Email, u.Password, u.Salt, u.Hint1, u.Hint2, u.Hint3, u.Locked, u.Active,c.ProfilePic}).First();\n"
},
{
"answer_id": 48500439,
"author": "ammad khan",
"author_id": 9281814,
"author_profile": "https://Stackoverflow.com/users/9281814",
"pm_score": 2,
"selected": false,
"text": "var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID orderby od.OrderID select new { od.OrderID,\n pd.ProductID,\n pd.Name,\n pd.UnitPrice,\n od.Quantity,\n od.Price,\n }).ToList(); \n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
] |
37,335 |
<p>I am writing a client-side <strong>Swing</strong> application (graphical font designer) on <strong>Java 5</strong>. Recently, I am running into <code>java.lang.OutOfMemoryError: Java heap space</code> error because I am not being conservative on memory usage. The user can open unlimited number of files, and the program keeps the opened objects in the memory. After a quick research I found <a href="http://java.sun.com/docs/hotspot/gc5.0/ergo5.html" rel="noreferrer">Ergonomics in the 5.0 Java Virtual Machine</a> and others saying on Windows machine the JVM defaults max heap size as <code>64MB</code>.</p>
<p>Given this situation, how should I deal with this constraint?</p>
<p>I could increase the <strong>max heap size</strong> using <strong>command line</strong> option to java, but that would require figuring out available RAM and writing some launching program or script. Besides, increasing to some <strong>finite</strong> max does not <strong>ultimately</strong> get rid of the issue.</p>
<p>I could rewrite some of my code to persist objects to file system frequently (using database is the same thing) to free up the memory. It could work, but it's probably a lot work too.</p>
<p>If you could point me to details of above ideas or some alternatives like <strong>automatic virtual memory, extending heap size dynamically</strong>, that will be great.</p>
|
[
{
"answer_id": 37349,
"author": "Ben Childs",
"author_id": 2925,
"author_profile": "https://Stackoverflow.com/users/2925",
"pm_score": 9,
"selected": true,
"text": "2GB"
},
{
"answer_id": 37466,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 7,
"selected": false,
"text": "-Xmx"
},
{
"answer_id": 186390,
"author": "kohlerm",
"author_id": 26056,
"author_profile": "https://Stackoverflow.com/users/26056",
"pm_score": 4,
"selected": false,
"text": "-Xmx"
},
{
"answer_id": 186957,
"author": "Leigh",
"author_id": 26061,
"author_profile": "https://Stackoverflow.com/users/26061",
"pm_score": 3,
"selected": false,
"text": "java.lang.management MBeans"
},
{
"answer_id": 747593,
"author": "David",
"author_id": 57246,
"author_profile": "https://Stackoverflow.com/users/57246",
"pm_score": 5,
"selected": false,
"text": "-Xmx1600m"
},
{
"answer_id": 3500230,
"author": "mwangi",
"author_id": 422550,
"author_profile": "https://Stackoverflow.com/users/422550",
"pm_score": 3,
"selected": false,
"text": "System.gc() //Mimimum acceptable free memory you think your app needs\nlong minRunningMemory = (1024*1024);\n\nRuntime runtime = Runtime.getRuntime();\n\nif(runtime.freeMemory()<minRunningMemory)\n System.gc();\n"
},
{
"answer_id": 5121287,
"author": "allenhwkim",
"author_id": 454252,
"author_profile": "https://Stackoverflow.com/users/454252",
"pm_score": 7,
"selected": false,
"text": " Run As - Run Configuration - Arguments - Vm Arguments, \n -Xmx2048m\n"
},
{
"answer_id": 6299069,
"author": "loveall",
"author_id": 791703,
"author_profile": "https://Stackoverflow.com/users/791703",
"pm_score": 5,
"selected": false,
"text": "Run --> Run Configurations --> -Xmx1024m Run --> Run Configurations --> select the \"JRE\" tab --> Xmx1024m"
},
{
"answer_id": 7297504,
"author": "chaukssey",
"author_id": 927269,
"author_profile": "https://Stackoverflow.com/users/927269",
"pm_score": 3,
"selected": false,
"text": "OutOfMemoryError -Xmx512M export JVM_ARGS=\"-Xms1024m -Xmx1024m\""
},
{
"answer_id": 19222984,
"author": "Pradip Bhatt",
"author_id": 2098900,
"author_profile": "https://Stackoverflow.com/users/2098900",
"pm_score": 4,
"selected": false,
"text": "catalina.sh JAVA_OPTS=\"-Djava.awt.headless=true -Dfile.encoding=UTF-8 -server -Xms1536m \n-Xmx1536m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m \n-XX:MaxPermSize=256m -XX:+DisableExplicitGC\"\n"
},
{
"answer_id": 37460287,
"author": "Musa",
"author_id": 4720910,
"author_profile": "https://Stackoverflow.com/users/4720910",
"pm_score": 3,
"selected": false,
"text": "-Xms<size> set initial Java heap size\n-Xmx<size> set maximum Java heap size\n-Xss<size> set java thread stack size\n\n-XX:ParallelGCThreads=8\n-XX:+CMSClassUnloadingEnabled\n-XX:InitiatingHeapOccupancyPercent=70\n-XX:+UnlockDiagnosticVMOptions\n-XX:+UseConcMarkSweepGC\n-Xms512m\n-Xmx8192m\n-XX:MaxPermSize=256m (in java 8 optional)\n touch /opt/tomcat/bin/setenv.sh\n nano /opt/tomcat/bin/setenv.sh \n\nexport CATALINA_OPTS=\"$CATALINA_OPTS -XX:ParallelGCThreads=8\"\nexport CATALINA_OPTS=\"$CATALINA_OPTS -XX:+CMSClassUnloadingEnabled\"\nexport CATALINA_OPTS=\"$CATALINA_OPTS -XX:InitiatingHeapOccupancyPercent=70\"\nexport CATALINA_OPTS=\"$CATALINA_OPTS -XX:+UnlockDiagnosticVMOptions\"\nexport CATALINA_OPTS=\"$CATALINA_OPTS -XX:+UseConcMarkSweepGC\"\nexport CATALINA_OPTS=\"$CATALINA_OPTS -Xms512m\"\nexport CATALINA_OPTS=\"$CATALINA_OPTS -Xmx8192m\"\nexport CATALINA_OPTS=\"$CATALINA_OPTS -XX:MaxMetaspaceSize=256M\"\n service tomcat restart"
},
{
"answer_id": 43212058,
"author": "satish",
"author_id": 5281441,
"author_profile": "https://Stackoverflow.com/users/5281441",
"pm_score": 1,
"selected": false,
"text": "JAVA_OPTS=\"$JAVA_OPTS -XX:MaxMetaspaceSize=256M\""
},
{
"answer_id": 64514498,
"author": "Nima Ganji",
"author_id": 10589851,
"author_profile": "https://Stackoverflow.com/users/10589851",
"pm_score": 3,
"selected": false,
"text": "gradle.properties (Global Properties) ...\norg.gradle.jvmargs=-XX\\:MaxHeapSize\\=1024m -Xmx1024m \n"
},
{
"answer_id": 68934961,
"author": "CodingEra",
"author_id": 9920209,
"author_profile": "https://Stackoverflow.com/users/9920209",
"pm_score": 3,
"selected": false,
"text": "org.gradle.jvmargs=-Xmx4096m -XX:MaxPermSize=4096m -XX:+HeapDumpOnOutOfMemoryError\norg.gradle.daemon=true\norg.gradle.parallel=true\norg.gradle.configureondemand=true\n"
},
{
"answer_id": 68973465,
"author": "Chukwunazaekpere",
"author_id": 12589424,
"author_profile": "https://Stackoverflow.com/users/12589424",
"pm_score": 1,
"selected": false,
"text": "./gradlew clean\n ./gradlew assembleRelease\n"
},
{
"answer_id": 69098151,
"author": "Muhammad Raqib",
"author_id": 4491818,
"author_profile": "https://Stackoverflow.com/users/4491818",
"pm_score": 3,
"selected": false,
"text": "cd android/ && ./gradlew clean && cd ..\n"
},
{
"answer_id": 70096676,
"author": "Talha Akbar",
"author_id": 7798091,
"author_profile": "https://Stackoverflow.com/users/7798091",
"pm_score": 3,
"selected": false,
"text": "org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8\n"
},
{
"answer_id": 71047778,
"author": "Morteza",
"author_id": 13989422,
"author_profile": "https://Stackoverflow.com/users/13989422",
"pm_score": 2,
"selected": false,
"text": "Shared build process heap size"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3827/"
] |
37,346 |
<p>If I create a class like so: </p>
<pre><code>// B.h
#ifndef _B_H_
#define _B_H_
class B
{
private:
int x;
int y;
};
#endif // _B_H_
</code></pre>
<p>and use it like this:</p>
<pre><code>// main.cpp
#include <iostream>
#include <vector>
class B; // Forward declaration.
class A
{
public:
A() {
std::cout << v.size() << std::endl;
}
private:
std::vector<B> v;
};
int main()
{
A a;
}
</code></pre>
<p>The compiler fails when compiling <code>main.cpp</code>. Now the solution I know is to <code>#include "B.h"</code>, but I'm curious as to why it fails. Neither <code>g++</code> or <code>cl</code>'s error messages were very enlightening in this matter.</p>
|
[
{
"answer_id": 37348,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 6,
"selected": true,
"text": "std::vector<B*>"
},
{
"answer_id": 14010890,
"author": "daotheman",
"author_id": 1924938,
"author_profile": "https://Stackoverflow.com/users/1924938",
"pm_score": 0,
"selected": false,
"text": "std::vector .cpp"
},
{
"answer_id": 15382714,
"author": "fyzix",
"author_id": 2164823,
"author_profile": "https://Stackoverflow.com/users/2164823",
"pm_score": 5,
"selected": false,
"text": "// A.h\n#include <vector>\n\nclass B; // Forward declaration.\n\nclass A\n{\npublic:\n A(); // only declare, don't implement here\n\nprivate:\n std::vector<B> v;\n};\n // A.cpp\n#include \"A.h\"\n#include \"B.h\"\n\nA::A() // this implicitly calls vector<B>'s constructor\n{\n std::cout << v.size() << std::endl;\n}\n // main.cpp\n#include \"A.h\"\n\nint main()\n{\n A a; // compiles OK\n}\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] |
37,374 |
<p>We've just started using LINQ to SQL at work for our DAL & we haven't really come up with a standard for out caching model. Previously we had being using a base 'DAL' class that implemented a cache manager property that all our DAL classes inherited from, but now we don't have that. I'm wondering if anyone has come up with a 'standard' approach to caching LINQ to SQL results?</p>
<p>We're working in a web environment (IIS) if that makes a difference. I know this may well end up being a <a href="https://stackoverflow.com/questions/tagged/subjective">subjective</a> question, but I still think the info would be valuable.</p>
<p><strong>EDIT:</strong> To clarify, I'm not talking about caching an individual result, I'm after more of an architecture solution, as in how do you set up caching so that all your link methods use the same caching architecture.</p>
|
[
{
"answer_id": 37432,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 2,
"selected": false,
"text": "List<TableItem> myResult = (from t in db.Table select t).ToList();\n"
},
{
"answer_id": 357970,
"author": "Pete Montgomery",
"author_id": 40759,
"author_profile": "https://Stackoverflow.com/users/40759",
"pm_score": 5,
"selected": false,
"text": "var q = from c in context.Customers\n where c.City == \"London\"\n select new { c.Name, c.Phone };\n\nvar result = q.Take(10).FromCache();\n"
},
{
"answer_id": 3384861,
"author": "Remus Rusanu",
"author_id": 105929,
"author_profile": "https://Stackoverflow.com/users/105929",
"pm_score": 1,
"selected": false,
"text": "dbo.Table Table"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
] |
37,375 |
<p>We have a whole bunch of DLLs that give us access to our database and other applications and services.</p>
<p>We've wrapped these DLLs with a thin WCF service layer which our clients then consume.</p>
<p>I'm a little unsure on how to write unit tests that only test the WCF service layer. Should I just write unit tests for the DLLs, and integration tests for the WCF services? I'd appreciate any wisdom... I know that if my unit tests actually go to the database they won't actually be true unit tests. I also understand that I don't really need to test the WCF service host in a unit test. </p>
<p>So, I'm confused about exactly what to test and how.</p>
|
[
{
"answer_id": 37385,
"author": "Toran Billups",
"author_id": 2701,
"author_profile": "https://Stackoverflow.com/users/2701",
"pm_score": 3,
"selected": false,
"text": "Public Class ProductService\n Implements IProductService\n\n Private mRepository As IProductRepository\n\n Public Sub New()\n mRepository = New ProductRepository()\n End Sub\n\n Public Sub New(ByVal repository As IProductRepository)\n mRepository = repository\n End Sub\n\n Public Function GetProducts() As System.Collections.Generic.List(Of Product) Implements IProductService.GetProducts\n Return mRepository.GetProducts()\n End Function\nEnd Class\n <TestMethod()> _\nPublic Sub ShouldPopulateProductsListOnViewLoadWhenPostBackIsFalse()\n mMockery = New MockRepository()\n mView = DirectCast(mMockery.Stub(Of IProductView)(), IProductView)\n mProductService = DirectCast(mMockery.DynamicMock(Of IProductService)(), IProductService)\n mPresenter = New ProductPresenter(mView, mProductService)\n Dim ProductList As New List(Of Product)()\n ProductList.Add(New Product)\n Using mMockery.Record()\n SetupResult.For(mView.PageIsPostBack).Return(False).Repeat.Once()\n Expect.Call(mProductService.GetProducts()).Return(ProductList).Repeat.Once()\n End Using\n Using mMockery.Playback()\n mPresenter.OnViewLoad()\n End Using\n 'Verify that we hit the service dependency during the method when postback is false\n Assert.AreEqual(1, mView.Products.Count)\n mMockery.VerifyAll()\nEnd Sub\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] |
37,378 |
<p>Everyone I work with is obsessed with the data-centric approach to enterprise development and hates the idea of using custom collections/objects. What is the best way to convince them otherwise?</p>
|
[
{
"answer_id": 37475,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 1,
"selected": false,
"text": "Collection<T>"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2701/"
] |
37,381 |
<p>I'm exploring the possibility of writing an application in Erlang, but it would need to have a portion written in Cocoa (presumably Objective-C). I'd like the front-end and back-end to be able to communicate easily. How can this best be done?</p>
<p>I can think of using C ports and connected processes, but I think I'd like a reverse situation (the front-end starting and connecting to the back-end). There are named pipes (FIFOs), or I could use network communications over a TCP port or a named BSD socket. Does anyone have experience in this area?</p>
|
[
{
"answer_id": 37408,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 4,
"selected": true,
"text": "launchd launchd launchd launchd launchd"
},
{
"answer_id": 37683,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 1,
"selected": false,
"text": "NSTask stdin stdout stderr NSTask exec fork system"
},
{
"answer_id": 3769189,
"author": "chad",
"author_id": 455025,
"author_profile": "https://Stackoverflow.com/users/455025",
"pm_score": 1,
"selected": false,
"text": "open -a Safari http://web.archive.org/web/20080324145441/http://www.bignerdranch.com/applications.shtml\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3948/"
] |
37,391 |
<p>Ok, so PHP isn't the best language to be dealing with arbitrarily large integers in, considering that it only natively supports 32-bit signed integers. What I'm trying to do though is create a class that could represent an arbitrarily large binary number and be able to perform simple arithmetic operations on two of them (add/subtract/multiply/divide).</p>
<p>My target is dealing with 128-bit integers.</p>
<p>There's a couple of approaches I'm looking at, and problems I see with them. Any input or commentary on what you would choose and how you might go about it would be greatly appreciated.</p>
<p><strong>Approach #1:</strong> Create a 128-bit integer class that stores its integer internally as four 32-bit integers. The only problem with this approach is that I'm not sure how to go about handling overflow/underflow issues when manipulating individual chunks of the two operands.</p>
<p><strong>Approach #2:</strong> Use the bcmath extension, as this looks like something it was designed to tackle. My only worry in taking this approach is the scale setting of the bcmath extension, because there can't be any rounding errors in my 128-bit integers; they must be precise. I'm also worried about being able to eventually convert the result of the bcmath functions into a binary string (which I'll later need to shove into some mcrypt encryption functions).</p>
<p><strong>Approach #3:</strong> Store the numbers as binary strings (probably LSB first). Theoretically I should be able to store integers of any arbitrary size this way. All I would have to do is write the four basic arithmetic functions to perform add/sub/mult/div on two binary strings and produce a binary string result. This is exactly the format I need to hand over to mcrypt as well, so that's an added plus. This is the approach I think has the most promise at the moment, but the one sticking point I've got is that PHP doesn't offer me any way to manipulate the individual bits (that I know of). I believe I'd have to break it up into byte-sized chunks (no pun intended), at which point my questions about handling overflow/underflow from Approach #1 apply.</p>
|
[
{
"answer_id": 1381855,
"author": "Jonathon Hill",
"author_id": 168815,
"author_profile": "https://Stackoverflow.com/users/168815",
"pm_score": 3,
"selected": true,
"text": "gmp_strval(gmp_init($n, 10), 2);\n"
},
{
"answer_id": 20730795,
"author": "Alix Axel",
"author_id": 89771,
"author_profile": "https://Stackoverflow.com/users/89771",
"pm_score": 0,
"selected": false,
"text": "function BC($string, $precision = 32)\n{\n if (extension_loaded('bcmath') === true)\n {\n if (is_array($string) === true)\n {\n if ((count($string = array_slice($string, 1)) == 3) && (bcscale($precision) === true))\n {\n $callback = array('^' => 'pow', '*' => 'mul', '/' => 'div', '%' => 'mod', '+' => 'add', '-' => 'sub');\n\n if (array_key_exists($operator = current(array_splice($string, 1, 1)), $callback) === true)\n {\n $x = 1;\n $result = @call_user_func_array('bc' . $callback[$operator], $string);\n\n if ((strcmp('^', $operator) === 0) && (($i = fmod(array_pop($string), 1)) > 0))\n {\n $y = BC(sprintf('((%1$s * %2$s ^ (1 - %3$s)) / %3$s) - (%2$s / %3$s) + %2$s', $string = array_shift($string), $x, $i = pow($i, -1)));\n\n do\n {\n $x = $y;\n $y = BC(sprintf('((%1$s * %2$s ^ (1 - %3$s)) / %3$s) - (%2$s / %3$s) + %2$s', $string, $x, $i));\n }\n\n while (BC(sprintf('%s > %s', $x, $y)));\n }\n\n if (strpos($result = bcmul($x, $result), '.') !== false)\n {\n $result = rtrim(rtrim($result, '0'), '.');\n\n if (preg_match(sprintf('~[.][9]{%u}$~', $precision), $result) > 0)\n {\n $result = bcadd($result, (strncmp('-', $result, 1) === 0) ? -1 : 1, 0);\n }\n\n else if (preg_match(sprintf('~[.][0]{%u}[1]$~', $precision - 1), $result) > 0)\n {\n $result = bcmul($result, 1, 0);\n }\n }\n\n return $result;\n }\n\n return intval(version_compare(call_user_func_array('bccomp', $string), 0, $operator));\n }\n\n $string = array_shift($string);\n }\n\n $string = str_replace(' ', '', str_ireplace('e', ' * 10 ^ ', $string));\n\n while (preg_match('~[(]([^()]++)[)]~', $string) > 0)\n {\n $string = preg_replace_callback('~[(]([^()]++)[)]~', __FUNCTION__, $string);\n }\n\n foreach (array('\\^', '[\\*/%]', '[\\+-]', '[<>]=?|={1,2}') as $operator)\n {\n while (preg_match(sprintf('~(?<![0-9])(%1$s)(%2$s)(%1$s)~', '[+-]?(?:[0-9]++(?:[.][0-9]*+)?|[.][0-9]++)', $operator), $string) > 0)\n {\n $string = preg_replace_callback(sprintf('~(?<![0-9])(%1$s)(%2$s)(%1$s)~', '[+-]?(?:[0-9]++(?:[.][0-9]*+)?|[.][0-9]++)', $operator), __FUNCTION__, $string, 1);\n }\n }\n }\n\n return (preg_match('~^[+-]?[0-9]++(?:[.][0-9]++)?$~', $string) > 0) ? $string : false;\n}\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384/"
] |
37,441 |
<p>Why are SQL distributions so non-standard despite an ANSI standard existing for SQL? Are there really that many meaningful differences in the way SQL databases work or is it just the two databases with which I have been working: MS-SQL and PostgreSQL? Why do these differences arise?</p>
|
[
{
"answer_id": 37443,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "AUTO INCREMENT"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
37,449 |
<p>I've used the StAX API in Java quite a bit, and find it quite a clean way of dealing with XML files. Is there any equivalent library I could use for performing similar processing in C?</p>
|
[
{
"answer_id": 465382,
"author": "OJW",
"author_id": 46478,
"author_profile": "https://Stackoverflow.com/users/46478",
"pm_score": -1,
"selected": false,
"text": "\n #include \"expat.h\"`\nVRM_parser = XML_ParserCreate(\"ISO-8859-1\");\nXML_SetElementHandler(VRM_parser, CbStartTagHandler, CbEndTagHandler);\nXML_Parse(VRM_parser, text, strlen(text), 0); // start of XML\nXML_Parse(VRM_parser, text, strlen(text), 0); // more XML\nXML_Parse(VRM_parser, text, strlen(text), 0); // more XML\nXML_Parse(VRM_parser, text, strlen(text), 0); // more XML\nXML_Parse(VRM_parser, \"\", 0, 1); // to finish parsing\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] |
37,464 |
<p>If I create an application on my Mac, is there any way I can get it to run on an iPhone without going through the app store?</p>
<p>It doesn't matter if the iPhone has to be jailbroken, as long as I can still run an application created using the official SDK. For reasons I won't get into, I can't have this program going through the app store.</p>
|
[
{
"answer_id": 37522,
"author": "Jason Weathered",
"author_id": 3736,
"author_profile": "https://Stackoverflow.com/users/3736",
"pm_score": 9,
"selected": true,
"text": "openssh uikittools jasoniphone.local mobile root build/Release-iphoneos scp -r AccelerometerGraph.app root@jasoniphone:/Applications/ ssh [email protected] uicache ssh [email protected] rm -r /Applications/AccelerometerGraph.app &&\nssh [email protected] uicache\n"
},
{
"answer_id": 2671953,
"author": "Mattias Wadman",
"author_id": 56686,
"author_profile": "https://Stackoverflow.com/users/56686",
"pm_score": 1,
"selected": false,
"text": "/Developer/Platforms/iPhoneOS.platform/Info.plist com.apple.debugserver Info.plist"
},
{
"answer_id": 4423913,
"author": "Richard J. Ross III",
"author_id": 427309,
"author_profile": "https://Stackoverflow.com/users/427309",
"pm_score": 3,
"selected": false,
"text": "# compress application.\n/bin/mkdir -p $CONFIGURATION_BUILD_DIR/Payload\n/bin/cp -R $CONFIGURATION_BUILD_DIR/MyApp.app $CONFIGURATION_BUILD_DIR/Payload\n/bin/cp iTunesCrap/logo_itunes.png $CONFIGURATION_BUILD_DIR/iTunesArtwork\n/bin/cp iTunesCrap/iTunesMetadata.plist $CONFIGURATION_BUILD_DIR/iTunesMetadata.plist\n\ncd $CONFIGURATION_BUILD_DIR\n\n# zip up the HelloWorld directory\n\n/usr/bin/zip -r MyApp.ipa Payload iTunesArtwork iTunesMetadata.plist\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>appleId</key>\n <string></string>\n <key>artistId</key>\n <integer>0</integer>\n <key>artistName</key>\n <string>MYCOMPANY</string>\n <key>buy-only</key>\n <true/>\n <key>buyParams</key>\n <string></string>\n <key>copyright</key>\n <string></string>\n <key>drmVersionNumber</key>\n <integer>0</integer>\n <key>fileExtension</key>\n <string>.app</string>\n <key>genre</key>\n <string></string>\n <key>genreId</key>\n <integer>0</integer>\n <key>itemId</key>\n <integer>0</integer>\n <key>itemName</key>\n <string>MYAPP</string>\n <key>kind</key>\n <string>software</string>\n <key>playlistArtistName</key>\n <string>MYCOMPANY</string>\n <key>playlistName</key>\n <string>MYAPP</string>\n <key>price</key>\n <integer>0</integer>\n <key>priceDisplay</key>\n <string>nil</string>\n <key>rating</key>\n <dict>\n <key>content</key>\n <string></string>\n <key>label</key>\n <string>4+</string>\n <key>rank</key>\n <integer>100</integer>\n <key>system</key>\n <string>itunes-games</string>\n </dict>\n <key>releaseDate</key>\n <string>Sunday, December 12, 2010</string>\n <key>s</key>\n <integer>143441</integer>\n <key>softwareIcon57x57URL</key>\n <string></string>\n <key>softwareIconNeedsShine</key>\n <false/>\n <key>softwareSupportedDeviceIds</key>\n <array>\n <integer>1</integer>\n </array>\n <key>softwareVersionBundleId</key>\n <string>com.mycompany.myapp</string>\n <key>softwareVersionExternalIdentifier</key>\n <integer>0</integer>\n <key>softwareVersionExternalIdentifiers</key>\n <array>\n <integer>1466803</integer>\n <integer>1529132</integer>\n <integer>1602608</integer>\n <integer>1651681</integer>\n <integer>1750461</integer>\n <integer>1930253</integer>\n <integer>1961532</integer>\n <integer>1973932</integer>\n <integer>2026202</integer>\n <integer>2526384</integer>\n <integer>2641622</integer>\n <integer>2703653</integer>\n </array>\n <key>vendorId</key>\n <integer>0</integer>\n <key>versionRestrictions</key>\n <integer>0</integer>\n</dict>\n</plist>\n ~/Documents/Installous/Downloads"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/752/"
] |
37,468 |
<p>I have a site running in a Windows shared hosting environment. In their control panel for the shared hosting account I have it set to use ASP.NET version 3.0 but it doesn't say 3.5 SP1 specifically.</p>
<p>How can I view the installed version running on the server where my website is hosted in an asp.net page?</p>
|
[
{
"answer_id": 6564854,
"author": "JanBorup",
"author_id": 276414,
"author_profile": "https://Stackoverflow.com/users/276414",
"pm_score": 1,
"selected": false,
"text": "<%=Environment.Version%>"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] |
37,471 |
<p>The minimum spanning tree problem is to take a connected weighted graph and find the subset of its edges with the lowest total weight while keeping the graph connected (and as a consequence resulting in an acyclic graph).</p>
<p>The algorithm I am considering is:</p>
<ul>
<li>Find all cycles.</li>
<li>remove the largest edge from each cycle.</li>
</ul>
<p>The impetus for this version is an environment that is restricted to "rule satisfaction" without any iterative constructs. It might also be applicable to insanely parallel hardware (i.e. a system where you expect to have several times more degrees of parallelism then cycles).</p>
<p>Edits:</p>
<p>The above is done in a stateless manner (all edges that are not the largest edge in any cycle are selected/kept/ignored, all others are removed).</p>
|
[
{
"answer_id": 37477,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 1,
"selected": false,
"text": "V = { a, b, c, d }\nE = { (a,b,1), (b,c,2), (c,a,4), (b,d,9), (d,a,3) }\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
37,473 |
<p>If I use <code>assert()</code> and the assertion fails then <code>assert()</code> will call <code>abort()</code>, ending the running program abruptly. I can't afford that in my production code. Is there a way to assert in runtime yet be able to catch failed assertions so I have the chance to handle them gracefully?</p>
|
[
{
"answer_id": 37474,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 6,
"selected": true,
"text": "assert() assert() abort() template <typename X, typename A>\ninline void Assert(A assertion)\n{\n if( !assertion ) throw X();\n}\n terminate() abort() Assert() #ifdef NDEBUG\n const bool CHECK_WRONG = false;\n#else\n const bool CHECK_WRONG = true;\n#endif\n #include<iostream>\n\nstruct Wrong { };\n\nint main()\n{\n try {\n Assert<Wrong>(!CHECK_WRONG || 2 + 2 == 5);\n std::cout << \"I can go to sleep now.\\n\";\n }\n catch( Wrong e ) {\n std::cerr << \"Someone is wrong on the internet!\\n\";\n }\n\n return 0;\n}\n CHECK_WRONG Assert() CHECK_WRONG Assert() if( !assertion ) throw X();\n assert()"
},
{
"answer_id": 168611,
"author": "indiv",
"author_id": 19719,
"author_profile": "https://Stackoverflow.com/users/19719",
"pm_score": 4,
"selected": false,
"text": "#define RETURN_IF_FAIL(expr) do { \\\n if (!(expr)) \\\n { \\\n fprintf(stderr, \\\n \"file %s: line %d (%s): precondition `%s' failed.\", \\\n __FILE__, \\\n __LINE__, \\\n __PRETTY_FUNCTION__, \\\n #expr); \\\n print_stack_trace(2); \\\n return; \\\n }; } while(0)\n#define RETURN_VAL_IF_FAIL(expr, val) do { \\\n if (!(expr)) \\\n { \\\n fprintf(stderr, \\\n \"file %s: line %d (%s): precondition `%s' failed.\", \\\n __FILE__, \\\n __LINE__, \\\n __PRETTY_FUNCTION__, \\\n #expr); \\\n print_stack_trace(2); \\\n return val; \\\n }; } while(0)\n void print_stack_trace(int fd)\n{\n void *array[256];\n size_t size;\n\n size = backtrace (array, 256);\n backtrace_symbols_fd(array, size, fd);\n}\n char *doSomething(char *ptr)\n{\n RETURN_VAL_IF_FAIL(ptr != NULL, NULL); // same as assert(ptr != NULL), but returns NULL if it fails.\n\n if( ptr != NULL ) // Necessary if you want to define the macro only for debug builds\n {\n ...\n }\n\n return ptr;\n}\n\nvoid doSomethingElse(char *ptr)\n{\n RETURN_IF_FAIL(ptr != NULL);\n}\n"
},
{
"answer_id": 270797,
"author": "rlerallut",
"author_id": 20055,
"author_profile": "https://Stackoverflow.com/users/20055",
"pm_score": 3,
"selected": false,
"text": "#define assert(e) ((void) ((e) ? 0 : __assert (#e, __FILE__, __LINE__)))\n#define __assert(e, file, line) ((void)printf (\"%s:%u: failed assertion `%s'\\n\", file, line, e), abort(), 0)\n #define assert(e) ((void) ((e) ? 0 : my_assert (#e, __FILE__, __LINE__)))\n#define my_assert( e, file, line ) ( throw std::runtime_error(\\\n std::string(file:)+boost::lexical_cast<std::string>(line)+\": failed assertion \"+e))\n void my_assert( const char* e, const char* file, int line);\n"
},
{
"answer_id": 26253587,
"author": "najoast",
"author_id": 4120604,
"author_profile": "https://Stackoverflow.com/users/4120604",
"pm_score": -1,
"selected": false,
"text": "_set_error_mode(_OUT_TO_MSGBOX);\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/456/"
] |
37,479 |
<p>Below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name.</p>
<pre><code>import cgi
class ClassX(object):
pass # ... with own __repr__
class ClassY(object):
pass # ... with own __repr__
inst_x=ClassX()
inst_y=ClassY()
inst_z=[ i*i for i in range(25) ]
inst_b=True
class HTMLDecorator(object):
def html(self): # an "enhanced" version of __repr__
return cgi.escape(self.__repr__()).join(("<H1>","</H1>"))
print HTMLDecorator(inst_x).html()
print HTMLDecorator(inst_y).html()
wrapped_z = HTMLDecorator(inst_z)
inst_z[0] += 70
wrapped_z[0] += 71
print wrapped_z.html()
print HTMLDecorator(inst_b).html()
</code></pre>
<p>Output:</p>
<pre>Traceback (most recent call last):
File "html.py", line 21, in
print HTMLDecorator(inst_x).html()
TypeError: default __new__ takes no parameters</pre>
<p>Is what I'm trying to do possible? If so, what am I doing wrong?</p>
|
[
{
"answer_id": 37488,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 0,
"selected": false,
"text": "HTMLDecorator.__init__() def decorator (func):\n def new_func ():\n return \"new_func %s\" % func ()\n return new_func\n\n@decorator\ndef a ():\n return \"a\"\n\ndef b ():\n return \"b\"\n\nprint a() # new_func a\nprint decorator (b)() # new_func b\n"
},
{
"answer_id": 37513,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 0,
"selected": false,
"text": "__repr__"
},
{
"answer_id": 37526,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 0,
"selected": false,
"text": "import cgi\n\nclass ClassX(object):\n def __repr__ (self):\n return \"<class X>\"\n\nclass HTMLDecorator(object):\n def __init__ (self, wrapped):\n self.__wrapped = wrapped\n\n def html (self):\n sep = cgi.escape (repr (self.__wrapped))\n return sep.join ((\"<H1>\", \"</H1>\"))\n\ninst_x=ClassX()\ninst_b=True\n\nprint HTMLDecorator(inst_x).html()\nprint HTMLDecorator(inst_b).html()\n"
},
{
"answer_id": 37544,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 0,
"selected": false,
"text": "import cgi\nfrom math import sqrt\n\nclass ClassX(object): \n def __repr__(self): \n return \"Best Guess\"\n\nclass ClassY(object):\n pass # ... with own __repr__\n\ninst_x=ClassX()\n\ninst_y=ClassY()\n\ninst_z=[ i*i for i in range(25) ]\n\ninst_b=True\n\navoid=\"__class__ __init__ __dict__ __weakref__\"\n\nclass HTMLDecorator(object):\n def __init__(self,master):\n self.master = master\n for attr in dir(self.master):\n if ( not attr.startswith(\"__\") or \n attr not in avoid.split() and \"attr\" not in attr):\n self.__setattr__(attr, self.master.__getattribute__(attr))\n\n def html(self): # an \"enhanced\" version of __repr__\n return cgi.escape(self.__repr__()).join((\"<H1>\",\"</H1>\"))\n\n def length(self):\n return sqrt(sum(self.__iter__()))\n\nprint HTMLDecorator(inst_x).html()\nprint HTMLDecorator(inst_y).html()\nwrapped_z = HTMLDecorator(inst_z)\nprint wrapped_z.length()\ninst_z[0] += 70\n#wrapped_z[0] += 71\nwrapped_z.__setitem__(0,wrapped_z.__getitem__(0)+ 71)\nprint wrapped_z.html()\nprint HTMLDecorator(inst_b).html()\n"
},
{
"answer_id": 37571,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": true,
"text": "bool def HTMLDecorator (obj):\n def html ():\n sep = cgi.escape (repr (obj))\n return sep.join ((\"<H1>\", \"</H1>\"))\n obj.html = html\n return obj\n class HTMLDecorator(object):\n def __init__ (self, wrapped):\n self.__wrapped = wrapped\n\n def html (self):\n sep = cgi.escape (repr (self.__wrapped))\n return sep.join ((\"<H1>\", \"</H1>\"))\n\n def __getattr__ (self, name):\n return getattr (self.__wrapped, name)\n\n def __setattr__ (self, name, value):\n if not name.startswith ('_HTMLDecorator__'):\n setattr (self.__wrapped, name, value)\n return\n super (HTMLDecorator, self).__setattr__ (name, value)\n\n def __delattr__ (self, name):\n delattr (self.__wraped, name)\n"
},
{
"answer_id": 37619,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 2,
"selected": false,
"text": "import cgi\n\nclass ClassX(object):\n pass # ... with own __repr__\n\nclass ClassY(object):\n pass # ... with own __repr__\n\ninst_x=ClassX()\ninst_y=ClassY()\n\nclass HTMLDecorator:\n def html(self): # an \"enhanced\" version of __repr__\n return cgi.escape(self.__repr__()).join((\"<H1>\",\"</H1>\"))\n\nClassX.__bases__ += (HTMLDecorator,)\nClassY.__bases__ += (HTMLDecorator,)\n\nprint inst_x.html()\nprint inst_y.html()\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1057/"
] |
37,483 |
<p>I suck at math. I need to figure out how to calculate a video duration with only a few examples of values. For example, a value of 70966 is displayed as 1:10 minutes. A value of 30533 displays as 30 seconds. A value of 7007 displays as 7 seconds. </p>
|
[
{
"answer_id": 37487,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 0,
"selected": false,
"text": " 70966 / 70 seconds = 1013.8\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2601/"
] |
37,486 |
<p>Because regular expressions scare me, I'm trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python.</p>
|
[
{
"answer_id": 37504,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 1,
"selected": false,
"text": " <div>5 < 7</div>\n < 7</div>\n"
},
{
"answer_id": 37512,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 6,
"selected": true,
"text": "import lxml.html\nt = lxml.html.fromstring(\"...\")\nt.text_content()\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3971/"
] |
37,495 |
<p>I'm trying to get some stats on how many of the visitors to our website have Silverlight enabled browsers. </p>
<p>We currently use Google Analytics for the rest of our stats so ideally we'd like to just add 'Silverlight enabled' tracking in with the rest of our Google Analytics stats. But if it has to get written out to a DB etc then so be it. </p>
<p>Nikhil has <a href="http://www.nikhilk.net/Silverlight-Analytics.aspx" rel="nofollow noreferrer">some javascript</a> to Silverlight tracking to Google Analytics. I have tried this code but Google Analytics doesn't pick it up.</p>
<p>Does anyone have any other ideas/techniques?</p>
|
[
{
"answer_id": 3323399,
"author": "mdarnall",
"author_id": 42998,
"author_profile": "https://Stackoverflow.com/users/42998",
"pm_score": 0,
"selected": false,
"text": "__utmSetVar() _setCustomVar()"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/242/"
] |
37,501 |
<p>Thanks to a Q&A on stackoverflow. I just found out how to determine the installed version on my hosting provider's server. Now I need to know what that number means.</p>
<p>Using <code><%=Environment.Version%></code> on my local machine returns 2.0.50727.3053.</p>
<p>Can someone give me a list of the version 1, 1.1, 2, etc. to the actual <code>Environment.Version</code> codes or break down what that code means?</p>
|
[
{
"answer_id": 56390256,
"author": "RBT",
"author_id": 465053,
"author_profile": "https://Stackoverflow.com/users/465053",
"pm_score": 0,
"selected": false,
"text": "<%=Environment.Version%>"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] |
37,525 |
<p>Imagine we have a program trying to write to a particular file, but failing.</p>
<p>On the Windows platform, what are the possible things which might be causing the file to be un-writable, and what steps could be suggested to an end user/administrator to fix it.</p>
<hr />
<p>Please include steps which might require administrator permissions (obviously users may not be administrators, but for this question, let's assume they are (or can become) administrators.</p>
<p>Also, I'm not really familiar with how permissions are calculated in windows. - Does the user need write access to each directory up the tree, or anything similar to that?</p>
|
[
{
"answer_id": 37527,
"author": "Michael Ratanapintha",
"author_id": 1879,
"author_profile": "https://Stackoverflow.com/users/1879",
"pm_score": 3,
"selected": true,
"text": "attrib -r"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] |
37,529 |
<p>I'd like to pull a stream of PCM samples from a Mac's line-in or built-in mic and do a little live analysis (the exact nature doesn't pertain to this question, but it could be an FFT every so often, or some basic statistics on the sample levels, or what have you).</p>
<p>What's a good fit for this? Writing an AudioUnit that just passes the sound through and incidentally hands it off somewhere for analysis? Writing a JACK-aware app and figuring out how to get it to play with the JACK server? Ecasound?</p>
<p>This is a cheesy proof-of-concept hobby project, so simplicity of API is the driving factor (followed by reasonable choice of programming language).</p>
|
[
{
"answer_id": 38543,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 3,
"selected": false,
"text": "AudioQueueNewInput /Developer/Examples/CoreAudio/SimpleSDK"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3462/"
] |
37,535 |
<p>I've got a bunch of FoxPro (VFP9) DBF files on my Ubuntu system, is there a library to open these in Python? I only need to read them, and would preferably have access to the memo fields too.</p>
<p><strong>Update</strong>: Thanks @cnu, I used Yusdi Santoso's <a href="http://www.physics.ox.ac.uk/users/santoso/dbf.py.src" rel="noreferrer"><code>dbf.py</code></a> and it works nicely. One gotcha: The memo file name extension must be lower case, i.e. <code>.fpt</code>, not <code>.FPT</code> which was how the filename came over from Windows.</p>
|
[
{
"answer_id": 37917,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 4,
"selected": false,
"text": ".DBF"
},
{
"answer_id": 10254842,
"author": "Steve Koch",
"author_id": 868718,
"author_profile": "https://Stackoverflow.com/users/868718",
"pm_score": 4,
"selected": false,
"text": "from dbf import *\ntest = Table(\"testfile.dbf\")\nfor record in test:\n print record\n x = raw_input(\"\") # to pause between showing records\n"
},
{
"answer_id": 38730628,
"author": "Shawn",
"author_id": 6615512,
"author_profile": "https://Stackoverflow.com/users/6615512",
"pm_score": 3,
"selected": false,
"text": "import dbf\n\nd=dbf.Table('mydbf.dbf')\nd.open()\ndbf.export(d, filename='mydf_exported.csv', format='csv', header=True)\n import dbf\n\nd=dbf.Table('mydbf.dbf', ignore_memos=True)\nd.open()\ndbf.export(d, filename='mydf_exported.csv', format='csv', header=True)\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715/"
] |
37,538 |
<p>How do I determine the size of my array in C? </p>
<p>That is, the number of elements the array can hold?</p>
|
[
{
"answer_id": 37539,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 12,
"selected": true,
"text": "int a[17];\nsize_t n = sizeof(a)/sizeof(a[0]);\n sizeof int a[17];\nsize_t n = sizeof(a);\n int a[17];\nsize_t n = sizeof(a) / sizeof(int);\n a sizeof(int) sizeof(a[0]) sizeof(*a) int a[17];\nsize_t n = sizeof(a) / sizeof(a[0]);\n #define NELEMS(x) (sizeof(x) / sizeof((x)[0]))\n\nint a[17];\nsize_t n = NELEMS(a);\n"
},
{
"answer_id": 37541,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 4,
"selected": false,
"text": "sizeof(array) / sizeof(array[0])\n"
},
{
"answer_id": 37545,
"author": "Magnus Hoff",
"author_id": 2971,
"author_profile": "https://Stackoverflow.com/users/2971",
"pm_score": 7,
"selected": false,
"text": "sizeof int a[10];\nint* p = a;\n\nassert(sizeof(a) / sizeof(a[0]) == 10);\nassert(sizeof(p) == sizeof(int*));\nassert(sizeof(*p) == sizeof(int));\n"
},
{
"answer_id": 204232,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 6,
"selected": false,
"text": "sizeof sizeof int myArray[10];\n size_t n = sizeof myArray / sizeof *myArray;\n sizeof send() void send(const void *object, size_t size);\n int foo = 4711;\nsend(&foo, sizeof (int));\n foo send(&foo, sizeof foo);\n"
},
{
"answer_id": 7093560,
"author": "Andreas Spindler",
"author_id": 887771,
"author_profile": "https://Stackoverflow.com/users/887771",
"pm_score": 4,
"selected": false,
"text": "#define g_rgDialogRows 2\n#define g_rgDialogCols 7\n\nstatic char const* g_rgDialog[g_rgDialogRows][g_rgDialogCols] =\n{\n { \" \", \" \", \" \", \" 494\", \" 210\", \" Generic Sample Dialog\", \" \" },\n { \" 1\", \" 330\", \" 174\", \" 88\", \" \", \" OK\", \" \" },\n};\n #define rows_of_array(name) \\\n (sizeof(name ) / sizeof(name[0][0]) / columns_of_array(name))\n#define columns_of_array(name) \\\n (sizeof(name[0]) / sizeof(name[0][0]))\n\nstatic char* g_rgDialog[][7] = { /* ... */ };\n\nassert( rows_of_array(g_rgDialog) == 2);\nassert(columns_of_array(g_rgDialog) == 7);\n sizeof(name[0][0][0])\nsizeof(name[0][0][0][0])\n"
},
{
"answer_id": 8129291,
"author": "Ohad",
"author_id": 1046490,
"author_profile": "https://Stackoverflow.com/users/1046490",
"pm_score": 0,
"selected": false,
"text": "#define MY_ARRAY_LENGTH 15\nint myArray[MY_ARRAY_LENGTH];\n // vector is a template, the <int> means it is a vector of ints\nvector<int> numbers; \n\n// push_back() puts a new value at the end (or back) of the vector\nfor (int i = 0; i < 10; i++)\n numbers.push_back(i);\n\n// Determine the size of the array\ncout << numbers.size();\n"
},
{
"answer_id": 10349610,
"author": "Elideb",
"author_id": 481534,
"author_profile": "https://Stackoverflow.com/users/481534",
"pm_score": 10,
"selected": false,
"text": "sizeof sizeof size_t size #include <stdio.h>\n#include <stdlib.h>\n\nvoid printSizeOf(int intArray[]);\nvoid printLength(int intArray[]);\n\nint main(int argc, char* argv[])\n{\n int array[] = { 0, 1, 2, 3, 4, 5, 6 };\n\n printf(\"sizeof of array: %d\\n\", (int) sizeof(array));\n printSizeOf(array);\n\n printf(\"Length of array: %d\\n\", (int)( sizeof(array) / sizeof(array[0]) ));\n printLength(array);\n}\n\nvoid printSizeOf(int intArray[])\n{\n printf(\"sizeof of parameter: %d\\n\", (int) sizeof(intArray));\n}\n\nvoid printLength(int intArray[])\n{\n printf(\"Length of parameter: %d\\n\", (int)( sizeof(intArray) / sizeof(intArray[0]) ));\n}\n sizeof of array: 28\nsizeof of parameter: 8\nLength of array: 7\nLength of parameter: 2\n sizeof of array: 28\nsizeof of parameter: 4\nLength of array: 7\nLength of parameter: 1\n"
},
{
"answer_id": 16354807,
"author": "Shih-En Chou",
"author_id": 924578,
"author_profile": "https://Stackoverflow.com/users/924578",
"pm_score": 2,
"selected": false,
"text": "& #include<stdio.h>\n#include<stdlib.h>\nint main(){\n\n int a[10];\n\n int *p; \n\n printf(\"%p\\n\", (void *)a); \n printf(\"%p\\n\", (void *)(&a+1));\n printf(\"---- diff----\\n\");\n printf(\"%zu\\n\", sizeof(a[0]));\n printf(\"The size of array a is %zu\\n\", ((char *)(&a+1)-(char *)a)/(sizeof(a[0])));\n\n\n return 0;\n};\n 1549216672\n1549216712\n---- diff----\n4\nThe size of array a is 10\n"
},
{
"answer_id": 17089267,
"author": "Joel Dentici",
"author_id": 2482551,
"author_profile": "https://Stackoverflow.com/users/2482551",
"pm_score": 3,
"selected": false,
"text": "Array.arr[i] Array.size /* Absolutely no one should use this...\n By the time you're done implementing it you'll wish you just passed around\n an array and size to your functions */\n/* This is a static implementation. You can get a dynamic implementation and \n cut out the array in main by using the stdlib memory allocation methods,\n but it will work much slower since it will store your array on the heap */\n\n#include <stdio.h>\n#include <string.h>\n/*\n#include \"MyTypeArray.h\"\n*/\n/* MyTypeArray.h \n#ifndef MYTYPE_ARRAY\n#define MYTYPE_ARRAY\n*/\ntypedef struct MyType\n{\n int age;\n char name[20];\n} MyType;\ntypedef struct MyTypeArray\n{\n int size;\n MyType *arr;\n} MyTypeArray;\n\nMyType new_MyType(int age, char *name);\nMyTypeArray newMyTypeArray(int size, MyType *first);\n/*\n#endif\nEnd MyTypeArray.h */\n\n/* MyTypeArray.c */\nMyType new_MyType(int age, char *name)\n{\n MyType d;\n d.age = age;\n strcpy(d.name, name);\n return d;\n}\n\nMyTypeArray new_MyTypeArray(int size, MyType *first)\n{\n MyTypeArray d;\n d.size = size;\n d.arr = first;\n return d;\n}\n/* End MyTypeArray.c */\n\n\nvoid print_MyType_names(MyTypeArray d)\n{\n int i;\n for (i = 0; i < d.size; i++)\n {\n printf(\"Name: %s, Age: %d\\n\", d.arr[i].name, d.arr[i].age);\n }\n}\n\nint main()\n{\n /* First create an array on the stack to store our elements in.\n Note we could create an empty array with a size instead and\n set the elements later. */\n MyType arr[] = {new_MyType(10, \"Sam\"), new_MyType(3, \"Baxter\")};\n /* Now create a \"MyTypeArray\" which will use the array we just\n created internally. Really it will just store the value of the pointer\n \"arr\". Here we are manually setting the size. You can use the sizeof\n trick here instead if you're sure it will work with your compiler. */\n MyTypeArray array = new_MyTypeArray(2, arr);\n /* MyTypeArray array = new_MyTypeArray(sizeof(arr)/sizeof(arr[0]), arr); */\n print_MyType_names(array);\n return 0;\n}\n"
},
{
"answer_id": 20447621,
"author": "Arjun Sreedharan",
"author_id": 997813,
"author_profile": "https://Stackoverflow.com/users/997813",
"pm_score": 5,
"selected": false,
"text": "int size = (&arr)[1] - arr;\n"
},
{
"answer_id": 21208828,
"author": "Abhitesh khatri",
"author_id": 1863721,
"author_profile": "https://Stackoverflow.com/users/1863721",
"pm_score": 5,
"selected": false,
"text": "int arr[] = {23, 12, 423, 43, 21, 43, 65, 76, 22};\n\nint noofele = sizeof(arr)/sizeof(int);\n noofele = sizeof(arr)/sizeof(arr[0]);\n arr"
},
{
"answer_id": 22084606,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "ARRAYELEMENTCOUNT(x) /* Compile as: CL /P \"macro.c\" */\n# define ARRAYELEMENTCOUNT(x) (sizeof (x) / sizeof (x[0]))\n\nARRAYELEMENTCOUNT(p + 1);\n (sizeof (p + 1) / sizeof (p + 1[0]));\n /* Compile as: CL /P \"macro.c\" */\n# define ARRAYELEMENTCOUNT(x) (sizeof (x) / sizeof (x)[0])\n\nARRAYELEMENTCOUNT(p + 1);\n (sizeof (p + 1) / sizeof (p + 1)[0]);\n p + 1"
},
{
"answer_id": 33820627,
"author": "Yogeesh H T",
"author_id": 3725702,
"author_profile": "https://Stackoverflow.com/users/3725702",
"pm_score": 4,
"selected": false,
"text": "int a[10];\nsize_t size_of_array = sizeof(a); // Size of array a\nint n = sizeof (a) / sizeof (a[0]); // Number of elements in array a\nsize_t size_of_element = sizeof(a[0]); // Size of each element in array a \n // Size of each element = size of type\n"
},
{
"answer_id": 35459621,
"author": "Paulo Pinheiro",
"author_id": 5343389,
"author_profile": "https://Stackoverflow.com/users/5343389",
"pm_score": 3,
"selected": false,
"text": "typedef struct {\n int *array;\n int elements;\n} list_s;\n"
},
{
"answer_id": 39453211,
"author": "Andy Nugent",
"author_id": 2964597,
"author_profile": "https://Stackoverflow.com/users/2964597",
"pm_score": 4,
"selected": false,
"text": "#define SIZE_OF_ARRAY(_array) (sizeof(_array) / sizeof(_array[0]))\n"
},
{
"answer_id": 44217128,
"author": "Mohd Shibli",
"author_id": 5947210,
"author_profile": "https://Stackoverflow.com/users/5947210",
"pm_score": 5,
"selected": false,
"text": "len = sizeof(arr)/sizeof(arr[0])\n"
},
{
"answer_id": 51392277,
"author": "Pygirl",
"author_id": 6660373,
"author_profile": "https://Stackoverflow.com/users/6660373",
"pm_score": -1,
"selected": false,
"text": "int a[10];\nint size = (*(&a+1)-a);\n"
},
{
"answer_id": 51927643,
"author": "Keivan",
"author_id": 4623372,
"author_profile": "https://Stackoverflow.com/users/4623372",
"pm_score": 3,
"selected": false,
"text": "sizeof sizeof int array[10]; int array[10];\nsize_t sizeOfArray = sizeof(array)/sizeof(int);\n"
},
{
"answer_id": 57408735,
"author": "Jency",
"author_id": 9384858,
"author_profile": "https://Stackoverflow.com/users/9384858",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n\nint main(void) {\n\n int a[] = {2,3,4,5,4,5,6,78,9,91,435,4,5,76,7,34}; // For example only\n int size;\n\n size = sizeof(a)/sizeof(a[0]); // Method\n\n printf(\"size = %d\", size);\n return 0;\n}\n"
},
{
"answer_id": 57537491,
"author": "alx",
"author_id": 6872717,
"author_profile": "https://Stackoverflow.com/users/6872717",
"pm_score": 5,
"selected": false,
"text": "sizeof sizeof(ptr) sizeof(arr) #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + must_be_array(arr))\n#define ARRAY_BYTES(arr) (sizeof(arr) + must_be_array(arr))\n must_be_array(arr) -Wsizeof-pointer-div #define is_same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))\n#define is_array(arr) (!is_same_type((arr), &(arr)[0]))\n#define must_be(e) \\\n( \\\n 0 * (int)sizeof( \\\n struct { \\\n static_assert(e); \\\n char ISO_C_forbids_a_struct_with_no_members__; \\\n } \\\n ) \\\n)\n#define must_be_array(arr) must_be(is_array(arr))\n void foo(size_t nmemb, int arr[nmemb])\n{\n qsort(arr, nmemb, sizeof(arr[0]), cmp);\n}\n qsort() ARRAY_SIZE #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))\n void foo(size_t nmemb)\n{\n char buf[nmemb];\n\n fgets(buf, ARRAY_SIZE(buf), stdin);\n}\n\nvoid bar(size_t nmemb)\n{\n int arr[nmemb];\n\n for (size_t i = 0; i < ARRAY_SIZE(arr); i++)\n arr[i] = i;\n}\n void foo(size_t nmemb, char buf[nmemb])\n{\n fgets(buf, nmemb, stdin);\n}\n\nvoid bar(size_t nmemb, int arr[nmemb])\n{\n for (size_t i = nmemb - 1; i < nmemb; i--)\n arr[i] = i;\n}\n ARRAY_SIZE sizeof(arr) #define ARRAY_BYTES(arr) (sizeof((arr)[0]) * ARRAY_SIZE(arr))\n ARRAY_SIZE sizeof(arr) ARRAY_SIZE void foo(size_t nmemb)\n{\n int arr[nmemb];\n\n memset(arr, 0, ARRAY_BYTES(arr));\n}\n memset() void foo(size_t nmemb, int arr[nmemb])\n{\n memset(arr, 0, sizeof(arr[0]) * nmemb);\n}\n -Wsizeof-pointer-div /usr/local/include/ /usr/include/ #include <foo.h> #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) static_assert() #include <assert.h>\n\n\n#define is_same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))\n#define is_array(arr) (!is_same_type((arr), &(arr)[0]))\n#define Static_assert_array(arr) static_assert(is_array(arr))\n\n#define ARRAY_SIZE(arr) \\\n({ \\\n Static_assert_array(arr); \\\n sizeof(arr) / sizeof((arr)[0]); \\\n})\n ARRAY_SIZE() __arraycount() __arraycount() <sys/cdefs.h> #inlcude <assert.h>\n#include <stddef.h>\n#include <sys/cdefs.h>\n#include <sys/types.h>\n\n\n#define is_same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))\n#define is_array(arr) (!is_same_type((arr), &(arr)[0]))\n#define Static_assert_array(arr) static_assert(is_array(arr))\n\n#define ARRAY_SIZE(arr) \\\n({ \\\n Static_assert_array(arr); \\\n __arraycount((arr)); \\\n})\n\n#define ARRAY_BYTES(arr) (sizeof((arr)[0]) * ARRAY_SIZE(arr))\n nitems() <sys/param.h> ({}) sizeof(struct {}) 0 (int) (int)0 ARRAY_BYTES() #include <assert.h>\n#include <stddef.h>\n#include <sys/cdefs.h>\n#include <sys/types.h>\n\n\n#define is_same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))\n#define is_array(arr) (!is_same_type((arr), &(arr)[0]))\n#define must_be(e) \\\n( \\\n 0 * (int)sizeof( \\\n struct { \\\n static_assert(e); \\\n char ISO_C_forbids_a_struct_with_no_members__; \\\n } \\\n ) \\\n)\n#define must_be_array(arr) must_be(is_array(arr))\n\n#define ARRAY_SIZE(arr) (__arraycount((arr)) + must_be_array(arr))\n#define ARRAY_BYTES(arr) (sizeof(arr) + must_be_array(arr))\n __builtin_types_compatible_p() typeof() static_assert() static_assert()"
},
{
"answer_id": 59946948,
"author": "Azatik1000",
"author_id": 5533889,
"author_profile": "https://Stackoverflow.com/users/5533889",
"pm_score": 2,
"selected": false,
"text": "size_t size = sizeof(a) / sizeof(*a);\n"
},
{
"answer_id": 60565087,
"author": "RobertS supports Monica Cellio",
"author_id": 12139179,
"author_profile": "https://Stackoverflow.com/users/12139179",
"pm_score": -1,
"selected": false,
"text": "sizeof(a) / sizeof (a[0])\n a char unsigned char signed char sizeof sizeof 1 sizeof char unsigned char signed char 1 sizeof(a) / sizeof (a[0]) NUMBER OF ARRAY ELEMENTS / 1 a char unsigned char signed char sizeof(a)\n char a[10];\nsize_t length = sizeof(a);\n"
},
{
"answer_id": 68236983,
"author": "Mano S",
"author_id": 16056201,
"author_profile": "https://Stackoverflow.com/users/16056201",
"pm_score": -1,
"selected": false,
"text": " int a[] = {1, 2, 3, 4, 5, 6};\n element _count = sizeof(a) / sizeof(a[0]);\n"
},
{
"answer_id": 72008351,
"author": "Punisher",
"author_id": 10213913,
"author_profile": "https://Stackoverflow.com/users/10213913",
"pm_score": -1,
"selected": false,
"text": "int a[10];\nint len = sizeof(a)/sizeof(int);\n #include <stdio.h>\n\nint main(){\n int a[10];\n printf(\"%d\\n\", sizeof(a)/sizeof(int));\n int *first = a;\n int *last = &(a[9]);\n printf(\"%d\\n\", (last-first) + 1);\n}\n 10\n10\n #include <stdio.h>\n\nint main(){\n int a[10];\n printf(\"%d\\n\", sizeof(a)/sizeof(int));\n void *first = a;\n void *last = &(a[9]);\n printf(\"%d\\n\", (last-first)/sizeof(int) + 1);\n}\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] |
37,551 |
<p>I have a problem with an application running on Fedora Core 6 with JDK 1.5.0_08.</p>
<p>After some amount of uptime (usually some days) threads begin getting stuck in native methods.</p>
<p>The threads are locked in something like this:</p>
<pre><code>"pool-2-thread-2571" prio=1 tid=0x08dd0b28 nid=0x319e waiting for monitor entry [0xb91fe000..0xb91ff7d4]
at java.lang.Class.getDeclaredConstructors0(Native Method)
</code></pre>
<p>or</p>
<pre><code>"pool-2-thread-2547" prio=1 tid=0x75641620 nid=0x1745 waiting for monitor entry [0xbc7fe000..0xbc7ff554]
at sun.misc.Unsafe.defineClass(Native Method)
</code></pre>
<p>Especially puzzling to me is this one:</p>
<pre><code>"HealthMonitor-10" daemon prio=1 tid=0x0868d1c0 nid=0x2b72 waiting for monitor entry [0xbe5ff000..0xbe5ff4d4]
at java.lang.Thread.dumpThreads(Native Method)
at java.lang.Thread.getStackTrace(Thread.java:1383)
</code></pre>
<p>The threads remain stuck until the VM is restarted.</p>
<p>Can anyone give me an idea as to what is happening here, what might be causing the native methods to block?
The monitor entry address range at the top of each stuck thread is different. How can I figure out what is holding this monitor?</p>
|
[
{
"answer_id": 177855,
"author": "VoidPointer",
"author_id": 23424,
"author_profile": "https://Stackoverflow.com/users/23424",
"pm_score": 1,
"selected": false,
"text": "\"Thread-0\" prio=5 tid=0x0100b060 nid=0x84c000 waiting for monitor entry [0xb0c8a000..0xb0c8ad90]\n at Deadlock$1.run(Deadlock.java:8)\n - waiting to lock <0x255e5b38> (a java.lang.Object)\n...\n\"main\" prio=5 tid=0x01001350 nid=0xb0801000 waiting on condition [0xb07ff000..0xb0800148]\n at java.lang.Thread.sleep(Native Method)\n at Deadlock.main(Deadlock.java:21)\n- locked <0x255e5b38> (a java.lang.Object)\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3904/"
] |
37,568 |
<p>How do I find duplicate addresses in a database, or better stop people already when filling in the form ? I guess the earlier the better?</p>
<p>Is there any good way of abstracting street, postal code etc so that typos and simple attempts to get 2 registrations can be detected? like: </p>
<pre><code>Quellenstrasse 66/11
Quellenstr. 66a-11
</code></pre>
<p>I'm talking German addresses...
Thanks!</p>
|
[
{
"answer_id": 44897826,
"author": "Sagar V",
"author_id": 2427065,
"author_profile": "https://Stackoverflow.com/users/2427065",
"pm_score": 0,
"selected": false,
"text": "Quellenstrasse 66/11 Quellenstr. 66a-11"
},
{
"answer_id": 44935403,
"author": "kichik",
"author_id": 492773,
"author_profile": "https://Stackoverflow.com/users/492773",
"pm_score": 0,
"selected": false,
"text": "<AddressValidateRequest USERID=\"XXXXX\">\n <IncludeOptionalElements>true</IncludeOptionalElements>\n <ReturnCarrierRoute>true</ReturnCarrierRoute>\n <Address ID=\"0\"> \n <FirmName /> \n <Address1 /> \n <Address2>205 bagwell ave</Address2> \n <City>nutter fort</City> \n <State>wv</State> \n <Zip5></Zip5> \n <Zip4></Zip4> \n </Address> \n</AddressValidateRequest>\n <AddressValidateResponse>\n <Address ID=\"0\">\n <Address2>205 BAGWELL AVE</Address2>\n <City>NUTTER FORT</City>\n <State>WV</State>\n <Zip5>26301</Zip5>\n <Zip4>4322</Zip4>\n <DeliveryPoint>05</DeliveryPoint>\n <CarrierRoute>C025</CarrierRoute>\n </Address>\n</AddressValidateResponse>\n"
},
{
"answer_id": 44986716,
"author": "Muhammad Muazzam",
"author_id": 2456918,
"author_profile": "https://Stackoverflow.com/users/2456918",
"pm_score": 0,
"selected": false,
"text": " <!DOCTYPE html>\n <html lang=\"en\">\n\n <head>\n <meta http-equiv=\"Content-Language\" content=\"en-us\">\n <title>Address Autocomplete</title>\n <meta charset=\"utf-8\">\n <link href=\"//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\" rel=\"stylesheet\">\n <script src=\"//code.jquery.com/jquery-2.1.4.min.js\"></script>\n <script src=\"//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js\"></script>\n <script src=\"//netsh.pp.ua/upwork-demo/1/js/typeahead.js\"></script>\n <style>\n h1 {\n font-size: 20px;\n color: #111;\n }\n\n .content {\n width: 80%;\n margin: 0 auto;\n margin-top: 50px;\n }\n\n .tt-hint,\n .city {\n border: 2px solid #CCCCCC;\n border-radius: 8px 8px 8px 8px;\n font-size: 24px;\n height: 45px;\n line-height: 30px;\n outline: medium none;\n padding: 8px 12px;\n width: 400px;\n }\n\n .tt-dropdown-menu {\n width: 400px;\n margin-top: 5px;\n padding: 8px 12px;\n background-color: #fff;\n border: 1px solid #ccc;\n border: 1px solid rgba(0, 0, 0, 0.2);\n border-radius: 8px 8px 8px 8px;\n font-size: 18px;\n color: #111;\n background-color: #F1F1F1;\n }\n </style>\n <script>\n $(document).ready(function() {\n\n $('input.city').typeahead({\n name: 'city',\n remote: 'city.php?query=%QUERY'\n\n });\n\n })\n </script>\n\n <script>\n function register_address()\n {\n $.ajax({\n type: \"POST\",\n data: {\n City: $('#city').val(),\n },\n url: \"addressexists.php\",\n success: function(data)\n {\n if(data === 'ADDRESS_EXISTS')\n {\n $('#address')\n .css('color', 'red')\n .html(\"This address already exists!\");\n }\n\n }\n }) \n }\n </script>\n </head>\n\n <body>\n <div class=\"content\">\n\n <form>\n <h1>Try it yourself</h1>\n <input type=\"text\" name=\"city\" size=\"30\" id=\"city\" class=\"city\" placeholder=\"Please Enter City or ZIP code\">\n<span id=\"address\"></span>\n </form>\n </div>\n </body>\n</html>\n <?php\n\n//CREDENTIALS FOR DB\ndefine ('DBSERVER', 'localhost');\ndefine ('DBUSER', 'user');\ndefine ('DBPASS','password');\ndefine ('DBNAME','dbname');\n\n//LET'S INITIATE CONNECT TO DB\n$connection = mysqli_connect(DBSERVER, DBUSER, DBPASS,\"DBNAME\") or die(\"Can't connect to server. Please check credentials and try again\");\n\n\n//CREATE QUERY TO DB AND PUT RECEIVED DATA INTO ASSOCIATIVE ARRAY\nif (isset($_REQUEST['query'])) {\n $query = $_REQUEST['query'];\n $sql = mysqli_query ($connection ,\"SELECT zip, city FROM zips WHERE city LIKE '%{$query}%' OR zip LIKE '%{$query}%'\");\n $array = array();\n while ($row = mysqli_fetch_array($sql,MYSQLI_NUM)) {\n $array[] = array (\n 'label' => $row['city'].', '.$row['zip'],\n 'value' => $row['city'],\n );\n }\n //RETURN JSON ARRAY\n echo json_encode ($array);\n}\n\n?>\n <?php//CREDENTIALS FOR DB\n define ('DBSERVER', 'localhost');\n define ('DBUSER', 'user');\n define ('DBPASS','password');\n define ('DBNAME','dbname');\n\n //LET'S INITIATE CONNECT TO DB\n $connection = mysqli_connect(DBSERVER, DBUSER, DBPASS,\"DBNAME\") or die(\"Can't connect to server. Please check credentials and try again\");\n\n\n $city= mysqli_real_escape_string($_POST['city']); // $_POST is an array (not a function)\n // mysqli_real_escape_string is to prevent sql injection\n\n $sql = \"SELECT username FROM \".TABLENAME.\" WHERE city='\".$city.\"'\"; // City must enclosed in two quotations\n\n $query = mysqli_query($connection,$sql);\n\n if(mysqli_num_rows($query) != 0)\n\n {\n echo('ADDRESS_EXISTS');\n }\n?>\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925/"
] |
37,586 |
<p>Our application is interfacing with a lot of web services these days. We have our own package that someone wrote a few years back using UTL_HTTP and it generally works, but needs some hard-coding of the SOAP envelope to work with certain systems. I would like to make it more generic, but lack experience to know how many scenarios I would have to deal with. The variations are in what namespaces need to be declared and the format of the elements. We have to handle both simple calls with a few parameters and those that pass a large amount of data in an encoded string.</p>
<p>I know that 10g has UTL_DBWS, but there are not a huge number of use-cases on-line. Is it stable and flexible enough for general use? <a href="http://stanford.edu/dept/itss/docs/oracle/10g/java.101/b12021/callouts.htm" rel="nofollow noreferrer">Documentation</a></p>
|
[
{
"answer_id": 67977,
"author": "Sten Vesterli",
"author_id": 9363,
"author_profile": "https://Stackoverflow.com/users/9363",
"pm_score": 4,
"selected": true,
"text": "UTL_HTTP UTL_DBWS"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1895/"
] |
37,591 |
<p>I would like to display details of an xml error log to a user in a winforms application and am looking for the best control to do the job.</p>
<p>The error data contains all of the sever variables at the time that the error occurred. These have been formatted into an XML document that looks something to the effect of:</p>
<pre><code><error>
<serverVariables>
<item>
<value>
</item>
</serverVariables>
<queryString>
<item name="">
<value string="">
</item>
</queryString>
</error>
</code></pre>
<p>I would like to read this data from the string that it is stored in and display it to the user via a windows form in a useful way. XML Notepad does a cool job of formatting xml, but is not really was I am looking for since I would prefer to rather display item details in a <em>Name : string</em> format.</p>
<p>Any suggestions or am I looking and a custom implementation?</p>
<p>[EDIT] A section of the data that needs to be displayed:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<error host="WIN12" type="System.Web.HttpException" message="The file '' does not exist." source="System.Web" detail="System.Web.HttpException: The file '' does not exist. at System.Web.UI.Util.CheckVirtualFileExists(VirtualPath virtualPath) at" time="2008-09-01T07:13:08.9171250+02:00" statusCode="404">
<serverVariables>
<item name="ALL_HTTP">
<value string="HTTP_CONNECTION:close HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) " />
</item>
<item name="AUTH_TYPE">
<value string="" />
</item>
<item name="HTTPS">
<value string="off" />
</item>
<item name="HTTPS_KEYSIZE">
<value string="" />
</item>
<item name="HTTP_USER_AGENT">
<value string="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)" />
</item>
</serverVariables>
<queryString>
<item name="tid">
<value string="196" />
</item>
</queryString>
</error>
</code></pre>
|
[
{
"answer_id": 37612,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 0,
"selected": false,
"text": "DataGridView"
},
{
"answer_id": 37631,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": true,
"text": "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"text\"/>\n <xsl:template match=\"//error/serverVariables\">\n <xsl:text>Server variables:\n </xsl:text>\n <xsl:for-each select=\"item\">\n <xsl:value-of select=\"@name\"/>:<xsl:value-of select=\"value/@string\"/>\n <xsl:text>\n </xsl:text>\n </xsl:for-each>\n </xsl:template>\n <xsl:template match=\"//error/queryString\">\n <xsl:text>Query string items:\n </xsl:text>\n <xsl:for-each select=\"item\">\n <xsl:value-of select=\"@name\"/>:<xsl:value-of select=\"value/@string\"/>\n <xsl:text>\n </xsl:text>\n </xsl:for-each>\n </xsl:template>\n</xsl:stylesheet>\n"
},
{
"answer_id": 37740,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 0,
"selected": false,
"text": "System.Xml.Serialization.XmlSerializer"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231/"
] |
37,593 |
<p>What is the best source of free Vista style graphics for application development? I want <strong>32x32</strong> and <strong>16x16</strong> that I can use in a Winforms application.</p>
|
[
{
"answer_id": 37596,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": true,
"text": "Common7\\VS2008ImageLibrary"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2608/"
] |
37,597 |
<p>TreeNodeCollection, like some of the other control collections in System.Windows.Forms, implements IEnumerable. Is there any design reason behind this or is it just a hangover from the days before generics?</p>
|
[
{
"answer_id": 37609,
"author": "Artem Tikhomirov",
"author_id": 2313,
"author_profile": "https://Stackoverflow.com/users/2313",
"pm_score": 4,
"selected": true,
"text": "using System.Linq; \n... \nvar nodes = GetTreeNodeCollection().OfType<TreeNode>();\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2608/"
] |
37,628 |
<p>What is reflection, and why is it useful?</p>
<p>I'm particularly interested in Java, but I assume the principles are the same in any language.</p>
|
[
{
"answer_id": 37632,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 12,
"selected": true,
"text": "Method method = foo.getClass().getMethod(\"doSomething\", null);\nmethod.invoke(foo, null);\n"
},
{
"answer_id": 37638,
"author": "Liedman",
"author_id": 890,
"author_profile": "https://Stackoverflow.com/users/890",
"pm_score": 8,
"selected": false,
"text": "getClass() Object C++"
},
{
"answer_id": 39918,
"author": "Ben Williams",
"author_id": 2453,
"author_profile": "https://Stackoverflow.com/users/2453",
"pm_score": 7,
"selected": false,
"text": "import java.lang.reflect.Array;\nimport java.lang.reflect.Field;\n\npublic static String dump(Object o, int callCount) {\n callCount++;\n StringBuffer tabs = new StringBuffer();\n for (int k = 0; k < callCount; k++) {\n tabs.append(\"\\t\");\n }\n StringBuffer buffer = new StringBuffer();\n Class oClass = o.getClass();\n if (oClass.isArray()) {\n buffer.append(\"\\n\");\n buffer.append(tabs.toString());\n buffer.append(\"[\");\n for (int i = 0; i < Array.getLength(o); i++) {\n if (i < 0)\n buffer.append(\",\");\n Object value = Array.get(o, i);\n if (value.getClass().isPrimitive() ||\n value.getClass() == java.lang.Long.class ||\n value.getClass() == java.lang.String.class ||\n value.getClass() == java.lang.Integer.class ||\n value.getClass() == java.lang.Boolean.class\n ) {\n buffer.append(value);\n } else {\n buffer.append(dump(value, callCount));\n }\n }\n buffer.append(tabs.toString());\n buffer.append(\"]\\n\");\n } else {\n buffer.append(\"\\n\");\n buffer.append(tabs.toString());\n buffer.append(\"{\\n\");\n while (oClass != null) {\n Field[] fields = oClass.getDeclaredFields();\n for (int i = 0; i < fields.length; i++) {\n buffer.append(tabs.toString());\n fields[i].setAccessible(true);\n buffer.append(fields[i].getName());\n buffer.append(\"=\");\n try {\n Object value = fields[i].get(o);\n if (value != null) {\n if (value.getClass().isPrimitive() ||\n value.getClass() == java.lang.Long.class ||\n value.getClass() == java.lang.String.class ||\n value.getClass() == java.lang.Integer.class ||\n value.getClass() == java.lang.Boolean.class\n ) {\n buffer.append(value);\n } else {\n buffer.append(dump(value, callCount));\n }\n }\n } catch (IllegalAccessException e) {\n buffer.append(e.getMessage());\n }\n buffer.append(\"\\n\");\n }\n oClass = oClass.getSuperclass();\n }\n buffer.append(tabs.toString());\n buffer.append(\"}\\n\");\n }\n return buffer.toString();\n}\n"
},
{
"answer_id": 16406534,
"author": "Ess Kay",
"author_id": 2267583,
"author_profile": "https://Stackoverflow.com/users/2267583",
"pm_score": 3,
"selected": false,
"text": "Reflection"
},
{
"answer_id": 17531269,
"author": "Nikhil Shekhar",
"author_id": 1772534,
"author_profile": "https://Stackoverflow.com/users/1772534",
"pm_score": 5,
"selected": false,
"text": "Class myObjectClass = MyObject.class;\nMethod[] method = myObjectClass.getMethods();\n\n//Here the method takes a string parameter if there is no param, put null.\nMethod method = aClass.getMethod(\"method_name\", String.class); \n\nObject returnValue = method.invoke(null, \"parameter-value1\");\n public class A{\n\n private String str= null;\n\n public A(String str) {\n this.str= str;\n }\n}\n A obj= new A(\"Some value\");\n\nField privateStringField = A.class.getDeclaredField(\"privateString\");\n\n//Turn off access check for this field\nprivateStringField.setAccessible(true);\n\nString fieldValue = (String) privateStringField.get(obj);\nSystem.out.println(\"fieldValue = \" + fieldValue);\n java.lang.reflect java.lang.Class"
},
{
"answer_id": 25721335,
"author": "VeKe",
"author_id": 1878022,
"author_profile": "https://Stackoverflow.com/users/1878022",
"pm_score": 5,
"selected": false,
"text": "Method[] methods = MyObject.class.getMethods();\n\n for(Method method : methods){\n System.out.println(\"method = \" + method.getName());\n }\n <bean id=\"someID\" class=\"com.example.Foo\">\n <property name=\"someField\" value=\"someValue\" />\n</bean>\n Method method = targetClass.getDeclaredMethod(methodName, argClasses);\nmethod.setAccessible(true);\nreturn method.invoke(targetObject, argObjects);\n Field field = targetClass.getDeclaredField(fieldName);\nfield.setAccessible(true);\nfield.set(object, value);\n"
},
{
"answer_id": 25953852,
"author": "catch23",
"author_id": 1498427,
"author_profile": "https://Stackoverflow.com/users/1498427",
"pm_score": 4,
"selected": false,
"text": "toString() class ObjectAnalyzer {\n\n private ArrayList<Object> visited = new ArrayList<Object>();\n\n /**\n * Converts an object to a string representation that lists all fields.\n * @param obj an object\n * @return a string with the object's class name and all field names and\n * values\n */\n public String toString(Object obj) {\n if (obj == null) return \"null\";\n if (visited.contains(obj)) return \"...\";\n visited.add(obj);\n Class cl = obj.getClass();\n if (cl == String.class) return (String) obj;\n if (cl.isArray()) {\n String r = cl.getComponentType() + \"[]{\";\n for (int i = 0; i < Array.getLength(obj); i++) {\n if (i > 0) r += \",\";\n Object val = Array.get(obj, i);\n if (cl.getComponentType().isPrimitive()) r += val;\n else r += toString(val);\n }\n return r + \"}\";\n }\n\n String r = cl.getName();\n // inspect the fields of this class and all superclasses\n do {\n r += \"[\";\n Field[] fields = cl.getDeclaredFields();\n AccessibleObject.setAccessible(fields, true);\n // get the names and values of all fields\n for (Field f : fields) {\n if (!Modifier.isStatic(f.getModifiers())) {\n if (!r.endsWith(\"[\")) r += \",\";\n r += f.getName() + \"=\";\n try {\n Class t = f.getType();\n Object val = f.get(obj);\n if (t.isPrimitive()) r += val;\n else r += toString(val);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n r += \"]\";\n cl = cl.getSuperclass();\n } while (cl != null);\n\n return r;\n } \n}\n"
},
{
"answer_id": 26771874,
"author": "Isuru Jayakantha",
"author_id": 4216954,
"author_profile": "https://Stackoverflow.com/users/4216954",
"pm_score": 5,
"selected": false,
"text": "public class Test {\n\n public void firstMoveChoice(){\n System.out.println(\"First Move\");\n } \n public void secondMOveChoice(){\n System.out.println(\"Second Move\");\n }\n public void thirdMoveChoice(){\n System.out.println(\"Third Move\");\n }\n\n public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { \n Test test = new Test();\n Method[] method = test.getClass().getMethods();\n //firstMoveChoice\n method[0].invoke(test, null);\n //secondMoveChoice\n method[1].invoke(test, null);\n //thirdMoveChoice\n method[2].invoke(test, null);\n }\n\n}\n"
},
{
"answer_id": 35379881,
"author": "Ravindra babu",
"author_id": 4999394,
"author_profile": "https://Stackoverflow.com/users/4999394",
"pm_score": 3,
"selected": false,
"text": "java.lang.reflect AccessibleObject ReflectPermission java.lang.Class Object Serialization JavaBeans Class"
},
{
"answer_id": 42945244,
"author": "roottraveller",
"author_id": 5167682,
"author_profile": "https://Stackoverflow.com/users/5167682",
"pm_score": 4,
"selected": false,
"text": "java.lang.reflect package java.lang java.lang.reflect getClass() getConstructors() getMethods()"
},
{
"answer_id": 53626477,
"author": "BSeitkazin",
"author_id": 3631743,
"author_profile": "https://Stackoverflow.com/users/3631743",
"pm_score": 2,
"selected": false,
"text": "Hibernate Reflection API CRUD Hibernate Lombok Project Hibernate reflection MethodHandles Reflection API Logger LOGGER = Logger.getLogger(MethodHandles.lookup().lookupClass().getName());\n"
},
{
"answer_id": 70494517,
"author": "Bhushan",
"author_id": 12965752,
"author_profile": "https://Stackoverflow.com/users/12965752",
"pm_score": 1,
"selected": false,
"text": "Object obj = Class.forName(config.getClassPath())\n .getDeclaredConstructor()\n .newInstance();\nMethod method = obj.getClass().getMethod(\"getCustomer\", SearchObject.class, ObjectConfig.class,\n HttpServletRequest.class);\nmethod.invoke(obj, searchObject, config, request);\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142/"
] |
37,644 |
<p>I have a set of Berkeley DB files on my Linux file system that I'd like to examine.</p>
<p>What useful tools exist for getting a quick overview of the contents? I can write Perl scripts that use BDB modules for examining them, but I'm looking for some CLI utility to be able to take a look inside without having to start writing scripts.</p>
|
[
{
"answer_id": 37655,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 6,
"selected": true,
"text": "apt-get install db-util apt-get install db4.8-util"
},
{
"answer_id": 19793412,
"author": "strickli",
"author_id": 1612703,
"author_profile": "https://Stackoverflow.com/users/1612703",
"pm_score": 3,
"selected": false,
"text": "me@machine$ python\nPython 2.7.3 (default, Sep 26 2013, 20:03:06) \n>>> import dbhash\n>>> for k, v in dbhash.open( *<db filename here...>* ).iteritems(): print k, v\n...\n"
},
{
"answer_id": 23018271,
"author": "trjh",
"author_id": 2620,
"author_profile": "https://Stackoverflow.com/users/2620",
"pm_score": 4,
"selected": false,
"text": "# file foo.db\nfoo.db: Berkeley DB (Btree, version 9, native byte-order)\n\n# python\n>>> import bsddb\n>>> for k, v in bsddb.btopen(\"*<db filename here...>*\").iteritems():\n... print k,v\n...\n"
},
{
"answer_id": 34377228,
"author": "cdauth",
"author_id": 242365,
"author_profile": "https://Stackoverflow.com/users/242365",
"pm_score": 6,
"selected": false,
"text": "db_dump core/db db-util sys-libs/db db4.8_dump db_dump -p database.db db_dump -p database.db\n database.db db_dump -l database.db\n mydb database.db db_dump -p -s mydb database.db\n"
},
{
"answer_id": 71243626,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 1,
"selected": false,
"text": "from bsddb3 import db\nimport collections\nd = db.DB()\nd.open('./file.dat', 'dbname', db.DB_BTREE, db.DB_THREAD | db.DB_RDONLY)\nd.keys()\ncollections.OrderedDict((k, d[k]) for k in d.keys())\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1951/"
] |
37,649 |
<p>I have a MySQL table with coordinates, the column names are X and Y. Now I want to swap the column values in this table, so that X becomes Y and Y becomes X. The most apparent solution would be renaming the columns, but I don't want to make structure changes since I don't necessarily have permissions to do that.</p>
<p>Is this possible to do with <b>UPDATE</b> in some way? <b>UPDATE table SET X=Y, Y=X</b> obviously won't do what I want.</p>
<hr>
<p>Edit: Please note that my restriction on permissions, mentioned above, effectively prevents the use of ALTER TABLE or other commands that change the table/database structure. Renaming columns or adding new ones are unfortunately not options.</p>
|
[
{
"answer_id": 37657,
"author": "fijter",
"author_id": 3215,
"author_profile": "https://Stackoverflow.com/users/3215",
"pm_score": 2,
"selected": false,
"text": " ALTER TABLE table ADD COLUMN tmp;\nUPDATE table SET tmp = X;\nUPDATE table SET X = Y;\nUPDATE table SET Y = tmp;\nALTER TABLE table DROP COLUMN tmp;\n mysql> select * from test;\n+------+------+\n| x | y |\n+------+------+\n| 1 | 2 |\n| 3 | 4 |\n+------+------+\n2 rows in set (0.00 sec)\n\nmysql> update test set x=y, y=x;\nQuery OK, 2 rows affected (0.00 sec)\nRows matched: 2 Changed: 2 Warnings: 0\n\n mysql> select * from test;\n+------+------+\n| x | y |\n+------+------+\n| 2 | 2 |\n| 4 | 4 |\n+------+------+\n2 rows in set (0.00 sec)\n"
},
{
"answer_id": 37737,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 3,
"selected": false,
"text": "mysql> select * from swapper;\n+------+------+\n| foo | bar |\n+------+------+\n| 6 | 1 | \n| 5 | 2 | \n| 4 | 3 | \n+------+------+\n3 rows in set (0.00 sec)\n\nmysql> update swapper set \n -> foo = concat(foo, \"###\", bar),\n -> bar = replace(foo, concat(\"###\", bar), \"\"),\n -> foo = replace(foo, concat(bar, \"###\"), \"\");\n\nQuery OK, 3 rows affected (0.00 sec)\nRows matched: 3 Changed: 3 Warnings: 0\n\nmysql> select * from swapper;\n+------+------+\n| foo | bar |\n+------+------+\n| 1 | 6 | \n| 2 | 5 | \n| 3 | 4 | \n+------+------+\n3 rows in set (0.00 sec)\n update swapper set foo = foo ^ bar, bar = foo ^ bar, foo = foo ^ bar;\n"
},
{
"answer_id": 385713,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 1,
"selected": false,
"text": "SELECT BIT_XOR(foo) FROM table WHERE key = $1 OR key = $2\n\nUPDATE table SET foo = CAST(foo ^ $3 AS SIGNED) WHERE key = $1 OR key = $2\n"
},
{
"answer_id": 385733,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 2,
"selected": false,
"text": "UPDATE tbl SET @temp=X, X=Y, Y=@temp\n"
},
{
"answer_id": 395008,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "UPDATE tbl SET X=Y, Y=@temp where @temp:=X;\n"
},
{
"answer_id": 559291,
"author": "Artem Russakovskii",
"author_id": 47680,
"author_profile": "https://Stackoverflow.com/users/47680",
"pm_score": 9,
"selected": true,
"text": "UPDATE table SET X=Y, Y=X UPDATE swap_test SET x=y, y=@temp WHERE (@temp:=x) IS NOT NULL; UPDATE swap_test SET x=(@temp:=x), x = y, y = @temp; UPDATE swap_test s1, swap_test s2 SET s1.x=s1.y, s1.y=s2.x WHERE s1.id=s2.id; CREATE TABLE `swap_test` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `x` varchar(255) DEFAULT NULL,\n `y` varchar(255) DEFAULT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB;\n\nINSERT INTO `swap_test` VALUES ('1', 'a', '10');\nINSERT INTO `swap_test` VALUES ('2', NULL, '20');\nINSERT INTO `swap_test` VALUES ('3', 'c', NULL);\n"
},
{
"answer_id": 562230,
"author": "Dipin",
"author_id": 67976,
"author_profile": "https://Stackoverflow.com/users/67976",
"pm_score": 6,
"selected": false,
"text": "UPDATE swap_test\n SET x=(@temp:=x), x = y, y = @temp\n"
},
{
"answer_id": 11749453,
"author": "RolandoMySQLDBA",
"author_id": 491757,
"author_profile": "https://Stackoverflow.com/users/491757",
"pm_score": 6,
"selected": false,
"text": "UPDATE swaptest SET X=X+Y,Y=X-Y,X=X-Y;\n mysql> use test\nDatabase changed\nmysql> drop table if exists swaptest;\nQuery OK, 0 rows affected (0.03 sec)\n\nmysql> create table swaptest (X int,Y int);\nQuery OK, 0 rows affected (0.12 sec)\n\nmysql> INSERT INTO swaptest VALUES (1,2),(3,4),(-5,-8),(-13,27);\nQuery OK, 4 rows affected (0.08 sec)\nRecords: 4 Duplicates: 0 Warnings: 0\n\nmysql> SELECT * FROM swaptest;\n+------+------+\n| X | Y |\n+------+------+\n| 1 | 2 |\n| 3 | 4 |\n| -5 | -8 |\n| -13 | 27 |\n+------+------+\n4 rows in set (0.00 sec)\n\nmysql>\n mysql> UPDATE swaptest SET X=X+Y,Y=X-Y,X=X-Y;\nQuery OK, 4 rows affected (0.07 sec)\nRows matched: 4 Changed: 4 Warnings: 0\n\nmysql> SELECT * FROM swaptest;\n+------+------+\n| X | Y |\n+------+------+\n| 2 | 1 |\n| 4 | 3 |\n| -8 | -5 |\n| 27 | -13 |\n+------+------+\n4 rows in set (0.00 sec)\n\nmysql>\n"
},
{
"answer_id": 25444064,
"author": "http8086",
"author_id": 1356874,
"author_profile": "https://Stackoverflow.com/users/1356874",
"pm_score": 3,
"selected": false,
"text": "update z set c1 = @c := c1, c1 = c2, c2 = @c\n update z set c1 = c1 ^ c2, c2 = c1 ^ c2, c1 = c1 ^ c2\n update z set c1 = c1 + c2, c2 = c1 - c2, c1 = c1 - c2\n update z set c1 = c2, c2 = @c where @c := c1\n update z set c1 = c2, c2 = @c where if((@c := c1), true, true)\n mysql> create table z (c1 int, c2 int)\n -> ;\nQuery OK, 0 rows affected (0.02 sec)\n\nmysql> insert into z values(0, 1), (-1, 1), (pow(2, 31) - 1, pow(2, 31) - 2)\n -> ;\nQuery OK, 3 rows affected (0.00 sec)\nRecords: 3 Duplicates: 0 Warnings: 0\n\nmysql> select * from z;\n+------------+------------+\n| c1 | c2 |\n+------------+------------+\n| 0 | 1 |\n| -1 | 1 |\n| 2147483647 | 2147483646 |\n+------------+------------+\n3 rows in set (0.02 sec)\n\nmysql> update z set c1 = c1 ^ c2, c2 = c1 ^ c2, c1 = c1 ^ c2;\nERROR 1264 (22003): Out of range value for column 'c1' at row 2\nmysql> update z set c1 = c1 + c2, c2 = c1 - c2, c1 = c1 - c2;\nERROR 1264 (22003): Out of range value for column 'c1' at row 3\n\nmysql> select * from z;\n+------------+------------+\n| c1 | c2 |\n+------------+------------+\n| 0 | 1 |\n| 1 | -1 |\n| 2147483646 | 2147483647 |\n+------------+------------+\n3 rows in set (0.02 sec)\n\nmysql> update z set c1 = c2, c2 = @c where @c := c1;\nQuery OK, 2 rows affected (0.00 sec)\nRows matched: 2 Changed: 2 Warnings: 0\n\nmysql> select * from z;\n+------------+------------+\n| c1 | c2 |\n+------------+------------+\n| 0 | 1 |\n| -1 | 1 |\n| 2147483647 | 2147483646 |\n+------------+------------+\n3 rows in set (0.00 sec)\n\nmysql> select * from z;\n+------------+------------+\n| c1 | c2 |\n+------------+------------+\n| 1 | 0 |\n| 1 | -1 |\n| 2147483646 | 2147483647 |\n+------------+------------+\n3 rows in set (0.00 sec)\n\nmysql> update z set c1 = @c := c1, c1 = c2, c2 = @c;\nQuery OK, 3 rows affected (0.02 sec)\nRows matched: 3 Changed: 3 Warnings: 0\n\nmysql> select * from z;\n+------------+------------+\n| c1 | c2 |\n+------------+------------+\n| 0 | 1 |\n| -1 | 1 |\n| 2147483647 | 2147483646 |\n+------------+------------+\n3 rows in set (0.00 sec)\n\nmysql>update z set c1 = c2, c2 = @c where if((@c := c1), true, true);\nQuery OK, 3 rows affected (0.02 sec)\nRows matched: 3 Changed: 3 Warnings: 0\n\nmysql> select * from z;\n+------------+------------+\n| c1 | c2 |\n+------------+------------+\n| 1 | 0 |\n| 1 | -1 |\n| 2147483646 | 2147483647 |\n+------------+------------+\n3 rows in set (0.00 sec)\n"
},
{
"answer_id": 28415690,
"author": "Ashutosh SIngh",
"author_id": 3725409,
"author_profile": "https://Stackoverflow.com/users/3725409",
"pm_score": 0,
"selected": false,
"text": "CREATE TABLE Names\n(\nF_NAME VARCHAR(22),\nL_NAME VARCHAR(22)\n);\n\nINSERT INTO Names VALUES('Ashutosh', 'Singh'),('Anshuman','Singh'),('Manu', 'Singh');\n\nUPDATE Names N1 , Names N2 SET N1.F_NAME = N2.L_NAME , N1.L_NAME = N2.F_NAME \nWHERE N1.F_NAME = N2.F_NAME;\n\nSELECT * FROM Names;\n"
},
{
"answer_id": 38007428,
"author": "Archer1974",
"author_id": 6507575,
"author_profile": "https://Stackoverflow.com/users/6507575",
"pm_score": 0,
"selected": false,
"text": "Update MyTable set X= (@temp:= X), X = 0, Y = @temp WHERE ID= 999;\n"
},
{
"answer_id": 52201000,
"author": "Andrew Foster",
"author_id": 2227342,
"author_profile": "https://Stackoverflow.com/users/2227342",
"pm_score": 0,
"selected": false,
"text": "UPDATE monitor_date mdu\nINNER JOIN monitor_date mdc\n ON mdu.register_id = mdc.register_id\n AND mdu.start_date = mdc.start_date\n AND mdu.end_date = mdc.end_date\nSET mdu.start_date = mdu.end_date, mdu.end_date = mdc.start_date\nWHERE mdu.start_date > mdu.end_date;\n"
},
{
"answer_id": 57119800,
"author": "SamK",
"author_id": 11810251,
"author_profile": "https://Stackoverflow.com/users/11810251",
"pm_score": 2,
"selected": false,
"text": "update swaptable \nset col1 = t2.col2,\ncol2 = t2.col1\nfrom swaptable t2\nwhere id = t2.id\n"
},
{
"answer_id": 57193703,
"author": "Felix Labayen",
"author_id": 2503754,
"author_profile": "https://Stackoverflow.com/users/2503754",
"pm_score": 0,
"selected": false,
"text": "UPDATE tb_user a\nINNER JOIN tb_user_copy b\nON a.id = b.id\nSET a.first_name = b.last_name, a.last_name = b.first_name\n"
},
{
"answer_id": 62861002,
"author": "Tanumay Saha",
"author_id": 12347807,
"author_profile": "https://Stackoverflow.com/users/12347807",
"pm_score": 1,
"selected": false,
"text": "Table name: studentname\nonly single column available: name\n\n\nupdate studentnames \nset names = case names \nwhen \"Tanu\" then \"dipan\"\nwhen \"dipan\" then \"Tanu\"\nend;\n\nor\n\nupdate studentnames \nset names = case names \nwhen \"Tanu\" then \"dipan\"\nelse \"Tanu\"\nend;\n"
},
{
"answer_id": 63548307,
"author": "Naveen Kashyap",
"author_id": 12311615,
"author_profile": "https://Stackoverflow.com/users/12311615",
"pm_score": 0,
"selected": false,
"text": "UPDATE table_name SET column_name = CASE column_name WHERE 'value of col is x' THEN 'swap it to y' ELSE 'swap it to x' END;"
},
{
"answer_id": 64128356,
"author": "PKS",
"author_id": 14163532,
"author_profile": "https://Stackoverflow.com/users/14163532",
"pm_score": 0,
"selected": false,
"text": "UPDATE sex\nSET sex = CASE sex\nWHEN 'm' THEN 'f'\nELSE 'm'\nEND;\n"
},
{
"answer_id": 71355271,
"author": "pbarney",
"author_id": 62536,
"author_profile": "https://Stackoverflow.com/users/62536",
"pm_score": 2,
"selected": false,
"text": "id UPDATE mytable t1, mytable t2\nSET t1.column1 = t1.column2,\n t1.column2 = t2.column1\nWHERE t1.id = t2.id;\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/890/"
] |
37,650 |
<p>What is the best way to implement, from a web page a download action using asp.net 2.0?</p>
<p>Log files for a action are created in a directory called [Application Root]/Logs. I have the full path and want to provide a button, that when clicked will download the log file from the IIS server to the users local pc.</p>
|
[
{
"answer_id": 37656,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 6,
"selected": true,
"text": "Response.ContentType = \"application/octet-stream\";\nResponse.AppendHeader(\"Content-Disposition\",\"attachment; filename=logfile.txt\");\nResponse.TransmitFile( Server.MapPath(\"~/logfile.txt\") );\nResponse.End();\n"
},
{
"answer_id": 2583641,
"author": "BiLaL",
"author_id": 309856,
"author_profile": "https://Stackoverflow.com/users/309856",
"pm_score": 4,
"selected": false,
"text": "string filename = @\"Specify the file path in the server over here....\";\nFileInfo fileInfo = new FileInfo(filename);\n\nif (fileInfo.Exists)\n{\n Response.Clear();\n Response.AddHeader(\"Content-Disposition\", \"attachment; filename=\" + fileInfo.Name);\n Response.AddHeader(\"Content-Length\", fileInfo.Length.ToString());\n Response.ContentType = \"application/octet-stream\";\n Response.Flush();\n Response.TransmitFile(fileInfo.FullName);\n Response.End();\n}\n Response.AddHeader(\"Content-Disposition\", \"inline;attachment; filename=\" + fileInfo.Name);\n attachment"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3416/"
] |
37,662 |
<p>I'm writing a Perl script and would like to use a n-ary tree data structure.</p>
<p>Is there a good implementation that is available as source code (rather than part of a Perl library) ?</p>
|
[
{
"answer_id": 38857,
"author": "nohat",
"author_id": 3101,
"author_profile": "https://Stackoverflow.com/users/3101",
"pm_score": 2,
"selected": false,
"text": " t\n / \\\n a d\n / \\ / \\\n b c e f\n $tree = [ t => [ a => [ b => [], c => [] ]\n d => [ e => [], f => [] ] ] ];\n => $tree = [ 't', [ 'a' , [ 'b' , [], 'c' , [] ]\n 'd' , [ 'e' , [], 'f' , [] ] ] ];\n sub elements {\n my $tree = shift;\n\n my @elements;\n my @queue = @$tree;\n while (@queue) {\n my $element = shift @queue;\n my $children = shift @queue;\n push @elements, $element;\n unshift @queue, @$children;\n }\n\n return @elements;\n}\n\n@elements = elements($tree) # qw(t a b c d e f)\n unshift @queue, @$children push @queue, @$children"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
] |
37,665 |
<p>When <strong>Eclipse</strong> creates a new file (<strong>.c</strong> or <strong>.h</strong> file) in a C project the editor always auto creates a <code>#define</code> at the top of the file like this: If the file is named 'myCFile.c' there will be a <code>#define</code> at the start of the file like this</p>
<pre><code>#ifndef MYCFILE_C_
#define MYCFILE_C_
</code></pre>
<p>I have seen other editors do this as well (Codewright and SlikEdit I think).
The <code>#defines</code> don't seem to do anything for the editor as I can just delete them without any problem, and I can't think of a reason why <em>I</em> would want to use them. Does anyone know why they are there? </p>
|
[
{
"answer_id": 38416,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 1,
"selected": false,
"text": "#pragma once\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2079/"
] |
37,684 |
<p>I am using the function below to match URLs inside a given text and replace them for HTML links. The regular expression is working great, but currently I am only replacing the first match.</p>
<p>How I can replace all the URL? I guess I should be using the <em>exec</em> command, but I did not really figure how to do it.</p>
<pre><code>function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
return text.replace(exp,"<a href='$1'>$1</a>");
}
</code></pre>
|
[
{
"answer_id": 37687,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 8,
"selected": false,
"text": ".museum /ig;\n"
},
{
"answer_id": 2166104,
"author": "Travis",
"author_id": 252828,
"author_profile": "https://Stackoverflow.com/users/252828",
"pm_score": 5,
"selected": false,
"text": "function Linkify(inputText) {\n //URLs starting with http://, https://, or ftp://\n var replacePattern1 = /(\\b(https?|ftp):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])/gim;\n var replacedText = inputText.replace(replacePattern1, '<a href=\"$1\" target=\"_blank\">$1</a>');\n\n //URLs starting with www. (without // before it, or it'd re-link the ones done above)\n var replacePattern2 = /(^|[^\\/])(www\\.[\\S]+(\\b|$))/gim;\n var replacedText = replacedText.replace(replacePattern2, '$1<a href=\"http://$2\" target=\"_blank\">$2</a>');\n\n //Change email addresses to mailto:: links\n var replacePattern3 = /(\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,6})/gim;\n var replacedText = replacedText.replace(replacePattern3, '<a href=\"mailto:$1\">$1</a>');\n\n return replacedText\n}\n"
},
{
"answer_id": 2250355,
"author": "Uwe Keim",
"author_id": 107625,
"author_profile": "https://Stackoverflow.com/users/107625",
"pm_score": 1,
"selected": false,
"text": "// Change e-mail addresses to mailto: links.\nconst RegexOptions o = RegexOptions.Multiline | RegexOptions.IgnoreCase;\nconst string pat3 = @\"([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,6})\";\nconst string rep3 = @\"<a href=\"\"mailto:$1@$2.$3\"\">$1@$2.$3</a>\";\ntext = Regex.Replace(text, pat3, rep3, o);\n"
},
{
"answer_id": 3890175,
"author": "cloud8421",
"author_id": 470194,
"author_profile": "https://Stackoverflow.com/users/470194",
"pm_score": 7,
"selected": false,
"text": "function linkify(inputText) {\n var replacedText, replacePattern1, replacePattern2, replacePattern3;\n\n //URLs starting with http://, https://, or ftp://\n replacePattern1 = /(\\b(https?|ftp):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])/gim;\n replacedText = inputText.replace(replacePattern1, '<a href=\"$1\" target=\"_blank\">$1</a>');\n\n //URLs starting with \"www.\" (without // before it, or it'd re-link the ones done above).\n replacePattern2 = /(^|[^\\/])(www\\.[\\S]+(\\b|$))/gim;\n replacedText = replacedText.replace(replacePattern2, '$1<a href=\"http://$2\" target=\"_blank\">$2</a>');\n\n //Change email addresses to mailto:: links.\n replacePattern3 = /(([a-zA-Z0-9\\-\\_\\.])+@[a-zA-Z\\_]+?(\\.[a-zA-Z]{2,6})+)/gim;\n replacedText = replacedText.replace(replacePattern3, '<a href=\"mailto:$1\">$1</a>');\n\n return replacedText;\n}\n"
},
{
"answer_id": 7123542,
"author": "Roshambo",
"author_id": 610051,
"author_profile": "https://Stackoverflow.com/users/610051",
"pm_score": 6,
"selected": false,
"text": "Linkify() String var text = '[email protected]';\ntext.linkify();\n\n'http://stackoverflow.com/'.linkify();\n if(!String.linkify) {\n String.prototype.linkify = function() {\n\n // http://, https://, ftp://\n var urlPattern = /\\b(?:https?|ftp):\\/\\/[a-z0-9-+&@#\\/%?=~_|!:,.;]*[a-z0-9-+&@#\\/%=~_|]/gim;\n\n // www. sans http:// or https://\n var pseudoUrlPattern = /(^|[^\\/])(www\\.[\\S]+(\\b|$))/gim;\n\n // Email addresses\n var emailAddressPattern = /[\\w.]+@[a-zA-Z_-]+?(?:\\.[a-zA-Z]{2,6})+/gim;\n\n return this\n .replace(urlPattern, '<a href=\"$&\">$&</a>')\n .replace(pseudoUrlPattern, '$1<a href=\"http://$2\">$2</a>')\n .replace(emailAddressPattern, '<a href=\"mailto:$&\">$&</a>');\n };\n}\n"
},
{
"answer_id": 7138764,
"author": "Christian Koch",
"author_id": 725349,
"author_profile": "https://Stackoverflow.com/users/725349",
"pm_score": 4,
"selected": false,
"text": "if(!String.linkify) {\n String.prototype.linkify = function() {\n\n // http://, https://, ftp://\n var urlPattern = /\\b(?:https?|ftp):\\/\\/[a-z0-9-+&@#\\/%?=~_|!:,.;]*[a-z0-9-+&@#\\/%=~_|]/gim;\n\n // www. sans http:// or https://\n var pseudoUrlPattern = /(^|[^\\/])(www\\.[\\S]+(\\b|$))/gim;\n\n // Email addresses *** here I've changed the expression ***\n var emailAddressPattern = /(([a-zA-Z0-9_\\-\\.]+)@[a-zA-Z_]+?(?:\\.[a-zA-Z]{2,6}))+/gim;\n\n return this\n .replace(urlPattern, '<a target=\"_blank\" href=\"$&\">$&</a>')\n .replace(pseudoUrlPattern, '$1<a target=\"_blank\" href=\"http://$2\">$2</a>')\n .replace(emailAddressPattern, '<a target=\"_blank\" href=\"mailto:$1\">$1</a>');\n };\n}\n"
},
{
"answer_id": 8443010,
"author": "Artjom Kurapov",
"author_id": 158448,
"author_profile": "https://Stackoverflow.com/users/158448",
"pm_score": 3,
"selected": false,
"text": "function replaceURLWithHTMLLinks(text) {\n var exp = /(\\b(https?|ftp|file):\\/\\/([-A-Z0-9+&@#%?=~_|!:,.;]*)([-A-Z0-9+&@#%?\\/=~_|!:,.;]*)[-A-Z0-9+&@#\\/%=~_|])/ig;\n return text.replace(exp, \"<a href='$1' target='_blank'>$3</a>\");\n}\n"
},
{
"answer_id": 10498205,
"author": "Vebjorn Ljosa",
"author_id": 17498,
"author_profile": "https://Stackoverflow.com/users/17498",
"pm_score": 4,
"selected": false,
"text": "urlize urlize urlize('Go to SO (stackoverflow.com) and ask. <grin>', \n {nofollow: true, autoescape: true})\n=> \"Go to SO (<a href=\"http://stackoverflow.com\" rel=\"nofollow\">stackoverflow.com</a>) and ask. <grin>\"\n rel=\"nofollow\""
},
{
"answer_id": 13518703,
"author": "rlemon",
"author_id": 829835,
"author_profile": "https://Stackoverflow.com/users/829835",
"pm_score": 3,
"selected": false,
"text": " function make_link(string) {\n var words = string.split(' '),\n ret = document.createDocumentFragment();\n for (var i = 0, l = words.length; i < l; i++) {\n if (words[i].match(/[-a-zA-Z0-9@:%_\\+.~#?&//=]{2,256}\\.[a-z]{2,4}\\b(\\/[-a-zA-Z0-9@:%_\\+.~#?&//=]*)?/gi)) {\n var elm = document.createElement('a');\n elm.href = words[i];\n elm.textContent = words[i];\n if (ret.childNodes.length > 0) {\n ret.lastChild.textContent += ' ';\n }\n ret.appendChild(elm);\n } else {\n if (ret.lastChild && ret.lastChild.nodeType === 3) {\n ret.lastChild.textContent += ' ' + words[i];\n } else {\n ret.appendChild(document.createTextNode(' ' + words[i]));\n }\n }\n }\n return ret;\n}\n"
},
{
"answer_id": 19772928,
"author": "Mike Mestnik",
"author_id": 1153319,
"author_profile": "https://Stackoverflow.com/users/1153319",
"pm_score": 1,
"selected": false,
"text": "function replaceURLWithHTMLLinks(text) {\n var re = /(\\(.*?)?\\b((?:https?|ftp|file):\\/\\/[-a-z0-9+&@#\\/%?=~_()|!:,.;]*[-a-z0-9+&@#\\/%=~_()|])/ig;\n return text.replace(re, function(match, lParens, url) {\n var rParens = '';\n lParens = lParens || '';\n\n // Try to strip the same number of right parens from url\n // as there are left parens. Here, lParenCounter must be\n // a RegExp object. You cannot use a literal\n // while (/\\(/g.exec(lParens)) { ... }\n // because an object is needed to store the lastIndex state.\n var lParenCounter = /\\(/g;\n while (lParenCounter.exec(lParens)) {\n var m;\n // We want m[1] to be greedy, unless a period precedes the\n // right parenthesis. These tests cannot be simplified as\n // /(.*)(\\.?\\).*)/.exec(url)\n // because if (.*) is greedy then \\.? never gets a chance.\n if (m = /(.*)(\\.\\).*)/.exec(url) ||\n /(.*)(\\).*)/.exec(url)) {\n url = m[1];\n rParens = m[2] + rParens;\n }\n }\n return lParens + \"<a href='\" + url + \"'>\" + url + \"</a>\" + rParens;\n });\n}\n"
},
{
"answer_id": 21455918,
"author": "Nishant Kumar",
"author_id": 430803,
"author_profile": "https://Stackoverflow.com/users/430803",
"pm_score": 2,
"selected": false,
"text": "/(\\b((https?|ftp|file):\\/\\/|(www))[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|]*)/ig function UriphiMe(text) {\n var exp = /(\\b((https?|ftp|file):\\/\\/|(www))[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|]*)/ig; \n return text.replace(exp,\"<a href='$1'>$1</a>\");\n}\n www /(\\b((https?|ftp|file):\\/\\/|(www))[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])/ig"
},
{
"answer_id": 21925491,
"author": "Dan Dascalescu",
"author_id": 1269037,
"author_profile": "https://Stackoverflow.com/users/1269037",
"pm_score": 10,
"selected": true,
"text": ".museum .etc href"
},
{
"answer_id": 23887643,
"author": "Andrew Murphy",
"author_id": 2008831,
"author_profile": "https://Stackoverflow.com/users/2008831",
"pm_score": 2,
"selected": false,
"text": "maps.bing.com/something?key=!\"£$%^*()&lat=65&lon&lon=20 http(s):// (anything but a space)+ www. (anything but a space)+ [^'\"<>\\s] href=\"...\" src=\"...\" if html.match( /(href)|(src)/i )) {\n return html; // text already has a hyper link in it\n }\n\nhtml = html.replace( \n /\\b(https?:\\/\\/[^\\s\\(\\)\\'\\\"\\<\\>]+)/ig, \n \"<a ref='nofollow' href='$1'>$1</a>\" \n );\n\nhtml = html.replace( \n /\\s(www\\.[^\\s\\(\\)\\'\\\"\\<\\>]+)/ig, \n \"<a ref='nofollow' href='http://$1'>$1</a>\" \n );\n\nhtml = html.replace( \n /^(www\\.[^\\s\\(\\)\\'\\\"\\<\\>]+)/ig, \n \"<a ref='nofollow' href='http://$1'>$1</a>\" \n );\n\nreturn html;\n"
},
{
"answer_id": 30280085,
"author": "Vitaly",
"author_id": 1031804,
"author_profile": "https://Stackoverflow.com/users/1031804",
"pm_score": 2,
"selected": false,
"text": "linkify-it"
},
{
"answer_id": 36202408,
"author": "degenerate",
"author_id": 482115,
"author_profile": "https://Stackoverflow.com/users/482115",
"pm_score": 4,
"selected": false,
"text": "$('p').each(function(){\n $(this).html( $(this).html().replace(/((http|https|ftp):\\/\\/[\\w?=&.\\/-;#~%-]+(?![\\w\\s?&.\\/;#~%\"=-]*>))/g, '<a href=\"$1\">$1</a> ') );\n});\n"
},
{
"answer_id": 36988874,
"author": "Moritz",
"author_id": 5587737,
"author_profile": "https://Stackoverflow.com/users/5587737",
"pm_score": 2,
"selected": false,
"text": "/g /(\\b(https?|ftp|file):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])/gi"
},
{
"answer_id": 51499913,
"author": "Johann",
"author_id": 753632,
"author_profile": "https://Stackoverflow.com/users/753632",
"pm_score": 1,
"selected": false,
"text": "var content = \"Visit https://wwww.google.com or watch this video: https://www.youtube.com/watch?v=0T4DQYgsazo and news at http://www.bbc.com\";\ncontent = replaceUrlsWithLinks(content, \"http://\");\ncontent = replaceUrlsWithLinks(content, \"https://\");\n\nfunction replaceUrlsWithLinks(content, protocol) {\n var startPos = 0;\n var s = 0;\n\n while (s < content.length) {\n startPos = content.indexOf(protocol, s);\n\n if (startPos < 0)\n return content;\n\n let endPos = content.indexOf(\" \", startPos + 1);\n\n if (endPos < 0)\n endPos = content.length;\n\n let url = content.substr(startPos, endPos - startPos);\n\n if (url.endsWith(\".\") || url.endsWith(\"?\") || url.endsWith(\",\")) {\n url = url.substr(0, url.length - 1);\n endPos--;\n }\n\n if (ROOTNS.utils.stringsHelper.validUrl(url)) {\n let link = \"<a href='\" + url + \"'>\" + url + \"</a>\";\n content = content.substr(0, startPos) + link + content.substr(endPos);\n s = startPos + link.length;\n } else {\n s = endPos + 1;\n }\n }\n\n return content;\n}\n\nfunction validUrl(url) {\n try {\n new URL(url);\n return true;\n } catch (e) {\n return false;\n }\n}\n"
},
{
"answer_id": 55114398,
"author": "Moonis Abidi",
"author_id": 7791324,
"author_profile": "https://Stackoverflow.com/users/7791324",
"pm_score": 2,
"selected": false,
"text": "function anchorify(text){\n var exp = /(\\b(https?|ftp|file):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])/ig;\n var text1=text.replace(exp, \"<a href='$1'>$1</a>\");\n var exp2 =/(^|[^\\/])(www\\.[\\S]+(\\b|$))/gim;\n return text1.replace(exp2, '$1<a target=\"_blank\" href=\"http://$2\">$2</a>');\n}\n alert(anchorify(\"Hola amigo! https://www.sharda.ac.in/academics/\"));"
},
{
"answer_id": 55570404,
"author": "Rahul Hirve",
"author_id": 7509309,
"author_profile": "https://Stackoverflow.com/users/7509309",
"pm_score": 1,
"selected": false,
"text": "function replaceLinkClickableLink(url = '') {\nlet pattern = new RegExp('^(https?:\\\\/\\\\/)?'+\n '((([a-z\\\\d]([a-z\\\\d-]*[a-z\\\\d])*)\\\\.?)+[a-z]{2,}|'+\n '((\\\\d{1,3}\\\\.){3}\\\\d{1,3}))'+\n '(\\\\:\\\\d+)?(\\\\/[-a-z\\\\d%_.~+]*)*'+\n '(\\\\?[;&a-z\\\\d%_.~+=-]*)?'+\n '(\\\\#[-a-z\\\\d_]*)?$','i');\n\nlet isUrl = pattern.test(url);\nif (isUrl) {\n return `<a href=\"${url}\" target=\"_blank\">${url}</a>`;\n}\nreturn url;\n}\n"
},
{
"answer_id": 55575592,
"author": "Zuhair Taha",
"author_id": 1274894,
"author_profile": "https://Stackoverflow.com/users/1274894",
"pm_score": 3,
"selected": false,
"text": "/**\n * Convert URLs in a string to anchor buttons\n * @param {!string} string\n * @returns {!string}\n */\n\nfunction URLify(string){\n var urls = string.match(/(((ftp|https?):\\/\\/)[\\-\\w@:%_\\+.~#?,&\\/\\/=]+)/g);\n if (urls) {\n urls.forEach(function (url) {\n string = string.replace(url, '<a target=\"_blank\" href=\"' + url + '\">' + url + \"</a>\");\n });\n }\n return string.replace(\"(\", \"<br/>(\");\n}\n"
},
{
"answer_id": 67165342,
"author": "majid nazari",
"author_id": 6763995,
"author_profile": "https://Stackoverflow.com/users/6763995",
"pm_score": 0,
"selected": false,
"text": "var urlRegex =/(\\b((https?|ftp|file):\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*(\\?[;&a-z\\d%_.~+=-]*)?(\\#[-a-z\\d_]*)?)/ig;\n\nreturn text.replace(urlRegex, function(url) {\n var newUrl = url.indexOf(\"http\") === -1 ? \"http://\" + url : url;\n return '<a href=\"' + newUrl + '\">' + url + '</a>';\n});\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
37,696 |
<p>I have three tables <code>tag</code>, <code>page</code>, <code>pagetag</code></p>
<p>With the data below</p>
<p><strong><em>page</em></strong></p>
<pre><code>ID NAME
1 page 1
2 page 2
3 page 3
4 page 4
</code></pre>
<p><strong><em>tag</em></strong></p>
<pre><code>ID NAME
1 tag 1
2 tag 2
3 tag 3
4 tag 4
</code></pre>
<p><strong><em>pagetag</em></strong></p>
<pre><code>ID PAGEID TAGID
1 2 1
2 2 3
3 3 4
4 1 1
5 1 2
6 1 3
</code></pre>
<p>I would like to get a string containing the correspondent tag names for each page with SQL in a single query. This is my desired output.</p>
<pre><code>ID NAME TAGS
1 page 1 tag 1, tag 2, tag 3
2 page 2 tag 1, tag 3
3 page 3 tag 4
4 page 4
</code></pre>
<p>Is this possible with SQL?</p>
<hr>
<p>I am using MySQL. Nonetheless, I would like a database vendor independent solution if possible.</p>
|
[
{
"answer_id": 37700,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 2,
"selected": false,
"text": "SELECT page_tag.id, page.name, group_concat(tags.name)\nFROM tag, page, page_tag\nWHERE page_tag.page_id = page.page_id AND page_tag.tag_id = tag.id;\n"
},
{
"answer_id": 37711,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "select ID as 'PageId', Name as 'PageName', null as 'Tags'\ninto #temp \nfrom [PageTable]\n\ndeclare @lastOp int\nset @lastOp = 1\n\nwhile @lastOp > 0\nbegin\n update p\n set p.tags = isnull(tags + ', ', '' ) + t.[Tagid]\n from #temp p\n inner join [TagTable] t\n on p.[PageId] = t.[PageId]\n where p.tags not like '%' + t.[Tagid] + '%'\n\n set @lastOp == @@rowcount\nend\n\nselect * from #temp\n"
},
{
"answer_id": 37724,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 1,
"selected": false,
"text": "SELECT field1 | ', ' | field2\nFROM table;\n SELECT field1 + ', ' + field2\nFROM table;\n SELECT concat(field1,', ',field2)\nFROM table;\n SELECT field1 || ', ' || field2\nFROM table;\n"
},
{
"answer_id": 37761,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 3,
"selected": true,
"text": "SELECT pagetag.id, page.name, group_concat(tag.name)\nFROM\n(\n page LEFT JOIN pagetag ON page.id = pagetag.pageid\n)\nLEFT JOIN tag ON pagetag.tagid = tag.id\nGROUP BY page.id;\n pagetag.id group_concat(tag.name) null"
},
{
"answer_id": 37787,
"author": "Sergio del Amo",
"author_id": 2138,
"author_profile": "https://Stackoverflow.com/users/2138",
"pm_score": 1,
"selected": false,
"text": "SELECT\n page.id AS id,\n page.name AS name,\n tagstable.tags AS tags\nFROM page \nLEFT OUTER JOIN \n(\n SELECT pagetag.pageid, GROUP_CONCAT(distinct tag.name) AS tags\n FROM tag INNER JOIN pagetag ON tagid = tag.id\n GROUP BY pagetag.pageid\n)\nAS tagstable ON tagstable.pageid = page.id\nGROUP BY page.id\n id name tags\n---------------------------\n1 page 1 tag2,tag3,tag1\n2 page 2 tag1,tag3\n3 page 3 tag4\n4 page 4 NULL\n"
},
{
"answer_id": 37789,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 0,
"selected": false,
"text": "COALESCE select COALESCE(pagetag.id, '') AS id ...\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
37,702 |
<p>Sorry for this not being a "real" question, but Sometime back i remember seeing a post here about randomizing a randomizer randomly to generate truly random numbers, not just pseudo random. I dont see it if i search for it.</p>
<p>Does anybody know about that article?</p>
|
[
{
"answer_id": 37716,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": false,
"text": "/dev/random"
},
{
"answer_id": 172268,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 3,
"selected": false,
"text": "/dev/random"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2759376/"
] |
37,731 |
<p>I seem right now to be embroiled in a debate with another programmer on this project who thinks that views have no merits. He proposes a system that PHP looks something like this:</p>
<pre><code>$draw = new Draw;
$nav = $draw->wideHeaderBox().
$draw->left().
$draw->image().
Image::get($image,60,array('id'=>'header_image')).
$draw->imageEnd().
$draw->leftEnd().
$draw->left(10).
'<div id="header_text">'.
self::defaultSectionText().
'</div>'.
$draw->leftEnd().
</code></pre>
<p>and so on (this is in the controller btw). Now his arguments for this actually make some sense, he claims that if there is a redesign all we need to do is change the HTML in one place and it changes everywhere automatically. For some reason however, this method still rubs me the wrong way, is there any merit to views over this method? I mean besides not having to retype HTML by hand.</p>
|
[
{
"answer_id": 37768,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 4,
"selected": true,
"text": "new Draw wideHeaderBox left wideHeaderBox HTML::link(\"Wikipedia\", \"http://en.wikipedia.org\");\nHTML::bulleted_list(array(\n HTML::list_item(\"Dogs\"),\n HTML::list_item(\"Cats\"),\n HTML::list_item(\"Armadillos\")\n));\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2594/"
] |
37,732 |
<p>What is the RegEx pattern for DateTime (2008-09-01 12:35:45 ) ?</p>
<p>I get this error:</p>
<blockquote>
<p>No ending delimiter '^' found</p>
</blockquote>
<p>Using:</p>
<pre><code>preg_match('(?n:^(?=\d)((?<day>31(?!(.0?[2469]|11))|30(?!.0?2)|29(?(.0?2)(?=.{3,4}(1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(16|[2468][048]|[3579][26])00))|0?[1-9]|1\d|2[0-8])(?<sep>[/.-])(?<month>0?[1-9]|1[012])\2(?<year>(1[6-9]|[2-9]\d)\d{2})(?:(?=\x20\d)\x20|$))?(?<time>((0?[1-9]|1[012])(:[0-5]\d){0,2}(?i:\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$)', '2008-09-01 12:35:45');
</code></pre>
<p>Gives this error: </p>
<blockquote>
<p>Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 0 in E:\www\index.php on line 19</p>
</blockquote>
|
[
{
"answer_id": 37758,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 5,
"selected": false,
"text": "(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}) \n"
},
{
"answer_id": 37767,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 7,
"selected": true,
"text": "(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})\n $year = $1;\n$month = $2;\n$day = $3;\n$hour = $4;\n$minute = $5;\n$second = $6;\n"
},
{
"answer_id": 37875,
"author": "Imran",
"author_id": 1897,
"author_profile": "https://Stackoverflow.com/users/1897",
"pm_score": -1,
"selected": false,
"text": "preg_match('/\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}/', '2008-09-01 12:35:45');\n\n// or this, to allow matching 0:00:00 time too.\npreg_match('/\\d{4}-\\d{2}-\\d{2} \\d{1,2}:\\d{2}:\\d{2}/', '2008-09-01 12:35:45');\n preg_match('/^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/', '2008-09-01 12:35:45');\n"
},
{
"answer_id": 4727571,
"author": "deni",
"author_id": 580368,
"author_profile": "https://Stackoverflow.com/users/580368",
"pm_score": 1,
"selected": false,
"text": "preg_match('/\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}/', '2008-09-01 12:35:45', $m1);\nprint_r( $m1 );\npreg_match('/\\d{4}-\\d{2}-\\d{2} \\d{1,2}:\\d{2}:\\d{2}/', '2008-09-01 12:35:45', $m2);\nprint_r( $m2 );\npreg_match('/^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/', '2008-09-01 12:35:45', $m3);\nprint_r( $m3 );\n Array ( [0] => 2008-09-01 12:35:45 )\nArray ( [0] => 2008-09-01 12:35:45 )\nArray ( [0] => 2008-09-01 12:35:45 ) \n"
},
{
"answer_id": 11794812,
"author": "Javad Yousefi",
"author_id": 616493,
"author_profile": "https://Stackoverflow.com/users/616493",
"pm_score": 2,
"selected": false,
"text": "^([2][0]\\d{2}\\/([0]\\d|[1][0-2])\\/([0-2]\\d|[3][0-1]))$|^([2][0]\\d{2}\\/([0]\\d|[1][0-2])\\/([0-2]\\d|[3][0-1])\\s([0-1]\\d|[2][0-3])\\:[0-5]\\d\\:[0-5]\\d)$\n"
},
{
"answer_id": 22798655,
"author": "Philip",
"author_id": 866466,
"author_profile": "https://Stackoverflow.com/users/866466",
"pm_score": 3,
"selected": false,
"text": "$date = \"2014-04-01 12:00:00\";\n\npreg_match('/(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})/',$date, $matches);\n\nprint_r($matches);\n Array ( \n [0] => 2014-04-01 12:00:00 \n [1] => 2014 \n [2] => 04 \n [3] => 01 \n [4] => 12 \n [5] => 00 \n [6] => 00\n)\n"
},
{
"answer_id": 24689706,
"author": "Duc Tran",
"author_id": 617146,
"author_profile": "https://Stackoverflow.com/users/617146",
"pm_score": -1,
"selected": false,
"text": "^(?=\\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\\x20|$))|(?:2[0-8]|1\\d|0?[1-9]))([-./])(?:1[012]|0?[1-9])\\1(?:1[6-9]|[2-9]\\d)?\\d\\d(?:(?=\\x20\\d)\\x20|$))(|([01]\\d|2[0-3])(:[0-5]\\d){1,2})?$\n"
},
{
"answer_id": 32867745,
"author": "Tornike",
"author_id": 413026,
"author_profile": "https://Stackoverflow.com/users/413026",
"pm_score": 0,
"selected": false,
"text": "/^(2[0-9]{3})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]) (0[0-9]|1[0-9]|2[0123])\\:([012345][0-9])\\:([012345][0-9])$/u\n"
},
{
"answer_id": 40124570,
"author": "Yeongjun Kim",
"author_id": 3793078,
"author_profile": "https://Stackoverflow.com/users/3793078",
"pm_score": -1,
"selected": false,
"text": "[12]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01]) ([01][0-9]|2[0-3]):[0-5]\\d\n"
},
{
"answer_id": 40842114,
"author": "themepark",
"author_id": 7086012,
"author_profile": "https://Stackoverflow.com/users/7086012",
"pm_score": 0,
"selected": false,
"text": "^(?=\\d)(?:(?:1[6-9]|[2-9]\\d)?\\d\\d([-.\\/])(?:1[012]|0?[1-9])\\1(?:31(?<!.(?:0[2469]|11))|(?:30|29)(?<!.02)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\\x20|$))|(?:2[0-8]|1\\d|0?[1-9]))(?:(?=\\x20\\d)\\x20|$))?(((0?[1-9]|1[012])(:[0-5]\\d){0,2}(\\x20[AP]M))|([01]\\d|2[0-3])(:[0-5]\\d){1,2})?$\n"
},
{
"answer_id": 61888323,
"author": "Milkncookiez",
"author_id": 1430394,
"author_profile": "https://Stackoverflow.com/users/1430394",
"pm_score": 1,
"selected": false,
"text": "(\\d{4})-(\\d{2})-(\\d{2})( (\\d{2}):(\\d{2}):(\\d{2}))?\n 2008-09-01 12:35:42 2008-09-01"
},
{
"answer_id": 73302581,
"author": "Seongjoo Park",
"author_id": 11589521,
"author_profile": "https://Stackoverflow.com/users/11589521",
"pm_score": 1,
"selected": false,
"text": "^(\\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$\n"
},
{
"answer_id": 74500646,
"author": "ali t",
"author_id": 6028779,
"author_profile": "https://Stackoverflow.com/users/6028779",
"pm_score": 0,
"selected": false,
"text": "[1-9][0-9][0-9][0-9]-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4013/"
] |
37,743 |
<p>I'd like to find the different ways to solve a real life problem I had: imagine to have a contest, or a game, during which the users collect points. You have to build a query to show the list of users with the best "n" scores. </p>
<p>I'm making an example to clarify. Let's say that this is the Users table, with the points earned:</p>
<pre><code>UserId - Points
1 - 100
2 - 75
3 - 50
4 - 50
5 - 50
6 - 25
</code></pre>
<p>If I want the top 3 scores, the result will be:</p>
<pre><code>UserId - Points
1 - 100
2 - 75
3 - 50
4 - 50
5 - 50
</code></pre>
<p>This can be realized in a view or a stored procedure, as you want. My target db is Sql Server. Actually I solved this, but I think there are different way to obtain the result... faster or more efficent than mine.</p>
|
[
{
"answer_id": 37750,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 5,
"selected": true,
"text": "select * from users where points in\n(select distinct top 3 points from users order by points desc)\n"
},
{
"answer_id": 37753,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 0,
"selected": false,
"text": "select userid, points \n from scores \n where points in (select top 3 points \n from scores \n order by points desc) \n order by points desc\n"
},
{
"answer_id": 37760,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 0,
"selected": false,
"text": "select userid, points from users\nwhere points in (select distinct top N points from users order by points desc) \n declare @SQL nvarchar(2000)\nset @SQL = \"select userID, points from users \"\nset @SQL = @SQL + \" where points in (select distinct top \" + @N\nset @SQL = @SQL + \" points from users order by points desc)\"\n\nexecute @SQL\n SELECT UserID, Points\nFROM (SELECT ROW_NUMBER() OVER (ORDER BY points DESC)\n AS Row, UserID, Points FROM Users)\n AS usersWithPoints\nWHERE Row between 0 and @N\n"
},
{
"answer_id": 37765,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "select top N points from users order by points desc\n"
},
{
"answer_id": 37781,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 1,
"selected": false,
"text": "select top 3 with ties points \nfrom scores\norder by points desc\n select top (@n) with ties points \nfrom scores\norder by points desc\n"
},
{
"answer_id": 37813,
"author": "crucible",
"author_id": 3717,
"author_profile": "https://Stackoverflow.com/users/3717",
"pm_score": 2,
"selected": false,
"text": "with scores as (\n select 1 userid, 100 points\n union select 2, 75\n union select 3, 50\n union select 4, 50\n union select 5, 50\n union select 6, 25\n),\nresults as (\n select userid, points, RANK() over (order by points desc) as ranking \n from scores\n)\nselect userid, points, ranking\nfrom results\nwhere ranking <= 3\n"
},
{
"answer_id": 89325,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "SELECT \n userid, points \nFROM users u\nINNER JOIN \n(\n SELECT DISTINCT TOP N \n points \n FROM users \n ORDER BY points DESC\n) AS p ON p.points = u.points\n"
},
{
"answer_id": 100867,
"author": "kedar kamthe",
"author_id": 18709,
"author_profile": "https://Stackoverflow.com/users/18709",
"pm_score": 0,
"selected": false,
"text": "select top N points from users order by points desc\n"
},
{
"answer_id": 19721941,
"author": "Krishna Gupta",
"author_id": 2443267,
"author_profile": "https://Stackoverflow.com/users/2443267",
"pm_score": 0,
"selected": false,
"text": "select * from users order by points desc limit 0,5"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1178/"
] |
37,759 |
<p>I have the following code in a web.config file of the default IIS site.</p>
<pre><code><httpModules>
<add type="MDL.BexWebControls.Charts.ChartStreamHandler,Charts" name="ChartStreamHandler"/>
</httpModules>
</code></pre>
<p>Then when I setup and browse to a virtual directory I get this error</p>
<p>Could not load file or assembly 'Charts' or one of its dependencies. The system cannot find the file specified.</p>
<p>The virtual directory is inheriting the modules from the default web.config.</p>
<p>How do you stop this inheritance?</p>
|
[
{
"answer_id": 37762,
"author": "John Owen",
"author_id": 2471,
"author_profile": "https://Stackoverflow.com/users/2471",
"pm_score": 5,
"selected": true,
"text": "<location path=\".\" inheritInChildApplications=\"false\">\n <system.web>\n <httpModules>\n <add type=\"MDL.BexWebControls.Charts.ChartStreamHandler,Charts\" name=\"ChartStreamHandler\"/>\n </httpModules>\n </system.web>\n</location>\n <remove />"
},
{
"answer_id": 37763,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 2,
"selected": false,
"text": "<httpModules>\n <remove name=\"ChartStreamHandler\"/>\n</httpModules>\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2471/"
] |
37,791 |
<p>At the moment my code (PHP) has too many SQL queries in it. eg...</p>
<pre><code>// not a real example, but you get the idea...
$results = $db->GetResults("SELECT * FROM sometable WHERE iUser=$userid");
if ($results) {
// Do something
}
</code></pre>
<p>I am looking into using stored procedures to reduce this and make things a little more robust, but I have some concerns..</p>
<p>I have hundreds of different queries in use around the web site, and many of them are quite similar. How should I manage all these queries when they are removed from their context (the code that uses the results) and placed in a stored procedure on the database?</p>
|
[
{
"answer_id": 38053,
"author": "Gary Richardson",
"author_id": 2506,
"author_profile": "https://Stackoverflow.com/users/2506",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM sometable WHERE iUser = ?\n"
},
{
"answer_id": 38186,
"author": "Slacker",
"author_id": 4053,
"author_profile": "https://Stackoverflow.com/users/4053",
"pm_score": 1,
"selected": false,
"text": "function MakeTableTypes($TableName, $FieldNames)\n{\n $Types = array();\n\n foreach ($FieldNames as $FieldName => $FieldValue)\n {\n $Types[] = $this->Tables[$TableName]['schema'][$FieldName]['type'];\n }\n\n return $Types;\n}\n function UpdateArticle($Article)\n{\n $Types = $this->MakeTableTypes($table_name, $Article);\n\n $res = $this->MDB2->extended->autoExecute($table_name,\n $Article,\n MDB2_AUTOQUERY_UPDATE,\n 'id = '.$this->MDB2->quote($Article['id'], 'integer'),\n $Types);\n}\n"
},
{
"answer_id": 87738,
"author": "Willem",
"author_id": 15447,
"author_profile": "https://Stackoverflow.com/users/15447",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM USERS;\n"
},
{
"answer_id": 88500,
"author": "lewis",
"author_id": 14442,
"author_profile": "https://Stackoverflow.com/users/14442",
"pm_score": 0,
"selected": false,
"text": "function getFromDB($table, $wherefield=null, $whereval=null, $orderby=null) {\n if($wherefield != null) { \n $q = \"SELECT * FROM $table WHERE $wherefield = '$whereval'\"; \n } else { \n $q = \"SELECT * FROM $table\";\n }\n if($orderby != null) { \n $q .= \" ORDER BY \".$orderby; \n }\n\n $result = mysql_query($q)) or die(\"ERROR: \".mysql_error());\n while($row = mysql_fetch_assoc($result)) {\n $records[] = $row;\n }\n return $records;\n}\n $blogposts = getFromDB('myblog', 'author', 'Lewis', 'date DESC');\n echo $blogposts[0]['title'];\n"
},
{
"answer_id": 89454,
"author": "Shabbyrobe",
"author_id": 15004,
"author_profile": "https://Stackoverflow.com/users/15004",
"pm_score": 6,
"selected": true,
"text": "// UserManager.php:\n\nclass UserManager\n{\n function getUsers()\n {\n $pdo = new PDO(...);\n $stmt = $pdo->prepare('\n SELECT u.userId as id,\n u.userName,\n g.groupId,\n g.groupName\n FROM user u\n INNER JOIN group g\n ON u.groupId = g.groupId\n ORDER BY u.userName, g.groupName\n ');\n // iterate over result and prepare return value\n }\n\n function getUser($id) {\n // db code here\n }\n}\n\n// index.php:\nrequire_once(\"UserManager.php\");\n$um = new UserManager;\n$users = $um->getUsers();\nforeach ($users as $user) echo $user['name'];\n // optional\n$attrs = array(PDO::ATTR_PERSISTENT => true);\n\n// create the PDO object\n$pdo = new PDO(\"mysql:host=localhost;dbname=test\", \"user\", \"pass\", $attrs);\n\n// also optional, but it makes PDO raise exceptions instead of \n// PHP errors which are far more useful for debugging\n$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n\n$stmt = $pdo->prepare('INSERT INTO venue(venueName, regionId) VALUES(:venueName, :regionId)');\n$stmt->bindValue(\":venueName\", \"test\");\n$stmt->bindValue(\":regionId\", 1);\n\n$stmt->execute();\n\n$lastInsertId = $pdo->lastInsertId();\nvar_dump($lastInsertId);\n string(1) \"1\" PDO->lastInsertId() bool(true) // regular equality test\nvar_dump($lastInsertId == 1); \n var_dump(is_int($lastInsertId));\nvar_dump($lastInsertId === 1);\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4012/"
] |
37,799 |
<p>Is it possible to use gcov for coverage testing of multi-threaded applications? </p>
<p>I've set some trivial tests of our code-base up, but it would be nice to have some idea of the coverage we're achieving. If gcov isn't appropriate can anyone recommend an alternative tool (possible oprofile), ideally with some good documentation on getting started.</p>
|
[
{
"answer_id": 38317,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 4,
"selected": true,
"text": "-fprofile-arcs -ftest-coverage"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2246/"
] |
37,805 |
<p>I have a <code>List<int></code> and a <code>List<customObject></code>. The customObject class has an ID property. How can I get a <code>List<customObject></code> containing only the objects where the ID property is in the <code>List<int></code> using LINQ?</p>
<p><strong>Edit</strong>: I accepted Konrads answer because it is easier/more intuitive to read.</p>
|
[
{
"answer_id": 37807,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 3,
"selected": false,
"text": "var matches = from o in objList \n join i in intList on o.ID equals i\n select o;\n"
},
{
"answer_id": 37810,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": true,
"text": "var result = from o in objList where intList.Contains(o.ID) select o\n"
},
{
"answer_id": 158915,
"author": "Lucas",
"author_id": 24231,
"author_profile": "https://Stackoverflow.com/users/24231",
"pm_score": 2,
"selected": false,
"text": "var matches = from o in customObjectList\n from i in intList\n where o.ID == i\n select o;\n"
},
{
"answer_id": 1491976,
"author": "Henryk",
"author_id": 18659,
"author_profile": "https://Stackoverflow.com/users/18659",
"pm_score": 3,
"selected": false,
"text": "objList.RemoveAll(x => !intList.Contains(x.id));\n"
},
{
"answer_id": 6962016,
"author": "Diana ",
"author_id": 881256,
"author_profile": "https://Stackoverflow.com/users/881256",
"pm_score": 0,
"selected": false,
"text": "Some part of your SQL statement is nested too deeply. Rewrite the query or break it up into smaller queries."
},
{
"answer_id": 19765766,
"author": "Robin Winslow",
"author_id": 613540,
"author_profile": "https://Stackoverflow.com/users/613540",
"pm_score": 4,
"selected": false,
"text": "using System.Linq;\n\nobjList.Where(x => intList.Contains(x.id));\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2257/"
] |
37,809 |
<p>How can I go about generating a Friendly URL in C#? Currently I simple replace spaces with an underscore, but how would I go about generating URL's like Stack Overflow?</p>
<p>For example how can I convert:</p>
<blockquote>
<p>How do I generate a Friendly URL in C#?</p>
</blockquote>
<p>Into</p>
<blockquote>
<p>how-do-i-generate-a-friendly-url-in-C</p>
</blockquote>
|
[
{
"answer_id": 37817,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 4,
"selected": false,
"text": "if (String.IsNullOrEmpty(title)) return \"\";\n\n// remove entities\ntitle = Regex.Replace(title, @\"&\\w+;\", \"\");\n// remove anything that is not letters, numbers, dash, or space\ntitle = Regex.Replace(title, @\"[^A-Za-z0-9\\-\\s]\", \"\");\n// remove any leading or trailing spaces left over\ntitle = title.Trim();\n// replace spaces with single dash\ntitle = Regex.Replace(title, @\"\\s+\", \"-\");\n// if we end up with multiple dashes, collapse to single dash \ntitle = Regex.Replace(title, @\"\\-{2,}\", \"-\");\n// make it all lower case\ntitle = title.ToLower();\n// if it's too long, clip it\nif (title.Length > 80)\n title = title.Substring(0, 79);\n// remove trailing dash, if there is one\nif (title.EndsWith(\"-\"))\n title = title.Substring(0, title.Length - 1);\nreturn title;\n"
},
{
"answer_id": 37818,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 3,
"selected": false,
"text": "new Regex(\"[^a-zA-Z-_]\").Replace(s, \"-\")\n"
},
{
"answer_id": 37880,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": true,
"text": "if (String.IsNullOrEmpty(title)) return \"\";\n // remove any leading or trailing spaces left over\n… muuuch later:\n// remove trailing dash, if there is one\n // replace spaces with single dash\ntitle = Regex.Replace(title, @\"\\s+\", \"-\");\n// if we end up with multiple dashes, collapse to single dash \ntitle = Regex.Replace(title, @\"\\-{2,}\", \"-\");\n // make it all lower case\ntitle = title.ToLower();\n// remove entities\ntitle = Regex.Replace(title, @\"&\\w+;\", \"\");\n// remove anything that is not letters, numbers, dash, or space\ntitle = Regex.Replace(title, @\"[^a-z0-9\\-\\s]\", \"\");\n// replace spaces\ntitle = title.Replace(' ', '-');\n// collapse dashes\ntitle = Regex.Replace(title, @\"-{2,}\", \"-\");\n// trim excessive dashes at the beginning\ntitle = title.TrimStart(new [] {'-'});\n// if it's too long, clip it\nif (title.Length > 80)\n title = title.Substring(0, 79);\n// remove trailing dashes\ntitle = title.TrimEnd(new [] {'-'});\nreturn title;\n"
},
{
"answer_id": 58835281,
"author": "Arslan Ali",
"author_id": 3492230,
"author_profile": "https://Stackoverflow.com/users/3492230",
"pm_score": 0,
"selected": false,
"text": " public static string GenerateUrl(string Url)\n {\n string UrlPeplaceSpecialWords = Regex.Replace(Url, @\""|['\"\",&?%\\.!()@$^_+=*:#/\\\\-]\", \" \").Trim();\n string RemoveMutipleSpaces = Regex.Replace(UrlPeplaceSpecialWords, @\"\\s+\", \" \");\n string ReplaceDashes = RemoveMutipleSpaces.Replace(\" \", \"-\");\n string DuplicateDashesRemove = ReplaceDashes.Replace(\"--\", \"-\");\n return DuplicateDashesRemove.ToLower();\n }\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] |
37,822 |
<p>I have read that the iPhone SDK (part of Xcode 3) is restricted to Mac's with the intel chipset. Does this restriction apply to only the simulator part of the SDK or the complete shebang?</p>
<p>I have a Powerbook G4 running Leopard and would very much like to do dev on it rather than fork out for a new machine.</p>
<p>It is also worth clarifying that I am interested in development for personal reasons and therefore accept that I would need a certified platform to create a submission for the App Store. </p>
|
[
{
"answer_id": 38577,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 1,
"selected": false,
"text": "xcodebuild"
},
{
"answer_id": 45592,
"author": "Clokey",
"author_id": 2438,
"author_profile": "https://Stackoverflow.com/users/2438",
"pm_score": 3,
"selected": false,
"text": "/Platforms /Developer/Platforms iPhone Simulator Architectures.xcspec /Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Specifications Name = \"Standard (iPhone Simulator: i386 ppc)\"; RealArchitectures = ( i386, ppc );"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2438/"
] |
37,830 |
<p>I want to show a chromeless modal window with a close button in the upper right corner.
Is this possible?</p>
|
[
{
"answer_id": 37878,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": true,
"text": "<Window WindowStyle=\"None\">\n"
},
{
"answer_id": 37883,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<Window x:Class=\"WpfApplication1.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"Window1\" Height=\"300\" Width=\"300\" WindowStyle=\"None\" ResizeMode=\"NoResize\">\n <Button HorizontalAlignment=\"Right\" Name=\"button1\" VerticalAlignment=\"Top\" >Close</Button>\n</Window>\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2374/"
] |
37,912 |
<p>How do you use the the org.springframework.ws.transport.jms.WebServiceMessageDrivenBean class from the Java Spring Framework - Spring-WS project?</p>
<p>There is very little documentation or examples available on the web.</p>
|
[
{
"answer_id": 92867,
"author": "Keith Lyall",
"author_id": 17719,
"author_profile": "https://Stackoverflow.com/users/17719",
"pm_score": 0,
"selected": false,
"text": "public class HelloWorldMessageDrivenBean extends WebServiceMessageDrivenBean {\n private static final long serialVersionUID = -2905491432314736668L;\n}\n <env-entry> \n <description></description> \n <env-entry-name>ejb/BeanFactoryPath</env-entry-name> \n <env-entry-type>java.lang.String</env-entry-type> \n <env-entry-value> \n application-context.xml \n </env-entry-value> \n</env-entry>\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
37,920 |
<p>I have developed a COM component (dll) that implements an Edit() method displaying a WTL modal dialog.</p>
<p>The complete interface to this COM component corresponds to a software standard used in the chemical process industry (CAPE-OPEN) and as a result this COM component is supposed to be usable by a range of 3rd party executables that are out of my control.</p>
<p>My component works as expected in many of these EXEs, but for one in particular the Edit() method just hangs without the dialog appearing.</p>
<p>However, if I make a call to <code>::MessageBox()</code> immediately before <code>DoModal()</code> the dialog displays and behaves correctly after first showing the MessageBox.</p>
<p>I have a suspicion that the problem may be something to do with this particular EXE running as a 'hidden window application'.</p>
<p>I have tried using both NULL and the return value from <code>::GetConsoleWindow()</code> as the dialog's parent, neither have worked.</p>
<p>The dialog itself is an ATL/WTL CPropertySheetImpl.</p>
<p>The parent application (EXE) in question is out of my control as it is developed by a (mildly hostile) 3rd party.</p>
<p>I do know that I can successfully call <code>::MessageBox()</code> or display the standard Windows File Dialog from my COM component, and that after doing so I am then able to display my custom dialog. I'm just unable to display my custom dialog without first displaying a 'standard' dialog.</p>
<p>Can anyone suggest how I might get it to display the dialog without first showing an unnecessary MessageBox? I know it is possible because I've seen this EXE display the dialogs from other COM components corresponding to the same interface.</p>
|
[
{
"answer_id": 37943,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 1,
"selected": false,
"text": "MyDialog dialog(pParent);\ndialog.DoModal();\n"
},
{
"answer_id": 37954,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 1,
"selected": false,
"text": " while(GetMessage(&msg, NULL, 0, 0))\n {\n if(!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) \n {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n }\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3229/"
] |
37,929 |
<p>I am reviewing a big java application to see if there are any performance bottlenecks. The real problem is that I cannot pinpoint the performance issues to any single module. The whole application is slow as such.</p>
<p>Is there some tool/technique I can use to help me out in this?</p>
|
[
{
"answer_id": 39056,
"author": "wvdschel",
"author_id": 2018,
"author_profile": "https://Stackoverflow.com/users/2018",
"pm_score": 3,
"selected": false,
"text": "Java -Xprof"
},
{
"answer_id": 15366173,
"author": "Riking",
"author_id": 1210278,
"author_profile": "https://Stackoverflow.com/users/1210278",
"pm_score": 0,
"selected": false,
"text": "jstack"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] |
37,931 |
<p>The <a href="http://msdn.microsoft.com/en-us/library/y23b5415.aspx" rel="nofollow noreferrer">official guidelines</a> suggest that there can be very few practical uses for these. Does anyone have examples of where they've put them to good use?</p>
|
[
{
"answer_id": 37938,
"author": "Chris James",
"author_id": 3193,
"author_profile": "https://Stackoverflow.com/users/3193",
"pm_score": 0,
"selected": false,
"text": "enum MyWeirdType {\nTypeA, TypeB, TypeC};\n\nswitch(value){\ncase MyWeirdType.TypeA:\n...\n"
},
{
"answer_id": 37978,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 0,
"selected": false,
"text": "using System;\n\nnamespace StructClassTest {\n\n struct A {\n public string Foobar { get; set; }\n }\n\n class B {\n public string Foobar { get; set; }\n }\n\n class Program {\n static void Main() {\n A a = new A();\n a.Foobar = \"hi\";\n B b = new B();\n b.Foobar = \"hi\";\n\n StructTest(a);\n ClassTest(b);\n\n Console.WriteLine(\"a.Foobar={0}, b.Foobar={1}\", a.Foobar, b.Foobar);\n\n Console.ReadKey(true);\n }\n\n static void StructTest(A a) {\n a.Foobar = \"hello\";\n }\n\n static void ClassTest(B b) {\n b.Foobar = \"hello\";\n }\n }\n}\n a.Foobar=hi, b.Foobar=hello\n"
},
{
"answer_id": 37981,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "int Complex BigInteger DateTime Point"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3974/"
] |
37,932 |
<p>I'd like to do the following and can't find an elegant way:</p>
<ol>
<li>Read an XML template into a <code>System.Xml.XmlDocument</code> </li>
<li>Populate it with data from my UI </li>
<li>Transform it with an <code>XSLT</code> I've written </li>
<li>Apply a <code>CSS</code> Stylesheet </li>
<li>Render it to a <code>WebBrowser</code> control </li>
</ol>
<p>I'm currently reading it from a file on disk, populating it, then saving it back out to disk after populating it. I reference the <code>XSLT</code> in the template, and the <code>CSS</code> in the <code>XSLT</code> and then use the <code>WebBrowser.Navigate([filename])</code> method to display the XML file.</p>
<p>Obviously, when I come to deploy this app, it'll break horribly as the file won't exist on disk, and I won't be able to reference the <code>XSLT</code> and <code>CSS</code> files in the <code>XML</code> file as they'll be resources. I'm planning to include the template as a resource, but can't find a neat way to proceed from there.</p>
<p>Any help much appreciated</p>
|
[
{
"answer_id": 165236,
"author": "rasx",
"author_id": 22944,
"author_profile": "https://Stackoverflow.com/users/22944",
"pm_score": 0,
"selected": false,
"text": "void WireUpBrowserEvents()\n{\n\n HtmlElement table = this._browser.Document.GetElementById( \"UnitFormsTable\" );\n if ( table != null )\n {\n HtmlElementCollection thead = table.GetElementsByTagName( \"thead\" );\n if ( ( thead != null ) && ( thead.Count == 1 ) )\n {\n HtmlElementCollection links = thead[0].GetElementsByTagName( \"a\" );\n if ( ( links != null ) && ( links.Count > 0 ) )\n {\n foreach ( HtmlElement a in links )\n {\n a.Click += new HtmlElementEventHandler( XslSort_Click );\n }\n }\n }\n }\n}\n\nvoid XslSort_Click( object sender, HtmlElementEventArgs e )\n{\n e.ReturnValue = false;\n\n if ( this._xslSortWorker.IsBusy ) return;\n\n if ( sender is HtmlElement )\n {\n HtmlElement a = sender as HtmlElement;\n this._browser.Hide();\n this._browserMessage.Visible = true;\n this._browserMessage.Refresh();\n this._xslSortWorker.RunWorkerAsync( a.Id );\n }\n}\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4019/"
] |
37,956 |
<p>I would like to open a small video file and map every frames in memory (to apply some custom filter). I don't want to handle the video codec, I would rather let the library handle that for me.</p>
<p>I've tried to use Direct Show with the SampleGrabber filter (using this sample <a href="http://msdn.microsoft.com/en-us/library/ms787867(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms787867(VS.85).aspx</a>), but I only managed to grab some frames (not every frames!). I'm quite new in video software programming, maybe I'm not using the best library, or I'm doing it wrong. </p>
<p>I've pasted a part of my code (mainly a modified copy/paste from the msdn example), unfortunately it doesn't grabb the 25 first frames as expected...</p>
<pre><code>[...]
hr = pGrabber->SetOneShot(TRUE);
hr = pGrabber->SetBufferSamples(TRUE);
pControl->Run(); // Run the graph.
pEvent->WaitForCompletion(INFINITE, &evCode); // Wait till it's done.
// Find the required buffer size.
long cbBuffer = 0;
hr = pGrabber->GetCurrentBuffer(&cbBuffer, NULL);
for( int i = 0 ; i < 25 ; ++i )
{
pControl->Run(); // Run the graph.
pEvent->WaitForCompletion(INFINITE, &evCode); // Wait till it's done.
char *pBuffer = new char[cbBuffer];
hr = pGrabber->GetCurrentBuffer(&cbBuffer, (long*)pBuffer);
AM_MEDIA_TYPE mt;
hr = pGrabber->GetConnectedMediaType(&mt);
VIDEOINFOHEADER *pVih;
pVih = (VIDEOINFOHEADER*)mt.pbFormat;
[...]
}
[...]
</code></pre>
<p>Is there somebody, with video software experience, who can advise me about code or other simpler library?</p>
<p>Thanks</p>
<p>Edit:
Msdn links seems not to work (<a href="http://stackoverflow.uservoice.com/pages/general/suggestions/19963" rel="noreferrer">see the bug</a>)</p>
|
[
{
"answer_id": 21258871,
"author": "Bob",
"author_id": 3154041,
"author_profile": "https://Stackoverflow.com/users/3154041",
"pm_score": 2,
"selected": false,
"text": "ThreadLibManager()\n{\n List<MyThreads> listOfActiveThreads;\n public AddThread(MyThreads);\n}\nYour thread class is something like:-\nclass MyThread\n{\n public Thread threadForThisInstance { get; set; }\n public MyFFMpegTools mpegTools { get; set; }\n}\nMyFFMpegTools performs many different video operations, so you want your own event \nargs to tell your parent code precisely what type of operation has just raised and \nevent.\nenum MyFmpegArgs\n{\npublic int thisThreadID { get; set; } //Set as a new MyThread is added to the List<>\npublic MyFfmpegType operationType {get; set;}\n//output paths etc that the parent handler will need to find output files\n}\nenum MyFfmpegType\n{\n FF_CONVERTFILE = 0, FF_CREATETHUMBNAIL, FF_EXTRACTFRAMES ...\n}\n public string GetVideoInfo(FileInfo fi)\n {\n outputBuilder.Clear();\n string strCommand = string.Concat(\" -i \\\"\", fi.FullName, \"\\\"\");\n string ffPath = \n System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + \"\\\\ffmpeg.exe\";\n string oStr = \"\";\n\n try\n {\n Process build = new Process();\n //build.StartInfo.WorkingDirectory = @\"dir\";\n build.StartInfo.Arguments = strCommand;\n build.StartInfo.FileName = ffPath;\n\n build.StartInfo.UseShellExecute = false;\n build.StartInfo.RedirectStandardOutput = true;\n build.StartInfo.RedirectStandardError = true;\n build.StartInfo.CreateNoWindow = true;\n build.ErrorDataReceived += build_ErrorDataReceived;\n build.OutputDataReceived += build_ErrorDataReceived;\n build.EnableRaisingEvents = true;\n build.Start();\n build.BeginOutputReadLine();\n build.BeginErrorReadLine();\n build.WaitForExit();\n\n\n string findThis = \"start\";\n int offset = 0;\n foreach (string str in outputBuilder)\n {\n if (str.Contains(\"Duration\"))\n {\n offset = str.IndexOf(findThis);\n oStr = str.Substring(0, offset);\n }\n }\n }\n catch\n {\n oStr = \"Error collecting file information\";\n }\n\n return oStr;\n }\n private void build_ErrorDataReceived(object sender, DataReceivedEventArgs e)\n {\n string strMessage = e.Data;\n if (outputBuilder != null && strMessage != null)\n {\n outputBuilder.Add(string.Concat(strMessage, \"\\n\"));\n }\n } \n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1578/"
] |
37,969 |
<p><strong>Can anyone recommend a tool for quickly posting test messages onto a JMS queue?</strong></p>
<p><strong>Description</strong>:</p>
<ol>
<li>The tool should allow the user to enter some data, perhaps an XML
payload, and then submit it to a queue.</li>
<li>I should be able to test consumer without producer.</li>
</ol>
|
[
{
"answer_id": 73737,
"author": "James Strachan",
"author_id": 2068211,
"author_profile": "https://Stackoverflow.com/users/2068211",
"pm_score": 2,
"selected": false,
"text": "from(\"file://someDirectory\").\n to(\"activemq:MyQueue\");\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2454/"
] |
37,996 |
<p>We are using SourceForge Enterprise Edition 4.4 in one of our project.</p>
<p>My question is, in CollabNet SFEE (SourceForge Enterprise Edition 4.4), how will we get attachments associated with an Artifacts Using SFEE SOAP API?</p>
<p>We have made our own .net 2.0 client. We are not using .net SDK provided by Collabnet,</p>
|
[
{
"answer_id": 187019,
"author": "binco",
"author_id": 19671,
"author_profile": "https://Stackoverflow.com/users/19671",
"pm_score": 0,
"selected": false,
"text": "/usr/local/sourceforge/sourceforge_home/integration/post-commit.py\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/37996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
] |
38,005 |
<p>Now that <code>LINQ</code> to <code>SQL</code> is a little more mature, I'd like to know of any techniques people are using to create an <strong>n-tiered solution</strong> using the technology, because it does not seem that obvious to me.</p>
|
[
{
"answer_id": 38330,
"author": "Giovanni Galbo",
"author_id": 4050,
"author_profile": "https://Stackoverflow.com/users/4050",
"pm_score": 0,
"selected": false,
"text": "var emps = from e in Employees\n join m in Employees\n on e.ManagerEmpID equals m.EmpID\n select new\n { e,\n m.FullName\n };\n"
},
{
"answer_id": 38551,
"author": "liammclennan",
"author_id": 2785,
"author_profile": "https://Stackoverflow.com/users/2785",
"pm_score": 0,
"selected": false,
"text": "var emps = from e in Employees\n join m in Employees\n on e.ManagerEmpID equals m.EmpID\n select new Employee\n { e,\n m.FullName\n };\n"
},
{
"answer_id": 39204,
"author": "Giovanni Galbo",
"author_id": 4050,
"author_profile": "https://Stackoverflow.com/users/4050",
"pm_score": 0,
"selected": false,
"text": "public class EmployeesDAL\n{\n public IEnumerable LoadEmployeesAndManagers()\n {\n MyCompanyContext context = new MyCompanyContext();\n\n var emps = from e in context.Employees\n join m in context.Employees\n on e.ManagerEmpID equals m.EmpID\n select new\n { e,\n m.FullName\n };\n\n return emps;\n }\n\n}\n EmployeesDAL dal = new EmployeesDAL;\nvar emps = dal.LoadEmployeesAndManagers();\n txtEmployeeName.Text = emps[0].FullName\n"
},
{
"answer_id": 39251,
"author": "Giovanni Galbo",
"author_id": 4050,
"author_profile": "https://Stackoverflow.com/users/4050",
"pm_score": 1,
"selected": false,
"text": "public class EmployeesDAL\n{\n ...\n SaveEmployee(Employee employee)\n {\n //data formatting\n employee.FirstName = employee.FirstName.Trim();\n employee.LastName = employee.LastName.Trim();\n\n //business rules\n if(employee.FirstName.Length > 0 && employee.LastName.Length > 0)\n {\n MyCompanyContext context = new MyCompanyContext();\n\n //insert\n if(employee.empid == 0)\n context.Employees.InsertOnSubmit(employee);\n else\n {\n //update goes here\n }\n\n context.SubmitChanges();\n\n\n }\n else \n throw new BusinessRuleException(\"Employees must have first and last names\");\n }\n }\n public ISingleResult<GetEmployeesAndManagersResult> LoadEmployeesAndManagers()\n {\n MyCompanyContext context = new MyCompanyContext();\n\n var emps = context.GetEmployeesAndManagers();\n\n return emps;\n }\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4050/"
] |
38,010 |
<p>When performing string concatentation of an existing string in the intern pool, is a new string entered into the intern pool or is a reference returned to the existing string in the intern pool? According to this article, String.Concat and StringBuilder will insert new string instances into the intern pool? </p>
<p><a href="http://community.bartdesmet.net/blogs/bart/archive/2006/09/27/4472.aspx" rel="nofollow noreferrer">http://community.bartdesmet.net/blogs/bart/archive/2006/09/27/4472.aspx</a></p>
<p>Can anyone explain how concatenation works with the intern pool?</p>
|
[
{
"answer_id": 38040,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "String.IsInterned null"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2993/"
] |
38,014 |
<p>I am facing problem with an Oracle Query in a .net 2.0 based windows application. I am using <code>System.Data.OracleClient</code> to connect to oracle database. Name of database is <code>myDB</code>. Below the the connection string I am using:</p>
<pre><code>Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)
(HOST = 172.16.0.24)(PORT = 1522)))(CONNECT_DATA =(SERVICE_NAME = ORCL)));
User ID=myDB;Password=myDB;Unicode=True
</code></pre>
<p>If I run the below query then it will given me wrong result (here wrong result means incorrect data. The data doesn't belongs to myDB):</p>
<pre><code>SELECT ID, NAME
FROM MyTempTable
WHERE ID IN (10780, 10760, 11890)
</code></pre>
<p>But if I append the database name along with it the it is giving correct result:</p>
<pre><code>SELECT ID, NAME
FROM "myDB".MyTempTable
WHERE ID IN (10780, 10760, 11890)
</code></pre>
<p>My limitation is that I cannot append the database name as this is a generic application and can run with any database on run time. Please help.</p>
|
[
{
"answer_id": 38022,
"author": "skolima",
"author_id": 3205,
"author_profile": "https://Stackoverflow.com/users/3205",
"pm_score": 0,
"selected": false,
"text": "CONNECT_DATA=(SID=myDB)(SERVICE_NAME=ORCL)\n"
},
{
"answer_id": 6239631,
"author": "Gary Myers",
"author_id": 25714,
"author_profile": "https://Stackoverflow.com/users/25714",
"pm_score": 2,
"selected": false,
"text": "ALTER SESSION SET CURRENT_SCHEMA=abc;\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
] |
38,021 |
<p>How can I find the origins of conflicting DNS records?</p>
|
[
{
"answer_id": 38025,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 1,
"selected": false,
"text": " NS51.DOMAINCONTROL.COM\n NS52.DOMAINCONTROL.COM\n"
},
{
"answer_id": 38028,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 10,
"selected": true,
"text": "command line> nslookup\n> set querytype=soa\n> stackoverflow.com\nServer: 217.30.180.230\nAddress: 217.30.180.230#53\n\nNon-authoritative answer:\nstackoverflow.com\n origin = ns51.domaincontrol.com # (\"primary name server\" on Windows)\n mail addr = dns.jomax.net # (\"responsible mail addr\" on Windows)\n serial = 2008041300\n refresh = 28800\n retry = 7200\n expire = 604800\n minimum = 86400\nAuthoritative answers can be found from:\nstackoverflow.com nameserver = ns52.domaincontrol.com.\nstackoverflow.com nameserver = ns51.domaincontrol.com.\n"
},
{
"answer_id": 38029,
"author": "David Precious",
"author_id": 4040,
"author_profile": "https://Stackoverflow.com/users/4040",
"pm_score": 4,
"selected": false,
"text": "[davidp@supernova:~]$ host -t ns stackoverflow.com\nstackoverflow.com name server ns51.domaincontrol.com.\nstackoverflow.com name server ns52.domaincontrol.com.\n"
},
{
"answer_id": 38034,
"author": "aryeh",
"author_id": 3288,
"author_profile": "https://Stackoverflow.com/users/3288",
"pm_score": 5,
"selected": false,
"text": "$ dig -t ns <domain name>\n"
},
{
"answer_id": 38038,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "whois dig host nslookup nslookup $ whois stackoverflow.com\n[...]\n Domain servers in listed order:\n NS51.DOMAINCONTROL.COM\n NS52.DOMAINCONTROL.COM\n dig dig ns stackoverflow.com\n"
},
{
"answer_id": 390986,
"author": "bortzmeyer",
"author_id": 15625,
"author_profile": "https://Stackoverflow.com/users/15625",
"pm_score": 8,
"selected": false,
"text": " % dig +short NS stackoverflow.com\n ns52.domaincontrol.com.\n ns51.domaincontrol.com.\n % dig +short SOA stackoverflow.com | cut -d' ' -f1\nns51.domaincontrol.com.\n check_soa % check_soa stackoverflow.com\nns51.domaincontrol.com has serial number 2008041300\nns52.domaincontrol.com has serial number 2008041300\n"
},
{
"answer_id": 39960663,
"author": "Alex",
"author_id": 1328737,
"author_profile": "https://Stackoverflow.com/users/1328737",
"pm_score": 4,
"selected": false,
"text": "dig SOA +trace stackoverflow.com\n"
},
{
"answer_id": 61221144,
"author": "dannyw",
"author_id": 3518106,
"author_profile": "https://Stackoverflow.com/users/3518106",
"pm_score": 2,
"selected": false,
"text": "analyticsdcs.ccs.mcafee.com. host -t NS analyticsdcs.ccs.mcafee.com. host -t SOA analyticsdcs.ccs.mcafee.com. dig +trace analyticsdcs.ccs.mcafee.com. | grep -w 'IN[[:space:]]*NS' | tail -1 host analyticsdcs.ccs.mcafee.com. gtm2.mcafee.com."
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/319/"
] |
38,027 |
<p>Both are mathematical values, however the float does have more precision. Is that the only reason for the error - the difference in precision? Or is there another potential (and more serious) problem?</p>
|
[
{
"answer_id": 43486,
"author": "smh",
"author_id": 1077,
"author_profile": "https://Stackoverflow.com/users/1077",
"pm_score": 1,
"selected": false,
"text": "short -> 15 bits\nfloat -> 23 bits\nlong -> 31 bits\ndouble -> 52 bits\n float short double long"
},
{
"answer_id": 181446,
"author": "Chris Arguin",
"author_id": 25704,
"author_profile": "https://Stackoverflow.com/users/25704",
"pm_score": 2,
"selected": false,
"text": "int double_equals(double a, double b, double epsilon)\n{\n return ( a > ( b - epsilon ) && a < ( b + epsilon ) );\n}\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
38,035 |
<p>I'm building a basic search functionality, using LIKE (I'd be using fulltext but can't at the moment) and I'm wondering if MySQL can, on searching for a keyword (e.g. WHERE field LIKE '%word%') return 20 words either side of the keyword, as well?</p>
|
[
{
"answer_id": 38188,
"author": "JimmyJ",
"author_id": 2083,
"author_profile": "https://Stackoverflow.com/users/2083",
"pm_score": 0,
"selected": false,
"text": "SELECT SUBSTRING(field_name, LOCATE('keyword', field_name) - chars_before, total_chars) FROM table_name WHERE field_name LIKE \"%keyword%\"\n SUBSTRING(field_name, LOCATE('keyword', field_name) - 15, 30)\n"
},
{
"answer_id": 38245,
"author": "Fernando Barrocal",
"author_id": 2274,
"author_profile": "https://Stackoverflow.com/users/2274",
"pm_score": 0,
"selected": false,
"text": ".*(\\w+)\\s*WORD\\s*(\\w+).*\n WORD"
},
{
"answer_id": 2509444,
"author": "Paulo Pinto",
"author_id": 189929,
"author_profile": "https://Stackoverflow.com/users/189929",
"pm_score": 3,
"selected": true,
"text": "CONCAT_WS(\n' ',\n-- 20 words before\nTRIM(\n SUBSTRING_INDEX(\n SUBSTRING(field, 1, INSTR(field, 'word') - 1 ),\n ' ',\n -20\n )\n),\n-- your word\n'word',\n-- 20 words after\nTRIM(\n SUBSTRING_INDEX(\n SUBSTRING(field, INSTR(field, 'word') + LENGTH('word') ),\n ' ',\n 20\n )\n)\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/393028/"
] |
38,037 |
<p>In my C++ program I want to parse a small piece of XML, insert some nodes, then extract the new XML (preferably as a <code>std::string</code>).<br>
<a href="http://rapidxml.sourceforge.net/" rel="nofollow noreferrer">RapidXml</a> has been recommended to me, but I can't see how to retrieve the XML back as a text string.<br>
(I could iterate over the nodes and attributes and build it myself, but surely there's a build in function that I am missing.)<br>
Thank you.</p>
|
[
{
"answer_id": 38413,
"author": "Thomas Watnedal",
"author_id": 4059,
"author_profile": "https://Stackoverflow.com/users/4059",
"pm_score": 4,
"selected": true,
"text": "#include <iostream>\n#include <sstream>\n#include \"rapidxml/rapidxml.hpp\"\n#include \"rapidxml/rapidxml_print.hpp\"\n\nint main(int argc, char* argv[]) {\n char xml[] = \"<?xml version=\\\"1.0\\\" encoding=\\\"latin-1\\\"?>\"\n \"<book>\"\n \"</book>\";\n\n //Parse the original document\n rapidxml::xml_document<> doc;\n doc.parse<0>(xml);\n std::cout << \"Name of my first node is: \" << doc.first_node()->name() << \"\\n\";\n\n //Insert something\n rapidxml::xml_node<> *node = doc.allocate_node(rapidxml::node_element, \"author\", \"John Doe\");\n doc.first_node()->append_node(node);\n\n std::stringstream ss;\n ss <<*doc.first_node();\n std::string result_xml = ss.str();\n std::cout <<result_xml<<std::endl;\n return 0;\n}\n"
},
{
"answer_id": 161930,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "print rapidxml_print.hpp stringstream"
},
{
"answer_id": 3484223,
"author": "Petrus Theron",
"author_id": 198927,
"author_profile": "https://Stackoverflow.com/users/198927",
"pm_score": 2,
"selected": false,
"text": "xml_document<> doc; // character type defaults to char\n// ... some code to fill the document\n\n// Print to stream using operator <<\nstd::cout << doc; \n\n// Print to stream using print function, specifying printing flags\nprint(std::cout, doc, 0); // 0 means default printing flags\n\n// Print to string using output iterator\nstd::string s;\nprint(std::back_inserter(s), doc, 0);\n\n// Print to memory buffer using output iterator\nchar buffer[4096]; // You are responsible for making the buffer large enough!\nchar *end = print(buffer, doc, 0); // end contains pointer to character after last printed character\n*end = 0; // Add string terminator after XML\n"
},
{
"answer_id": 8442106,
"author": "danath",
"author_id": 1089219,
"author_profile": "https://Stackoverflow.com/users/1089219",
"pm_score": 2,
"selected": false,
"text": "std::stringstream stream;\nstd::ostream_iterator<char> iter(stream);\n\nrapidxml::print(iter, doc, rapidxml::print_no_indenting);\n\nprintf(\"%s\\n\", stream.str().c_str());\nprintf(\"len = %d\\n\", stream.str().size());\n"
},
{
"answer_id": 15023568,
"author": "uilianries",
"author_id": 2036859,
"author_profile": "https://Stackoverflow.com/users/2036859",
"pm_score": 0,
"selected": false,
"text": "rapidxml::xml_document<> doc;\nrapidxml::xml_node <> * root_node = doc.first_node();\nstd::string strBuff;\n\ndoc.parse<0>(xml);\n\n.\n.\n.\nstrBuff = static_cast<std::string>(root_node->first_attribute(\"attribute_name\")->value());\n"
},
{
"answer_id": 15086468,
"author": "duckduckgo",
"author_id": 988930,
"author_profile": "https://Stackoverflow.com/users/988930",
"pm_score": 0,
"selected": false,
"text": "std::string s;\nprint(back_inserter(s), doc, 0);\ncout << s;\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3590/"
] |
38,039 |
<p>How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#?</p>
<p>Something like:</p>
<pre><code>DateTime.Now.StartWeek(Monday);
</code></pre>
|
[
{
"answer_id": 38049,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 4,
"selected": false,
"text": "DateTime t = DateTime.Now;\nt -= new TimeSpan ((int) t.DayOfWeek, 0, 0, 0);\n"
},
{
"answer_id": 38051,
"author": "firedfly",
"author_id": 3123,
"author_profile": "https://Stackoverflow.com/users/3123",
"pm_score": 1,
"selected": false,
"text": "private DateTime getStartOfWeek(bool useSunday)\n{\n DateTime now = DateTime.Now;\n int dayOfWeek = (int)now.DayOfWeek;\n\n if(!useSunday)\n dayOfWeek--;\n\n if(dayOfWeek < 0)\n {// day of week is Sunday and we want to use Monday as the start of the week\n // Sunday is now the seventh day of the week\n dayOfWeek = 6;\n }\n\n return now.AddDays(-1 * (double)dayOfWeek);\n}\n"
},
{
"answer_id": 38060,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 4,
"selected": false,
"text": "DateTime now = DateTime.Now;\nint dayOfWeek = (int)now.DayOfWeek;\ndayOfWeek = dayOfWeek == 0 ? 7 : dayOfWeek;\nDateTime startOfWeek = now.AddDays(1 - (int)now.DayOfWeek);\n DateTime now = DateTime.Now;\nint dayOfWeek = (int)now.DayOfWeek;\nDateTime startOfWeek = now.AddDays(-(int)now.DayOfWeek);\n"
},
{
"answer_id": 38064,
"author": "Compile This",
"author_id": 4048,
"author_profile": "https://Stackoverflow.com/users/4048",
"pm_score": 11,
"selected": true,
"text": "public static class DateTimeExtensions\n{\n public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)\n {\n int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;\n return dt.AddDays(-1 * diff).Date;\n }\n}\n DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);\nDateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);\n"
},
{
"answer_id": 38067,
"author": "Jason Navarrete",
"author_id": 3920,
"author_profile": "https://Stackoverflow.com/users/3920",
"pm_score": 6,
"selected": false,
"text": "System.Globalization.CultureInfo ci = \n System.Threading.Thread.CurrentThread.CurrentCulture;\nDayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;\nDayOfWeek today = DateTime.Now.DayOfWeek;\nDateTime sow = DateTime.Now.AddDays(-(today - fdow)).Date;\n"
},
{
"answer_id": 38076,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 2,
"selected": false,
"text": "DateTime t = DateTime.Now;\nt -= new TimeSpan ((int) t.DayOfWeek, t.Hour, t.Minute, t.Second);\n DateTime t = DateTime.Now;\nt -= new TimeSpan ((int) t.DayOfWeek - 1, t.Hour, t.Minute, t.Second);\n"
},
{
"answer_id": 38137,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 1,
"selected": false,
"text": "using nVentive.Umbrella.Extensions.Calendar;\nDateTime beginning = DateTime.Now.BeginningOfWeek();\n nVentive.Umbrella.Extensions.Calendar.DefaultDateTimeCalendarExtensions.WeekBeginsOn // Or DateTime.Now.PreviousDay(DayOfWeek.Monday)\nDateTime monday = DateTime.Now.PreviousMonday(); \nDateTime sunday = DateTime.Now.PreviousSunday();\n BeginningOfWeek"
},
{
"answer_id": 38406,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": false,
"text": "public static class DateTimeExtensions\n{\n public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)\n {\n System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;\n DayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;\n return DateTime.Today.AddDays(-(DateTime.Today.DayOfWeek- fdow));\n }\n}\n"
},
{
"answer_id": 1378914,
"author": "Simon",
"author_id": 53158,
"author_profile": "https://Stackoverflow.com/users/53158",
"pm_score": 5,
"selected": false,
"text": "var monday = DateTime.Now.Previous(DayOfWeek.Monday);\nvar sunday = DateTime.Now.Previous(DayOfWeek.Sunday);\n"
},
{
"answer_id": 1830189,
"author": "mails2008",
"author_id": 222558,
"author_profile": "https://Stackoverflow.com/users/222558",
"pm_score": -1,
"selected": false,
"text": "public static System.DateTime getstartweek()\n{\n System.DateTime dt = System.DateTime.Now;\n System.DayOfWeek dmon = System.DayOfWeek.Monday;\n int span = dt.DayOfWeek - dmon;\n dt = dt.AddDays(-span);\n return dt;\n}\n"
},
{
"answer_id": 2883306,
"author": "user324365",
"author_id": 324365,
"author_profile": "https://Stackoverflow.com/users/324365",
"pm_score": 2,
"selected": false,
"text": "public static class DateTimeExtensions\n{\n //http://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week\n //http://stackoverflow.com/questions/1788508/calculate-date-with-monday-as-dayofweek1\n public static DateTime StartOfWeek(this DateTime dt)\n {\n //difference in days\n int diff = (int)dt.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; //sunday=always0, monday=always1, etc.\n\n //As a result we need to have day 0,1,2,3,4,5,6 \n if (diff < 0)\n {\n diff += 7;\n }\n return dt.AddDays(-1 * diff).Date;\n }\n\n public static int DayNoOfWeek(this DateTime dt)\n {\n //difference in days\n int diff = (int)dt.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; //sunday=always0, monday=always1, etc.\n\n //As a result we need to have day 0,1,2,3,4,5,6 \n if (diff < 0)\n {\n diff += 7;\n }\n return diff + 1; //Make it 1..7\n }\n}\n"
},
{
"answer_id": 2926472,
"author": "Zamir",
"author_id": 352544,
"author_profile": "https://Stackoverflow.com/users/352544",
"pm_score": 0,
"selected": false,
"text": " private string[] GetWeekRange(DateTime dateToCheck)\n {\n string[] result = new string[2];\n TimeSpan duration = new TimeSpan(0, 0, 0, 0); //One day \n DateTime dateRangeBegin = dateToCheck;\n DateTime dateRangeEnd = DateTime.Today.Add(duration);\n\n dateRangeBegin = dateToCheck.AddDays(-(int)dateToCheck.DayOfWeek);\n dateRangeEnd = dateToCheck.AddDays(6 - (int)dateToCheck.DayOfWeek);\n\n result[0] = dateRangeBegin.Date.ToString();\n result[1] = dateRangeEnd.Date.ToString();\n return result;\n\n }\n"
},
{
"answer_id": 10553208,
"author": "Janspeed",
"author_id": 1343550,
"author_profile": "https://Stackoverflow.com/users/1343550",
"pm_score": 5,
"selected": false,
"text": " public static DateTime FirstDateInWeek(this DateTime dt)\n {\n while (dt.DayOfWeek != System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek)\n dt = dt.AddDays(-1);\n return dt;\n }\n public static DateTime FirstDateInWeek(this DateTime dt, DayOfWeek weekStartDay)\n {\n while (dt.DayOfWeek != weekStartDay)\n dt = dt.AddDays(-1);\n return dt;\n }\n"
},
{
"answer_id": 10685884,
"author": "yeasir007",
"author_id": 1326559,
"author_profile": "https://Stackoverflow.com/users/1326559",
"pm_score": 2,
"selected": false,
"text": "DateTime firstDate = GetFirstDateOfWeek(DateTime.Parse(\"05/09/2012\").Date, DayOfWeek.Sunday);\nDateTime lastDate = GetLastDateOfWeek(DateTime.Parse(\"05/09/2012\").Date, DayOfWeek.Saturday);\n\npublic static DateTime GetFirstDateOfWeek(DateTime dayInWeek, DayOfWeek firstDay)\n{\n DateTime firstDayInWeek = dayInWeek.Date;\n while (firstDayInWeek.DayOfWeek != firstDay)\n firstDayInWeek = firstDayInWeek.AddDays(-1);\n\n return firstDayInWeek;\n}\n\npublic static DateTime GetLastDateOfWeek(DateTime dayInWeek, DayOfWeek firstDay)\n{\n DateTime lastDayInWeek = dayInWeek.Date;\n while (lastDayInWeek.DayOfWeek != firstDay)\n lastDayInWeek = lastDayInWeek.AddDays(1);\n\n return lastDayInWeek;\n}\n"
},
{
"answer_id": 11379841,
"author": "Matthew Hintzen",
"author_id": 597406,
"author_profile": "https://Stackoverflow.com/users/597406",
"pm_score": 3,
"selected": false,
"text": "public static DateTime StartOfWeek ( this DateTime dt, DayOfWeek? firstDayOfWeek )\n{\n DayOfWeek fdow;\n\n if ( firstDayOfWeek.HasValue )\n {\n fdow = firstDayOfWeek.Value;\n }\n else\n {\n System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;\n fdow = ci.DateTimeFormat.FirstDayOfWeek;\n }\n\n int diff = dt.DayOfWeek - fdow;\n\n if ( diff < 0 )\n {\n diff += 7;\n }\n\n return dt.AddDays( -1 * diff ).Date;\n\n}\n"
},
{
"answer_id": 14609184,
"author": "Eric",
"author_id": 408879,
"author_profile": "https://Stackoverflow.com/users/408879",
"pm_score": 7,
"selected": false,
"text": "var sunday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek);\n var monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Monday);\n\nvar tuesday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Tuesday);\n"
},
{
"answer_id": 15224122,
"author": "Andreas Kromann",
"author_id": 2135748,
"author_profile": "https://Stackoverflow.com/users/2135748",
"pm_score": 2,
"selected": false,
"text": "public static class DateTimeExtension\n{\n public static DateTime GetFirstDayOfThisWeek(this DateTime d)\n {\n CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;\n var first = (int)ci.DateTimeFormat.FirstDayOfWeek;\n var current = (int)d.DayOfWeek;\n\n var result = first <= current ?\n d.AddDays(-1 * (current - first)) :\n d.AddDays(first - current - 7);\n\n return result;\n }\n}\n\nclass Program\n{\n static void Main()\n {\n System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(\"en-US\");\n Console.WriteLine(\"Current culture set to en-US\");\n RunTests();\n Console.WriteLine();\n System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(\"da-DK\");\n Console.WriteLine(\"Current culture set to da-DK\");\n RunTests();\n Console.ReadLine();\n }\n\n static void RunTests()\n {\n Console.WriteLine(\"Today {1}: {0}\", DateTime.Today.Date.GetFirstDayOfThisWeek(), DateTime.Today.Date.ToString(\"yyyy-MM-dd\"));\n Console.WriteLine(\"Saturday 2013-03-02: {0}\", new DateTime(2013, 3, 2).GetFirstDayOfThisWeek());\n Console.WriteLine(\"Sunday 2013-03-03: {0}\", new DateTime(2013, 3, 3).GetFirstDayOfThisWeek());\n Console.WriteLine(\"Monday 2013-03-04: {0}\", new DateTime(2013, 3, 4).GetFirstDayOfThisWeek());\n }\n}\n"
},
{
"answer_id": 18821567,
"author": "HelloWorld",
"author_id": 1394710,
"author_profile": "https://Stackoverflow.com/users/1394710",
"pm_score": 3,
"selected": false,
"text": "var now = System.DateTime.Now;\n\nvar result = now.AddDays(-((now.DayOfWeek - System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 7) % 7)).Date;\n"
},
{
"answer_id": 26167621,
"author": "Denis",
"author_id": 495799,
"author_profile": "https://Stackoverflow.com/users/495799",
"pm_score": 0,
"selected": false,
"text": " namespace DateTimeExample\n {\n using System;\n\n public static class DateTimeExtension\n {\n public static DateTime GetMonday(this DateTime time)\n {\n if (time.DayOfWeek != DayOfWeek.Monday)\n return GetMonday(time.AddDays(-1)); //Recursive call\n\n return time;\n }\n }\n\n internal class Program\n {\n private static void Main()\n {\n Console.WriteLine(DateTime.Now.GetMonday());\n Console.ReadLine();\n }\n }\n } \n"
},
{
"answer_id": 29106459,
"author": "Adrian",
"author_id": 4682104,
"author_profile": "https://Stackoverflow.com/users/4682104",
"pm_score": -1,
"selected": false,
"text": " d = DateTime.Now;\n int dayofweek =(int) d.DayOfWeek;\n if (dayofweek != 0)\n {\n d = d.AddDays(1 - dayofweek);\n }\n else { d = d.AddDays(-6); }\n"
},
{
"answer_id": 34108838,
"author": "Rabbex",
"author_id": 5644465,
"author_profile": "https://Stackoverflow.com/users/5644465",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Globalization;\n\nnamespace MySpace\n{\n public static class DateTimeExtention\n {\n // ToDo: Need to provide culturaly neutral versions.\n\n public static DateTime GetStartOfWeek(this DateTime dt)\n {\n DateTime ndt = dt.Subtract(TimeSpan.FromDays((int)dt.DayOfWeek));\n return new DateTime(ndt.Year, ndt.Month, ndt.Day, 0, 0, 0, 0);\n }\n\n public static DateTime GetEndOfWeek(this DateTime dt)\n {\n DateTime ndt = dt.GetStartOfWeek().AddDays(6);\n return new DateTime(ndt.Year, ndt.Month, ndt.Day, 23, 59, 59, 999);\n }\n\n public static DateTime GetStartOfWeek(this DateTime dt, int year, int week)\n {\n DateTime dayInWeek = new DateTime(year, 1, 1).AddDays((week - 1) * 7);\n return dayInWeek.GetStartOfWeek();\n }\n\n public static DateTime GetEndOfWeek(this DateTime dt, int year, int week)\n {\n DateTime dayInWeek = new DateTime(year, 1, 1).AddDays((week - 1) * 7);\n return dayInWeek.GetEndOfWeek();\n }\n }\n}\n"
},
{
"answer_id": 34353217,
"author": "Piotr Lewandowski",
"author_id": 5694667,
"author_profile": "https://Stackoverflow.com/users/5694667",
"pm_score": 2,
"selected": false,
"text": "private static DateTime GetFirstDayOfWeek(DateTime date)\n{\n return date.AddDays(\n -(((int)date.DayOfWeek - 1) -\n (int)Math.Floor((double)((int)date.DayOfWeek - 1) / 7) * 7));\n}\n"
},
{
"answer_id": 37902263,
"author": "Threezool",
"author_id": 5131763,
"author_profile": "https://Stackoverflow.com/users/5131763",
"pm_score": 2,
"selected": false,
"text": "int delta = DayOfWeek.Monday - DateTime.Now.DayOfWeek;\nDateTime monday = DateTime.Now.AddDays(delta == 1 ? -6 : delta);\nreturn monday;\n"
},
{
"answer_id": 43684154,
"author": "F.H.",
"author_id": 2906568,
"author_profile": "https://Stackoverflow.com/users/2906568",
"pm_score": 2,
"selected": false,
"text": " public static DateTime EndOfWeek(this DateTime dt)\n {\n int diff = 7 - (int)dt.DayOfWeek;\n\n diff = diff == 7 ? 0 : diff;\n\n DateTime eow = dt.AddDays(diff).Date;\n\n return new DateTime(eow.Year, eow.Month, eow.Day, 23, 59, 59, 999) { };\n }\n"
},
{
"answer_id": 48411638,
"author": "Mike",
"author_id": 7612816,
"author_profile": "https://Stackoverflow.com/users/7612816",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n/// Gets the date of the first day of the week for the date.\n/// </summary>\n/// <param name=\"date\">The date to be used</param>\n/// <param name=\"cultureInfo\">If none is provided, the current culture is used</param>\n/// <returns>The date of the beggining of the week based on the culture specifed</returns>\npublic static DateTime StartOfWeek(this DateTime date, CultureInfo cultureInfo=null) =>\n date.AddDays(-1 * (7 + (date.DayOfWeek - (cultureInfo ?? CultureInfo.CurrentCulture).DateTimeFormat.FirstDayOfWeek)) % 7).Date;\n public static void TestFirstDayOfWeekExtension() {\n DateTime date = DateTime.Now;\n foreach(System.Globalization.CultureInfo culture in CultureInfo.GetCultures(CultureTypes.UserCustomCulture | CultureTypes.SpecificCultures)) {\n Console.WriteLine($\"{culture.EnglishName}: {date.ToShortDateString()} First Day of week: {date.StartOfWeek(culture).ToShortDateString()}\");\n }\n}\n"
},
{
"answer_id": 48494983,
"author": "Ali Umair",
"author_id": 2156152,
"author_profile": "https://Stackoverflow.com/users/2156152",
"pm_score": 0,
"selected": false,
"text": "public static DateTime GetDateInCurrentWeek(this DateTime date, DayOfWeek day)\n{\n var temp = date;\n var limit = (int)date.DayOfWeek;\n var returnDate = DateTime.MinValue;\n\n if (date.DayOfWeek == day) \n return date;\n\n for (int i = limit; i < 6; i++)\n {\n temp = temp.AddDays(1);\n\n if (day == temp.DayOfWeek)\n {\n returnDate = temp;\n break;\n }\n }\n if (returnDate == DateTime.MinValue)\n {\n for (int i = limit; i > -1; i++)\n {\n date = date.AddDays(-1);\n\n if (day == date.DayOfWeek)\n {\n returnDate = date;\n break;\n }\n }\n }\n return returnDate;\n}\n"
},
{
"answer_id": 52720346,
"author": "George Stavrou",
"author_id": 6050375,
"author_profile": "https://Stackoverflow.com/users/6050375",
"pm_score": 4,
"selected": false,
"text": "DateTime startAtMonday = DateTime.Now.AddDays(DayOfWeek.Monday - DateTime.Now.DayOfWeek);\n DateTime startAtSunday = DateTime.Now.AddDays(DayOfWeek.Sunday- DateTime.Now.DayOfWeek);\n"
},
{
"answer_id": 53518108,
"author": "pixelda",
"author_id": 1489673,
"author_profile": "https://Stackoverflow.com/users/1489673",
"pm_score": 0,
"selected": false,
"text": "var weekStartDate = DateTime.Now.AddDays(-((int)now.DayOfWeek - (int)DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek));\n"
},
{
"answer_id": 55514986,
"author": "Muhammad Abbas",
"author_id": 5834683,
"author_profile": "https://Stackoverflow.com/users/5834683",
"pm_score": 3,
"selected": false,
"text": "public static class TIMEE\n{\n public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)\n {\n int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;\n return dt.AddDays(-1 * diff).Date;\n }\n\n public static DateTime EndOfWeek(this DateTime dt, DayOfWeek startOfWeek)\n {\n int diff = (7 - (dt.DayOfWeek - startOfWeek)) % 7;\n return dt.AddDays(1 * diff).Date;\n }\n}\n DateTime dt = TIMEE.StartOfWeek(DateTime.Now ,DayOfWeek.Monday);\nDateTime dt1 = TIMEE.EndOfWeek(DateTime.Now, DayOfWeek.Sunday);\n"
},
{
"answer_id": 57274114,
"author": "Rowan Richards",
"author_id": 5821656,
"author_profile": "https://Stackoverflow.com/users/5821656",
"pm_score": 1,
"selected": false,
"text": "public static DateTime GetDayOfWeek(DateTime dateTime, DayOfWeek dayOfWeek)\n{\n var monday = dateTime.Date.AddDays((7 + (dateTime.DayOfWeek - DayOfWeek.Monday) % 7) * -1);\n\n var diff = dayOfWeek - DayOfWeek.Monday;\n\n if (diff == -1)\n {\n diff = 6;\n }\n\n return monday.AddDays(diff);\n}\n"
},
{
"answer_id": 60892025,
"author": "mihauuuu",
"author_id": 8549646,
"author_profile": "https://Stackoverflow.com/users/8549646",
"pm_score": -1,
"selected": false,
"text": " DateTime WeekBeginning(DateTime input)\n {\n do\n {\n if (input.DayOfWeek.ToString() == \"Monday\")\n return input;\n else\n return WeekBeginning(input.AddDays(-1));\n } while (input.DayOfWeek.ToString() == \"Monday\");\n }\n"
},
{
"answer_id": 61554096,
"author": "C. Keats",
"author_id": 8273351,
"author_profile": "https://Stackoverflow.com/users/8273351",
"pm_score": 0,
"selected": false,
"text": "//Replace with whatever input date you want\nDateTime inputDate = DateTime.Now;\n\n//For this example, weeks start on Monday\nint startOfWeek = (int)DayOfWeek.Monday;\n\n//Calculate the number of days it has been since the start of the week\nint daysSinceStartOfWeek = ((int)inputDate.DayOfWeek + 7 - startOfWeek) % 7;\n\nDateTime previousStartOfWeek = inputDate.AddDays(-daysSinceStartOfWeek);\n"
},
{
"answer_id": 64763247,
"author": "DReact",
"author_id": 11487686,
"author_profile": "https://Stackoverflow.com/users/11487686",
"pm_score": 2,
"selected": false,
"text": "public static DateTime GetStartOfWeekDate()\n{\n // Get today's date\n DateTime today = DateTime.Today;\n // Get the value for today. DayOfWeek is an enum with 0 being Sunday, 1 Monday, etc\n var todayDayOfWeek = (int)today.DayOfWeek;\n\n var dateStartOfWeek = today;\n // If today is not Monday, then get the date for Monday\n if (todayDayOfWeek != 1)\n {\n // How many days to get back to Monday from today\n var daysToStartOfWeek = (todayDayOfWeek - 1);\n // Subtract from today's date the number of days to get to Monday\n dateStartOfWeek = today.AddDays(-daysToStartOfWeek);\n }\n\n return dateStartOfWeek;\n\n}\n"
},
{
"answer_id": 68382467,
"author": "Noob",
"author_id": 8604852,
"author_profile": "https://Stackoverflow.com/users/8604852",
"pm_score": -1,
"selected": false,
"text": "DateTime.Now.Date.AddDays(-(DateTime.Now.Date.DayOfWeek == 0 ? 7 : (int)DateTime.Now.Date.DayOfWeek) + 1)\n private static DateTime GetDay(DateTime date, int daysAmount = 1)\n{\n return date.Date.AddDays(-(date.Date.DayOfWeek == 0 ? 7 : (int)date.Date.DayOfWeek) + daysAmount);\n}\n private static DateTime GetDayOfWeek(DateTime date, DayOfWeek dayOfWeek = DayOfWeek.Monday)\n{\n return date.Date.AddDays(-(date.Date.DayOfWeek == 0 ? 7 : (int)date.Date.DayOfWeek) + (dayOfWeek == 0 ? 7 : (int)dayOfWeek));\n}\n"
},
{
"answer_id": 72867015,
"author": "Display Name",
"author_id": 2815956,
"author_profile": "https://Stackoverflow.com/users/2815956",
"pm_score": 0,
"selected": false,
"text": "// Adding 7 so remainder is always positive; Otherwise % returns -1 on Sunday.\nvar daysToSubtract = (7 + (int)today.DayOfWeek - (int)DayOfWeek.Monday) % 7;\n\nvar monday = today\n .AddDays(-daysToSubtract)\n .Date;\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] |
38,056 |
<p>The only <em>nice</em> way I've found is:</p>
<pre><code>import sys
import os
try:
os.kill(int(sys.argv[1]), 0)
print "Running"
except:
print "Not running"
</code></pre>
<p>(<a href="http://www.unix.com/unix-advanced-expert-users/79267-trick-bash-scripters-check-if-process-running.html" rel="noreferrer">Source</a>)<br>
But is this reliable? Does it work with every process and every distribution?</p>
|
[
{
"answer_id": 38196,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 4,
"selected": false,
"text": "/proc os.kill import sys\nimport os\nimport errno\n\ntry:\n os.kill(int(sys.argv[1]), 0)\nexcept OSError, err:\n if err.errno == errno.ESRCH:\n print \"Not running\"\n elif err.errno == errno.EPERM:\n print \"No permission to signal this process!\"\n else:\n print \"Unknown error\"\nelse:\n print \"Running\"\n"
},
{
"answer_id": 38230,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 7,
"selected": true,
"text": " >>> import os.path\n >>> os.path.exists(\"/proc/0\")\n False\n >>> os.path.exists(\"/proc/12\")\n True\n"
},
{
"answer_id": 4139017,
"author": "sivabudh",
"author_id": 65313,
"author_profile": "https://Stackoverflow.com/users/65313",
"pm_score": 3,
"selected": false,
"text": "import os\nimport subprocess\nimport re\n\ndef findThisProcess( process_name ):\n ps = subprocess.Popen(\"ps -eaf | grep \"+process_name, shell=True, stdout=subprocess.PIPE)\n output = ps.stdout.read()\n ps.stdout.close()\n ps.wait()\n\n return output\n\n# This is the function you can use \ndef isThisRunning( process_name ):\n output = findThisProcess( process_name )\n\n if re.search('path/of/process'+process_name, output) is None:\n return False\n else:\n return True\n\n# Example of how to use\nif isThisRunning('some_process') == False:\n print(\"Not running\")\nelse:\n print(\"Running!\")\n"
},
{
"answer_id": 7008599,
"author": "Maksym Kozlenko",
"author_id": 171847,
"author_profile": "https://Stackoverflow.com/users/171847",
"pm_score": 0,
"selected": false,
"text": "def process_exists(proc_name):\n ps = subprocess.Popen(\"ps ax -o pid= -o args= \", shell=True, stdout=subprocess.PIPE)\n ps_pid = ps.pid\n output = ps.stdout.read()\n ps.stdout.close()\n ps.wait()\n\n for line in output.split(\"\\n\"):\n res = re.findall(\"(\\d+) (.*)\", line)\n if res:\n pid = int(res[0][0])\n if proc_name in res[0][1] and pid != os.getpid() and pid != ps_pid:\n return True\n return False\n"
},
{
"answer_id": 11784942,
"author": "mr.m",
"author_id": 1572451,
"author_profile": "https://Stackoverflow.com/users/1572451",
"pm_score": 2,
"selected": false,
"text": "#proc -> name/id of the process\n#id = 1 -> search for pid\n#id = 0 -> search for name (default)\n\ndef process_exists(proc, id = 0):\n ps = subprocess.Popen(\"ps -A\", shell=True, stdout=subprocess.PIPE)\n ps_pid = ps.pid\n output = ps.stdout.read()\n ps.stdout.close()\n ps.wait()\n\n for line in output.split(\"\\n\"):\n if line != \"\" and line != None:\n fields = line.split()\n pid = fields[0]\n pname = fields[3]\n\n if(id == 0):\n if(pname == proc):\n return True\n else:\n if(pid == proc):\n return True\nreturn False\n"
},
{
"answer_id": 18259642,
"author": "felbus",
"author_id": 236805,
"author_profile": "https://Stackoverflow.com/users/236805",
"pm_score": 3,
"selected": false,
"text": "import os\n\nprocessname = 'somprocessname'\ntmp = os.popen(\"ps -Af\").read()\nproccount = tmp.count(processname)\n\nif proccount > 0:\n print(proccount, ' processes running of ', processname, 'type')\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1531/"
] |
38,057 |
<pre><code>@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Problem {
@ManyToOne
private Person person;
}
@Entity
@DiscriminatorValue("UP")
public class UglyProblem extends Problem {}
@Entity
public class Person {
@OneToMany(mappedBy="person")
private List< UglyProblem > problems;
}
</code></pre>
<p>I think it is pretty clear what I am trying to do. I expect @ManyToOne person to be inherited by UglyProblem class. But there will be an exception saying something like: "There is no such property found in UglyProblem class (mappedBy="person")".</p>
<p>All I found is <a href="http://opensource.atlassian.com/projects/hibernate/browse/ANN-558" rel="noreferrer">this</a>. I was not able to find the post by Emmanuel Bernard explaining reasons behind this. </p>
<hr>
<blockquote>
<p>Unfortunately, according to the Hibernate documentation "Properties from superclasses not mapped as @MappedSuperclass are ignored."</p>
</blockquote>
<p>Well I think this means that if I have these two classes:</p>
<pre><code>public class A {
private int foo;
}
@Entity
public class B extens A {
}
</code></pre>
<p>then field <code>foo</code> will not be mapped for class B. Which makes sense. But if I have something like this:</p>
<pre><code>@Entity
public class Problem {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Entity
public class UglyProblem extends Problem {
private int levelOfUgliness;
public int getLevelOfUgliness() {
return levelOfUgliness;
}
public void setLevelOfUgliness(int levelOfUgliness) {
this.levelOfUgliness = levelOfUgliness;
}
}
</code></pre>
<p>I expect the class UglyProblem to have fileds <code>id</code> and <code>name</code> and both classes to be mapped using same table. (In fact, this is exactly what happens, I have just checked again). I have got this table:</p>
<pre><code>CREATE TABLE "problem" (
"DTYPE" varchar(31) NOT NULL,
"id" bigint(20) NOT NULL auto_increment,
"name" varchar(255) default NULL,
"levelOfUgliness" int(11) default NULL,
PRIMARY KEY ("id")
) AUTO_INCREMENT=2;
</code></pre>
<p>Going back to my question:</p>
<blockquote>
<p>I expect @ManyToOne person to be inherited by UglyProblem class.</p>
</blockquote>
<p>I expect that because all other mapped fields are inherited and I do not see any reason to make this exception for ManyToOne relationships.</p>
<hr>
<p>Yeah, I saw that. In fact, I used Read-Only solution for my case. But my question was "Why..." :). I know that there is an explanation given by a member of hibernate team. I was not able to find it and that is why I asked.</p>
<p>I want to find out the motivation of this design decision.</p>
<p>(if you interested how I have faced this problem: I inherited a project built using hibernate 3. It was Jboss 4.0.something + hibernate was already there (you'd download it all together). I was moving this project to Jboss 4.2.2 and I found out that there are inherited mappings of "@OneToMany mappedBy" and it worked fine on old setup...)</p>
|
[
{
"answer_id": 38992,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 3,
"selected": false,
"text": "public interface Problem {\n public Person getPerson();\n}\n\npublic interface UglyProblem extends Problem {\n}\n @MappedSuperclass\npublic abstract class AbstractProblemImpl implements Problem {\n @ManyToOne\n private Person person;\n\n public Person getPerson() {\n return person;\n }\n}\n\n@Entity\npublic class ProblemImpl extends AbstractProblemImpl implements Problem {\n}\n\n@Entity\npublic class UglyProblemImpl extends AbstractProblemImpl implements UglyProblem {\n}\n"
},
{
"answer_id": 53448,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 4,
"selected": true,
"text": " _____________\n |__PROBLEMS__| |__PEOPLE__|\n |id <PK> | | |\n |person <FK> | -------->| |\n |problemType | |_________ |\n -------------- \n @MappedSuperclass"
},
{
"answer_id": 1923659,
"author": "Bill Leeper",
"author_id": 234014,
"author_profile": "https://Stackoverflow.com/users/234014",
"pm_score": 1,
"selected": false,
"text": "@Entity\n@Inheritance(strategy = InheritanceType.SINGLE_TABLE)\n@ForceDiscriminator\npublic class Problem {\n\n}\n\n@Entity\n@DiscriminatorValue(\"UP\")\npublic class UglyProblem extends Problem {\n @ManyToOne\n private Person person;\n}\n\n@Entity\npublic class Person {\n @OneToMany(mappedBy=\"person\")\n private List< UglyProblem > problems;\n}\n"
},
{
"answer_id": 26091090,
"author": "Guillaume Carre",
"author_id": 1084836,
"author_profile": "https://Stackoverflow.com/users/1084836",
"pm_score": 3,
"selected": false,
"text": "@OneToMany(mappedBy=\"person\")\n@Where(clause=\"DTYPE='UP'\")\nprivate List< UglyProblem > problems;\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4052/"
] |
38,068 |
<p>Is there any shorthand way of defining and using generic definitions without having to keep repeating a particular generic description such that if there is a change I don't have to change all definitions/usages though out the codebase for example is something like this possible:</p>
<pre><code>Typedef myGenDef = < Object1, Object2 >;
HashMap< myGenDef > hm = new HashMap< myGenDef >();
for (Entry< myGenDef > ent : hm..entrySet())
{
.
.
.
}
</code></pre>
|
[
{
"answer_id": 38098,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 1,
"selected": false,
"text": "def map = new HashMap<complicated generic expression>();\n"
},
{
"answer_id": 38102,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 5,
"selected": true,
"text": "class StringList extends ArrayList<String> { }\n"
},
{
"answer_id": 38116,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 2,
"selected": false,
"text": " <K, V> Map<K, V> getSomething() {\n //...\n }\n final Map<String, Object> something = getsomething();\n final Map<String, Object> something = this.<String, Object>getsomething();\n"
},
{
"answer_id": 38118,
"author": "zaca",
"author_id": 3031,
"author_profile": "https://Stackoverflow.com/users/3031",
"pm_score": 2,
"selected": false,
"text": "public Map<String, Integer> createGenMap(){\n return new HashMap<String,Integer>();\n\n }\n"
},
{
"answer_id": 39325,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 2,
"selected": false,
"text": "class A {\n private Map<String, Integer> values = new HashMap<String, Integer>();\n}\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
38,074 |
<p>If you create an Oracle dblink you cannot directly access LOB columns in the target tables.</p>
<p>For instance, you create a dblink with:</p>
<pre><code>create database link TEST_LINK
connect to TARGETUSER IDENTIFIED BY password using 'DATABASESID';
</code></pre>
<p>After this you can do stuff like:</p>
<pre><code>select column_a, column_b
from data_user.sample_table@TEST_LINK
</code></pre>
<p>Except if the column is a LOB, then you get the error:</p>
<pre><code>ORA-22992: cannot use LOB locators selected from remote tables
</code></pre>
<p>This is <a href="http://docs.oracle.com/cd/B10501_01/appdev.920/a96591/adl04mng.htm#98328" rel="noreferrer">a documented restriction</a>.</p>
<p>The same page suggests you fetch the values into a local table, but that is... kind of messy:</p>
<pre><code>CREATE TABLE tmp_hello
AS SELECT column_a
from data_user.sample_table@TEST_LINK
</code></pre>
<p>Any other ideas?</p>
|
[
{
"answer_id": 14547653,
"author": "user2015502",
"author_id": 2015502,
"author_profile": "https://Stackoverflow.com/users/2015502",
"pm_score": 4,
"selected": false,
"text": "SELECT (select column_b from sample_table@TEST_LINK) AS column_b FROM DUAL\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2846/"
] |
38,081 |
<p>I need to create a quick-n-dirty knob control in Visual Basic 2005 Express, the value of which is incremented/decremented by "grabbing" it with the mouse and moving the cursor up/down. Because the knob itself doesn't move, I need to keep tracking the mouse movement outside of the rectangle of the control.</p>
<p>I use a <code>Label</code> with an <code>ImageList</code> to implement this (I have a list of 127 bitmaps representing the knob in various positions).</p>
<p>Which events should I react to?</p>
|
[
{
"answer_id": 14547653,
"author": "user2015502",
"author_id": 2015502,
"author_profile": "https://Stackoverflow.com/users/2015502",
"pm_score": 4,
"selected": false,
"text": "SELECT (select column_b from sample_table@TEST_LINK) AS column_b FROM DUAL\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2095/"
] |
38,160 |
<p>Lets say I have a loop in Bash:</p>
<pre><code>for foo in `some-command`
do
do-something $foo
done
</code></pre>
<p><code>do-something</code> is cpu bound and I have a nice shiny 4 core processor. I'd like to be able to run up to 4 <code>do-something</code>'s at once.</p>
<p>The naive approach seems to be:</p>
<pre><code>for foo in `some-command`
do
do-something $foo &
done
</code></pre>
<p>This will run <em>all</em> <code>do-something</code>s at once, but there are a couple downsides, mainly that do-something may also have some significant I/O which performing <em>all</em> at once might slow down a bit. The other problem is that this code block returns immediately, so no way to do other work when all the <code>do-something</code>s are finished.</p>
<p>How would you write this loop so there are always X <code>do-something</code>s running at once?</p>
|
[
{
"answer_id": 38166,
"author": "skolima",
"author_id": 3205,
"author_profile": "https://Stackoverflow.com/users/3205",
"pm_score": 4,
"selected": false,
"text": "make -jX wait man wait wait maxjobs = 10\n\nforeach line in `cat file.txt` {\n jobsrunning = 0\n while jobsrunning < maxjobs {\n do job &\n jobsrunning += 1\n }\nwait\n}\n\njob ( ){\n...\n}\n wait"
},
{
"answer_id": 880864,
"author": "Grumbel",
"author_id": 28113,
"author_profile": "https://Stackoverflow.com/users/28113",
"pm_score": 4,
"selected": false,
"text": "function pwait() {\n while [ $(jobs -p | wc -l) -ge $1 ]; do\n sleep 1\n done\n}\n & for i in *; do\n do_something $i &\n pwait 10\ndone\n wait jobs -p"
},
{
"answer_id": 881392,
"author": "lhunath",
"author_id": 58803,
"author_profile": "https://Stackoverflow.com/users/58803",
"pm_score": 3,
"selected": false,
"text": "bash bstark scheduleAll() {\n local job i=0 max=4 pids=()\n\n for job; do\n (( ++i % max == 0 )) && {\n wait \"${pids[@]}\"\n pids=()\n }\n\n bash -c \"$job\" & pids+=(\"$!\")\n done\n\n wait \"${pids[@]}\"\n}\n scheduleAll kill -0 wait kill -0 kill -0 bash"
},
{
"answer_id": 881450,
"author": "Fritz G. Mehner",
"author_id": 57457,
"author_profile": "https://Stackoverflow.com/users/57457",
"pm_score": 7,
"selected": true,
"text": "cpus=$( ls -d /sys/devices/system/cpu/cpu[[:digit:]]* | wc -w )\n\nfind . -name \\*.pdf | xargs --max-args=1 --max-procs=$cpus pdf2ps\n --max-procs=max-procs\n-P max-procs\n Run up to max-procs processes at a time; the default is 1.\n If max-procs is 0, xargs will run as many processes as possible at a\n time. Use the -n option with -P; otherwise chances are that only one\n exec will be done.\n"
},
{
"answer_id": 894986,
"author": "Idelic",
"author_id": 109744,
"author_profile": "https://Stackoverflow.com/users/109744",
"pm_score": 3,
"selected": false,
"text": "make"
},
{
"answer_id": 3011097,
"author": "Ole Tange",
"author_id": 363028,
"author_profile": "https://Stackoverflow.com/users/363028",
"pm_score": 5,
"selected": false,
"text": "some-command | parallel do-something\n some-command | parallel -S server1,server2 do-something\n cat list_of_files | \\\nparallel --trc {.}.out -S server1,server2,: \\\n\"my_script {} > {.}.out\"\n some-command | parallel do-something | postprocess\n"
},
{
"answer_id": 6773673,
"author": "cat",
"author_id": 712124,
"author_profile": "https://Stackoverflow.com/users/712124",
"pm_score": 1,
"selected": false,
"text": "#!/bin/bash\n\nn=0\nmaxjobs=10\n\nfor i in *.m4a ; do\n # ( DO SOMETHING ) &\n\n # limit jobs\n if (( $(($((++n)) % $maxjobs)) == 0 )) ; then\n wait # wait until all have finished (not optimal, but most times good enough)\n echo $n wait\n fi\ndone\n"
},
{
"answer_id": 8196788,
"author": "Adam Zalcman",
"author_id": 1023815,
"author_profile": "https://Stackoverflow.com/users/1023815",
"pm_score": 0,
"selected": false,
"text": "for i in {1..N}; do\n (for j in {1..M}; do do_something; done & );\ndone\n"
},
{
"answer_id": 9392829,
"author": "ilnar",
"author_id": 1225511,
"author_profile": "https://Stackoverflow.com/users/1225511",
"pm_score": 2,
"selected": false,
"text": "parallel ()\n{\n awk \"BEGIN{print \\\"all: ALL_TARGETS\\\\n\\\"}{print \\\"TARGET_\\\"NR\\\":\\\\n\\\\t@-\\\"\\$0\\\"\\\\n\\\"}END{printf \\\"ALL_TARGETS:\\\";for(i=1;i<=NR;i++){printf \\\" TARGET_%d\\\",i};print\\\"\\\\n\\\"}\" | make $@ -f - all\n}\n cat my_commands | parallel -j 4\n"
},
{
"answer_id": 21156538,
"author": "Jack",
"author_id": 1327414,
"author_profile": "https://Stackoverflow.com/users/1327414",
"pm_score": -1,
"selected": false,
"text": "some-command eval `some-command for $DOMAINS` &\n\n job[$i]=$!\n\n i=$(( i + 1))\n echo $DOMAINS |wc -w"
},
{
"answer_id": 33108323,
"author": "Fernando",
"author_id": 1543263,
"author_profile": "https://Stackoverflow.com/users/1543263",
"pm_score": 1,
"selected": false,
"text": " #! /bin/bash\n\n MAX_JOBS=32\n\n FILE_LIST=($(cat ${1}))\n\n echo Length ${#FILE_LIST[@]}\n\n for ((INDEX=0; INDEX < ${#FILE_LIST[@]}; INDEX=$((${INDEX}+${MAX_JOBS})) ));\n do\n JOBS_RUNNING=0\n while ((JOBS_RUNNING < MAX_JOBS))\n do\n I=$((${INDEX}+${JOBS_RUNNING}))\n FILE=${FILE_LIST[${I}]}\n if [ \"$FILE\" != \"\" ];then\n echo $JOBS_RUNNING $FILE\n ./M22Checker ${FILE} &\n else\n echo $JOBS_RUNNING NULL &\n fi\n JOBS_RUNNING=$((JOBS_RUNNING+1))\n done\n wait\n done\n"
},
{
"answer_id": 39189370,
"author": "Orsiris de Jong",
"author_id": 2635443,
"author_profile": "https://Stackoverflow.com/users/2635443",
"pm_score": 0,
"selected": false,
"text": "function log {\n echo \"$1\"\n}\n\n# Take a list of commands to run, runs them sequentially with numberOfProcesses commands simultaneously runs\n# Returns the number of non zero exit codes from commands\nfunction ParallelExec {\n local numberOfProcesses=\"${1}\" # Number of simultaneous commands to run\n local commandsArg=\"${2}\" # Semi-colon separated list of commands\n\n local pid\n local runningPids=0\n local counter=0\n local commandsArray\n local pidsArray\n local newPidsArray\n local retval\n local retvalAll=0\n local pidState\n local commandsArrayPid\n\n IFS=';' read -r -a commandsArray <<< \"$commandsArg\"\n\n log \"Runnning ${#commandsArray[@]} commands in $numberOfProcesses simultaneous processes.\"\n\n while [ $counter -lt \"${#commandsArray[@]}\" ] || [ ${#pidsArray[@]} -gt 0 ]; do\n\n while [ $counter -lt \"${#commandsArray[@]}\" ] && [ ${#pidsArray[@]} -lt $numberOfProcesses ]; do\n log \"Running command [${commandsArray[$counter]}].\"\n eval \"${commandsArray[$counter]}\" &\n pid=$!\n pidsArray+=($pid)\n commandsArrayPid[$pid]=\"${commandsArray[$counter]}\"\n counter=$((counter+1))\n done\n\n\n newPidsArray=()\n for pid in \"${pidsArray[@]}\"; do\n # Handle uninterruptible sleep state or zombies by ommiting them from running process array (How to kill that is already dead ? :)\n if kill -0 $pid > /dev/null 2>&1; then\n pidState=$(ps -p$pid -o state= 2 > /dev/null)\n if [ \"$pidState\" != \"D\" ] && [ \"$pidState\" != \"Z\" ]; then\n newPidsArray+=($pid)\n fi\n else\n # pid is dead, get it's exit code from wait command\n wait $pid\n retval=$?\n if [ $retval -ne 0 ]; then\n log \"Command [${commandsArrayPid[$pid]}] failed with exit code [$retval].\"\n retvalAll=$((retvalAll+1))\n fi\n fi\n done\n pidsArray=(\"${newPidsArray[@]}\")\n\n # Add a trivial sleep time so bash won't eat all CPU\n sleep .05\n done\n\n return $retvalAll\n}\n cmds=\"du -csh /var;du -csh /tmp;sleep 3;du -csh /root;sleep 10; du -csh /home\"\n\n# Execute 2 processes at a time\nParallelExec 2 \"$cmds\"\n\n# Execute 4 processes at a time\nParallelExec 4 \"$cmds\"\n"
},
{
"answer_id": 54472111,
"author": "Skrat",
"author_id": 316622,
"author_profile": "https://Stackoverflow.com/users/316622",
"pm_score": 2,
"selected": false,
"text": "parallel function run_parallel_jobs {\n local concurrent_max=$1\n local callback=$2\n local cmds=(\"${@:3}\")\n local jobs=( )\n\n while [[ \"${#cmds[@]}\" -gt 0 ]] || [[ \"${#jobs[@]}\" -gt 0 ]]; do\n while [[ \"${#jobs[@]}\" -lt $concurrent_max ]] && [[ \"${#cmds[@]}\" -gt 0 ]]; do\n local cmd=\"${cmds[0]}\"\n cmds=(\"${cmds[@]:1}\")\n\n bash -c \"$cmd\" &\n jobs+=($!)\n done\n\n local job=\"${jobs[0]}\"\n jobs=(\"${jobs[@]:1}\")\n\n local state=\"$(ps -p $job -o state= 2>/dev/null)\"\n\n if [[ \"$state\" == \"D\" ]] || [[ \"$state\" == \"Z\" ]]; then\n $callback $job\n else\n wait $job\n $callback $job $?\n fi\n done\n}\n function job_done {\n if [[ $# -lt 2 ]]; then\n echo \"PID $1 died unexpectedly\"\n else\n echo \"PID $1 exited $2\"\n fi\n}\n\ncmds=( \\\n \"echo 1; sleep 1; exit 1\" \\\n \"echo 2; sleep 2; exit 2\" \\\n \"echo 3; sleep 3; exit 3\" \\\n \"echo 4; sleep 4; exit 4\" \\\n \"echo 5; sleep 5; exit 5\" \\\n)\n\n# cpus=\"$(getconf _NPROCESSORS_ONLN)\"\ncpus=3\nrun_parallel_jobs $cpus \"job_done\" \"${cmds[@]}\"\n 1\n2\n3\nPID 56712 exited 1\n4\nPID 56713 exited 2\n5\nPID 56714 exited 3\nPID 56720 exited 4\nPID 56724 exited 5\n $$ function job_done {\n cat \"$1.log\"\n}\n\ncmds=( \\\n \"echo 1 \\$\\$ >\\$\\$.log\" \\\n \"echo 2 \\$\\$ >\\$\\$.log\" \\\n)\n\nrun_parallel_jobs 2 \"job_done\" \"${cmds[@]}\"\n 1 56871\n2 56872\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163/"
] |
38,181 |
<p>I have a basic understanding of mock and fake objects, but I'm not sure I have a feeling about when/where to use mocking - especially as it would apply to this scenario <a href="https://stackoverflow.com/questions/37375/how-do-i-unit-test-a-wcf-service"><strong>here</strong></a>.</p>
|
[
{
"answer_id": 38260,
"author": "Jan Soltis",
"author_id": 3997,
"author_profile": "https://Stackoverflow.com/users/3997",
"pm_score": 8,
"selected": false,
"text": "sendInvitations(MailServer mailServer) MailServer.createMessage() MailServer.sendMessage(m) MailServer MailServerImpl TestMailServer MailServer MailServer MySorter // the correct way of testing\ntestSort() {\n testList = [1, 7, 3, 8, 2] \n MySorter.sort(testList)\n\n assert testList equals [1, 2, 3, 7, 8]\n}\n\n\n// incorrect, testing implementation\ntestSort() {\n testList = [1, 7, 3, 8, 2] \n MySorter.sort(testList)\n\n assert that compare(1, 2) was called once \n assert that compare(1, 3) was not called \n assert that compare(2, 3) was called once \n ....\n}\n MySorter sendInvitations(PdfFormatter pdfFormatter, MailServer mailServer) PdfFormatter testInvitations() {\n // train as stub\n pdfFormatter = create mock of PdfFormatter\n let pdfFormatter.getCanvasWidth() returns 100\n let pdfFormatter.getCanvasHeight() returns 300\n let pdfFormatter.addText(x, y, text) returns true \n let pdfFormatter.drawLine(line) does nothing\n\n // train as mock\n mailServer = create mock of MailServer\n expect mailServer.sendMail() called exactly once\n\n // do the test\n sendInvitations(pdfFormatter, mailServer)\n\n assert that all pdfFormatter expectations are met\n assert that all mailServer expectations are met\n}\n PdfFormatter sendInvitation() sendInvitations() sendInvitations() PdfFormatter sendInvitations() PdfFormatterImpl TestPdfFormatter"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] |
38,190 |
<p>Is it possible to read a disk directly with .NET? By directly, I mean via the device bypassing the file system. I think I would go about this by opening the device some way "\Device\Ide\IdeDeviceP2T0L0-1" for example.</p>
<p>If I can't open the device with a .NET API, knowing which Win32 API to use would be helpful.</p>
|
[
{
"answer_id": 38275,
"author": "Darryl Braaten",
"author_id": 1834,
"author_profile": "https://Stackoverflow.com/users/1834",
"pm_score": 4,
"selected": false,
"text": "using System;\nusing System.Runtime.InteropServices;\nusing System.IO;\nusing Microsoft.Win32.SafeHandles;\n\nnamespace ReadFromDevice\n{\n public class DeviceStream : Stream, IDisposable\n {\n public const short FILE_ATTRIBUTE_NORMAL = 0x80;\n public const short INVALID_HANDLE_VALUE = -1;\n public const uint GENERIC_READ = 0x80000000;\n public const uint GENERIC_WRITE = 0x40000000;\n public const uint CREATE_NEW = 1;\n public const uint CREATE_ALWAYS = 2;\n public const uint OPEN_EXISTING = 3;\n\n // Use interop to call the CreateFile function.\n // For more information about CreateFile,\n // see the unmanaged MSDN reference library.\n [DllImport(\"kernel32.dll\", SetLastError = true, CharSet = CharSet.Unicode)]\n private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess,\n uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,\n uint dwFlagsAndAttributes, IntPtr hTemplateFile);\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n private static extern bool ReadFile(\n IntPtr hFile, // handle to file\n byte[] lpBuffer, // data buffer\n int nNumberOfBytesToRead, // number of bytes to read\n ref int lpNumberOfBytesRead, // number of bytes read\n IntPtr lpOverlapped\n //\n // ref OVERLAPPED lpOverlapped // overlapped buffer\n );\n\n private SafeFileHandle handleValue = null;\n private FileStream _fs = null;\n\n public DeviceStream(string device)\n {\n Load(device);\n }\n\n private void Load(string Path)\n {\n if (string.IsNullOrEmpty(Path))\n {\n throw new ArgumentNullException(\"Path\");\n }\n\n // Try to open the file.\n IntPtr ptr = CreateFile(Path, GENERIC_READ, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);\n\n handleValue = new SafeFileHandle(ptr, true);\n _fs = new FileStream(handleValue, FileAccess.Read);\n\n // If the handle is invalid,\n // get the last Win32 error \n // and throw a Win32Exception.\n if (handleValue.IsInvalid)\n {\n Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());\n }\n }\n\n public override bool CanRead\n {\n get { return true; }\n }\n\n public override bool CanSeek\n {\n get { return false; }\n }\n\n public override bool CanWrite\n {\n get { return false; }\n }\n\n public override void Flush()\n {\n return;\n }\n\n public override long Length\n {\n get { return -1; }\n }\n\n public override long Position\n {\n get\n {\n throw new NotImplementedException();\n }\n set\n {\n throw new NotImplementedException();\n }\n }\n /// <summary>\n /// </summary>\n /// <param name=\"buffer\">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and \n /// (offset + count - 1) replaced by the bytes read from the current source. </param>\n /// <param name=\"offset\">The zero-based byte offset in buffer at which to begin storing the data read from the current stream. </param>\n /// <param name=\"count\">The maximum number of bytes to be read from the current stream.</param>\n /// <returns></returns>\n public override int Read(byte[] buffer, int offset, int count)\n {\n int BytesRead =0;\n var BufBytes = new byte[count];\n if (!ReadFile(handleValue.DangerousGetHandle(), BufBytes, count, ref BytesRead, IntPtr.Zero))\n {\n Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());\n }\n for (int i = 0; i < BytesRead; i++)\n {\n buffer[offset + i] = BufBytes[i];\n }\n return BytesRead;\n }\n public override int ReadByte()\n {\n int BytesRead = 0;\n var lpBuffer = new byte[1];\n if (!ReadFile(\n handleValue.DangerousGetHandle(), // handle to file\n lpBuffer, // data buffer\n 1, // number of bytes to read\n ref BytesRead, // number of bytes read\n IntPtr.Zero\n ))\n { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); ;}\n return lpBuffer[0];\n }\n\n public override long Seek(long offset, SeekOrigin origin)\n {\n throw new NotImplementedException();\n }\n\n public override void SetLength(long value)\n {\n throw new NotImplementedException();\n }\n\n public override void Write(byte[] buffer, int offset, int count)\n {\n throw new NotImplementedException();\n }\n\n public override void Close()\n {\n handleValue.Close();\n handleValue.Dispose();\n handleValue = null;\n base.Close();\n }\n private bool disposed = false;\n\n new void Dispose()\n {\n Dispose(true);\n base.Dispose();\n GC.SuppressFinalize(this);\n }\n\n private new void Dispose(bool disposing)\n {\n // Check to see if Dispose has already been called.\n if (!this.disposed)\n {\n if (disposing)\n {\n if (handleValue != null)\n {\n _fs.Dispose();\n handleValue.Close();\n handleValue.Dispose();\n handleValue = null;\n }\n }\n // Note disposing has been done.\n disposed = true;\n\n }\n }\n\n }\n}\n static void Main(string[] args)\n {\n var reader = new BinaryReader(new DeviceStream(@\"\\\\.\\PhysicalDrive3\"));\n var writer = new BinaryWriter(new FileStream(@\"g:\\test.dat\", FileMode.Create));\n var buffer = new byte[MB];\n int count;\n int loopcount=0;\n try{\n while((count=reader.Read(buffer,0,MB))>0)\n {\n writer.Write(buffer,0,count);\n System.Console.Write('.');\n if(loopcount%100==0)\n {\n System.Console.WriteLine();\n System.Console.WriteLine(\"100MB written\");\n writer.Flush();\n }\n loopcount++;\n }\n }\n catch(Exception e)\n {\n Console.WriteLine(e.Message);\n }\n reader.Close();\n writer.Flush();\n writer.Close();\n }\n"
},
{
"answer_id": 67999566,
"author": "OZone",
"author_id": 8989752,
"author_profile": "https://Stackoverflow.com/users/8989752",
"pm_score": -1,
"selected": false,
"text": "new FileStream(@\"\\\\.\\PhysicalDrive1\", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1834/"
] |
38,193 |
<p>Is there an easy way to tell if a ruby script is already running and then handle it appropriately? For example: I have a script called really_long_script.rb. I have it cronned to run every 5 minutes. When it runs, I want to see if the previous run is still running and then stop the execution of the second script. Any ideas?</p>
|
[
{
"answer_id": 38200,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 0,
"selected": false,
"text": "if ps aux | grep really_long_script.rb | grep -vq grep\nthen\n echo Script already running\nelse\n ruby really_long_script.rb\nfi\n"
},
{
"answer_id": 31044129,
"author": "John La Rooy",
"author_id": 174728,
"author_profile": "https://Stackoverflow.com/users/174728",
"pm_score": 2,
"selected": false,
"text": "gem install highlander\n require 'highlander' # This should be the -first- thing in your code.\n# Your code here\n # First attempt, works. Assume it's running in the background.\nruby your_script.rb\n\n# Second attempt while the first instance is still running, fails.\nruby your_script.rb # => RuntimeError\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4082/"
] |
38,197 |
<p>The primary class in the <code>subprocess</code> module is name <code>Popen</code>, and represents a subprocess. <code>Popen</code> sounds like someone was trying to force the name to follow some function naming format, rather than chosing a name that actually represents what the object is. Does anyone know why it was chosen over something simple like, say, <code>Subprocess</code>?</p>
|
[
{
"answer_id": 38202,
"author": "Sergio Acosta",
"author_id": 2954,
"author_profile": "https://Stackoverflow.com/users/2954",
"pm_score": -1,
"selected": false,
"text": "subprocess os os.popen"
},
{
"answer_id": 38206,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 3,
"selected": false,
"text": "subprocess.Popen os.popenX Popen Popen"
},
{
"answer_id": 38222,
"author": "Wayne Werner",
"author_id": 4080,
"author_profile": "https://Stackoverflow.com/users/4080",
"pm_score": 4,
"selected": true,
"text": "Popen Popen ProcessOpen"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1114/"
] |
38,198 |
<p><code>celsius = (5.0/9.0) * (fahr-32.0);</code></p>
<p>Is it just a development choice that the C developers decided upon or is there a reason to this? I believe a float is smaller than a double, so it might be to prevent overflows caused by not knowing what decimal format to use. Is that the reason, or am I overlooking something?</p>
|
[
{
"answer_id": 38229,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 5,
"selected": false,
"text": "celsius = (5.0/9.0) * (fahr-32.0);\n 5.0 9.0 32.0 double float F celsius = (5.0F/9.0F) * (fahr-32.0F);\n fahr double double"
},
{
"answer_id": 38234,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\nint main() {\n float celsius;\n float fahr = 212;\n printf(\"sizeof(celsius) ---------------------> %d\\n\", sizeof(celsius));\n printf(\"sizeof(fahr) ------------------------> %d\\n\", sizeof(fahr));\n printf(\"sizeof(double) ----------------------> %d\\n\", sizeof(double));\n celsius = (5.0f/9.0f) * (fahr-32.0f);\n printf(\"sizeof((5.0f/9.0f) * (fahr-32.0f)) --> %d\\n\", sizeof((5.0f/9.0f) * (fahr-32.0f)));\n printf(\"sizeof((5.0/9.0) * (fahr-32.0)) -----> %d\\n\", sizeof((5.0/9.0) * (fahr-32.0)));\n printf(\"celsius -----------------------------> %f\\n\", celsius);\n}\n sizeof(celsius) ---------------------> 4\nsizeof(fahr) ------------------------> 4\nsizeof(double) ----------------------> 8\nsizeof((5.0f/9.0f) * (fahr-32.0f)) --> 4\nsizeof((5.0/9.0) * (fahr-32.0)) -----> 8\ncelsius -----------------------------> 100.000008\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.