qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
78,181
<p>If I am given a <code>MemoryStream</code> that I know has been populated with a <code>String</code>, how do I get a <code>String</code> back out?</p>
[ { "answer_id": 78190, "author": "Brian", "author_id": 320, "author_profile": "https://Stackoverflow.com/users/320", "pm_score": 7, "selected": false, "text": "<Extension()> _\nPublic Function ReadAll(ByVal memStream As MemoryStream) As String\n ' Reset the stream otherwise you will just get an empty string.\n ' Remember the position so we can restore it later.\n Dim pos = memStream.Position\n memStream.Position = 0\n\n Dim reader As New StreamReader(memStream)\n Dim str = reader.ReadToEnd()\n\n ' Reset the position so that subsequent writes are correct.\n memStream.Position = pos\n\n Return str\nEnd Function\n" }, { "answer_id": 149993, "author": "Brian", "author_id": 320, "author_profile": "https://Stackoverflow.com/users/320", "pm_score": 10, "selected": true, "text": "Imports System.IO\n\nModule Module1\n Sub Main()\n ' We don't need to dispose any of the MemoryStream \n ' because it is a managed object. However, just for \n ' good practice, we'll close the MemoryStream.\n Using ms As New MemoryStream\n Dim sw As New StreamWriter(ms)\n sw.WriteLine(\"Hello World\")\n ' The string is currently stored in the \n ' StreamWriters buffer. Flushing the stream will \n ' force the string into the MemoryStream.\n sw.Flush()\n ' If we dispose the StreamWriter now, it will close \n ' the BaseStream (which is our MemoryStream) which \n ' will prevent us from reading from our MemoryStream\n 'sw.Dispose()\n\n ' The StreamReader will read from the current \n ' position of the MemoryStream which is currently \n ' set at the end of the string we just wrote to it. \n ' We need to set the position to 0 in order to read \n ' from the beginning.\n ms.Position = 0\n Dim sr As New StreamReader(ms)\n Dim myStr = sr.ReadToEnd()\n Console.WriteLine(myStr)\n\n ' We can dispose our StreamWriter and StreamReader \n ' now, though this isn't necessary (they don't hold \n ' any resources open on their own).\n sw.Dispose()\n sr.Dispose()\n End Using\n\n Console.WriteLine(\"Press any key to continue.\")\n Console.ReadKey()\n End Sub\nEnd Module\n" }, { "answer_id": 234262, "author": "Coderer", "author_id": 26286, "author_profile": "https://Stackoverflow.com/users/26286", "pm_score": 9, "selected": false, "text": "Encoding.ASCII.GetString(ms.ToArray());\n" }, { "answer_id": 2592074, "author": "James", "author_id": 310910, "author_profile": "https://Stackoverflow.com/users/310910", "pm_score": 3, "selected": false, "text": "Public Function ReadAll(ByVal memStream As MemoryStream, Optional ByVal startPos As Integer = 0) As String\n ' reset the stream or we'll get an empty string returned\n ' remember the position so we can restore it later\n Dim Pos = memStream.Position\n memStream.Position = startPos\n\n Dim reader As New StreamReader(memStream)\n Dim str = reader.ReadToEnd()\n\n ' reset the position so that subsequent writes are correct\n memStream.Position = Pos\n\n Return str\nEnd Function\n" }, { "answer_id": 13086317, "author": "Arek Bal", "author_id": 1749204, "author_profile": "https://Stackoverflow.com/users/1749204", "pm_score": 5, "selected": false, "text": "using(var stream = new System.IO.MemoryStream())\n{\n var serializer = new DataContractJsonSerializer(typeof(IEnumerable<ExportData>), new[]{typeof(ExportData)}, Int32.MaxValue, true, null, false); \n serializer.WriteObject(stream, model); \n\n\n var jsonString = Encoding.Default.GetString((stream.ToArray()));\n}\n" }, { "answer_id": 26559972, "author": "Mehdi Khademloo", "author_id": 4038978, "author_profile": "https://Stackoverflow.com/users/4038978", "pm_score": 5, "selected": false, "text": "ReadToEnd MemoryStream public static class SetExtensions\n{\n public static string ReadToEnd(this MemoryStream BASE)\n {\n BASE.Position = 0;\n StreamReader R = new StreamReader(BASE);\n return R.ReadToEnd();\n }\n}\n using (MemoryStream m = new MemoryStream())\n{\n //for example i want to serialize an object into MemoryStream\n //I want to use XmlSeralizer\n XmlSerializer xs = new XmlSerializer(_yourVariable.GetType());\n xs.Serialize(m, _yourVariable);\n\n //the easy way to use ReadToEnd method in MemoryStream\n MessageBox.Show(m.ReadToEnd());\n}\n" }, { "answer_id": 26892264, "author": "Alexandru", "author_id": 982639, "author_profile": "https://Stackoverflow.com/users/982639", "pm_score": 3, "selected": false, "text": "public static class MemoryStreamExtensions\n{\n\n static object streamLock = new object();\n\n public static void WriteLine(this MemoryStream stream, string text, bool flush)\n {\n byte[] bytes = Encoding.UTF8.GetBytes(text + Environment.NewLine);\n lock (streamLock)\n {\n stream.Write(bytes, 0, bytes.Length);\n if (flush)\n {\n stream.Flush();\n }\n }\n }\n\n public static void WriteLine(this MemoryStream stream, string formatString, bool flush, params string[] strings)\n {\n byte[] bytes = Encoding.UTF8.GetBytes(String.Format(formatString, strings) + Environment.NewLine);\n lock (streamLock)\n {\n stream.Write(bytes, 0, bytes.Length);\n if (flush)\n {\n stream.Flush();\n }\n }\n }\n\n public static void WriteToConsole(this MemoryStream stream)\n {\n lock (streamLock)\n {\n long temporary = stream.Position;\n stream.Position = 0;\n using (StreamReader reader = new StreamReader(stream, Encoding.UTF8, false, 0x1000, true))\n {\n string text = reader.ReadToEnd();\n if (!String.IsNullOrEmpty(text))\n {\n Console.WriteLine(text);\n }\n }\n stream.Position = temporary;\n }\n }\n}\n" }, { "answer_id": 31437966, "author": "Sebastian Ferrari", "author_id": 1231657, "author_profile": "https://Stackoverflow.com/users/1231657", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Runtime.Serialization;\nusing System.Runtime.Serialization.Json;\nusing System.Threading;\n\nnamespace JsonSample\n{\n class Program\n {\n static void Main(string[] args)\n {\n var phones = new List<Phone>\n {\n new Phone { Type = PhoneTypes.Home, Number = \"28736127\" },\n new Phone { Type = PhoneTypes.Movil, Number = \"842736487\" }\n };\n var p = new Person { Id = 1, Name = \"Person 1\", BirthDate = DateTime.Now, Phones = phones };\n\n Console.WriteLine(\"New object 'Person' in the server side:\");\n Console.WriteLine(string.Format(\"Id: {0}, Name: {1}, Birthday: {2}.\", p.Id, p.Name, p.BirthDate.ToShortDateString()));\n Console.WriteLine(string.Format(\"Phone: {0} {1}\", p.Phones[0].Type.ToString(), p.Phones[0].Number));\n Console.WriteLine(string.Format(\"Phone: {0} {1}\", p.Phones[1].Type.ToString(), p.Phones[1].Number));\n\n Console.Write(Environment.NewLine);\n Thread.Sleep(2000);\n\n var stream1 = new MemoryStream();\n var ser = new DataContractJsonSerializer(typeof(Person));\n\n ser.WriteObject(stream1, p);\n\n stream1.Position = 0;\n StreamReader sr = new StreamReader(stream1);\n Console.Write(\"JSON form of Person object: \");\n Console.WriteLine(sr.ReadToEnd());\n\n Console.Write(Environment.NewLine);\n Thread.Sleep(2000);\n\n var f = GetStringFromMemoryStream(stream1);\n\n Console.Write(Environment.NewLine);\n Thread.Sleep(2000);\n\n Console.WriteLine(\"Passing string parameter from server to client...\");\n\n Console.Write(Environment.NewLine);\n Thread.Sleep(2000);\n\n var g = GetMemoryStreamFromString(f);\n g.Position = 0;\n var ser2 = new DataContractJsonSerializer(typeof(Person));\n var p2 = (Person)ser2.ReadObject(g);\n\n Console.Write(Environment.NewLine);\n Thread.Sleep(2000);\n\n Console.WriteLine(\"New object 'Person' arrived to the client:\");\n Console.WriteLine(string.Format(\"Id: {0}, Name: {1}, Birthday: {2}.\", p2.Id, p2.Name, p2.BirthDate.ToShortDateString()));\n Console.WriteLine(string.Format(\"Phone: {0} {1}\", p2.Phones[0].Type.ToString(), p2.Phones[0].Number));\n Console.WriteLine(string.Format(\"Phone: {0} {1}\", p2.Phones[1].Type.ToString(), p2.Phones[1].Number));\n\n Console.Read();\n }\n\n private static MemoryStream GetMemoryStreamFromString(string s)\n {\n var stream = new MemoryStream();\n var sw = new StreamWriter(stream);\n sw.Write(s);\n sw.Flush();\n stream.Position = 0;\n return stream;\n }\n\n private static string GetStringFromMemoryStream(MemoryStream ms)\n {\n ms.Position = 0;\n using (StreamReader sr = new StreamReader(ms))\n {\n return sr.ReadToEnd();\n }\n }\n }\n\n [DataContract]\n internal class Person\n {\n [DataMember]\n public int Id { get; set; }\n [DataMember]\n public string Name { get; set; }\n [DataMember]\n public DateTime BirthDate { get; set; }\n [DataMember]\n public List<Phone> Phones { get; set; }\n }\n\n [DataContract]\n internal class Phone\n {\n [DataMember]\n public PhoneTypes Type { get; set; }\n [DataMember]\n public string Number { get; set; }\n }\n\n internal enum PhoneTypes\n {\n Home = 1,\n Movil = 2\n }\n}\n" }, { "answer_id": 43770727, "author": "Sadjad Khazaie", "author_id": 2116150, "author_profile": "https://Stackoverflow.com/users/2116150", "pm_score": 5, "selected": false, "text": "byte[] array = Encoding.ASCII.GetBytes(\"MyTest1 - MyTest2\");\nMemoryStream streamItem = new MemoryStream(array);\n\n// convert to string\nStreamReader reader = new StreamReader(streamItem);\nstring text = reader.ReadToEnd();\n" }, { "answer_id": 61205864, "author": "Riccardo Bassilichi", "author_id": 218415, "author_profile": "https://Stackoverflow.com/users/218415", "pm_score": 1, "selected": false, "text": "XmlSchema schema;\n// ... Use \"schema\" ...\n\nvar ret = \"\";\n\nusing (var ms = new MemoryStream())\n{\n schema.Write(ms);\n ret = Encoding.ASCII.GetString(ms.ToArray());\n}\n//here you can use \"ret\"\n// 6 Lines of code\n public static class MemoryStreamStringWrapper\n{\n public static string Write(Action<MemoryStream> action)\n {\n var ret = \"\";\n using (var ms = new MemoryStream())\n {\n action(ms);\n ret = Encoding.ASCII.GetString(ms.ToArray());\n }\n\n return ret;\n }\n}\n var ret = MemoryStreamStringWrapper.Write(schema.Write);\n" }, { "answer_id": 65290459, "author": "Harlin Acero", "author_id": 8921881, "author_profile": "https://Stackoverflow.com/users/8921881", "pm_score": -1, "selected": false, "text": "Convert.ToBase64String(inputStream.ToArray());\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/320/" ]
78,184
<p>I'm a beginning C++ programmer / network admin, but I figure I can learn how to do this if someone points me in the right direction. Most of the tutorials are demonstrated using old code that no longer works for some reason. </p> <p>Since I'm on Linux, all I need is an explanation on how to write raw Berkeley sockets. Can someone give me a quick run down?</p>
[ { "answer_id": 78209, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "#include <sys/socket.h>\n#include <sys/types.h>\n\nint socket(int protocolFamily, int Type, int Protocol)\n// returns a socket descriptor\n\nint bind(int socketDescriptor, struct sockaddr* localAddress, unsigned int addressLength)\n// returns 0 \n" }, { "answer_id": 78251, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 3, "selected": false, "text": "hostent *host = gethostbyname(HOSTNAME_CSTR);\n sockaddr_in sock;\nsock.sin_family = AF_INET;\nsock.sin_port = htons(REMOTE_PORT);\nsock.sin_addr.s_addr = ((struct in_addr *)(host->h_addr))->s_addr;\n s = socket(AF_INET, SOCK_STREAM, 0); \nconnect(s, (struct sockaddr *)&sock, sizeof(sock))\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
78,230
<p>I am just getting started with flex and am using the SDK (not Flex Builder). I was wondering what's the best way to compile a mxml file from an ant build script. </p>
[ { "answer_id": 222331, "author": "jgormley", "author_id": 29738, "author_profile": "https://Stackoverflow.com/users/29738", "pm_score": 3, "selected": false, "text": "<?xml version=\"1.0\"?>\n\n<project name=\"flexapptest\" default=\"buildAndRun\" basedir=\".\">\n\n <!-- \n make sure this jar file is in the ant lib directory \n classpath=\"${ANT_HOME}/lib/flexTasks.jar\" \n -->\n <taskdef resource=\"flexTasks.tasks\" />\n <property name=\"appname\" value=\"flexapptest\"/>\n <property name=\"appname_main\" value=\"Flexapptest\"/>\n <property name=\"FLEX_HOME\" value=\"/Applications/flex_sdk_3\"/>\n <property name=\"APP_ROOT\" value=\".\"/>\n <property name=\"swfOut\" value=\"dist/${appname}.swf\" />\n <!-- point this to your local copy of the flash player -->\n <property name=\"flash.player\" location=\"/Applications/Adobe Flash CS3/Players/Flash Player.app\" />\n\n <target name=\"compile\">\n <mxmlc file=\"${APP_ROOT}/src/${appname_main}.mxml\"\n output=\"${APP_ROOT}/${swfOut}\" \n keep-generated-actionscript=\"true\">\n\n <default-size width=\"800\" height=\"600\" />\n <load-config filename=\"${FLEX_HOME}/frameworks/flex-config.xml\"/>\n <source-path path-element=\"${FLEX_HOME}/frameworks\"/>\n <compiler.library-path dir=\"${APP_ROOT}/libs\" append=\"true\">\n <include name=\"*.swc\" />\n </compiler.library-path>\n </mxmlc>\n </target>\n\n <target name=\"buildAndRun\" depends=\"compile\">\n <exec executable=\"open\">\n <arg line=\"-a '${flash.player}'\"/>\n <arg line=\"${APP_ROOT}/${swfOut}\" />\n </exec>\n </target>\n\n <target name=\"clean\">\n <delete dir=\"${APP_ROOT}/src/generated\"/>\n <delete file=\"${APP_ROOT}/${swfOut}\"/>\n </target>\n\n</project>\n" }, { "answer_id": 1670928, "author": "Luke Bayes", "author_id": 105023, "author_profile": "https://Stackoverflow.com/users/105023", "pm_score": 2, "selected": false, "text": "require 'rubygems'\nrequire 'sprout'\n\ndesc 'Compile and run the SWF'\nflashplayer :run => 'bin/SomeProject.swf'\n\nmxmlc 'bin/SomeProject.swf' do |t|\n t.input = 'src/SomeProject.as'\n t.default_size = '800 600'\n t.default_background_color = '#ffffff'\n t.keep_generated_actionscript = true\n t.library_path << 'libs'\nend\n\ntask :default => :run\n rake\n rake clean\n rake -T\n # Generate a project and cd into it:\nsprout -n mxml SomeProject\ncd SomeProject\n\n# Compile and run the main debug SWF:\nrake\n\n# Generate a new class, test case and test suite:\nscript/generate class utils.MathUtil\n\n# Compile and run the test harness:\nrake test\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
78,233
<p>I have a dataset that I have modified into an xml document and then used a xsl sheet to transform into an Excel xml format in order to allow the data to be opened programatically from my application. I have run into two problems with this:</p> <ol> <li><p>Excel is not the default Windows application to open Excel files, therefore when Program.Start("xmlfilename.xml") is run, IE is opened and the XML file is not very readable.</p></li> <li><p>If you rename the file to .xlsx, you receive a warning, "This is not an excel file, do you wish to continue". This is not ideal for customers.</p></li> </ol> <p>Ideally, I would like Windows to open the file in Excel without modifying the default OS setting for opening Excel files. Office interop is a possibility, but seems like a little overkill for this application. Does anyone have any ideas to make this work?</p> <p>The solution is in .Net/C#, but I am open to other possibilities to create a clean solution.</p>
[ { "answer_id": 78292, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 2, "selected": true, "text": "Process.Start(@\"C:\\Program Files\\Microsoft Office\\Officexx\\excel.exe\", \"yourfile.xml\");\n" }, { "answer_id": 82799, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 2, "selected": false, "text": "<?mso-application progid=\"Excel.Sheet\"?>\n" }, { "answer_id": 15773216, "author": "aked", "author_id": 1060656, "author_profile": "https://Stackoverflow.com/users/1060656", "pm_score": 0, "selected": false, "text": "using Excel = Microsoft.Office.Interop.Excel;\n\nstring workbookPath= @\"C:\\temp\\Results_2013Apr02_110133_6692.xml\";\n\n this.lblResultFile.Text = string.Format(@\" File:{0}\",workbookPath);\n if (File.Exists(workbookPath))\n {\n Excel.Application excelApp = new Excel.Application();\n excelApp.Visible = true;\n Excel.Workbook excelWorkbook = excelApp.Workbooks.OpenXML(workbookPath, Type.Missing, Excel.XlXmlLoadOption.xlXmlLoadPromptUser);\n }\n else\n {\n MessageBox.Show(String.Format(\"File:{0} does not exists\", workbookPath));\n }\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2916/" ]
78,277
<p>When can 64-bit writes be guaranteed to be atomic, when programming in C on an Intel x86-based platform (in particular, an Intel-based Mac running MacOSX 10.4 using the Intel compiler)? For example:</p> <pre><code>unsigned long long int y; y = 0xfedcba87654321ULL; /* ... a bunch of other time-consuming stuff happens... */ y = 0x12345678abcdefULL; </code></pre> <p>If another thread is examining the value of y after the first assignment to y has finished executing, I would like to ensure that it sees either the value 0xfedcba87654321 or the value 0x12345678abcdef, and not some blend of them. I would like to do this without any locking, and if possible without any extra code. My hope is that, when using a 64-bit compiler (the 64-bit Intel compiler), on an operating system capable of supporting 64-bit code (MacOSX 10.4), that these 64-bit writes will be atomic. Is this always true?</p>
[ { "answer_id": 78383, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 5, "selected": false, "text": "NOP volatile" }, { "answer_id": 78399, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 4, "selected": false, "text": "volatile" }, { "answer_id": 78439, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "#include <libkern/OSAtomic.h>\n// bool OSAtomicCompareAndSwap64Barrier(int64_t oldValue, int64_t newValue, int64_t *theValue);\n\nvoid AtomicSet(uint64_t *target, uint64_t new_value)\n{\n while (true)\n {\n uint64_t old_value = *target;\n if (OSAtomicCompareAndSwap64Barrier(old_value, new_value, target)) return;\n }\n}\n\nuint64_t AtomicGet(uint64_t *target)\n{\n while (true)\n {\n int64 value = *target;\n if (OSAtomicCompareAndSwap64Barrier(value, value, target)) return value;\n }\n}\n if (*theValue != oldValue) return false;\n*theValue = newValue;\nreturn true;\n" }, { "answer_id": 29480621, "author": "Jeff Hammond", "author_id": 2189128, "author_profile": "https://Stackoverflow.com/users/2189128", "pm_score": 2, "selected": false, "text": "atomic_store(_explicit)" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
78,278
<p>How do I write a clean implementation of the strategy pattern in Perl? I want to do it in a way that leverages Perl's features.</p>
[ { "answer_id": 78301, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "sort { lc($a) cmp lc($b) } @items\n" }, { "answer_id": 83715, "author": "tsee", "author_id": 13164, "author_profile": "https://Stackoverflow.com/users/13164", "pm_score": 4, "selected": true, "text": "sort { lc($a) cmp lc($b) } @items\n package StrategyInterface;\nuse Moose::Role;\nrequires 'run';\n\n\npackage Context;\nuse Moose;\nhas 'strategy' => (\n is => 'rw',\n isa => 'StrategyInterface',\n handles => [ 'run' ],\n);\n\n\npackage SomeStrategy;\nuse Moose;\nwith 'StrategyInterface';\nsub run { warn \"applying SomeStrategy!\\n\"; }\n\n\npackage AnotherStrategy;\nuse Moose;\nwith 'StrategyInterface';\nsub run { warn \"applying AnotherStrategy!\\n\"; }\n\n\n###############\npackage main;\nmy $contextOne = Context->new(\n strategy => SomeStrategy->new()\n);\n\nmy $contextTwo = Context->new(\n strategy => AnotherStrategy->new()\n);\n\n$contextOne->run();\n$contextTwo->run();\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
78,296
<p>What are some reasons why PHP would force errors to show, no matter what you tell it to disable?</p> <p>I have tried </p> <pre><code>error_reporting(0); ini_set('display_errors', 0); </code></pre> <p>with no luck.</p>
[ { "answer_id": 17019832, "author": "komodosp", "author_id": 1495940, "author_profile": "https://Stackoverflow.com/users/1495940", "pm_score": 1, "selected": false, "text": "set_error_handler() error_reporting(0)" }, { "answer_id": 34137690, "author": "ob-ivan", "author_id": 2184166, "author_profile": "https://Stackoverflow.com/users/2184166", "pm_score": 0, "selected": false, "text": "php -l YOUR_FILE_HERE.php\n PHP Parse error: syntax error, unexpected '}' in Connection.class.php on line 31\n" }, { "answer_id": 47844586, "author": "dheerendra", "author_id": 7879171, "author_profile": "https://Stackoverflow.com/users/7879171", "pm_score": 0, "selected": false, "text": "ini_set('display_errors', False);\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14322/" ]
78,303
<p>I'm toying with my first remoting project and I need to create a RemotableType DLL. I know I can compile it by hand with csc, but I wonder if there are some facilities in place on Visual Studio to handle the Remoting case, or, more specificly, to tell it that a specific file should be compiled as a .dll without having to add another project to a solution exclusively to compile a class or two into DLLs. </p> <p>NOTE: I know I should toy with my first WCF project, but this has to run on 2.0.</p>
[ { "answer_id": 17019832, "author": "komodosp", "author_id": 1495940, "author_profile": "https://Stackoverflow.com/users/1495940", "pm_score": 1, "selected": false, "text": "set_error_handler() error_reporting(0)" }, { "answer_id": 34137690, "author": "ob-ivan", "author_id": 2184166, "author_profile": "https://Stackoverflow.com/users/2184166", "pm_score": 0, "selected": false, "text": "php -l YOUR_FILE_HERE.php\n PHP Parse error: syntax error, unexpected '}' in Connection.class.php on line 31\n" }, { "answer_id": 47844586, "author": "dheerendra", "author_id": 7879171, "author_profile": "https://Stackoverflow.com/users/7879171", "pm_score": 0, "selected": false, "text": "ini_set('display_errors', False);\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5190/" ]
78,336
<p>I need to figure out the hard drive name for a solaris box and it is not clear to me what the device name is. On linux, it would be something like <code>/dev/hda</code> or <code>/dev/sda</code>, but on solaris I am getting a bit lost in the partitions and what the device is called. I think that entries like <code>/dev/rdsk/c0t0d0s0</code> are the partitions, how is the whole hard drive referenced?</p>
[ { "answer_id": 8568676, "author": "jlliagre", "author_id": 211665, "author_profile": "https://Stackoverflow.com/users/211665", "pm_score": 2, "selected": false, "text": "c0t0d0s2 c0t0d0p0 s2" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13912/" ]
78,389
<p>I'm new to RhinoMocks, and trying to get a grasp on the syntax in addition to what is happening under the hood.</p> <p>I have a user object, we'll call it User, which has a property called IsAdministrator. The value for IsAdministrator is evaluated via another class that checks the User's security permissions, and returns either true or false based on those permissions. I'm trying to mock this User class, and fake the return value for IsAdministrator in order to isolate some Unit Tests.</p> <p>This is what I'm doing so far:</p> <pre><code>public void CreateSomethingIfUserHasAdminPermissions() { User user = _mocks.StrictMock&lt;User&gt;(); SetupResult.For(user.IsAdministrator).Return(true); // do something with my User object } </code></pre> <p>Now, I'm expecting that Rhino is going to 'fake' the call to the property getter, and just return true to me. Is this incorrect? Currently I'm getting an exception because of dependencies in the IsAdministrator property.</p> <p>Can someone explain how I can achieve my goal here?</p>
[ { "answer_id": 79719, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 5, "selected": true, "text": "public class FakeUserType: User\n{\n //overriding code here\n}\n public class User\n{\n public virtual Boolean IsAdministrator { get; set; }\n}\n public interface IUser\n{\n Boolean IsAdministrator { get; }\n}\n\npublic class User : IUser\n{\n private UserSecurity _userSecurity = new UserSecurity();\n\n public Boolean IsAdministrator\n {\n get { return _userSecurity.HasAccess(\"AdminPermissions\"); }\n }\n}\n\npublic void CreateSomethingIfUserHasAdminPermissions()\n{\n IUser user = _mocks.StrictMock<IUser>();\n SetupResult.For(user.IsAdministrator).Return(true);\n\n // do something with my User object\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769/" ]
78,392
<p>I have an application that works pretty well in Ubuntu, Windows and the Xandros that come with the Asus EeePC.</p> <p>Now we are moving to the <a href="http://en.wikipedia.org/wiki/Aspire_One" rel="nofollow noreferrer">Acer Aspire One</a> but I'm having a lot of trouble making php-gtk to compile under the Fedora-like (Linpus Linux Lite) Linux that come with it.</p>
[ { "answer_id": 99021, "author": "levhita", "author_id": 7946, "author_profile": "https://Stackoverflow.com/users/7946", "pm_score": 2, "selected": true, "text": "#!/bin/bash\nsudo yum install yum-utils\n#We don't want to update the main gtk2 by mistake so we download them\n#manually and install with no-deps[1](and forced because gtk version\n#version of AA1 and the gtk2-devel aren't compatible).\nsudo yumdownloader --disablerepo=updates gtk2-devel glib2-devel\nsudo rpm --force --nodeps -i gtk2*rpm glib2*rpm\n\n#We install the rest of the libraries needed.\nsudo yum --disablerepo=updates install atk-devel pango-devel libglade2-devel\nsudo yum install php-cli php-devel make gcc\n\n#We Download and compile php-gtk\nwget http://gtk.php.net/do_download.php?download_file=php-gtk-2.0.1.tar.gz\ntar -xvzf php-gtk-2.0.1.tar.gz\ncd php-gtk-2.0.1\n./buildconf\n./configure\nmake\nsudo make install\n ./configure -help php_gtk2.so /etc/php.ini extension=php_gtk2.so\n" }, { "answer_id": 4031145, "author": "Valent Turkovic", "author_id": 488518, "author_profile": "https://Stackoverflow.com/users/488518", "pm_score": 2, "selected": false, "text": "# phoronix-test-suite gui\nshell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory\npwd: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory\npwd: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory\n/usr/bin/phoronix-test-suite: line 28: [: /usr/share/phoronix-test-suite: unary operator expected\n su -c \"yum install php-cli php-devel make gcc gtk2-devel svn\"\n\nsvn co http://svn.php.net/repository/pecl/cairo/trunk pecl-cairo\ncd pecl-cairo/\nphpize\n./configure\nmake\nsu -c \"make install\"\n\ncd ..\n\nsvn co http://svn.php.net/repository/gtk/php-gtk/trunk php-gtk\ncd php-gtk\n./buildconf\n./configure\nmake\nsu -c \"make install\"\n\ncd ..\n\nwget http://www.phoronix-test-suite.com/download.php?file=phoronix-test-suite-2.8.1\ntar xvzf phoronix-test-suite-2.8.1.tar.gz\ncd phoronix-test-suite\nsu -c \"./install-sh\"\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7946/" ]
78,431
<p>I would like to replicate this in python:</p> <pre><code>gvimdiff &lt;(hg cat file.txt) file.txt </code></pre> <p>(hg cat file.txt outputs the most recently committed version of file.txt)</p> <p>I know how to pipe the file to gvimdiff, but it won't accept another file:</p> <pre><code>$ hg cat file.txt | gvimdiff file.txt - Too many edit arguments: "-" </code></pre> <p>Getting to the python part...</p> <pre><code># hgdiff.py import subprocess import sys file = sys.argv[1] subprocess.call(["gvimdiff", "&lt;(hg cat %s)" % file, file]) </code></pre> <p>When subprocess is called it merely passes <code>&lt;(hg cat file)</code> onto <code>gvimdiff</code> as a filename.</p> <p>So, is there any way to redirect a command as bash does? For simplicity's sake just cat a file and redirect it to diff:</p> <pre><code>diff &lt;(cat file.txt) file.txt </code></pre>
[ { "answer_id": 78459, "author": "Mark Hattarki", "author_id": 14424, "author_profile": "https://Stackoverflow.com/users/14424", "pm_score": 2, "selected": false, "text": "import commands\n\nstatus, output = commands.getstatusoutput(\"gvimdiff <(hg cat file.txt) file.txt\")\n" }, { "answer_id": 78482, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 4, "selected": true, "text": "import subprocess\nimport sys\n\nfile = sys.argv[1]\np1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE)\np2 = subprocess.Popen([\n 'gvimdiff',\n '/proc/self/fd/%s' % p1.stdout.fileno(),\n file])\np2.wait()\n file = sys.argv[1]\np1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE)\np2 = subprocess.Popen(['diff', '-', file], stdin=p1.stdout)\ndiff_text = p2.communicate()[0]\n" }, { "answer_id": 78923, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 2, "selected": false, "text": "p1 = Popen([\"dmesg\"], stdout=PIPE)\np2 = Popen([\"grep\", \"hda\"], stdin=p1.stdout, stdout=PIPE)\noutput = p2.communicate()[0]\n import subprocess\nimport sys\n\nfile = sys.argv[1]\np1 = Popen([\"hg\", \"cat\", file], stdout=PIPE)\np2 = Popen([\"gvimdiff\", \"file.txt\"], stdin=p1.stdout, stdout=PIPE)\noutput = p2.communicate()[0]\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12650/" ]
78,447
<p>How to create a DOM from a User's input in PHP5?</p>
[ { "answer_id": 78465, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 2, "selected": false, "text": "$dom = new DOMDocument();\n$dom->loadXML($xml);\n" }, { "answer_id": 89750, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "$xml = $dom->saveXML();\n$xml = substr( $xml, strlen( \"<?xml version=\\\"1.0\\\"?>\" ) );\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12854/" ]
78,450
<p>I'm trying to use Python with ReportLab 2.2 to create a PDF report.<br> According to the <a href="http://www.reportlab.com/docs/userguide.pdf" rel="noreferrer">user guide</a>,</p> <blockquote> <p>Special TableStyle Indeces [sic]</p> <p>In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation. This allows splitting tables with nicer effects around the split.</p> </blockquote> <p>I've tried using several style elements, including:</p> <pre><code>('TEXTCOLOR', (0, 'splitfirst'), (1, 'splitfirst'), colors.black) ('TEXTCOLOR', (0, 'splitfirst'), (1, 0), colors.black) ('TEXTCOLOR', (0, 'splitfirst'), (1, -1), colors.black) </code></pre> <p>and none of these seems to work. The first generates a TypeError with the message: </p> <pre><code>TypeError: cannot concatenate 'str' and 'int' objects </code></pre> <p>and the latter two generate TypeErrors with the message:</p> <pre><code>TypeError: an integer is required </code></pre> <p>Is this functionality simply broken or am I doing something wrong? If the latter, what am I doing wrong?</p>
[ { "answer_id": 94869, "author": "DLJessup", "author_id": 14382, "author_profile": "https://Stackoverflow.com/users/14382", "pm_score": 2, "selected": false, "text": "class XTable(Table):\n def onSplit(self, T, byRow=1):\n T.setStyle(TableStyle([\n ('TEXTCOLOR', (0, 1), (1, 1), colors.black)]))\n" }, { "answer_id": 2623783, "author": "Robin Macharg", "author_id": 314737, "author_profile": "https://Stackoverflow.com/users/314737", "pm_score": 1, "selected": false, "text": "Table._drawBkgrnd() y0 = rowpositions[sr]\n if sr == 'splitlast':\n y0 = rowpositions[-2] # last value is 0. Second last is the one we want.\nelse:\n y0 = rowpositions[sr]\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14382/" ]
78,468
<p>I am trying to understand left outer joins in LINQ to Entity. For example I have the following 3 tables:</p> <p>Company, CompanyProduct, Product</p> <p>The CompanyProduct is linked to its two parent tables, Company and Product.</p> <p>I want to return all of the Company records and the associated CompanyProduct whether the CompanyProduct exists or not for a given product. In Transact SQL I would go from the Company table using left outer joins as follows: </p> <pre><code>SELECT * FROM Company AS C LEFT OUTER JOIN CompanyProduct AS CP ON C.CompanyID=CP.CompanyID LEFT OUTER JOIN Product AS P ON CP.ProductID=P.ProductID WHERE P.ProductID = 14 OR P.ProductID IS NULL </code></pre> <p>My database has 3 companies, and 2 CompanyProduct records assocaited with the ProductID of 14. So the results from the SQL query are the expected 3 rows, 2 of which are connected to a CompanyProduct and Product and 1 which simply has the Company table and nulls in the CompanyProduct and Product tables. </p> <p>So how do you write the same kind of join in LINQ to Entity to acheive a similiar result? </p> <p>I have tried a few different things but can't get the syntax correct.</p> <p>Thanks.</p>
[ { "answer_id": 78714, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": 0, "selected": false, "text": "from s in db.Employees\njoin e in db.Employees on s.ReportsTo equals e.EmployeeId\njoin er in EmployeeRoles on s.EmployeeId equals er.EmployeeId\njoin r in Roles on er.RoleId equals r.RoleId\nwhere e.EmployeeId == employeeId &&\ner.Status == (int)DocumentStatus.Draft\nselect s;\n" }, { "answer_id": 175482, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 0, "selected": false, "text": "from s in db.Employees\nwhere s.Product == null || s.Product.ProductID == 14\nselect s;\n" }, { "answer_id": 175636, "author": "KyleLanser", "author_id": 12923, "author_profile": "https://Stackoverflow.com/users/12923", "pm_score": 4, "selected": false, "text": "theCompany.id: 1 \ntheProduct.id: 14 \ntheCompany.id: 2 \ntheProduct.id: 14 \ntheCompany.id: 3 \n --Company Table\nCREATE TABLE [theCompany](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [value] [nvarchar](50) NULL,\n CONSTRAINT [PK_theCompany] PRIMARY KEY CLUSTERED \n( [id] ASC ) WITH (\n PAD_INDEX = OFF, \n STATISTICS_NORECOMPUTE = OFF, \n IGNORE_DUP_KEY = OFF, \n ALLOW_ROW_LOCKS = ON, \n ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY];\nGO\n\n\n--Products Table\nCREATE TABLE [theProduct](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [value] [nvarchar](50) NULL,\n CONSTRAINT [PK_theProduct] PRIMARY KEY CLUSTERED \n( [id] ASC\n) WITH ( \n PAD_INDEX = OFF, \n STATISTICS_NORECOMPUTE = OFF, \n IGNORE_DUP_KEY = OFF, \n ALLOW_ROW_LOCKS = ON, \n ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY];\nGO\n\n\n--CompanyProduct Table\nCREATE TABLE [dbo].[CompanyProduct](\n [fk_company] [int] NOT NULL,\n [fk_product] [int] NOT NULL\n) ON [PRIMARY]; \nGO\n\nALTER TABLE [CompanyProduct] WITH CHECK ADD CONSTRAINT\n [FK_CompanyProduct_theCompany] FOREIGN KEY([fk_company]) \n REFERENCES [theCompany] ([id]);\nGO\n\nALTER TABLE [dbo].[CompanyProduct] CHECK CONSTRAINT \n [FK_CompanyProduct_theCompany];\nGO\n\nALTER TABLE [CompanyProduct] WITH CHECK ADD CONSTRAINT \n [FK_CompanyProduct_theProduct] FOREIGN KEY([fk_product]) \n REFERENCES [dbo].[theProduct] ([id]);\nGO\n\nALTER TABLE [dbo].[CompanyProduct] CHECK CONSTRAINT \n [FK_CompanyProduct_theProduct];\n SELECT [id] ,[value] FROM theCompany\nid value\n----------- --------------------------------------------------\n1 company1\n2 company2\n3 company3\n\nSELECT [id] ,[value] FROM theProduct\nid value\n----------- --------------------------------------------------\n14 Product 1\n\n\nSELECT [fk_company],[fk_product] FROM CompanyProduct;\nfk_company fk_product\n----------- -----------\n1 14\n2 14\n testEntities entity = new testEntities();\n\nvar theResultSet = from c in entity.theCompany\nselect new { company_id = c.id, product_id = c.theProduct.Select(e=>e) };\n\nforeach(var oneCompany in theResultSet)\n{\n Debug.WriteLine(\"theCompany.id: \" + oneCompany.company_id);\n foreach(var allProducts in oneCompany.product_id)\n {\n Debug.WriteLine(\"theProduct.id: \" + allProducts.id);\n }\n}\n theCompany.id: 1 \ntheProduct.id: 14 \ntheCompany.id: 2 \ntheProduct.id: 14 \ntheCompany.id: 3 \n" }, { "answer_id": 1511650, "author": "StriplingWarrior", "author_id": 120955, "author_profile": "https://Stackoverflow.com/users/120955", "pm_score": 3, "selected": false, "text": "var query = from p in Database.ProductSet\n where p.ProductId == 14\n from c in p.Companies\n select c;\n var query = Database.CompanySet\n .Where(c => c.Products.Any(p => p.ProductId == 14));\n var query = from p in Database.ProductSet\n where p.ProductId == 14\n select new\n {\n Product = p,\n Companies = p.Companies\n };\n" }, { "answer_id": 3529660, "author": "Martin", "author_id": 426177, "author_profile": "https://Stackoverflow.com/users/426177", "pm_score": 1, "selected": false, "text": "var list = from a in _datasource.table1\n join b in _datasource.table2\n on a.id equals b.table1.id\n into ab\n where ab.Count()==0\n select new { table1 = a, \n table2Count = ab.Count() };\n table1 table2 where table1" }, { "answer_id": 5351728, "author": "Deepak ", "author_id": 665993, "author_profile": "https://Stackoverflow.com/users/665993", "pm_score": 3, "selected": false, "text": "var query = from t1 in db.table1\n join t2 in db.table2\n on t1.Field1 equals t2.field1 into T1andT2\n from t2Join in T1andT2.DefaultIfEmpty()\n\n\n join t3 in db.table3\n on t2Join.Field2 equals t3.Field3 into T2andT3\n from t3Join in T2andT3.DefaultIfEmpty()\n where t1.someField = \"Some value\" \n select \n {\n t2Join.FieldXXX\n t3Join.FieldYYY\n\n\n };\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
78,471
<p>How can I find out the date a MS SQL Server 2000 object was last modified?</p> <p>I need to get a list of all the views, procs, functions etc that were modified since Aug 15th. In sysObjects I can see the date objects were created but I need to know when they were last altered.</p> <p>NB: this is an SQL 2000 database.</p>
[ { "answer_id": 2342967, "author": "Allov", "author_id": 130480, "author_profile": "https://Stackoverflow.com/users/130480", "pm_score": 4, "selected": false, "text": "USE [Your_DB] \nSELECT * FROM INFORMATION_SCHEMA.ROUTINES\n" }, { "answer_id": 22472528, "author": "Sudhir v. Usnale", "author_id": 3431963, "author_profile": "https://Stackoverflow.com/users/3431963", "pm_score": 3, "selected": false, "text": "SELECT name, create_date, modify_date \nFROM sys.objects\nWHERE type = 'p' \n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10422/" ]
78,474
<p>Using only ANSI C, what is the best way to, with fair certainty, determine if a C style string is either a integer or a real number (i.e float/double)?</p>
[ { "answer_id": 78485, "author": "nutbar", "author_id": 14425, "author_profile": "https://Stackoverflow.com/users/14425", "pm_score": 2, "selected": false, "text": "." }, { "answer_id": 78565, "author": "Patrick_O", "author_id": 11084, "author_profile": "https://Stackoverflow.com/users/11084", "pm_score": 6, "selected": true, "text": "#include <errno.h>\n\nchar* to_convert = \"some string\";\nchar* p = to_convert;\nerrno = 0;\nunsigned long val = strtoul(to_convert, &p, 10);\nif (errno != 0)\n // conversion failed (EINVAL, ERANGE)\nif (to_convert == p)\n // conversion failed (no characters consumed)\nif (*p != 0)\n // conversion failed (trailing data)\n" }, { "answer_id": 78580, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 3, "selected": false, "text": "int i;\nfloat f;\nif(sscanf(str, \"%d\", &i) != 0) //It's an int.\n ...\nif(sscanf(str \"%f\", &f) != 0) //It's a float.\n ...\n" }, { "answer_id": 21791935, "author": "Katie", "author_id": 3312224, "author_profile": "https://Stackoverflow.com/users/3312224", "pm_score": 0, "selected": false, "text": "if(atof(token) != NULL || strcmp(token, \"0\") == 0)\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9418/" ]
78,493
<p>I once read that one way to obtain a unique filename in a shell for temp files was to use a double dollar sign (<code>$$</code>). This does produce a number that varies from time to time... but if you call it repeatedly, it returns the same number. (The solution is to just use the time.)</p> <p>I am curious to know what <code>$$</code> actually is, and why it would be suggested as a way to generate unique filenames.</p>
[ { "answer_id": 78504, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 8, "selected": true, "text": "$$ mktemp" }, { "answer_id": 78546, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "trap \"echo 'Cleanup in progress'; rm -r $TMP_DIR\" EXIT\n" }, { "answer_id": 78581, "author": "emk", "author_id": 12089, "author_profile": "https://Stackoverflow.com/users/12089", "pm_score": 7, "selected": false, "text": "$$ $$ mktemp tempfoo=`basename $0`\nTMPFILE=`mktemp -t ${tempfoo}` || exit 1\necho \"program output\" >> $TMPFILE\n" }, { "answer_id": 78667, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 2, "selected": false, "text": " -k\n" }, { "answer_id": 48744969, "author": "Obivan", "author_id": 5444646, "author_profile": "https://Stackoverflow.com/users/5444646", "pm_score": 0, "selected": false, "text": "echo $(</proc/$$/login id). After that, you need to use getent command.\n" }, { "answer_id": 64850457, "author": "Édouard Lopez", "author_id": 802365, "author_profile": "https://Stackoverflow.com/users/802365", "pm_score": 1, "selected": false, "text": "3.1.2 $ set bar bazz\nset foo bar\necho $foo # bar\necho $$foo # same as echo $bar → bazz\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14345/" ]
78,497
<p>Does anyone know of any resources that talk about best practices or design patterns for shell scripts (sh, bash etc.)?</p>
[ { "answer_id": 739034, "author": "Stefano Borini", "author_id": 78374, "author_profile": "https://Stackoverflow.com/users/78374", "pm_score": 9, "selected": true, "text": "CommandLineOptions__config_file=\"\"\nCommandLineOptions__debug_level=\"\"\n\ngetopt_results=`getopt -s bash -o c:d:: --long config_file:,debug_level:: -- \"$@\"`\n\nif test $? != 0\nthen\n echo \"unrecognized option\"\n exit 1\nfi\n\neval set -- \"$getopt_results\"\n\nwhile true\ndo\n case \"$1\" in\n --config_file)\n CommandLineOptions__config_file=\"$2\";\n shift 2;\n ;;\n --debug_level)\n CommandLineOptions__debug_level=\"$2\";\n shift 2;\n ;;\n --)\n shift\n break\n ;;\n *)\n echo \"$0: unparseable option $1\"\n EXCEPTION=$Main__ParameterException\n EXCEPTION_MSG=\"unparseable option $1\"\n exit 1\n ;;\n esac\ndone\n\nif test \"x$CommandLineOptions__config_file\" == \"x\"\nthen\n echo \"$0: missing config_file parameter\"\n EXCEPTION=$Main__ParameterException\n EXCEPTION_MSG=\"missing config_file parameter\"\n exit 1\nfi\n function foo {\n local bar=\"$0\"\n}\n set -o nounset\n if test \"x${foo:-notset}\" == \"xnotset\"\nthen\n echo \"foo not set\"\nfi\n readonly readonly_var=\"foo\"\n set -o nounset\nfunction getScriptAbsoluteDir {\n # @description used to get the script path\n # @param $1 the script $0 parameter\n local script_invoke_path=\"$1\"\n local cwd=`pwd`\n\n # absolute path ? if so, the first character is a /\n if test \"x${script_invoke_path:0:1}\" = 'x/'\n then\n RESULT=`dirname \"$script_invoke_path\"`\n else\n RESULT=`dirname \"$cwd/$script_invoke_path\"`\n fi\n}\n\nscript_invoke_path=\"$0\"\nscript_name=`basename \"$0\"`\ngetScriptAbsoluteDir \"$script_invoke_path\"\nscript_absolute_dir=$RESULT\n\nfunction import() { \n # @description importer routine to get external functionality.\n # @description the first location searched is the script directory.\n # @description if not found, search the module in the paths contained in $SHELL_LIBRARY_PATH environment variable\n # @param $1 the .shinc file to import, without .shinc extension\n module=$1\n\n if test \"x$module\" == \"x\"\n then\n echo \"$script_name : Unable to import unspecified module. Dying.\"\n exit 1\n fi\n\n if test \"x${script_absolute_dir:-notset}\" == \"xnotset\"\n then\n echo \"$script_name : Undefined script absolute dir. Did you remove getScriptAbsoluteDir? Dying.\"\n exit 1\n fi\n\n if test \"x$script_absolute_dir\" == \"x\"\n then\n echo \"$script_name : empty script path. Dying.\"\n exit 1\n fi\n\n if test -e \"$script_absolute_dir/$module.shinc\"\n then\n # import from script directory\n . \"$script_absolute_dir/$module.shinc\"\n elif test \"x${SHELL_LIBRARY_PATH:-notset}\" != \"xnotset\"\n then\n # import from the shell script library path\n # save the separator and use the ':' instead\n local saved_IFS=\"$IFS\"\n IFS=':'\n for path in $SHELL_LIBRARY_PATH\n do\n if test -e \"$path/$module.shinc\"\n then\n . \"$path/$module.shinc\"\n return\n fi\n done\n # restore the standard separator\n IFS=\"$saved_IFS\"\n fi\n echo \"$script_name : Unable to find module $module.\"\n exit 1\n} \n # avoid double inclusion\nif test \"${BashInclude__imported+defined}\" == \"defined\"\nthen\n return 0\nfi\nBashInclude__imported=1\n # avoid double inclusion\nif test \"${Table__imported+defined}\" == \"defined\"\nthen\n return 0\nfi\nTable__imported=1\n\nreadonly Table__NoException=\"\"\nreadonly Table__ParameterException=\"Table__ParameterException\"\nreadonly Table__MySqlException=\"Table__MySqlException\"\nreadonly Table__NotInitializedException=\"Table__NotInitializedException\"\nreadonly Table__AlreadyInitializedException=\"Table__AlreadyInitializedException\"\n\n# an example for module enum constants, used in the mysql table, in this case\nreadonly Table__GENDER_MALE=\"GENDER_MALE\"\nreadonly Table__GENDER_FEMALE=\"GENDER_FEMALE\"\n\n# private: prefixed with p_ (a bash variable cannot start with _)\np_Table__mysql_exec=\"\" # will contain the executed mysql command \n\np_Table__initialized=0\n\nfunction Table__init {\n # @description init the module with the database parameters\n # @param $1 the mysql config file\n # @exception Table__NoException, Table__ParameterException\n\n EXCEPTION=\"\"\n EXCEPTION_MSG=\"\"\n EXCEPTION_FUNC=\"\"\n RESULT=\"\"\n\n if test $p_Table__initialized -ne 0\n then\n EXCEPTION=$Table__AlreadyInitializedException \n EXCEPTION_MSG=\"module already initialized\"\n EXCEPTION_FUNC=\"$FUNCNAME\"\n return 1\n fi\n\n\n local config_file=\"$1\"\n\n # yes, I am aware that I could put default parameters and other niceties, but I am lazy today\n if test \"x$config_file\" = \"x\"; then\n EXCEPTION=$Table__ParameterException\n EXCEPTION_MSG=\"missing parameter config file\"\n EXCEPTION_FUNC=\"$FUNCNAME\"\n return 1\n fi\n\n\n p_Table__mysql_exec=\"mysql --defaults-file=$config_file --silent --skip-column-names -e \"\n\n # mark the module as initialized\n p_Table__initialized=1\n\n EXCEPTION=$Table__NoException\n EXCEPTION_MSG=\"\"\n EXCEPTION_FUNC=\"\"\n return 0\n\n}\n\nfunction Table__getName() {\n # @description gets the name of the person \n # @param $1 the row identifier\n # @result the name\n\n EXCEPTION=\"\"\n EXCEPTION_MSG=\"\"\n EXCEPTION_FUNC=\"\"\n RESULT=\"\"\n\n if test $p_Table__initialized -eq 0\n then\n EXCEPTION=$Table__NotInitializedException\n EXCEPTION_MSG=\"module not initialized\"\n EXCEPTION_FUNC=\"$FUNCNAME\"\n return 1\n fi\n\n id=$1\n\n if test \"x$id\" = \"x\"; then\n EXCEPTION=$Table__ParameterException\n EXCEPTION_MSG=\"missing parameter identifier\"\n EXCEPTION_FUNC=\"$FUNCNAME\"\n return 1\n fi\n\n local name=`$p_Table__mysql_exec \"SELECT name FROM table WHERE id = '$id'\"`\n if test $? != 0 ; then\n EXCEPTION=$Table__MySqlException\n EXCEPTION_MSG=\"unable to perform select\"\n EXCEPTION_FUNC=\"$FUNCNAME\"\n return 1\n fi\n\n RESULT=$name\n EXCEPTION=$Table__NoException\n EXCEPTION_MSG=\"\"\n EXCEPTION_FUNC=\"\"\n return 0\n}\n function Main__interruptHandler() {\n # @description signal handler for SIGINT\n echo \"SIGINT caught\"\n exit\n} \nfunction Main__terminationHandler() { \n # @description signal handler for SIGTERM\n echo \"SIGTERM caught\"\n exit\n} \nfunction Main__exitHandler() { \n # @description signal handler for end of the program (clean or unclean). \n # probably redundant call, we already call the cleanup in main.\n exit\n} \n\ntrap Main__interruptHandler INT\ntrap Main__terminationHandler TERM\ntrap Main__exitHandler EXIT\n\nfunction Main__main() {\n # body\n}\n\n# catch signals and exit\ntrap exit INT TERM EXIT\n\nMain__main \"$@\"\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14437/" ]
78,536
<p>I want to do something like:</p> <pre><code>MyObject myObj = GetMyObj(); // Create and fill a new object MyObject newObj = myObj.Clone(); </code></pre> <p>And then make changes to the new object that are not reflected in the original object.</p> <p>I don't often need this functionality, so when it's been necessary, I've resorted to creating a new object and then copying each property individually, but it always leaves me with the feeling that there is a better or more elegant way of handling the situation.</p> <p>How can I clone or deep copy an object so that the cloned object can be modified without any changes being reflected in the original object?</p>
[ { "answer_id": 78612, "author": "johnc", "author_id": 5302, "author_profile": "https://Stackoverflow.com/users/5302", "pm_score": 12, "selected": true, "text": "ICloneable using System;\nusing System.IO;\nusing System.Runtime.Serialization;\nusing System.Runtime.Serialization.Formatters.Binary;\n\n/// <summary>\n/// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx\n/// Provides a method for performing a deep copy of an object.\n/// Binary Serialization is used to perform the copy.\n/// </summary>\npublic static class ObjectCopier\n{\n /// <summary>\n /// Perform a deep copy of the object via serialization.\n /// </summary>\n /// <typeparam name=\"T\">The type of object being copied.</typeparam>\n /// <param name=\"source\">The object instance to copy.</param>\n /// <returns>A deep copy of the object.</returns>\n public static T Clone<T>(T source)\n {\n if (!typeof(T).IsSerializable)\n {\n throw new ArgumentException(\"The type must be serializable.\", nameof(source));\n }\n\n // Don't serialize a null object, simply return the default for that object\n if (ReferenceEquals(source, null)) return default;\n\n using var Stream stream = new MemoryStream();\n IFormatter formatter = new BinaryFormatter();\n formatter.Serialize(stream, source);\n stream.Seek(0, SeekOrigin.Begin);\n return (T)formatter.Deserialize(stream);\n }\n}\n public static T Clone<T>(this T source)\n{\n // ...\n}\n objectBeingCloned.Clone(); /// <summary>\n/// Perform a deep Copy of the object, using Json as a serialization method. NOTE: Private members are not cloned using this method.\n/// </summary>\n/// <typeparam name=\"T\">The type of object being copied.</typeparam>\n/// <param name=\"source\">The object instance to copy.</param>\n/// <returns>The copied object.</returns>\npublic static T CloneJson<T>(this T source)\n{ \n // Don't serialize a null object, simply return the default for that object\n if (ReferenceEquals(source, null)) return default;\n\n // initialize inner objects individually\n // for example in default constructor some list property initialized with some values,\n // but in 'source' these items are cleaned -\n // without ObjectCreationHandling.Replace default constructor values will be added to result\n var deserializeSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace};\n\n return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), deserializeSettings);\n}\n" }, { "answer_id": 78856, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 8, "selected": false, "text": "MemberwiseClone MemberwiseClone Clone DeepClone Copy" }, { "answer_id": 1497125, "author": "Daniel Mošmondor", "author_id": 166251, "author_profile": "https://Stackoverflow.com/users/166251", "pm_score": 4, "selected": false, "text": "static public IEnumerable<SpotPlacement> CloneList(List<SpotPlacement> spotPlacements)\n{\n foreach (SpotPlacement sp in spotPlacements)\n {\n yield return (SpotPlacement)sp.Clone();\n }\n}\n public object Clone()\n{\n OrderItem newOrderItem = new OrderItem();\n ...\n newOrderItem._exactPlacements.AddRange(SpotPlacement.CloneList(_exactPlacements));\n ...\n return newOrderItem;\n}\n class Utility<T> where T : ICloneable\n{\n static public IEnumerable<T> CloneList(List<T> tl)\n {\n foreach (T t in tl)\n {\n yield return (T)t.Clone();\n }\n }\n}\n" }, { "answer_id": 1834578, "author": "Michael White", "author_id": 223103, "author_profile": "https://Stackoverflow.com/users/223103", "pm_score": 5, "selected": false, "text": "static public class SerializeHelper\n{\n //Michael White, Holly Springs Consulting, 2009\n //michael@hollyspringsconsulting.com\n public static T DeserializeXML<T>(string xmlData) \n where T:new()\n {\n if (string.IsNullOrEmpty(xmlData))\n return default(T);\n\n TextReader tr = new StringReader(xmlData);\n T DocItms = new T();\n XmlSerializer xms = new XmlSerializer(DocItms.GetType());\n DocItms = (T)xms.Deserialize(tr);\n\n return DocItms == null ? default(T) : DocItms;\n }\n\n public static string SeralizeObjectToXML<T>(T xmlObject)\n {\n StringBuilder sbTR = new StringBuilder();\n XmlSerializer xmsTR = new XmlSerializer(xmlObject.GetType());\n XmlWriterSettings xwsTR = new XmlWriterSettings();\n \n XmlWriter xmwTR = XmlWriter.Create(sbTR, xwsTR);\n xmsTR.Serialize(xmwTR,xmlObject);\n \n return sbTR.ToString();\n }\n\n public static T CloneObject<T>(T objClone) \n where T:new()\n {\n string GetString = SerializeHelper.SeralizeObjectToXML<T>(objClone);\n return SerializeHelper.DeserializeXML<T>(GetString);\n }\n}\n" }, { "answer_id": 5324679, "author": "Konstantin Salavatov", "author_id": 204647, "author_profile": "https://Stackoverflow.com/users/204647", "pm_score": 6, "selected": false, "text": "[Serializable] public static void CopyTo( this object S, object T )\n{\n foreach( var pS in S.GetType().GetProperties() )\n {\n foreach( var pT in T.GetType().GetProperties() )\n {\n if( pT.Name != pS.Name ) continue;\n ( pT.GetSetMethod() ).Invoke( T, new object[] \n { pS.GetGetMethod().Invoke( S, null ) } );\n }\n };\n}\n" }, { "answer_id": 7316457, "author": "dougajmcdonald", "author_id": 777733, "author_profile": "https://Stackoverflow.com/users/777733", "pm_score": 3, "selected": false, "text": "public static object CloneObject(object opSource)\n{\n //grab the type and create a new instance of that type\n Type opSourceType = opSource.GetType();\n object opTarget = CreateInstanceOfType(opSourceType);\n\n //grab the properties\n PropertyInfo[] opPropertyInfo = opSourceType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);\n\n //iterate over the properties and if it has a 'set' method assign it from the source TO the target\n foreach (PropertyInfo item in opPropertyInfo)\n {\n if (item.CanWrite)\n {\n //value types can simply be 'set'\n if (item.PropertyType.IsValueType || item.PropertyType.IsEnum || item.PropertyType.Equals(typeof(System.String)))\n {\n item.SetValue(opTarget, item.GetValue(opSource, null), null);\n }\n //object/complex types need to recursively call this method until the end of the tree is reached\n else\n {\n object opPropertyValue = item.GetValue(opSource, null);\n if (opPropertyValue == null)\n {\n item.SetValue(opTarget, null, null);\n }\n else\n {\n item.SetValue(opTarget, CloneObject(opPropertyValue), null);\n }\n }\n }\n }\n //return the new item\n return opTarget;\n}\n" }, { "answer_id": 8422769, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 3, "selected": false, "text": "ISelf<T> Self T ICloneable<out T> ISelf<T> T Clone() CloneBase protected virtual generic VirtualClone MemberwiseClone VirtualClone sealed ICloneable<theNonCloneableType> Foo DerivedFoo Foo" }, { "answer_id": 12609692, "author": "cregox", "author_id": 274502, "author_profile": "https://Stackoverflow.com/users/274502", "pm_score": 7, "selected": false, "text": "New public class Person : ICloneable\n{\n private final Brain brain; // brain is final since I do not want \n // any transplant on it once created!\n private int age;\n public Person(Brain aBrain, int theAge)\n {\n brain = aBrain; \n age = theAge;\n }\n protected Person(Person another)\n {\n Brain refBrain = null;\n try\n {\n refBrain = (Brain) another.brain.clone();\n // You can set the brain in the constructor\n }\n catch(CloneNotSupportedException e) {}\n brain = refBrain;\n age = another.age;\n }\n public String toString()\n {\n return \"This is person with \" + brain;\n // Not meant to sound rude as it reads!\n }\n public Object clone()\n {\n return new Person(this);\n }\n …\n}\n public class SkilledPerson extends Person\n{\n private String theSkills;\n public SkilledPerson(Brain aBrain, int theAge, String skills)\n {\n super(aBrain, theAge);\n theSkills = skills;\n }\n protected SkilledPerson(SkilledPerson another)\n {\n super(another);\n theSkills = another.theSkills;\n }\n\n public Object clone()\n {\n return new SkilledPerson(this);\n }\n public String toString()\n {\n return \"SkilledPerson: \" + super.toString();\n }\n}\n public class User\n{\n public static void play(Person p)\n {\n Person another = (Person) p.clone();\n System.out.println(p);\n System.out.println(another);\n }\n public static void main(String[] args)\n {\n Person sam = new Person(new Brain(), 1);\n play(sam);\n SkilledPerson bob = new SkilledPerson(new SmarterBrain(), 1, \"Writer\");\n play(bob);\n }\n}\n This is person with Brain@1fcc69\nThis is person with Brain@253498\nSkilledPerson: This is person with SmarterBrain@1fef6f\nSkilledPerson: This is person with SmarterBrain@209f4e\n" }, { "answer_id": 12901265, "author": "Michael Cox", "author_id": 372698, "author_profile": "https://Stackoverflow.com/users/372698", "pm_score": 5, "selected": false, "text": "MyObject oldObj; // The existing object to clone\n\nMyObject newObj = new MyObject();\nnewObj.InjectFrom(oldObj); // Using ValueInjecter syntax\n ISerializable ICloneable" }, { "answer_id": 15788750, "author": "craastad", "author_id": 1111732, "author_profile": "https://Stackoverflow.com/users/1111732", "pm_score": 9, "selected": false, "text": "public static T Clone<T>(T source)\n{\n var serialized = JsonConvert.SerializeObject(source);\n return JsonConvert.DeserializeObject<T>(serialized);\n}\n public static class SystemExtension\n{\n public static T Clone<T>(this T source)\n {\n var serialized = JsonConvert.SerializeObject(source);\n return JsonConvert.DeserializeObject<T>(serialized);\n }\n}\n" }, { "answer_id": 18123706, "author": "Ylli Prifti", "author_id": 693312, "author_profile": "https://Stackoverflow.com/users/693312", "pm_score": 1, "selected": false, "text": " public class PropertyCopy<TSource, TTarget> \n where TSource: class, new()\n where TTarget: class, new()\n {\n public static TTarget Copy(TSource src, TTarget trg, params string[] properties)\n {\n if (src==null) return trg;\n if (trg == null) trg = new TTarget();\n var fulllist = src.GetType().GetProperties().Where(c => c.CanWrite && c.CanRead).ToList();\n if (properties != null && properties.Count() > 0)\n fulllist = fulllist.Where(c => properties.Contains(c.Name)).ToList();\n if (fulllist == null || fulllist.Count() == 0) return trg;\n\n fulllist.ForEach(c =>\n {\n c.SetValue(trg, c.GetValue(src));\n });\n\n return trg;\n }\n }\n var cloned = Utils.PropertyCopy<TKTicket, TKTicket>.Copy(_tmp, dbsave,\n \"Creation\",\n \"Description\",\n \"IdTicketStatus\",\n \"IdUserCreated\",\n \"IdUserInCharge\",\n \"IdUserRequested\",\n \"IsUniqueTicketGenerated\",\n \"LastEdit\",\n \"Subject\",\n \"UniqeTicketRequestId\",\n \"Visibility\");\n var cloned = Utils.PropertyCopy<TKTicket, TKTicket>.Copy(_tmp, dbsave);\n" }, { "answer_id": 20767567, "author": "MarcinJuraszek", "author_id": 1163867, "author_profile": "https://Stackoverflow.com/users/1163867", "pm_score": 5, "selected": false, "text": "CloneExtensions Clone Copy GetClone<T>() var newInstance = source.GetClone();\n source newInstance CloningFlags var newInstance \n = source.GetClone(CloningFlags.Properties | CloningFlags.CollectionItems);\n GetClone<T> T T List<int> .Lambda #Lambda1<System.Func`4[System.Collections.Generic.List`1[System.Int32],CloneExtensions.CloningFlags,System.Collections.Generic.IDictionary`2[System.Type,System.Func`2[System.Object,System.Object]],System.Collections.Generic.List`1[System.Int32]]>(\n System.Collections.Generic.List`1[System.Int32] $source,\n CloneExtensions.CloningFlags $flags,\n System.Collections.Generic.IDictionary`2[System.Type,System.Func`2[System.Object,System.Object]] $initializers) {\n .Block(System.Collections.Generic.List`1[System.Int32] $target) {\n .If ($source == null) {\n .Return #Label1 { null }\n } .Else {\n .Default(System.Void)\n };\n .If (\n .Call $initializers.ContainsKey(.Constant<System.Type>(System.Collections.Generic.List`1[System.Int32]))\n ) {\n $target = (System.Collections.Generic.List`1[System.Int32]).Call ($initializers.Item[.Constant<System.Type>(System.Collections.Generic.List`1[System.Int32])]\n ).Invoke((System.Object)$source)\n } .Else {\n $target = .New System.Collections.Generic.List`1[System.Int32]()\n };\n .If (\n ((System.Byte)$flags & (System.Byte).Constant<CloneExtensions.CloningFlags>(Fields)) == (System.Byte).Constant<CloneExtensions.CloningFlags>(Fields)\n ) {\n .Default(System.Void)\n } .Else {\n .Default(System.Void)\n };\n .If (\n ((System.Byte)$flags & (System.Byte).Constant<CloneExtensions.CloningFlags>(Properties)) == (System.Byte).Constant<CloneExtensions.CloningFlags>(Properties)\n ) {\n .Block() {\n $target.Capacity = .Call CloneExtensions.CloneFactory.GetClone(\n $source.Capacity,\n $flags,\n $initializers)\n }\n } .Else {\n .Default(System.Void)\n };\n .If (\n ((System.Byte)$flags & (System.Byte).Constant<CloneExtensions.CloningFlags>(CollectionItems)) == (System.Byte).Constant<CloneExtensions.CloningFlags>(CollectionItems)\n ) {\n .Block(\n System.Collections.Generic.IEnumerator`1[System.Int32] $var1,\n System.Collections.Generic.ICollection`1[System.Int32] $var2) {\n $var1 = (System.Collections.Generic.IEnumerator`1[System.Int32]).Call $source.GetEnumerator();\n $var2 = (System.Collections.Generic.ICollection`1[System.Int32])$target;\n .Loop {\n .If (.Call $var1.MoveNext() != False) {\n .Call $var2.Add(.Call CloneExtensions.CloneFactory.GetClone(\n $var1.Current,\n $flags,\n\n\n $initializers))\n } .Else {\n .Break #Label2 { }\n }\n }\n .LabelTarget #Label2:\n }\n } .Else {\n .Default(System.Void)\n };\n .Label\n $target\n .LabelTarget #Label1:\n}\n (source, flags, initializers) =>\n{\n if(source == null)\n return null;\n\n if(initializers.ContainsKey(typeof(List<int>))\n target = (List<int>)initializers[typeof(List<int>)].Invoke((object)source);\n else\n target = new List<int>();\n\n if((flags & CloningFlags.Properties) == CloningFlags.Properties)\n {\n target.Capacity = target.Capacity.GetClone(flags, initializers);\n }\n\n if((flags & CloningFlags.CollectionItems) == CloningFlags.CollectionItems)\n {\n var targetCollection = (ICollection<int>)target;\n foreach(var item in (ICollection<int>)source)\n {\n targetCollection.Add(item.Clone(flags, initializers));\n }\n }\n\n return target;\n}\n Clone List<int>" }, { "answer_id": 23017515, "author": "Jeroen Ritmeijer", "author_id": 79448, "author_profile": "https://Stackoverflow.com/users/79448", "pm_score": 2, "selected": false, "text": "public static class ObjectCopier\n{\n\n /// <summary>\n /// Perform a deep Copy of an object that is marked with '[Serializable]' or '[DataContract]'\n /// </summary>\n /// <typeparam name=\"T\">The type of object being copied.</typeparam>\n /// <param name=\"source\">The object instance to copy.</param>\n /// <returns>The copied object.</returns>\n public static T Clone<T>(T source)\n {\n if (typeof(T).IsSerializable == true)\n {\n return CloneUsingSerializable<T>(source);\n }\n\n if (IsDataContract(typeof(T)) == true)\n {\n return CloneUsingDataContracts<T>(source);\n }\n\n throw new ArgumentException(\"The type must be Serializable or use DataContracts.\", \"source\");\n }\n\n\n /// <summary>\n /// Perform a deep Copy of an object that is marked with '[Serializable]'\n /// </summary>\n /// <remarks>\n /// Found on http://stackoverflow.com/questions/78536/cloning-objects-in-c-sharp\n /// Uses code found on CodeProject, which allows free use in third party apps\n /// - http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx\n /// </remarks>\n /// <typeparam name=\"T\">The type of object being copied.</typeparam>\n /// <param name=\"source\">The object instance to copy.</param>\n /// <returns>The copied object.</returns>\n public static T CloneUsingSerializable<T>(T source)\n {\n if (!typeof(T).IsSerializable)\n {\n throw new ArgumentException(\"The type must be serializable.\", \"source\");\n }\n\n // Don't serialize a null object, simply return the default for that object\n if (Object.ReferenceEquals(source, null))\n {\n return default(T);\n }\n\n IFormatter formatter = new BinaryFormatter();\n Stream stream = new MemoryStream();\n using (stream)\n {\n formatter.Serialize(stream, source);\n stream.Seek(0, SeekOrigin.Begin);\n return (T)formatter.Deserialize(stream);\n }\n }\n\n\n /// <summary>\n /// Perform a deep Copy of an object that is marked with '[DataContract]'\n /// </summary>\n /// <typeparam name=\"T\">The type of object being copied.</typeparam>\n /// <param name=\"source\">The object instance to copy.</param>\n /// <returns>The copied object.</returns>\n public static T CloneUsingDataContracts<T>(T source)\n {\n if (IsDataContract(typeof(T)) == false)\n {\n throw new ArgumentException(\"The type must be a data contract.\", \"source\");\n }\n\n // ** Don't serialize a null object, simply return the default for that object\n if (Object.ReferenceEquals(source, null))\n {\n return default(T);\n }\n\n DataContractSerializer dcs = new DataContractSerializer(typeof(T));\n using(Stream stream = new MemoryStream())\n {\n using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(stream))\n {\n dcs.WriteObject(writer, source);\n writer.Flush();\n stream.Seek(0, SeekOrigin.Begin);\n using (XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max))\n {\n return (T)dcs.ReadObject(reader);\n }\n }\n }\n }\n\n\n /// <summary>\n /// Helper function to check if a class is a [DataContract]\n /// </summary>\n /// <param name=\"type\">The type of the object to check.</param>\n /// <returns>Boolean flag indicating if the class is a DataContract (true) or not (false) </returns>\n public static bool IsDataContract(Type type)\n {\n object[] attributes = type.GetCustomAttributes(typeof(DataContractAttribute), false);\n return attributes.Length == 1;\n }\n\n} \n" }, { "answer_id": 23042982, "author": "will_m", "author_id": 3528734, "author_profile": "https://Stackoverflow.com/users/3528734", "pm_score": 1, "selected": false, "text": "T t = new T();\nT t2 = (T)t; //eh something like that\n\n List<myclass> cloneum;\n public void SomeFuncB(ref List<myclass> _mylist)\n {\n cloneum = new List<myclass>();\n cloneum = (List < myclass >) _mylist;\n cloneum.Add(new myclass(3));\n _mylist = new List<myclass>();\n }\n" }, { "answer_id": 23289451, "author": "Chtioui Malek", "author_id": 1254684, "author_profile": "https://Stackoverflow.com/users/1254684", "pm_score": 2, "selected": false, "text": "public class yourClass\n{\n // ...\n // ...\n\n public yourClass DeepCopy()\n {\n yourClass othercopy = (yourClass)this.MemberwiseClone();\n return othercopy;\n }\n}\n yourClass newLine = oldLine.DeepCopy();\n" }, { "answer_id": 28900160, "author": "LuckyLikey", "author_id": 4099159, "author_profile": "https://Stackoverflow.com/users/4099159", "pm_score": 3, "selected": false, "text": " public AnyObject(AnyObject anyObject)\n {\n foreach (var property in typeof(AnyObject).GetProperties())\n {\n property.SetValue(this, property.GetValue(anyObject));\n }\n foreach (var field in typeof(AnyObject).GetFields())\n {\n field.SetValue(this, field.GetValue(anyObject));\n }\n }\n" }, { "answer_id": 29749841, "author": "LuckyLikey", "author_id": 4099159, "author_profile": "https://Stackoverflow.com/users/4099159", "pm_score": 2, "selected": false, "text": "static public MyClass Clone(MyClass myClass)\n{\n MyClass clone;\n XmlSerializer ser = new XmlSerializer(typeof(MyClass), _xmlAttributeOverrides);\n using (var ms = new MemoryStream())\n {\n ser.Serialize(ms, myClass);\n ms.Position = 0;\n clone = (MyClass)ser.Deserialize(ms);\n }\n return clone;\n}\n" }, { "answer_id": 29856064, "author": "TarmoPikaro", "author_id": 2338477, "author_profile": "https://Stackoverflow.com/users/2338477", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\n\nnamespace TestDeepClone\n{\n class Program\n {\n static void Main(string[] args)\n {\n A a = new A();\n a.name = \"main_A\";\n a.b_list.Add(new B(a) { name = \"b1\" });\n a.b_list.Add(new B(a) { name = \"b2\" });\n\n A a2 = (A)a.DeepClone();\n a2.name = \"second_A\";\n\n // Perform re-parenting manually after deep copy.\n foreach( var b in a2.b_list )\n b.parent = a2;\n\n\n Debug.WriteLine(\"ok\");\n\n }\n }\n\n public class A\n {\n public String name = \"one\";\n public List<String> list = new List<string>();\n public List<String> null_list;\n public List<B> b_list = new List<B>();\n private int private_pleaseCopyMeAsWell = 5;\n\n public override string ToString()\n {\n return \"A(\" + name + \")\";\n }\n }\n\n public class B\n {\n public B() { }\n public B(A _parent) { parent = _parent; }\n public A parent;\n public String name = \"two\";\n }\n\n\n public static class ReflectionEx\n {\n public static Type GetUnderlyingType(this MemberInfo member)\n {\n Type type;\n switch (member.MemberType)\n {\n case MemberTypes.Field:\n type = ((FieldInfo)member).FieldType;\n break;\n case MemberTypes.Property:\n type = ((PropertyInfo)member).PropertyType;\n break;\n case MemberTypes.Event:\n type = ((EventInfo)member).EventHandlerType;\n break;\n default:\n throw new ArgumentException(\"member must be if type FieldInfo, PropertyInfo or EventInfo\", \"member\");\n }\n return Nullable.GetUnderlyingType(type) ?? type;\n }\n\n /// <summary>\n /// Gets fields and properties into one array.\n /// Order of properties / fields will be preserved in order of appearance in class / struct. (MetadataToken is used for sorting such cases)\n /// </summary>\n /// <param name=\"type\">Type from which to get</param>\n /// <returns>array of fields and properties</returns>\n public static MemberInfo[] GetFieldsAndProperties(this Type type)\n {\n List<MemberInfo> fps = new List<MemberInfo>();\n fps.AddRange(type.GetFields());\n fps.AddRange(type.GetProperties());\n fps = fps.OrderBy(x => x.MetadataToken).ToList();\n return fps.ToArray();\n }\n\n public static object GetValue(this MemberInfo member, object target)\n {\n if (member is PropertyInfo)\n {\n return (member as PropertyInfo).GetValue(target, null);\n }\n else if (member is FieldInfo)\n {\n return (member as FieldInfo).GetValue(target);\n }\n else\n {\n throw new Exception(\"member must be either PropertyInfo or FieldInfo\");\n }\n }\n\n public static void SetValue(this MemberInfo member, object target, object value)\n {\n if (member is PropertyInfo)\n {\n (member as PropertyInfo).SetValue(target, value, null);\n }\n else if (member is FieldInfo)\n {\n (member as FieldInfo).SetValue(target, value);\n }\n else\n {\n throw new Exception(\"destinationMember must be either PropertyInfo or FieldInfo\");\n }\n }\n\n /// <summary>\n /// Deep clones specific object.\n /// Analogue can be found here: https://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-an-object-in-net-c-specifically\n /// This is now improved version (list support added)\n /// </summary>\n /// <param name=\"obj\">object to be cloned</param>\n /// <returns>full copy of object.</returns>\n public static object DeepClone(this object obj)\n {\n if (obj == null)\n return null;\n\n Type type = obj.GetType();\n\n if (obj is IList)\n {\n IList list = ((IList)obj);\n IList newlist = (IList)Activator.CreateInstance(obj.GetType(), list.Count);\n\n foreach (object elem in list)\n newlist.Add(DeepClone(elem));\n\n return newlist;\n } //if\n\n if (type.IsValueType || type == typeof(string))\n {\n return obj;\n }\n else if (type.IsArray)\n {\n Type elementType = Type.GetType(type.FullName.Replace(\"[]\", string.Empty));\n var array = obj as Array;\n Array copied = Array.CreateInstance(elementType, array.Length);\n\n for (int i = 0; i < array.Length; i++)\n copied.SetValue(DeepClone(array.GetValue(i)), i);\n\n return Convert.ChangeType(copied, obj.GetType());\n }\n else if (type.IsClass)\n {\n object toret = Activator.CreateInstance(obj.GetType());\n\n MemberInfo[] fields = type.GetFieldsAndProperties();\n foreach (MemberInfo field in fields)\n {\n // Don't clone parent back-reference classes. (Using special kind of naming 'parent' \n // to indicate child's parent class.\n if (field.Name == \"parent\")\n {\n continue;\n }\n\n object fieldValue = field.GetValue(obj);\n\n if (fieldValue == null)\n continue;\n\n field.SetValue(toret, DeepClone(fieldValue));\n }\n\n return toret;\n }\n else\n {\n // Don't know that type, don't know how to clone it.\n if (Debugger.IsAttached)\n Debugger.Break();\n\n return null;\n }\n } //DeepClone\n }\n\n}\n" }, { "answer_id": 31223335, "author": "Contango", "author_id": 107409, "author_profile": "https://Stackoverflow.com/users/107409", "pm_score": 4, "selected": false, "text": "Demo 1 of shallow and deep copy, using classes and MemberwiseClone:\n Create Bob\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Clone Bob >> BobsSon\n Adjust BobsSon details\n BobsSon.Age=2, BobsSon.Purchase.Description=Toy car\n Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Elapsed time: 00:00:04.7795670,30000000\n\nDemo 2 of shallow and deep copy, using structs and value copying:\n Create Bob\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Clone Bob >> BobsSon\n Adjust BobsSon details:\n BobsSon.Age=2, BobsSon.Purchase.Description=Toy car\n Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Elapsed time: 00:00:01.0875454,30000000\n\nDemo 3 of deep copy, using class and serialize/deserialize:\n Elapsed time: 00:00:39.9339425,30000000\n // Nested MemberwiseClone example. \n// Added to demo how to deep copy a reference class.\n[Serializable] // Not required if using MemberwiseClone, only used for speed comparison using serialization.\npublic class Person\n{\n public Person(int age, string description)\n {\n this.Age = age;\n this.Purchase.Description = description;\n }\n [Serializable] // Not required if using MemberwiseClone\n public class PurchaseType\n {\n public string Description;\n public PurchaseType ShallowCopy()\n {\n return (PurchaseType)this.MemberwiseClone();\n }\n }\n public PurchaseType Purchase = new PurchaseType();\n public int Age;\n // Add this if using nested MemberwiseClone.\n // This is a class, which is a reference type, so cloning is more difficult.\n public Person ShallowCopy()\n {\n return (Person)this.MemberwiseClone();\n }\n // Add this if using nested MemberwiseClone.\n // This is a class, which is a reference type, so cloning is more difficult.\n public Person DeepCopy()\n {\n // Clone the root ...\n Person other = (Person) this.MemberwiseClone();\n // ... then clone the nested class.\n other.Purchase = this.Purchase.ShallowCopy();\n return other;\n }\n}\n// Added to demo how to copy a value struct (this is easy - a deep copy happens by default)\npublic struct PersonStruct\n{\n public PersonStruct(int age, string description)\n {\n this.Age = age;\n this.Purchase.Description = description;\n }\n public struct PurchaseType\n {\n public string Description;\n }\n public PurchaseType Purchase;\n public int Age;\n // This is a struct, which is a value type, so everything is a clone by default.\n public PersonStruct ShallowCopy()\n {\n return (PersonStruct)this;\n }\n // This is a struct, which is a value type, so everything is a clone by default.\n public PersonStruct DeepCopy()\n {\n return (PersonStruct)this;\n }\n}\n// Added only for a speed comparison.\npublic class MyDeepCopy\n{\n public static T DeepCopy<T>(T obj)\n {\n object result = null;\n using (var ms = new MemoryStream())\n {\n var formatter = new BinaryFormatter();\n formatter.Serialize(ms, obj);\n ms.Position = 0;\n result = (T)formatter.Deserialize(ms);\n ms.Close();\n }\n return (T)result;\n }\n}\n void MyMain(string[] args)\n{\n {\n Console.Write(\"Demo 1 of shallow and deep copy, using classes and MemberwiseCopy:\\n\");\n var Bob = new Person(30, \"Lamborghini\");\n Console.Write(\" Create Bob\\n\");\n Console.Write(\" Bob.Age={0}, Bob.Purchase.Description={1}\\n\", Bob.Age, Bob.Purchase.Description);\n Console.Write(\" Clone Bob >> BobsSon\\n\");\n var BobsSon = Bob.DeepCopy();\n Console.Write(\" Adjust BobsSon details\\n\");\n BobsSon.Age = 2;\n BobsSon.Purchase.Description = \"Toy car\";\n Console.Write(\" BobsSon.Age={0}, BobsSon.Purchase.Description={1}\\n\", BobsSon.Age, BobsSon.Purchase.Description);\n Console.Write(\" Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\\n\");\n Console.Write(\" Bob.Age={0}, Bob.Purchase.Description={1}\\n\", Bob.Age, Bob.Purchase.Description);\n Debug.Assert(Bob.Age == 30);\n Debug.Assert(Bob.Purchase.Description == \"Lamborghini\");\n var sw = new Stopwatch();\n sw.Start();\n int total = 0;\n for (int i = 0; i < 100000; i++)\n {\n var n = Bob.DeepCopy();\n total += n.Age;\n }\n Console.Write(\" Elapsed time: {0},{1}\\n\\n\", sw.Elapsed, total);\n }\n { \n Console.Write(\"Demo 2 of shallow and deep copy, using structs:\\n\");\n var Bob = new PersonStruct(30, \"Lamborghini\");\n Console.Write(\" Create Bob\\n\");\n Console.Write(\" Bob.Age={0}, Bob.Purchase.Description={1}\\n\", Bob.Age, Bob.Purchase.Description);\n Console.Write(\" Clone Bob >> BobsSon\\n\");\n var BobsSon = Bob.DeepCopy();\n Console.Write(\" Adjust BobsSon details:\\n\");\n BobsSon.Age = 2;\n BobsSon.Purchase.Description = \"Toy car\";\n Console.Write(\" BobsSon.Age={0}, BobsSon.Purchase.Description={1}\\n\", BobsSon.Age, BobsSon.Purchase.Description);\n Console.Write(\" Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\\n\");\n Console.Write(\" Bob.Age={0}, Bob.Purchase.Description={1}\\n\", Bob.Age, Bob.Purchase.Description); \n Debug.Assert(Bob.Age == 30);\n Debug.Assert(Bob.Purchase.Description == \"Lamborghini\");\n var sw = new Stopwatch();\n sw.Start();\n int total = 0;\n for (int i = 0; i < 100000; i++)\n {\n var n = Bob.DeepCopy();\n total += n.Age;\n }\n Console.Write(\" Elapsed time: {0},{1}\\n\\n\", sw.Elapsed, total);\n }\n {\n Console.Write(\"Demo 3 of deep copy, using class and serialize/deserialize:\\n\");\n int total = 0;\n var sw = new Stopwatch();\n sw.Start();\n var Bob = new Person(30, \"Lamborghini\");\n for (int i = 0; i < 100000; i++)\n {\n var BobsSon = MyDeepCopy.DeepCopy<Person>(Bob);\n total += BobsSon.Age;\n }\n Console.Write(\" Elapsed time: {0},{1}\\n\", sw.Elapsed, total);\n }\n Console.ReadKey();\n}\n ConcurrentQueue" }, { "answer_id": 32155648, "author": "KeyNone", "author_id": 1807643, "author_profile": "https://Stackoverflow.com/users/1807643", "pm_score": 1, "selected": false, "text": "[Serializable] public static T Clone<T>(this T source)\n{\n if(Attribute.GetCustomAttribute(typeof(T), typeof(ProtoBuf.ProtoContractAttribute))\n == null)\n {\n throw new ArgumentException(\"Type has no ProtoContract!\", \"source\");\n }\n\n if(Object.ReferenceEquals(source, null))\n {\n return default(T);\n }\n\n IFormatter formatter = ProtoBuf.Serializer.CreateFormatter<T>();\n using (Stream stream = new MemoryStream())\n {\n formatter.Serialize(stream, source);\n stream.Seek(0, SeekOrigin.Begin);\n return (T)formatter.Deserialize(stream);\n }\n}\n [ProtoContract]" }, { "answer_id": 34368738, "author": "Roma Borodov", "author_id": 4711853, "author_profile": "https://Stackoverflow.com/users/4711853", "pm_score": 2, "selected": false, "text": "static readonly Dictionary<Type, PropertyInfo[]> ProperyList = new Dictionary<Type, PropertyInfo[]>();\n foreach (var prop in propList)\n{\n var value = prop.GetValue(source, null); \n prop.SetValue(copyInstance, value, null);\n}\n" }, { "answer_id": 34998894, "author": "kalisohn", "author_id": 2792931, "author_profile": "https://Stackoverflow.com/users/2792931", "pm_score": 3, "selected": false, "text": "public class Person \n{\n [DeepClone(DeepCloneBehavior.Shallow)]\n private Job _currentJob; \n\n public string Name { get; set; }\n\n public Job CurrentJob \n { \n get{ return _currentJob; }\n set{ _currentJob = value; }\n }\n\n public Person Manager { get; set; }\n}\n\npublic class Address \n{ \n public Person PersonLivingHere { get; set; }\n}\n\nAddress adr = new Address();\nadr.PersonLivingHere = new Person(\"John\");\nadr.PersonLivingHere.BestFriend = new Person(\"James\");\nadr.PersonLivingHere.CurrentJob = new Job(\"Programmer\");\n\nAddress adrClone = adr.Clone();\n\n//RESULT\nadr.PersonLivingHere == adrClone.PersonLivingHere //false\nadr.PersonLivingHere.Manager == adrClone.PersonLivingHere.Manager //false\nadr.PersonLivingHere.CurrentJob == adrClone.PersonLivingHere.CurrentJob //true\nadr.PersonLivingHere.CurrentJob.AnyProperty == adrClone.PersonLivingHere.CurrentJob.AnyProperty //true\n" }, { "answer_id": 36575152, "author": "GorvGoyl", "author_id": 3073272, "author_profile": "https://Stackoverflow.com/users/3073272", "pm_score": 3, "selected": false, "text": "private static MyObj DeepCopy(MyObj source)\n {\n\n var DeserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };\n\n return JsonConvert.DeserializeObject<MyObj >(JsonConvert.SerializeObject(source), DeserializeSettings);\n\n }\n MyObj a = DeepCopy(b);" }, { "answer_id": 37498183, "author": "Stacked", "author_id": 1372621, "author_profile": "https://Stackoverflow.com/users/1372621", "pm_score": 4, "selected": false, "text": "MyType source = new MyType();\nMapper.CreateMap<MyType, MyType>();\nMyType target = Mapper.Map<MyType, MyType>(source);\n public static T Copy<T>(this T source)\n{\n T copy = default(T);\n Mapper.CreateMap<T, T>();\n copy = Mapper.Map<T, T>(source);\n return copy;\n}\n MyType copy = source.Copy();\n" }, { "answer_id": 37736016, "author": "Toxantron", "author_id": 6082960, "author_profile": "https://Stackoverflow.com/users/6082960", "pm_score": 3, "selected": false, "text": "ICloneable public partial class Root : ICloneable\n{\n public Root(int number)\n {\n _number = number;\n }\n private int _number;\n\n public Partial[] Partials { get; set; }\n\n public IList<ulong> Numbers { get; set; }\n\n public object Clone()\n {\n return Clone(true);\n }\n\n private Root()\n {\n }\n} \n\npublic partial class Root\n{\n public Root Clone(bool deep)\n {\n var copy = new Root();\n // All value types can be simply copied\n copy._number = _number; \n if (deep)\n {\n // In a deep clone the references are cloned \n var tempPartials = new Partial[Partials.Length];\n for (var i = 0; i < Partials.Length; i++)\n {\n var value = Partials[i];\n value = value.Clone(true);\n tempPartials[i] = value;\n }\n copy.Partials = tempPartials;\n var tempNumbers = new List<ulong>(Numbers.Count);\n for (var i = 0; i < Numbers.Count; i++)\n {\n var value = Numbers[i];\n tempNumbers.Add(value);\n }\n copy.Numbers = tempNumbers;\n }\n else\n {\n // In a shallow clone only references are copied\n copy.Partials = Partials; \n copy.Numbers = Numbers; \n }\n return copy;\n }\n}\n" }, { "answer_id": 38660465, "author": "Daniele D.", "author_id": 4454567, "author_profile": "https://Stackoverflow.com/users/4454567", "pm_score": 3, "selected": false, "text": "public class MyClass\n{\n public virtual MyClass DeepClone()\n {\n var returnObj = (MyClass)MemberwiseClone();\n var type = returnObj.GetType();\n var fieldInfoArray = type.GetRuntimeFields().ToArray();\n\n foreach (var fieldInfo in fieldInfoArray)\n {\n object sourceFieldValue = fieldInfo.GetValue(this);\n if (!(sourceFieldValue is MyClass))\n {\n continue;\n }\n\n var sourceObj = (MyClass)sourceFieldValue;\n var clonedObj = sourceObj.DeepClone();\n fieldInfo.SetValue(returnObj, clonedObj);\n }\n return returnObj;\n }\n}\n using System.Linq;\n using System.Reflection;\n public MyClass Clone(MyClass theObjectIneededToClone)\n{\n MyClass clonedObj = theObjectIneededToClone.DeepClone();\n}\n" }, { "answer_id": 38754644, "author": "frakon", "author_id": 2094687, "author_profile": "https://Stackoverflow.com/users/2094687", "pm_score": 5, "selected": false, "text": "public static T DeepClone<T>(this T originalObject)\n{ /* the cloning code */ }\n var copy = anyObject.DeepClone();\n" }, { "answer_id": 39044123, "author": "Sudhanva Kotabagi", "author_id": 5198209, "author_profile": "https://Stackoverflow.com/users/5198209", "pm_score": 2, "selected": false, "text": "MyObject myObj = GetMyObj(); // Create and fill a new object\nMyObject newObj = new MyObject(myObj); //DeepClone it\n" }, { "answer_id": 41988090, "author": "gaa", "author_id": 1842492, "author_profile": "https://Stackoverflow.com/users/1842492", "pm_score": -1, "selected": false, "text": "public static class CloneThroughJsonExtension\n{\n private static readonly JsonSerializerSettings DeserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };\n\n public static T CloneThroughJson<T>(this T source)\n {\n return ReferenceEquals(source, null) ? default(T) : JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), DeserializeSettings);\n }\n}\n public class WhatTheHeck\n{\n public string PrivateSet { get; private set; } // matches ctor param name\n\n public string GetOnly { get; } // matches ctor param name\n\n private readonly string _indirectField;\n public string Indirect => $\"Inception of: {_indirectField} \"; // matches ctor param name\n public string RealIndirectFieldVaule => _indirectField;\n\n public WhatTheHeck(string privateSet, string getOnly, string indirect)\n {\n PrivateSet = privateSet;\n GetOnly = getOnly;\n _indirectField = indirect;\n }\n}\n var clone = new WhatTheHeck(\"Private-Set-Prop cloned!\", \"Get-Only-Prop cloned!\", \"Indirect-Field clonned!\").CloneThroughJson();\nConsole.WriteLine($\"1. {clone.PrivateSet}\");\nConsole.WriteLine($\"2. {clone.GetOnly}\");\nConsole.WriteLine($\"3.1. {clone.Indirect}\");\nConsole.WriteLine($\"3.2. {clone.RealIndirectFieldVaule}\");\n 1. Private-Set-Prop cloned!\n2. Get-Only-Prop cloned!\n3.1. Inception of: Inception of: Indirect-Field cloned!\n3.2. Inception of: Indirect-Field cloned!\n" }, { "answer_id": 45557629, "author": "lindexi", "author_id": 6116637, "author_profile": "https://Stackoverflow.com/users/6116637", "pm_score": 1, "selected": false, "text": "public static class Clone\n{ \n // ReSharper disable once InconsistentNaming\n public static void CloneObjectWithIL<T>(T source, T los)\n {\n //see http://lindexi.oschina.io/lindexi/post/C-%E4%BD%BF%E7%94%A8Emit%E6%B7%B1%E5%85%8B%E9%9A%86/\n if (CachedIl.ContainsKey(typeof(T)))\n {\n ((Action<T, T>) CachedIl[typeof(T)])(source, los);\n return;\n }\n var dynamicMethod = new DynamicMethod(\"Clone\", null, new[] { typeof(T), typeof(T) });\n ILGenerator generator = dynamicMethod.GetILGenerator();\n\n foreach (var temp in typeof(T).GetProperties().Where(temp => temp.CanRead && temp.CanWrite))\n {\n //do not copy static that will except\n if (temp.GetAccessors(true)[0].IsStatic)\n {\n continue;\n }\n\n generator.Emit(OpCodes.Ldarg_1);// los\n generator.Emit(OpCodes.Ldarg_0);// s\n generator.Emit(OpCodes.Callvirt, temp.GetMethod);\n generator.Emit(OpCodes.Callvirt, temp.SetMethod);\n }\n generator.Emit(OpCodes.Ret);\n var clone = (Action<T, T>) dynamicMethod.CreateDelegate(typeof(Action<T, T>));\n CachedIl[typeof(T)] = clone;\n clone(source, los);\n }\n\n private static Dictionary<Type, Delegate> CachedIl { set; get; } = new Dictionary<Type, Delegate>();\n}\n" }, { "answer_id": 49276795, "author": "Matthew Watson", "author_id": 106159, "author_profile": "https://Stackoverflow.com/users/106159", "pm_score": 2, "selected": false, "text": "public static class Cloner\n{\n public static T Clone<T>(T source)\n {\n if (ReferenceEquals(source, null))\n return default(T);\n\n var settings = new JsonSerializerSettings { ContractResolver = new ContractResolver() };\n\n return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source, settings), settings);\n }\n\n class ContractResolver : DefaultContractResolver\n {\n protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)\n {\n var props = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)\n .Select(p => base.CreateProperty(p, memberSerialization))\n .Union(type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)\n .Select(f => base.CreateProperty(f, memberSerialization)))\n .ToList();\n props.ForEach(p => { p.Writable = true; p.Readable = true; });\n return props;\n }\n }\n}\n" }, { "answer_id": 50150204, "author": "Sameera R.", "author_id": 2016932, "author_profile": "https://Stackoverflow.com/users/2016932", "pm_score": 1, "selected": false, "text": " public static class AppExtensions\n { \n public static T DeepClone<T>(this T a)\n {\n using (var stream = new MemoryStream())\n {\n var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));\n\n serializer.Serialize(stream, a);\n stream.Position = 0;\n return (T)serializer.Deserialize(stream);\n }\n } \n }\n var obj2 = obj1.DeepClone()\n" }, { "answer_id": 52780057, "author": "qubits", "author_id": 1444319, "author_profile": "https://Stackoverflow.com/users/1444319", "pm_score": 2, "selected": false, "text": " public class Client\n {\n public string Name { get; set; }\n\n protected Client()\n {\n }\n\n public static Client Clone(Client copiedClient)\n {\n return new Client\n {\n Name = copiedClient.Name\n };\n }\n }\n\n public class Shop\n {\n public string Name { get; set; }\n\n public string Address { get; set; }\n\n public ICollection<Client> Clients { get; set; }\n\n public static Shop Clone(Shop copiedShop, string newAddress, ICollection<Client> clients)\n {\n var copiedClients = new List<Client>();\n foreach (var client in copiedShop.Clients)\n {\n copiedClients.Add(Client.Clone(client));\n }\n\n return new Shop\n {\n Name = copiedShop.Name,\n Address = newAddress,\n Clients = copiedClients\n };\n }\n }\n" }, { "answer_id": 53332691, "author": "Michael Brown", "author_id": 1395182, "author_profile": "https://Stackoverflow.com/users/1395182", "pm_score": 3, "selected": false, "text": "IClonable [IgnoreDataMember] [NonSerialized]" }, { "answer_id": 56691124, "author": "Ted Mucuzany", "author_id": 11652382, "author_profile": "https://Stackoverflow.com/users/11652382", "pm_score": 2, "selected": false, "text": ".net static class RandomHelper\n{\n private static readonly Random random = new Random();\n\n public static int Next(int maxValue) => random.Next(maxValue);\n}\n\nclass A\n{\n private readonly int random = RandomHelper.Next(100);\n\n public override string ToString() => $\"{typeof(A).Name}.{nameof(random)} = {random}\";\n}\n\nclass B : A\n{\n private readonly int random = RandomHelper.Next(100);\n\n public override string ToString() => $\"{typeof(B).Name}.{nameof(random)} = {random} {base.ToString()}\";\n}\n\nclass C : B\n{\n private readonly int random = RandomHelper.Next(100);\n\n public override string ToString() => $\"{typeof(C).Name}.{nameof(random)} = {random} {base.ToString()}\";\n}\n static class DeepCloneExtension\n{\n // consider instance fields, both public and non-public\n private static readonly BindingFlags bindingFlags =\n BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n\n public static T DeepClone<T>(this T obj) where T : new()\n {\n var type = obj.GetType();\n var result = (T)Activator.CreateInstance(type);\n\n do\n // copy all fields\n foreach (var field in type.GetFields(bindingFlags))\n field.SetValue(result, field.GetValue(obj));\n // for every level of hierarchy\n while ((type = type.BaseType) != typeof(object));\n\n return result;\n }\n}\n Console.WriteLine(new C());\nConsole.WriteLine(new C());\n\nvar c = new C();\nConsole.WriteLine($\"{Environment.NewLine}Image: {c}{Environment.NewLine}\");\n\nConsole.WriteLine(new C());\nConsole.WriteLine(new C());\n\nConsole.WriteLine($\"{Environment.NewLine}Clone: {c.DeepClone()}{Environment.NewLine}\");\n\nConsole.WriteLine(new C());\nConsole.WriteLine(new C());\n C.random = 92 B.random = 66 A.random = 71\nC.random = 36 B.random = 64 A.random = 17\n\nImage: C.random = 96 B.random = 18 A.random = 46\n\nC.random = 60 B.random = 7 A.random = 37\nC.random = 78 B.random = 11 A.random = 18\n\nClone: C.random = 96 B.random = 18 A.random = 46\n\nC.random = 33 B.random = 63 A.random = 38\nC.random = 4 B.random = 5 A.random = 79\n random clone image class D\n{\n public event EventHandler Event;\n public void RaiseEvent() => Event?.Invoke(this, EventArgs.Empty);\n}\n\n// ...\n\nvar image = new D();\nConsole.WriteLine($\"Created obj #{image.GetHashCode()}\");\n\nimage.Event += (sender, e) => Console.WriteLine($\"Event from obj #{sender.GetHashCode()}\");\nConsole.WriteLine($\"Subscribed to event of obj #{image.GetHashCode()}\");\n\nimage.RaiseEvent();\nimage.RaiseEvent();\n\nvar clone = image.DeepClone();\nConsole.WriteLine($\"obj #{image.GetHashCode()} cloned to obj #{clone.GetHashCode()}\");\n\nclone.RaiseEvent();\nimage.RaiseEvent();\n Created obj #46104728\nSubscribed to event of obj #46104728\nEvent from obj #46104728\nEvent from obj #46104728\nobj #46104728 cloned to obj #12289376\nEvent from obj #12289376\nEvent from obj #46104728\n" }, { "answer_id": 56805986, "author": "Konrad", "author_id": 2828480, "author_profile": "https://Stackoverflow.com/users/2828480", "pm_score": 1, "selected": false, "text": "System.Text.Json public static T DeepCopy<T>(this T source)\n{\n return source == null ? default : JsonSerializer.Parse<T>(JsonSerializer.ToString(source));\n}\n Span<T> ObjectCreationHandling.Replace" }, { "answer_id": 56933017, "author": "alelom", "author_id": 3873799, "author_profile": "https://Stackoverflow.com/users/3873799", "pm_score": 5, "selected": false, "text": "var deepClone = new { Id = 1, Name = \"222\" }.DeepClone();\nvar shallowClone = new { Id = 1, Name = \"222\" }.ShallowClone();\n" }, { "answer_id": 57279815, "author": "Marcell Toth", "author_id": 10614791, "author_profile": "https://Stackoverflow.com/users/10614791", "pm_score": 4, "selected": false, "text": "BinaryFormatter Serializable JsonConverter ObjectCloner var clone = ObjectCloner.DeepClone(original);\n ObjectCloner.Extensions var clone = original.DeepClone();\n BinaryFormatter" }, { "answer_id": 58975653, "author": "Erçin Dedeoğlu", "author_id": 2426367, "author_profile": "https://Stackoverflow.com/users/2426367", "pm_score": 2, "selected": false, "text": "using Newtonsoft.Json;\n public static T Clone<T>(T source) =>\n JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source));\n" }, { "answer_id": 61976233, "author": "Hidayet R. Colkusu", "author_id": 8614792, "author_profile": "https://Stackoverflow.com/users/8614792", "pm_score": 0, "selected": false, "text": "public static class Extentions\n{\n public static T Clone<T>(this T obj)\n {\n byte[] buffer = BinarySerialize(obj);\n return (T)BinaryDeserialize(buffer);\n }\n\n public static byte[] BinarySerialize(object obj)\n {\n using (var stream = new MemoryStream())\n {\n var formatter = new BinaryFormatter(); \n formatter.Serialize(stream, obj); \n return stream.ToArray();\n }\n }\n\n public static object BinaryDeserialize(byte[] buffer)\n {\n using (var stream = new MemoryStream(buffer))\n {\n var formatter = new BinaryFormatter(); \n return formatter.Deserialize(stream);\n }\n }\n}\n [Serializable]\npublic class MyObject\n{\n public string Name { get; set; }\n}\n MyObject myObj = GetMyObj();\nMyObject newObj = myObj.Clone();\n" }, { "answer_id": 62564309, "author": "Sean McAvoy", "author_id": 12367139, "author_profile": "https://Stackoverflow.com/users/12367139", "pm_score": 3, "selected": false, "text": "public static T Clone<T>(this T theObject)\n{\n string jsonData = JsonConvert.SerializeObject(theObject);\n return JsonConvert.DeserializeObject<T>(jsonData);\n}\n NewObject = OldObject.Clone();\n" }, { "answer_id": 66538192, "author": "Ogglas", "author_id": 3850405, "author_profile": "https://Stackoverflow.com/users/3850405", "pm_score": 0, "selected": false, "text": "System.Text.Json .NET >5 public static T Clone<T>(T source)\n{\n var serialized = JsonSerializer.Serialize(source);\n return JsonSerializer.Deserialize<T>(serialized);\n}\n public static class SystemExtension\n{\n public static T Clone<T>(this T source)\n {\n var serialized = JsonSerializer.Serialize(source);\n return JsonSerializer.Deserialize<T>(serialized);\n }\n}\n" }, { "answer_id": 67402990, "author": "Adel Tabareh", "author_id": 5007985, "author_profile": "https://Stackoverflow.com/users/5007985", "pm_score": 1, "selected": false, "text": "public static class CloneExtensions\n{\n public static T Clone<T>(this T cloneable) where T : new()\n {\n var toJson = JsonSerializer.Serialize(cloneable);\n return JsonSerializer.Deserialize<T>(toJson);\n }\n}\n" }, { "answer_id": 68663921, "author": "Izzy", "author_id": 1918179, "author_profile": "https://Stackoverflow.com/users/1918179", "pm_score": 2, "selected": false, "text": "with record record record using System;\n \npublic class Program\n{\n public class Example\n {\n public string A { get; set; }\n }\n \n public record ClonerRecord<T>(T a)\n {\n }\n\n public static void Main()\n {\n var foo = new Example {A = \"Hello World\"};\n var bar = (new ClonerRecord<Example>(foo) with {}).a;\n foo.A = \"Goodbye World :(\";\n Console.WriteLine(bar.A);\n }\n}\n struct record using System;\n\npublic class Program\n{\n public record Example\n {\n public string A { get; set; }\n }\n \n public static void Main()\n {\n var foo = new Example {A = \"Hello World\"};\n var bar = foo with {};\n foo.A = \"Goodbye World :(\";\n Console.WriteLine(bar.A);\n }\n}\n" }, { "answer_id": 69211283, "author": "Cinorid", "author_id": 6338072, "author_profile": "https://Stackoverflow.com/users/6338072", "pm_score": 1, "selected": false, "text": "BenchmarkDotNet=v0.13.1, OS=Windows 10.0.18363.1734 (1909/November2019Update/19H2)\n" }, { "answer_id": 69471766, "author": "ʞᴉɯ", "author_id": 182331, "author_profile": "https://Stackoverflow.com/users/182331", "pm_score": -1, "selected": false, "text": "DeepCloner" }, { "answer_id": 70899238, "author": "vivek nuna", "author_id": 6527049, "author_profile": "https://Stackoverflow.com/users/6527049", "pm_score": 2, "selected": false, "text": "public abstract class CloneablePrototype<T>\n{\n public T DeepCopy()\n {\n string result = JsonConvert.SerializeObject(this);\n return JsonConvert.DeserializeObject<T>(result);\n }\n}\npublic class YourClass : CloneablePrototype< YourClass>\n…\n…\n…\n YourClass newObj = (YourClass)oldObj.DeepCopy();\n public T ShallowCopy()\n{\n return (T)this.MemberwiseClone();\n}\n" }, { "answer_id": 71863562, "author": "David Oganov", "author_id": 7741097, "author_profile": "https://Stackoverflow.com/users/7741097", "pm_score": 2, "selected": false, "text": "record Record\n{\n public int Property1 { get; set; }\n\n public string Property2 { get; set; }\n}\n var object1 = new Record()\n{\n Property1 = 1,\n Property2 = \"2\"\n};\n\nvar object2 = object1 with { };\n// object2 now has Property1 = 1 & Property2 = \"2\"\n" }, { "answer_id": 73228716, "author": "Efreeto", "author_id": 2680660, "author_profile": "https://Stackoverflow.com/users/2680660", "pm_score": 0, "selected": false, "text": "DeepCopy using Newtonsoft.Json;\n\npublic static T DeepCopy<T>(this T source)\n{\n return (T)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(source), source.GetType());\n}\n" }, { "answer_id": 73300838, "author": "Adamy", "author_id": 657926, "author_profile": "https://Stackoverflow.com/users/657926", "pm_score": -1, "selected": false, "text": "var jsonBin = BinaryData.FromObjectAsJson(yourObject);\n var yourObjectCloned = jsonBin.ToObjectFromJson<YourType>();\n" }, { "answer_id": 73580774, "author": "Daniel Jonsson", "author_id": 595990, "author_profile": "https://Stackoverflow.com/users/595990", "pm_score": 2, "selected": false, "text": "ObjectExtensions.cs ObjectExtensions.cs using Baksteen.Extensions.DeepCopy;\n...\nvar myobject = new SomeClass();\n...\nvar myclone = myobject.DeepCopy()!; // creates a new deep copy of the original object \n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3742/" ]
78,548
<p>What is your way of passing data to Master Page (using ASP.NET MVC) without breaking MVC rules?</p> <p>Personally, I prefer to code abstract controller (base controller) or base class which is passed to all views.</p>
[ { "answer_id": 746011, "author": "Generic Error", "author_id": 40944, "author_profile": "https://Stackoverflow.com/users/40944", "pm_score": 7, "selected": true, "text": "public class MasterViewData\n{\n public ICollection<string> Navigation { get; set; }\n}\n public class IndexViewData : MasterViewData\n{\n public string Name { get; set; }\n public float Price { get; set; }\n}\n public interface IViewDataFactory\n{\n T Create<T>()\n where T : MasterViewData, new()\n}\n\npublic class ProductController : Controller\n{\n public ProductController(IViewDataFactory viewDataFactory)\n ...\n\n public ActionResult Index()\n {\n var viewData = viewDataFactory.Create<ProductViewData>();\n\n viewData.Name = \"My product\";\n viewData.Price = 9.95;\n\n return View(\"Index\", viewData);\n }\n}\n public class IndexViewData : MasterViewData\n{\n public string Name { get; set; }\n public float Price { get; set; }\n public SubViewData SubViewData { get; set; }\n}\n\n<% Html.RenderPartial(\"Sub\", Model.SubViewData); %>\n" }, { "answer_id": 1496250, "author": "rasx", "author_id": 22944, "author_profile": "https://Stackoverflow.com/users/22944", "pm_score": 0, "selected": false, "text": "<script runat=\"server\" type=\"text/C#\">\n protected override void OnLoad(EventArgs e)\n {\n base.OnLoad(e);\n MasterModel = SiteMasterViewData.Get(this.Context);\n }\n\n protected SiteMasterViewData MasterModel;\n</script>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/347616/" ]
78,560
<p>I have an SQL Server database where I have the data and log files stored on an external USB drive. I switch the external drive between my main development machine in my office and my laptop when not in my office. I am trying to use sp_detach_db and sp_attach_db when moving between desktop and laptop machines. I find that this works OK on the desktop - I can detach and reattach the database there no problems. But on the laptop I cannot reattach the database (the database was actually originally created on the laptop and the first detach happened there). When I try to reattach on the laptop I get the following error:</p> <p>Unable to open the physical file "p:\SQLData\AppManager.mdf". Operating system error 5: "5(error not found)"</p> <p>I find a lot of references to this error all stating that it is a permissions issue. So I went down this path and made sure that the SQL Server service account has appropriate permissions. I have also created a new database on this same path and been able to succesfully detach and reattach it. So I am confident permissions is not the issue.</p> <p>Further investigation reveals that I cannot rename, copy or move the data files as Windows thinks they are locked - even when the SQL Server service is stopped. Process Explorer does not show up any process locking the files. </p> <p>How can I find out what is locking the files and unlock them.</p> <p>I have verified that the databases do not show up in SSMS - so SQL Server does not still think they exist.</p> <p><strong>Update 18/09/2008</strong></p> <p>I have tried all of the suggested answers to date with no success. However trying these suggestions has helped to clarify the situation. I can verify the following:</p> <ol> <li>I can successfully detach and reattach the database only when the external drive is attached to the server that a copy of the database is restored to - effectively the server where the database is "created" - lets call this the "Source Server". </li> <li>I can move, copy or rename the data and log files, after detaching the database, while the external drive is still attached to the Source Server. </li> <li>As soon as I move the external drive to another machine the data and log files are "locked", although the 2 tools that I have tried - Process Explorer and Unlocker, both find no locking handles attached to the files. </li> </ol> <p>NB. After detaching the database I tried both stopping the SQL Server service and shutting down the Source Server prior to moving the external drive - still with no success.</p> <p>So at this stage all that I can do to move data between desktop and laptop is to make a backup of the data onto the external drive, move the external drive, restore the data from the backup. Works OK but takes a bit more time as the database is a reasonable size (1gb). Anyway this is the only choice I have at this stage even though I was trying to avoid having to go down this path.</p>
[ { "answer_id": 47219578, "author": "Ali Sheikhpour", "author_id": 4700922, "author_profile": "https://Stackoverflow.com/users/4700922", "pm_score": 0, "selected": false, "text": "group or usernames find now" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10135/" ]
78,592
<p>In perl one would simply do the following to store and iterate over a list of names</p> <pre><code>my @fruit = (apple, orange, kiwi); foreach (@fruit) { print $_; } </code></pre> <p>What would the equivalent be in bash?</p>
[ { "answer_id": 78601, "author": "emk", "author_id": 12089, "author_profile": "https://Stackoverflow.com/users/12089", "pm_score": 4, "selected": false, "text": "FRUITS=\"apple orange kiwi\"\nfor FRUIT in $FRUITS; do\n echo $FRUIT\ndone\n" }, { "answer_id": 78618, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "IFS fruits=\"apple,orange,kiwifruit,dried mango\"\n(IFS=,\n for fruit in $fruits; do\n echo \"$fruit\"\n done)\n IFS IFS" }, { "answer_id": 78631, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 7, "selected": true, "text": "fruits=(apple orange kiwi \"dried mango\")\nfor fruit in \"${fruits[@]}\"; do\n echo \"${fruit}\"\ndone\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10747/" ]
78,619
<p>What is the fastest way you know to convert a floating-point number to an int on an x86 CPU. Preferrably in C or assembly (that can be in-lined in C) for any combination of the following:</p> <ul> <li>32/64/80-bit float -> 32/64-bit integer</li> </ul> <p>I'm looking for some technique that is faster than to just let the compiler do it.</p>
[ { "answer_id": 78820, "author": "akauppi", "author_id": 14455, "author_profile": "https://Stackoverflow.com/users/14455", "pm_score": 3, "selected": false, "text": "lua_Number /*\n@@ lua_number2int is a macro to convert lua_Number to int.\n@@ lua_number2integer is a macro to convert lua_Number to lua_Integer.\n** CHANGE them if you know a faster way to convert a lua_Number to\n** int (with any rounding method and without throwing errors) in your\n** system. In Pentium machines, a naive typecast from double to int\n** in C is extremely slow, so any alternative is worth trying.\n*/\n\n/* On a Pentium, resort to a trick */\n#if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) && !defined(__SSE2__) && \\\n (defined(__i386) || defined (_M_IX86) || defined(__i386__))\n\n/* On a Microsoft compiler, use assembler */\n#if defined(_MSC_VER)\n\n#define lua_number2int(i,d) __asm fld d __asm fistp i\n#define lua_number2integer(i,n) lua_number2int(i, n)\n\n/* the next trick should work on any Pentium, but sometimes clashes\n with a DirectX idiosyncrasy */\n#else\n\nunion luai_Cast { double l_d; long l_l; };\n#define lua_number2int(i,d) \\\n { volatile union luai_Cast u; u.l_d = (d) + 6755399441055744.0; (i) = u.l_l; }\n#define lua_number2integer(i,n) lua_number2int(i, n)\n\n#endif\n\n/* this option always works, but may be slow */\n#else\n#define lua_number2int(i,d) ((i)=(int)(d))\n#define lua_number2integer(i,d) ((i)=(lua_Integer)(d))\n\n#endif\n" }, { "answer_id": 119538, "author": "Suma", "author_id": 16673, "author_profile": "https://Stackoverflow.com/users/16673", "pm_score": 3, "selected": false, "text": "static const float Snapper=3<<22;\n\nunion UFloatInt {\n int i;\n float f;\n};\n\n/** by Vlad Kaipetsky\nportable assuming FP24 set to nearest rounding mode\nefficient on x86 platform\n*/\ninline int toInt( float fval )\n{\n Assert( fabs(fval)<=0x003fffff ); // only 23 bit values handled\n UFloatInt &fi = *(UFloatInt *)&fval;\n fi.f += Snapper;\n return ( (fi.i)&0x007fffff ) - 0x00400000;\n}\n" }, { "answer_id": 16874325, "author": "Jan", "author_id": 2016181, "author_profile": "https://Stackoverflow.com/users/2016181", "pm_score": 2, "selected": false, "text": "_mm_cvtsd_si64x #include <intrin.h>\n #pragma intrinsic(_mm_cvtsd_si64x)\n long long _inline double2int(const double &d)\n {\n return _mm_cvtsd_si64x(*(__m128d*)&d);\n }\n i=double2int(d);\n000000013F651085 cvtsd2si rax,mmword ptr [rsp+38h] \n000000013F65108C mov qword ptr [rsp+28h],rax \n _control87(_RC_NEAR,_MCW_RC);\n float.h _control87() _asm fld d\n_asm fistp i\n" }, { "answer_id": 22048816, "author": "the swine", "author_id": 1140976, "author_profile": "https://Stackoverflow.com/users/1140976", "pm_score": 3, "selected": false, "text": "i = (int)f int convert(float x)\n{\n int n;\n __asm {\n fld x\n fisttp n // the extra 't' means truncate\n }\n return n;\n}\n #include <xmmintrin.h>\nint convert(float x)\n{\n return _mm_cvtt_ss2si(_mm_load_ss(&x)); // extra 't' means truncate\n}\n fistp void Set_Trunc()\n{\n // cw is a 16-bit register [_ _ _ ic rc1 rc0 pc1 pc0 iem _ pm um om zm dm im]\n __asm {\n push ax // use stack to store the control word\n fnstcw word ptr [esp]\n fwait // needed to make sure the control word is there\n mov ax, word ptr [esp] // or pop ax ...\n or ax, 0xc00 // set both rc bits (alternately \"or ah, 0xc\")\n mov word ptr [esp], ax // ... and push ax\n fldcw word ptr [esp]\n pop ax\n }\n}\n\nvoid convertArray(int *dest, const float *src, int n)\n{\n Set_Trunc();\n __asm {\n mov eax, src\n mov edx, dest\n mov ecx, n // load loop variables\n\n cmp ecx, 0\n je bottom // handle zero-length arrays\n\n top:\n fld dword ptr [eax]\n fistp dword ptr [edx]\n loop top // decrement ecx, jump to top\n bottom:\n }\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10184/" ]
78,696
<p>I'm trying to find out if there is any way to elevate a specific function within an application. For example, I have an app with system and user settings that are stored in the registry, I only need elevation for when the system settings need to be changed. </p> <p>Unfortunately all of the info I've come across talks about only starting a new process with elevated privileges. </p>
[ { "answer_id": 93379, "author": "Andrei Belogortseff", "author_id": 17037, "author_profile": "https://Stackoverflow.com/users/17037", "pm_score": 4, "selected": false, "text": "HRESULT \nCreateElevatedComObject (HWND hwnd, REFGUID guid, REFIID iid, void **ppv)\n{\n WCHAR monikerName[1024];\n WCHAR clsid[1024];\n BIND_OPTS3 bo;\n\n StringFromGUID2 (guid, clsid, sizeof (clsid) / 2);\n\n swprintf_s (monikerName, sizeof (monikerName) / 2, L\"Elevation:Administrator!new:%s\", clsid);\n\n memset (&bo, 0, sizeof (bo));\n bo.cbStruct = sizeof (bo);\n bo.hwnd = hwnd;\n bo.dwClassContext = CLSCTX_LOCAL_SERVER;\n\n // Prevent the GUI from being half-rendered when the UAC prompt \"freezes\" it\n MSG paintMsg;\n int MsgCounter = 5000; // Avoid endless processing of paint messages\n while (PeekMessage (&paintMsg, hwnd, 0, 0, PM_REMOVE | PM_QS_PAINT) != 0 && --MsgCounter > 0)\n {\n DispatchMessage (&paintMsg);\n }\n\n return CoGetObject (monikerName, &bo, iid, ppv);\n}\n" }, { "answer_id": 114714, "author": "Adrian Clark", "author_id": 148, "author_profile": "https://Stackoverflow.com/users/148", "pm_score": 2, "selected": false, "text": "%programfiles%" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14509/" ]
78,716
<p>A while ago, I started on a project where I designed a html-esque XML schema so that authors could write their content (educational course material) in a simplified format which would then be transformed into HTML via XSLT. I played around (struggled) with it for a while and got it to a very basic level but then was too annoyed by the limitations I was encountering (which may well have been limitations of my knowledge) and when I read a blog suggesting to ditch XSLT and just write your own XML-to-whatever parser in your language of choice, I eagerly jumped onto that and it's worked out brilliantly.</p> <p>I'm still working on it to this day (<em>I'm actually supposed to be working on it right now, instead of playing on SO</em>), and I am seeing more and more things which make me think that the decision to ditch XSLT was a good one.</p> <p>I know that XSLT has its place, in that it is an accepted standard, and that if everyone is writing their own interpreters, 90% of them will end up on <a href="http://thedailywtf.com" rel="noreferrer">TheDailyWTF</a>. But given that it is a <a href="http://en.wikipedia.org/wiki/Functional_programming" rel="noreferrer">functional style language</a> instead of the procedural style which most programmers are familiar with, for someone embarking on a project such as my own, <strong>would you recommend they go down the path that I did, or stick it out with XSLT</strong>?</p>
[ { "answer_id": 1270668, "author": "Adam Batkin", "author_id": 120808, "author_profile": "https://Stackoverflow.com/users/120808", "pm_score": 5, "selected": false, "text": "<ReleaseNotes>\n <FixedBugs>\n <Bug id=\"123\" component=\"Admin\">Error when clicking the Foo button</Bug>\n <Bug id=\"125\" component=\"Core\">Crash at startup when configuration is missing</Bug>\n <Bug id=\"127\" component=\"Admin\">Error when clicking the Bar button</Bug>\n </FixedBugs>\n</ReleaseNotes>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
78,717
<p>I have a 'foreach' macro I use frequently in C++ that works for most STL containers:</p> <pre><code>#define foreach(var, container) \ for(typeof((container).begin()) var = (container).begin(); \ var != (container).end(); \ ++var) </code></pre> <p>(Note that 'typeof' is a gcc extension.) It is used like this:</p> <pre><code>std::vector&lt; Blorgus &gt; blorgi = ...; foreach(blorgus, blorgi) { blorgus-&gt;draw(); } </code></pre> <p>I would like to make something similar that iterates over a map's values. Call it "foreach_value", perhaps. So instead of writing</p> <pre><code>foreach(pair, mymap) { pair-&gt;second-&gt;foo(); } </code></pre> <p>I would write</p> <pre><code>foreach_value(v, mymap) { v.foo(); } </code></pre> <p>I can't come up with a macro that will do this, because it requires declaring two variables: the iterator and the value variable ('v', above). I don't know how to do that in the initializer of a for loop, even using gcc extensions. I could declare it just before the foreach_value call, but then it will conflict with other instances of the foreach_value macro in the same scope. If I could suffix the current line number to the iterator variable name, it would work, but I don't know how to do that.</p>
[ { "answer_id": 78780, "author": "Tom Leys", "author_id": 11440, "author_profile": "https://Stackoverflow.com/users/11440", "pm_score": 3, "selected": false, "text": "// Valid C++ code (which does nothing useful)\n{\n int a = 21; // Which could be storage of your value type\n}\n// a out of scope here\n{ \n int a = 32; // Does not conflict with a above\n}\n" }, { "answer_id": 78793, "author": "porges", "author_id": 10311, "author_profile": "https://Stackoverflow.com/users/10311", "pm_score": 1, "selected": false, "text": "foreach transform_iterator" }, { "answer_id": 79071, "author": "archbishop", "author_id": 14529, "author_profile": "https://Stackoverflow.com/users/14529", "pm_score": 4, "selected": true, "text": "#define ci(container) container ## iter\n#define foreach_value(var, container) \\\n for (typeof((container).begin()) ci(container) = container.begin(); \\\n ci(container) != container.end(); ) \\\n for (typeof(ci(container)->second)* var = &ci(container)->second; \\\n ci(container) != container.end(); \\\n (++ci(container) != container.end()) ? \\\n (var = &ci(container)->second) : var)\n" }, { "answer_id": 79250, "author": "Zachary Garrett", "author_id": 14692, "author_profile": "https://Stackoverflow.com/users/14692", "pm_score": 2, "selected": false, "text": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cctype>\n\nint main(int argc, char* argv[]) {\n std::string s(\"my lowercase string\");\n std::transform(s.begin(), s.end(), s.begin(), toupper);\n std::cout << s << std::endl; // \"MY LOWERCASE STRING\"\n}\n" }, { "answer_id": 80671, "author": "Assaf Lavie", "author_id": 11208, "author_profile": "https://Stackoverflow.com/users/11208", "pm_score": 0, "selected": false, "text": "#define foreach(var, container) for (typeof((container).begin()) var = (container).begin(); var != (container).end(); ++var)\n" }, { "answer_id": 4214768, "author": "Artur Sowiński", "author_id": 512072, "author_profile": "https://Stackoverflow.com/users/512072", "pm_score": 1, "selected": false, "text": "#include <cstdio>\n#include <vector>\n#include \"foreach.h\"\n\nint main()\n{\n // make int vector and fill it\n vector<int> k;\n for (int i=0; i<10; ++i) k.push_back(i);\n\n // show what the upper loop filled\n foreach_ (it, k) printf(\"%i \",(*it));\n printf(\"\\n\");\n\n // show all of the data, but get rid of 4\n // http://en.wikipedia.org/wiki/Tetraphobia :)\n foreachdel_ (it, k)\n {\n if (*it == 4) it=k.erase(it);\n printf(\"%i \",(*it));\n }\n printf(\"\\n\");\n\n return 0;\n}\n 0 1 2 3 4 5 6 7 8 9\n0 1 2 3 5 6 7 8 9\n" }, { "answer_id": 7253042, "author": "Stuart Berg", "author_id": 162094, "author_profile": "https://Stackoverflow.com/users/162094", "pm_score": 1, "selected": false, "text": "#include <map>\n#include <string>\n#include <boost/range/adaptor/map.hpp>\n#include <boost/foreach.hpp>\n\nint main()\n{\n // Sample data\n std::map<int, std::string> myMap ;\n myMap[0] = \"Zero\" ;\n myMap[10] = \"Ten\" ;\n myMap[20] = \"Twenty\" ;\n\n // Loop over map values\n BOOST_FOREACH( std::string text, myMap | boost::adaptors::map_values )\n {\n std::cout << text << \" \" ;\n }\n}\n// Output:\n// Zero Ten Twenty\n" }, { "answer_id": 11972376, "author": "marko.ristin", "author_id": 1600678, "author_profile": "https://Stackoverflow.com/users/1600678", "pm_score": 0, "selected": false, "text": "foreach_value Boost foreach #include <boost/preprocessor/cat.hpp>\n#define MUNZEKONZA_FOREACH_IN_MAP_ID(x) BOOST_PP_CAT(x, __LINE__)\n\nnamespace munzekonza {\nnamespace foreach_in_map_private {\ninline bool set_false(bool& b) {\n b = false;\n return false;\n}\n\n}\n}\n\n#define MUNZEKONZA_FOREACH_VALUE(value, map) \\\nfor(auto MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_it) = map.begin(); \\\n MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_it) != map.end();) \\\nfor(bool MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue) = true; \\\n MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue) && \\\n MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_it) != map.end(); \\\n (MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue)) ? \\\n ((void)++MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_it)) : \\\n (void)0) \\\n if( munzekonza::foreach_in_map_private::set_false( \\\n MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue))) {} else \\\n for( value = MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_it)->second; \\\n !MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue); \\\n MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue) = true) \n #define MUNZEKONZA_FOREACH_VALUE foreach_value\n\nstd::map<int, std::string> mymap;\n// populate the map ...\n\nforeach_value( const std::string& value, mymap ) {\n // do something with value\n}\n\n// change value\nforeach_value( std::string& value, mymap ) {\n value = \"hey\";\n}\n" }, { "answer_id": 41991034, "author": "Zoltán Horváth", "author_id": 7503044, "author_profile": "https://Stackoverflow.com/users/7503044", "pm_score": 0, "selected": false, "text": "#define zforeach(var, container) for(auto var = (container).begin(); var != (container).end(); ++var)\n decltype((container).begin()) var \ndecltype(container)::iterator var\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14528/" ]
78,752
<p>I have read that using database keys in a URL is a bad thing to do.</p> <p>For instance,</p> <p>My table has 3 fields: <code>ID:int</code>, <code>Title:nvarchar(5)</code>, <code>Description:Text</code></p> <p>I want to create a page that displays a record. Something like ...</p> <pre><code>http://server/viewitem.aspx?id=1234 </code></pre> <ol> <li><p>First off, could someone elaborate on why this is a bad thing to do?</p></li> <li><p>and secondly, what are some ways to work around using primary keys in a url?</p></li> </ol>
[ { "answer_id": 78814, "author": "mislav", "author_id": 11687, "author_profile": "https://Stackoverflow.com/users/11687", "pm_score": 1, "selected": false, "text": "\"/questions/12345/delete\"" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14396/" ]
78,757
<p>How can I programmatically make a query in MS Access default to landscape when printed, specifically when viewing it as a PivotChart? I'm currently attempting this in MS Access 2003, but would like to see a solution for any version.</p>
[ { "answer_id": 79635, "author": "ahockley", "author_id": 8209, "author_profile": "https://Stackoverflow.com/users/8209", "pm_score": 3, "selected": true, "text": "Function SetLandscape()\n Application.Printer.Orientation = acPRORLandscape\nEnd Function\n" }, { "answer_id": 79740, "author": "Brettski", "author_id": 5836, "author_profile": "https://Stackoverflow.com/users/5836", "pm_score": 0, "selected": false, "text": "Private sub\n Application.Printer.Orientation = acPRORLandscape\n DoCmd.OpenQuery \"qry1\", acViewNormal, acReadOnly\n DoCmd.PrintOut acPrintAll\nEnd Sub\n docmd.Close acQuery, \"qry1\", acSaveNo\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3155/" ]
78,799
<p>What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right?</p> <p>I have code that looks something like this:</p> <pre><code>class DownloadThread: def foo(self): pass class DownloadManager(): def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadThread()) </code></pre> <p>But now I'm wondering if there's a situation where nesting would be better. Something like:</p> <pre><code>class DownloadManager(): class DownloadThread: def foo(self): pass def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadManager.DownloadThread()) </code></pre>
[ { "answer_id": 78858, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 8, "selected": true, "text": "class Foo(object):\n class __metaclass__(type):\n .... \n class Group(object):\n class cls1(object):\n ...\n\n class cls2(object):\n ...\n" }, { "answer_id": 78968, "author": "tim.tadh", "author_id": 14107, "author_profile": "https://Stackoverflow.com/users/14107", "pm_score": 3, "selected": false, "text": "class gen(object):\n class base_1(object): pass\n ...\n class base_n(object): pass\n\n def __init__(self, ...):\n ...\n def mk_cls(self, ..., type):\n '''makes a class based on the type passed in, the current state of\n the class, and the other inputs to the method'''\n" }, { "answer_id": 49812827, "author": "Thomas", "author_id": 4540266, "author_profile": "https://Stackoverflow.com/users/4540266", "pm_score": 4, "selected": false, "text": "class foo:\n\n class bar:\n ... # functionalities of a specific sub-feature of foo\n\n def __init__(self):\n self.a = self.bar()\n ...\n\n ... # other features of foo\n\n\nclass foo2(foo):\n\n class bar(foo.bar):\n ... # enhanced functionalities for this specific feature\n\n def __init__(self):\n foo.__init__(self)\n foo self.a = self.bar() foo.bar foo foo2.bar foo2 bar foo bar2 foo2 foo2 self.a = bar2()" }, { "answer_id": 66900415, "author": "Leon Chang", "author_id": 9749972, "author_profile": "https://Stackoverflow.com/users/9749972", "pm_score": 0, "selected": false, "text": "class Employee:\n\n def level(self, j):\n return j * 5E3\n\n def __init__(self, name, deg, yrs):\n self.name = name\n self.deg = deg\n self.yrs = yrs\n self.empInit = Employee.EmpInit(self.deg, self.level)\n self.base = Employee.EmpInit(self.deg, self.level).pay\n\n def pay(self):\n if self.deg in self.base:\n return self.base[self.deg]() + self.level(self.yrs)\n print(f\"Degree {self.deg} is not in the database {self.base.keys()}\")\n return 0\n\n class EmpInit:\n\n def __init__(self, deg, level):\n self.level = level\n self.j = deg\n self.pay = {1: self.t1, 2: self.t2, 3: self.t3}\n\n def t1(self): return self.level(1*self.j)\n def t2(self): return self.level(2*self.j)\n def t3(self): return self.level(3*self.j)\n\nif __name__ == '__main__':\n for loop in range(10):\n lst = [item for item in input(f\"Enter name, degree and years : \").split(' ')]\n e1 = Employee(lst[0], int(lst[1]), int(lst[2]))\n print(f'Employee {e1.name} with degree {e1.deg} and years {e1.yrs} is making {e1.pay()} dollars')\n print(\"EmpInit deg {0}\\nlevel {1}\\npay[deg]: {2}\".format(e1.empInit.j, e1.empInit.level, e1.base[e1.empInit.j]))\n" }, { "answer_id": 68819173, "author": "kharandziuk", "author_id": 1907902, "author_profile": "https://Stackoverflow.com/users/1907902", "pm_score": 1, "selected": false, "text": "class DownloadManager(object):\n class DowndloadException(Exception):\n pass\n\n def download(self):\n ...\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
78,801
<p>Running a rails site right now using SQLite3.</p> <p>About once every 500 requests or so, I get a</p> <p>ActiveRecord::StatementInvalid (SQLite3::BusyException: database is locked:...</p> <p>What's the way to fix this that would be minimally invasive to my code?</p> <p>I'm using SQLLite at the moment because you can store the DB in source control which makes backing up natural and you can push changes out very quickly. However, it's obviously not really set up for concurrent access. I'll migrate over to MySQL tomorrow morning.</p>
[ { "answer_id": 78870, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 0, "selected": false, "text": "- Open the database\ndb = sqlite3.open(\"filename\")\n\n-- Ten attempts are made to proceed, if the database is locked\nfunction my_busy_handler(attempts_made)\n if attempts_made < 10 then\n return true\n else\n return false\n end\nend\n\n-- Set the new busy handler\ndb:set_busy_handler(my_busy_handler)\n\n-- Use the database\ndb:exec(...)\n" }, { "answer_id": 739037, "author": "Rifkin Habsburg", "author_id": 89619, "author_profile": "https://Stackoverflow.com/users/89619", "pm_score": 6, "selected": false, "text": "production:\n adapter: sqlite3\n database: db/mysite_prod.sqlite3\n timeout: 10000\n" }, { "answer_id": 6099601, "author": "Ignacio Huerta", "author_id": 766296, "author_profile": "https://Stackoverflow.com/users/766296", "pm_score": 2, "selected": false, "text": " def begin_db_transaction #:nodoc:\n catch_schema_changes { @connection.transaction }\n end\n def begin_db_transaction #:nodoc:\n catch_schema_changes { @connection.transaction(:immediate) }\n end\n" }, { "answer_id": 26150137, "author": "Adrien Jarthon", "author_id": 304434, "author_profile": "https://Stackoverflow.com/users/304434", "pm_score": 2, "selected": false, "text": "active_record :immediate prepend module SqliteTransactionFix\n def begin_db_transaction\n log('begin immediate transaction', nil) { @connection.transaction(:immediate) }\n end\nend\n\nmodule ActiveRecord\n module ConnectionAdapters\n class SQLiteAdapter < AbstractAdapter\n prepend SqliteTransactionFix\n end\n end\nend\n" }, { "answer_id": 28494279, "author": "Balaji Radhakrishnan", "author_id": 3930758, "author_profile": "https://Stackoverflow.com/users/3930758", "pm_score": 2, "selected": false, "text": "bundle exec rake db:reset\n" }, { "answer_id": 28494445, "author": "John", "author_id": 3525295, "author_profile": "https://Stackoverflow.com/users/3525295", "pm_score": 0, "selected": false, "text": "ActiveRecord::Base.connection.execute(\"BEGIN TRANSACTION; END;\") \n" }, { "answer_id": 47793885, "author": "Elindor", "author_id": 3443954, "author_profile": "https://Stackoverflow.com/users/3443954", "pm_score": 1, "selected": false, "text": "db = SQLite3::Database.new \"#{path_to_your_db}/your_file.db\"\ndb.busy_timeout=(15000) # in ms, meaning it will retry for 15 seconds before it raises an exception.\n#This can be any number you want. Default value is 0.\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14559/" ]
78,826
<p>How do you use <code>gen_udp</code> in Erlang to do <a href="https://en.wikipedia.org/wiki/Multicast" rel="nofollow noreferrer">multicasting</a>? I know its in the code, there is just no documentation behind it. Sending out data is obvious and simple. I was wondering on how to add memberships. Not only adding memberships at start-up, but adding memberships while running would be useful too.</p>
[ { "answer_id": 81149, "author": "Bwooce", "author_id": 15290, "author_profile": "https://Stackoverflow.com/users/15290", "pm_score": 4, "selected": false, "text": " {ok, Socket} = gen_udp:open(Port, [binary, {active, false},\n {reuseaddr, true},{ip, Addr}, \n {add_membership, {Addr, LAddr}}]).\n Addr LAddr inet:setopts {drop_membership, {Addr, LAddr}}" }, { "answer_id": 1740065, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "-module(zcclient).\n\n-export([open/2,start/0]).\n-export([stop/1,receiver/0]).\n\nopen(Addr,Port) ->\n {ok,S} = gen_udp:open(Port,[{reuseaddr,true}, {ip,Addr}, {multicast_ttl,4}, {multicast_loop,false}, binary]),\n inet:setopts(S,[{add_membership,{Addr,{0,0,0,0}}}]),\n S.\n\nclose(S) -> gen_udp:close(S).\n\nstart() ->\n S=open({224,0,0,251},5353),\n Pid=spawn(?MODULE,receiver,[]),\n gen_udp:controlling_process(S,Pid),\n {S,Pid}.\n\nstop({S,Pid}) ->\n close(S),\n Pid ! stop.\n\nreceiver() ->\n receive\n {udp, _Socket, IP, InPortNo, Packet} ->\n io:format(\"~n~nFrom: ~p~nPort: ~p~nData: ~p~n\",[IP,InPortNo,inet_dns:decode(Packet)]),\n receiver();\n stop -> true;\n AnythingElse -> io:format(\"RECEIVED: ~p~n\",[AnythingElse]),\n receiver()\n end. \n" }, { "answer_id": 1880167, "author": "Matthias", "author_id": 228713, "author_profile": "https://Stackoverflow.com/users/228713", "pm_score": 2, "selected": false, "text": "{ok, Socket} = gen_udp:open(?PORT, [{reuseaddr,true}, {ip,?SERVER_IP},\n {multicast_ttl,4}, {multicast_loop,false}, binary]),\n {ok, Socket} = gen_udp:open(?PORT, [{reuseaddr,true}, {ip,?MULTICAST_IP},\n {multicast_ttl,4}, {multicast_loop,false}, binary]),\n -define(SERVER_IP, {10,31,123,123}). % The IP of the current computer\n-define(PORT, 5353).\n-define(MULTICAST_IP, {224,0,0,251}). \n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10432/" ]
78,849
<p>I have an image (mx) and i want to get the uint of the pixel that was clicked.</p> <p>Any ideas?</p>
[ { "answer_id": 79221, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 3, "selected": false, "text": "package {\n import flash.display.Bitmap;\n import flash.display.BitmapData;\n import flash.display.Loader;\n import flash.display.Sprite;\n import flash.events.Event;\n import flash.events.MouseEvent;\n import flash.net.URLRequest;\n\n public class BitmapDataExample extends Sprite {\n private var url:String = \"santa-drunk1.jpg\";\n private var size:uint = 200;\n private var image:Bitmap;\n\n public function BitmapDataExample() {\n configureAssets();\n }\n\n private function configureAssets():void {\n var loader:Loader = new Loader();\n loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);\n\n var request:URLRequest = new URLRequest(url);\n loader.load(request);\n addChild(loader);\n }\n\n private function completeHandler(event:Event):void {\n var loader:Loader = Loader(event.target.loader);\n this.image = Bitmap(loader.content);\n\n this.addEventListener(MouseEvent.CLICK, this.clickListener);\n }\n\n private function clickListener(event:MouseEvent):void {\n var pixelValue:uint = this.image.bitmapData.getPixel(event.localX, event.localY)\n trace(pixelValue.toString(16));\n }\n }\n}\n" }, { "answer_id": 85391, "author": "defmeta", "author_id": 10875, "author_profile": "https://Stackoverflow.com/users/10875", "pm_score": 4, "selected": true, "text": "import flash.display.Bitmap;\nimport flash.display.BitmapData;\nimport flash.events.*;\n\nstage.addEventListener(MouseEvent.CLICK, getColorSample);\n\nfunction getColorSample(e:MouseEvent):void {\n var bd:BitmapData = new BitmapData(stage.width, stage.height);\n bd.draw(stage);\n var b:Bitmap = new Bitmap(bd);\n trace(b.bitmapData.getPixel(stage.mouseX,stage.mouseX));\n}\n BitmapData Bitmap MOUSE_MOVE import flash.display.Bitmap;\nimport flash.display.BitmapData;\nimport flash.events.*;\n\nprivate var _stageBitmap:BitmapData;\n\nstage.addEventListener(MouseEvent.CLICK, getColorSample);\n\nfunction getColorSample(e:MouseEvent):void \n{\n if (_stageBitmap == null) {\n _stageBitmap = new BitmapData(stage.width, stage.height);\n }\n _stageBitmap.draw(stage);\n\n var rgb:uint = _stageBitmap.getPixel(stage.mouseX,stage.mouseY);\n\n var red:int = (rgb >> 16 & 0xff);\n var green:int = (rgb >> 8 & 0xff);\n var blue:int = (rgb & 0xff);\n\n trace(red + \",\" + green + \",\" + blue);\n}\n" }, { "answer_id": 8619705, "author": "darscan", "author_id": 53303, "author_profile": "https://Stackoverflow.com/users/53303", "pm_score": 3, "selected": false, "text": "private const bitmapData:BitmapData = new BitmapData(1, 1);\nprivate const matrix:Matrix = new Matrix();\nprivate const clipRect:Rectangle = new Rectangle(0, 0, 1, 1);\n\npublic function getColor(drawable:IBitmapDrawable, x:Number, y:Number):uint\n{\n matrix.setTo(1, 0, 0, 1, -x, -y)\n bitmapData.draw(drawable, matrix, null, null, clipRect);\n return bitmapData.getPixel(0, 0);\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1748529/" ]
78,852
<p>Mapping a collection of enums with NHibernate</p> <p>Specifically, using Attributes for the mappings.</p> <p>Currently I have this working mapping the collection as type Int32 and NH seems to take care of it, but it's not exactly ideal.</p> <p>The error I receive is "Unable to determine type" when trying to map the collection as of the type of the enum I am trying to map.</p> <p>I found a post that said to define a class as</p> <pre><code>public class CEnumType : EnumStringType { public CEnumType() : base(MyEnum) { } } </code></pre> <p>and then map the enum as CEnumType, but this gives "CEnumType is not mapped" or something similar.</p> <p>So has anyone got experience doing this?</p> <p>So anyway, just a simple reference code snippet to give an example with</p> <pre><code> [NHibernate.Mapping.Attributes.Class(Table = "OurClass")] public class CClass : CBaseObject { public enum EAction { do_action, do_other_action }; private IList&lt;EAction&gt; m_class_actions = new List&lt;EAction&gt;(); [NHibernate.Mapping.Attributes.Bag(0, Table = "ClassActions", Cascade="all", Fetch = CollectionFetchMode.Select, Lazy = false)] [NHibernate.Mapping.Attributes.Key(1, Column = "Class_ID")] [NHibernate.Mapping.Attributes.Element(2, Column = "EAction", Type = "Int32")] public virtual IList&lt;EAction&gt; Actions { get { return m_class_actions; } set { m_class_actions = value;} } } </code></pre> <p>So, anyone got the correct attributes for me to map this collection of enums as actual enums? It would be really nice if they were stored in the db as strings instead of ints too but it's not completely necessary.</p>
[ { "answer_id": 80485, "author": "alvin", "author_id": 15121, "author_profile": "https://Stackoverflow.com/users/15121", "pm_score": 1, "selected": false, "text": " public virtual ContractGroups Group\n {\n get\n {\n if (GroupString.IsNullOrEmpty())\n return ContractGroups.Default;\n\n return GroupString.ToEnum<ContractGroups>(); // extension method\n }\n set { GroupString = value.ToString(); }\n }\n\n // this is castle activerecord, you can map this property in NH mapping file as an ordinary string\n [Property(\"`Group`\", NotNull = true)] \n protected virtual string GroupString\n {\n get;\n set;\n }\n\n\n\n /// <summary>\n /// Converts to an enum of type <typeparamref name=\"TEnum\"/>.\n /// </summary>\n /// <typeparam name=\"TEnum\">The type of the enum.</typeparam>\n /// <param name=\"self\">The self.</param>\n /// <returns></returns>\n /// <remarks>From <see href=\"http://www.mono-project.com/Rocks\">Mono Rocks</see>.</remarks>\n public static TEnum ToEnum<TEnum>(this string self)\n where TEnum : struct, IComparable, IFormattable, IConvertible\n {\n Argument.SelfNotNull(self);\n\n return (TEnum)Enum.Parse(typeof(TEnum), self);\n }\n" }, { "answer_id": 214268, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 1, "selected": false, "text": "[NHibernate.Mapping.Attributes.Element(2, Column = \"EAction\", Type = \"Int32\")]\n [NHibernate.Mapping.Attributes.Element(2, Column = \"EAction\", Type = \"String\")]\n Int32 String" }, { "answer_id": 2807763, "author": "Lisa", "author_id": 314283, "author_profile": "https://Stackoverflow.com/users/314283", "pm_score": 2, "selected": false, "text": " \n\n<hibernate-mapping xmlns=\"urn:nhibernate-mapping-2.2\" assembly=\"YourAssembly\"\n auto-import=\"true\" default-lazy=\"false\">\n\n ...\n\n <class name=\"YourAssemblyNamespace.CEnum\" table=\"CEnumTable\" mutable=\"false\" >\n <id name=\"Id\" unsaved-value=\"0\" column=\"id\">\n <generator class=\"native\"/>\n </id>\n\n ...\n\n </class>\n\n</hibernate-mapping>\n\n\n <hibernate-mapping xmlns=\"urn:nhibernate-mapping-2.2\" assembly=\"YourAssembly\"\n auto-import=\"true\" default-lazy=\"false\">\n\n ...\n\n <class name=\"YourAssemblyNamespace.CEnum\" table=\"CEnumTable\" mutable=\"false\" >\n <id name=\"Id\" unsaved-value=\"0\" column=\"id\">\n <generator class=\"native\"/>\n </id>\n\n ...\n\n </class>\n\n</hibernate-mapping>\n [NHibernate.Mapping.Attributes.Class(Table = \"CEnumTable\")] //etc as you require" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/924607/" ]
78,869
<p>I'm looking around for a Java <a href="http://en.wikipedia.org/wiki/Code_signing" rel="noreferrer">code signing</a> certificate so my Java applets don't throw up such scary security warnings. However, all the places I've found offering them charge (in my opinion) way too much, like over USD200 per year. While doing research, a code signing certificate seems almost exactly the same as an <a href="http://en.wikipedia.org/wiki/SSL" rel="noreferrer">SSL</a> certificate.</p> <p>The main question I have: is it possible to buy an SSL certificate, but use it to sign Java applets?</p>
[ { "answer_id": 27676751, "author": "flup", "author_id": 1973271, "author_profile": "https://Stackoverflow.com/users/1973271", "pm_score": 1, "selected": false, "text": "/**\n * Check whether this certificate can be used for code signing.\n * @throws CertificateException if not.\n */\nprivate void checkCodeSigning(X509Certificate cert)\n throws CertificateException {\n Set<String> exts = getCriticalExtensions(cert);\n\n if (checkKeyUsage(cert, KU_SIGNATURE) == false) {\n throw new ValidatorException\n (\"KeyUsage does not allow digital signatures\",\n ValidatorException.T_EE_EXTENSIONS, cert);\n }\n\n if (checkEKU(cert, exts, OID_EKU_CODE_SIGNING) == false) {\n throw new ValidatorException\n (\"Extended key usage does not permit use for code signing\",\n ValidatorException.T_EE_EXTENSIONS, cert);\n }\n\n if (!SimpleValidator.getNetscapeCertTypeBit(cert, NSCT_SSL_CLIENT)) {\n throw new ValidatorException\n (\"Netscape cert type does not permit use for SSL client\",\n ValidatorException.T_EE_EXTENSIONS, cert);\n }\n\n // do not check Netscape cert type for JCE code signing checks\n // (some certs were issued with incorrect extensions)\n if (variant.equals(Validator.VAR_JCE_SIGNING) == false) {\n if (!SimpleValidator.getNetscapeCertTypeBit(cert, NSCT_CODE_SIGNING)) {\n throw new ValidatorException\n (\"Netscape cert type does not permit use for code signing\",\n ValidatorException.T_EE_EXTENSIONS, cert);\n }\n exts.remove(SimpleValidator.OID_NETSCAPE_CERT_TYPE);\n }\n\n // remove extensions we checked\n exts.remove(SimpleValidator.OID_KEY_USAGE);\n exts.remove(SimpleValidator.OID_EXTENDED_KEY_USAGE);\n\n checkRemainingExtensions(exts);\n}\n /**\n * Utility method checking if the extended key usage extension in\n * certificate cert allows use for expectedEKU.\n */\nprivate boolean checkEKU(X509Certificate cert, Set<String> exts,\n String expectedEKU) throws CertificateException {\n List<String> eku = cert.getExtendedKeyUsage();\n if (eku == null) {\n return true;\n }\n return eku.contains(expectedEKU) || eku.contains(OID_EKU_ANY_USAGE);\n}\n checkRemainingExtensions" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569/" ]
78,884
<p>I have an xslt sheet with some text similar to below:</p> <pre><code>&lt;xsl:text&gt;I am some text, and I want to be bold&lt;/xsl:text&gt; </code></pre> <p>I would like some text to be bold, but this doesn't work.</p> <pre><code>&lt;xsl:text&gt;I am some text, and I want to be &lt;strong&gt;bold&lt;strong&gt;&lt;/xsl:text&gt; </code></pre> <p>The deprecated b tag doesn't work either. How do I format text within an xsl:text tag?</p>
[ { "answer_id": 78904, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": false, "text": "<fo:inline font-weight=\"bold\"><xsl:text>Bold text</xsl:text></fo:inline>\n" }, { "answer_id": 80522, "author": "jelovirt", "author_id": 2679, "author_profile": "https://Stackoverflow.com/users/2679", "pm_score": 4, "selected": true, "text": "xsl:text <strong> <xsl:text>I am some text, and I want to be </xsl:text>\n<strong>bold<strong>\n<xsl:text> </xsl:text>\n" }, { "answer_id": 6410661, "author": "Pavan", "author_id": 732642, "author_profile": "https://Stackoverflow.com/users/732642", "pm_score": 0, "selected": false, "text": "<xsl:text>I am some text, and I want to be </xsl:text>\n<strong>bold<strong>\n<xsl:text> </xsl:text>\n <xsl:text disable-output-escaping=\"yes\">\n" }, { "answer_id": 59292527, "author": "Ricardo PSilva", "author_id": 3179207, "author_profile": "https://Stackoverflow.com/users/3179207", "pm_score": 0, "selected": false, "text": "<strong>This text is strong</strong>\n <strong>" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5989/" ]
78,905
<p>More specifically I am trying to make the mailto component show within my template; the same way as an article does. </p> <p>By default the mailto component opens in a new window. So far I changed the code so it opens on the same window, but that way the whole template is gone.</p> <p>Any suggestions?</p>
[ { "answer_id": 279605, "author": "Bingy", "author_id": 69518, "author_profile": "https://Stackoverflow.com/users/69518", "pm_score": 2, "selected": false, "text": "<jdoc:include type=\"component\" />\n <jdoc:include type=\"modules\" name=\"module_name_place_holder\" />\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131/" ]
78,909
<p>I have a few scripts on a site I recently started maintaining. I get those Object Not Found errors in IE6 (which Firefox fails to report in its Error Console?). What's the best way to debug these- any good cross-browser-compatible IDEs, or javascript debugging libraries of some sort?</p>
[ { "answer_id": 78930, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": 1, "selected": false, "text": "debugger;\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14563/" ]
78,913
<p>What is the single most effective practice to prevent <a href="http://en.wikipedia.org/wiki/Arithmetic_overflow" rel="nofollow noreferrer">arithmetic overflow</a> and <a href="http://en.wikipedia.org/wiki/Arithmetic_underflow" rel="nofollow noreferrer">underflow</a>?</p> <p>Some examples that come to mind are:</p> <ul> <li>testing based on valid input ranges</li> <li>validation using formal methods</li> <li>use of invariants</li> <li>detection at runtime using language features or libraries (this does not prevent it)</li> </ul>
[ { "answer_id": 78936, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 3, "selected": true, "text": "class CheckedInt\n{\nprivate: \n int Value;\n\npublic:\n // Constructor\n CheckedInt(int src) : Value(src) {}\n\n // Conversions back to int\n operator int&() { return Value; }\n operator const int &() const { return Value; }\n\n // Operators\n CheckedInt operator+(CheckedInt rhs) const\n {\n if (rhs.Value < 0 && rhs.Value + Value > Value)\n throw OverflowException();\n if (rhs.Value > 0 && rhs.Value + Value < Value)\n throw OverflowException();\n return CheckedInt(rhs.Value + Value);\n }\n\n // Lots more operators...\n};\n" }, { "answer_id": 1028197, "author": "mturquette", "author_id": 123330, "author_profile": "https://Stackoverflow.com/users/123330", "pm_score": 0, "selected": false, "text": "if (sum < operand1 || sum < operand2)\n omg_error();\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3836/" ]
78,924
<p>I have written a message handler function in Outlook's Visual Basic (we're using Outlook 2003 and Exchange Server) to help me sort out incoming email. </p> <p>It is working for me, except sometimes the rule fails and Outlook deactivates it. </p> <p>Then I turn the rule back on and manually run it on my Inbox to catch up. The rule spontaneously fails and deactivates several times a day. </p> <p>I would love to fix this once and for all.</p>
[ { "answer_id": 79000, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " Public WithEvents myOlItems As Outlook.Items\n\n Public Sub Application_Startup()\n ' Reference the items in the Inbox. Because myOlItems is declared\n ' \"WithEvents\" the ItemAdd event will fire below.\n ' Set myOlItems = Outlook.Session.GetDefaultFolder(olFolderInbox).Items\n Set myOlItems = Application.GetNamespace(\"MAPI\").GetDefaultFolder(olFolderInbox).Items\n End Sub\n\n Private Sub myOlItems_ItemAdd(ByVal Item As Object)\n On Error Resume Next\n If TypeName(Item) = \"MailItem\" Then\n MyMessageHandler Item\n End If\n End Sub\n\n Public Sub MyMessageHandler(ByRef Item As MailItem)\n Dim strSender As String\n Dim strSubject As String\n\n If TypeName(Item) <> \"MailItem\" Then\n Exit Sub\n End If\n\n strSender = LCase(Item.SenderEmailAddress)\n strSubject = Item.Subject\n\n rem do stuff\n rem do stuff\n rem do stuff\n End Sub\n strSubject = Item.Subject\n" }, { "answer_id": 8672202, "author": "Killian Tyler", "author_id": 1121762, "author_profile": "https://Stackoverflow.com/users/1121762", "pm_score": 4, "selected": false, "text": "Public Sub GetTypeNamesInbox()\nDim myOlItems As Outlook.Items\nSet myOlItems = application.GetNamespace(\"MAPI\").GetDefaultFolder(olFolderInbox).Items\nDim msg As Object\n\nFor Each msg In myOlItems\n Debug.Print TypeName(msg)\n 'emails are typename MailItem\n 'Meeting responses are typename MeetingItem\n 'Delivery receipts are typename ReportItem\nNext msg\n\nEnd Sub\n" }, { "answer_id": 11145745, "author": "JimmyPena", "author_id": 190829, "author_profile": "https://Stackoverflow.com/users/190829", "pm_score": 1, "selected": false, "text": "Object TypeOf TypeName MailItem Dim obj As Object\n\nIf TypeName(obj) = \"MailItem\" Then\n ' your code for mail items here\nEnd If\n" }, { "answer_id": 11634371, "author": "Radek", "author_id": 1549220, "author_profile": "https://Stackoverflow.com/users/1549220", "pm_score": 1, "selected": false, "text": "Dim objInboxFolder As MAPIFolder\nDim oItem As MailItem\nSet objInboxFolder = GetNamespace(\"MAPI\").GetDefaultFolder(olFolderInbox)\n\nFor Each Item In objInboxFolder.Items\n If TypeName(Item) = \"MailItem\" Then\n Set oItem = Item\n\nnext\n" }, { "answer_id": 12183994, "author": "Bruce E. Leandro", "author_id": 1634032, "author_profile": "https://Stackoverflow.com/users/1634032", "pm_score": 2, "selected": false, "text": "' Outlook Variables\n\n Dim objOutlook As Outlook.Application: Set objOutlook = New Outlook.Application\n Dim objNameSpace As Outlook.NameSpace: Set objNameSpace = objOutlook.GetNamespace(\"MAPI\")\n Dim objFolder As MAPIFolder: Set objFolder = objNameSpace.PickFolder()\n Dim objMailItem As Outlook.MailItem\n\n Dim iCounter As Integer: iCounter = objFolder.Items.Count\n Dim i As Integer\n\n For i = iCounter To 1 Step -1\n If TypeOf objFolder.Items(i) Is MailItem Then\n Set objMailItem = objFolder.Items(i)\n With objMailItem\n" }, { "answer_id": 16250499, "author": "htd", "author_id": 2234464, "author_profile": "https://Stackoverflow.com/users/2234464", "pm_score": 0, "selected": false, "text": "On Error Resume Next\nIf object.subject = Null 'produces an error when subject is null, otherwise allows a good read\n strSubject = \"\" 'sets the subject grab string to a null or empty string as a string\nElse\n strSubject = object.subject 'Sets the subject grab string to the subject of the message\\item\nEnd If\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
78,932
<p>I have the following HTML <code>&lt;select&gt;</code> element:</p> <pre><code>&lt;select id="leaveCode" name="leaveCode"&gt; &lt;option value="10"&gt;Annual Leave&lt;/option&gt; &lt;option value="11"&gt;Medical Leave&lt;/option&gt; &lt;option value="14"&gt;Long Service&lt;/option&gt; &lt;option value="17"&gt;Leave Without Pay&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Using a JavaScript function with the <code>leaveCode</code> number as a parameter, how do I select the appropriate option in the list?</p>
[ { "answer_id": 78945, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 11, "selected": true, "text": "function selectElement(id, valueToSelect) { \n let element = document.getElementById(id);\n element.value = valueToSelect;\n}\n\nselectElement('leaveCode', '11'); <select id=\"leaveCode\" name=\"leaveCode\">\n <option value=\"10\">Annual Leave</option>\n <option value=\"11\">Medical Leave</option>\n <option value=\"14\">Long Service</option>\n <option value=\"17\">Leave Without Pay</option>\n</select> element.dispatchEvent(new Event('change'))\n" }, { "answer_id": 78947, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 5, "selected": false, "text": "var formObj = document.getElementById('myForm');\nformObj.leaveCode[i].selected = true;\n for (var i = 0, len < formObj.leaveCode.length; i < len; i++) \n if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;\n" }, { "answer_id": 78950, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": -1, "selected": false, "text": "document.getElementById(\"optionID\").select();\n" }, { "answer_id": 78954, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 2, "selected": false, "text": "\nfunction foo(value)\n{\n var e = document.getElementById('leaveCode');\n if(e) e.value = value;\n}\n" }, { "answer_id": 78960, "author": "William", "author_id": 9193, "author_profile": "https://Stackoverflow.com/users/9193", "pm_score": 4, "selected": false, "text": "document.getElementById('leaveCode').value = '10';\n" }, { "answer_id": 78976, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 2, "selected": false, "text": "function setValue(inVal){\nvar dl = document.getElementById('leaveCode');\nvar el =0;\nfor (var i=0; i<dl.options.length; i++){\n if (dl.options[i].value == inVal){\n el=i;\n break;\n }\n}\ndl.selectedIndex = el;\n}\n" }, { "answer_id": 79040, "author": "Robert Swisher", "author_id": 1852, "author_profile": "https://Stackoverflow.com/users/1852", "pm_score": 1, "selected": false, "text": "function SelectElement(selectElementId, valueToSelect)\n{ \n var element = document.getElementById(selectElementId);\n element.value = valueToSelect;\n}\n" }, { "answer_id": 79528, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 2, "selected": false, "text": "function selectValue(val)\n{\n var lc = document.form1.leaveCode;\n for (i=0; i&lt;lc.length; i++)\n {\n if (lc.options[i].value == val)\n {\n lc.selectedIndex = i;\n return;\n }\n }\n}\n" }, { "answer_id": 79534, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 5, "selected": false, "text": "function setSelectValue (id, val) {\n document.getElementById(id).value = val;\n}\nsetSelectValue('leaveCode', 14);\n" }, { "answer_id": 4519880, "author": "Einar Ólafsson", "author_id": 373032, "author_profile": "https://Stackoverflow.com/users/373032", "pm_score": 7, "selected": false, "text": "$('#leaveCode').val('14');\n <option> Document document.querySelector document.querySelector('#leaveCode').value = '14'\n document.getElementById() id document.getElementById('leaveCode').value = '14'\n const jQueryFunction = () => {\n \n $('#leaveCode').val('14'); \n \n}\n\nconst querySelectorFunction = () => {\n \n document.querySelector('#leaveCode').value = '14' \n \n}\n\nconst getElementByIdFunction = () => {\n \n document.getElementById('leaveCode').value='14' \n \n} input {\n display:block;\n margin: 10px;\n padding: 10px\n} <select id=\"leaveCode\" name=\"leaveCode\">\n <option value=\"10\">Annual Leave</option>\n <option value=\"11\">Medical Leave</option>\n <option value=\"14\">Long Service</option>\n <option value=\"17\">Leave Without Pay</option>\n</select>\n\n<input type=\"button\" value=\"$('#leaveCode').val('14');\" onclick=\"jQueryFunction()\" />\n<input type=\"button\" value=\"document.querySelector('#leaveCode').value = '14'\" onclick=\"querySelectorFunction()\" />\n<input type=\"button\" value=\"document.getElementById('leaveCode').value = '14'\" onclick=\"getElementByIdFunction()\" />\n\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>" }, { "answer_id": 5346940, "author": "Lana", "author_id": 665322, "author_profile": "https://Stackoverflow.com/users/665322", "pm_score": 2, "selected": false, "text": "<a onclick=\"location.href='contact.php?option=1';\" style=\"cursor:pointer;\">Sales</a>\n<a onclick=\"location.href='contact.php?option=2';\" style=\"cursor:pointer;\">IT</a>\n <?\nif (isset($_GET['option']) && $_GET['option'] != \"\") {\n$pg = $_GET['option']; \n} ?>\n <select>\n<option value=\"Sales\" <? if ($pg == '1') { echo \"selected\"; } ?> >Sales</option>\n<option value=\"IT\" <? if ($pg == '2') { echo \"selected\"; } ?> >IT</option>\n</select>\n" }, { "answer_id": 11905147, "author": "Toskan", "author_id": 533426, "author_profile": "https://Stackoverflow.com/users/533426", "pm_score": 4, "selected": false, "text": "$(function() {\n var oldT = new Date().getTime();\n var element = document.getElementById('myId');\n element.value = 4;\n console.error(new Date().getTime() - oldT);\n\n oldT = new Date().getTime();\n $(\"#myId option\").filter(function() {\n return $(this).attr('value') == 4;\n }).attr('selected', true);\n console.error(new Date().getTime() - oldT);\n\n oldT = new Date().getTime();\n $(\"#myId\").val(\"4\");\n console.error(new Date().getTime() - oldT);\n});\n" }, { "answer_id": 21422704, "author": "almyz125", "author_id": 1253882, "author_profile": "https://Stackoverflow.com/users/1253882", "pm_score": -1, "selected": false, "text": "$value = '11';\n$first = '';\n$second = '';\n$third = '';\n$fourth = '';\n\nswitch($value) {\n case '10' :\n $first = 'selected';\n break;\n case '11' :\n $second = 'selected';\n break;\n case '14' :\n $third = 'selected';\n break;\n case '17' :\n $fourth = 'selected';\n break;\n }\n\necho'\n<select id=\"leaveCode\" name=\"leaveCode\">\n <option value=\"10\" '. $first .'>Annual Leave</option>\n <option value=\"11\" '. $second .'>Medical Leave</option>\n <option value=\"14\" '. $third .'>Long Service</option>\n <option value=\"17\" '. $fourth .'>Leave Without Pay</option>\n</select>';\n" }, { "answer_id": 30573683, "author": "lumi77", "author_id": 236928, "author_profile": "https://Stackoverflow.com/users/236928", "pm_score": 4, "selected": false, "text": "$(\"#leaveCode\").val(\"14\");\n var leaveCode = document.querySelector('#leaveCode');\nleaveCode[i].selected = true;\n $(\"#leaveCode\").val(\"14\").change();\n var leaveCode = document.querySelector('#leaveCode');\nleaveCode[i].selected = true;\n$(leaveCode).change();\n" }, { "answer_id": 37445649, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "$(\"._statusDDL\").val('2');\n $('select').prop('selectedIndex', 3); \n" }, { "answer_id": 63377136, "author": "Ashutosh Tiwari", "author_id": 12125692, "author_profile": "https://Stackoverflow.com/users/12125692", "pm_score": 0, "selected": false, "text": " window.addEventListener(\"load\", function () {\n // Selecting Element with ID - leaveCode //\n var formObj = document.getElementById('leaveCode');\n\n // Setting option as selected\n let len;\n for (let i = 0, len = formObj.length; i < len; i++){\n if (formObj[i].value == '<value to show in Select>') \n formObj.options[i].selected = true;\n }\n });\n" }, { "answer_id": 63882977, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 4, "selected": false, "text": "leaveCode.value = '14';\n leaveCode.value = '14'; <select id=\"leaveCode\" name=\"leaveCode\">\n <option value=\"10\">Annual Leave</option>\n <option value=\"11\">Medical Leave</option>\n <option value=\"14\">Long Service</option>\n <option value=\"17\">Leave Without Pay</option>\n</select>" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6340/" ]
78,974
<p>I've written a control that inherits from the <code>System.Web.UI.WebControls.DropDownList</code> and so I don't have any code in front for this control, but I still want to set the OutputCache directive. I there any way to set this in the C# code, say with an attribute or something like that? </p> <p>I'm particularly hoping to be able to replicate the <code>VaryByParam</code> property</p>
[ { "answer_id": 79012, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": 1, "selected": false, "text": "Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));\nResponse.Cache.SetCacheability(HttpCacheability.Server);\nResponse.Cache.SetValidUntilExpires(true);\n" }, { "answer_id": 3258564, "author": "matt-dot-net", "author_id": 380518, "author_profile": "https://Stackoverflow.com/users/380518", "pm_score": 3, "selected": true, "text": " List<Object> listOfObjects = null;\n//assuming a List of Objects... it doesn't matter whatever type of data you use\n if (Context.Cache[\"MyDataCacheKey\"] == null)\n {\n // data not cached, load it from database\n listOfObjects = GetDataFromDB();\n//add your data to the context cache with a sliding expiration of 10 minutes.\n Context.Cache.Add(\"MyDataCacheKey\", listOfObjects, null,\n System.Web.Caching.Cache.NoAbsoluteExpiration,\n TimeSpan.FromMinutes(10.0),\n System.Web.Caching.CacheItemPriority.Normal, null);\n }\n else\n listOfObjects = (List<Object>)Context.Cache[\"MyDataCacheKey\"];\n\n DropDownList1.DataSource = listOfObjects;\n DropDownList1.DataBind();\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975/" ]
78,978
<p>I'm working on a regular expression in a <code>.NET</code> project to get a specific tag. I would like to match the entire DIV tag and its contents:</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;title&gt;Test&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;p&gt;The first paragraph.&lt;/p&gt; &lt;div id='super_special'&gt; &lt;p&gt;The Store paragraph&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/head&gt; </code></pre> <p>Code:</p> <pre><code> Regex re = new Regex("(&lt;div id='super_special'&gt;.*?&lt;/div&gt;)", RegexOptions.Multiline); if (re.IsMatch(test)) Console.WriteLine("it matches"); else Console.WriteLine("no match"); </code></pre> <p>I want to match this:</p> <pre><code>&lt;div id="super_special"&gt; &lt;p&gt;Anything could go in here...doesn't matter. Let's get it all&lt;/p&gt; &lt;/div&gt; </code></pre> <p>I thought <code>.</code> was supposed to get all characters, but it seems to having trouble with the carriage returns. What is my regex missing?</p> <p>Thanks.</p>
[ { "answer_id": 78985, "author": "mopoke", "author_id": 14054, "author_profile": "https://Stackoverflow.com/users/14054", "pm_score": 1, "selected": false, "text": "m{<div id=\"super_special\">.*?</span>}s\n" }, { "answer_id": 78995, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "re.compile('<div id=\"super_special\">.*?</div>',re.S).sub(your_html,'')\n" }, { "answer_id": 79024, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 3, "selected": false, "text": "/m" }, { "answer_id": 79032, "author": "Bennor McCarthy", "author_id": 14451, "author_profile": "https://Stackoverflow.com/users/14451", "pm_score": 1, "selected": false, "text": "(?s)(<div id=\"super_special\">.*?</div>)\n" }, { "answer_id": 79066, "author": "Mike Tunnicliffe", "author_id": 13956, "author_profile": "https://Stackoverflow.com/users/13956", "pm_score": 1, "selected": false, "text": " <div id=\"super_special\">\n <div>Nothing</div>\n <p>Anything could go in here...doesn't matter. Let's get it all</p>\n </div>\n <div id=\"super_special\">\n <div>Nothing</div>\n" }, { "answer_id": 79079, "author": "André Chalella", "author_id": 4850, "author_profile": "https://Stackoverflow.com/users/4850", "pm_score": 2, "selected": true, "text": "<div id=\"super_special\">\n I'm the wanted div!\n</div>\n<div id=\"not_special\">\n I'm not wanted, but I've been caught too :(\n</div>\n </div> <div>" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27870/" ]
79,041
<p>I have a web system which has a classical parent-children menu saved in a database, with fields id as the PK, and parent_id to pointing to the owning menu. (Yes, I know this doesn't scale very well, but that's another topic). </p> <p>So for these records (id-parent_id pairs):</p> <pre><code>0-7 0-4 4-9 4-14 4-16 9-6 </code></pre> <p>I have this tree:</p> <pre><code>0 ├ 7 └ 4 ├ 9 | └ 6 ├ 14 └ 16 </code></pre> <p>I'm needing to hide a top node, so I have to make a list of all the childrens of that certain node, i.e. for 4, they will be (9, 6, 14, 16). Order doesn't matters.</p> <p>I'm confused... does this fits into the classical tree problems? or is it a graph one?</p> <p>How can I compose this structure and solve this problem using php?</p>
[ { "answer_id": 79067, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 2, "selected": true, "text": "nodeList = {}\nenumerateNodes(rootNode, nodeList);\n\nfunction enumerateNodes(node, nodeList) {\n nodeList += node;\n foreach ( childnode in node.children ) {\n enumerateNodes(childnode, nodeList);\n }\n}\n" }, { "answer_id": 79232, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 0, "selected": false, "text": "def get_subtree(node)\n if children.size > 0\n return children.collect { |n| get_subtree(n) }\n else\n return node\n end\nend\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/861/" ]
79,054
<p>Why does Leopard mangle some symbols with $non_lazy_ptr? More importantly what is the best method to fix undefined symbol errors because a symbol has been mangled with $non_lazy_ptr?</p>
[ { "answer_id": 3062322, "author": "Ciryon", "author_id": 22012, "author_profile": "https://Stackoverflow.com/users/22012", "pm_score": 1, "selected": false, "text": "extern NSString* const someString; NSString* const someString=@\"someString\";" }, { "answer_id": 3462790, "author": "Tom S.", "author_id": 393049, "author_profile": "https://Stackoverflow.com/users/393049", "pm_score": 2, "selected": false, "text": "ranlib -c libwhatever.a\n _PJ_NO_MEMORY_EXCEPTION _PJ_NO_MEMORY_EXCEPTION$non_lazy_ptr $(LIB): $(OBJDIRS) $(OBJS) $($(APP)_EXTRA_DEP)\n if test ! -d $(LIBDIR); then $(subst @@,$(subst /,$(HOST_PSEP),$(LIBDIR)),$(HOST_MKDIR)); fi\n $(LIBTOOL) -o $(LIB) $(OBJS)\n $(RANLIB) -c $(LIB)\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
79,111
<p>Kind of a special case problem:</p> <ul> <li>I start a process with <code>System.Diagnostics.Process.Start(..)</code></li> <li>The process opens a splash screen -- this splash screen becomes the main window.</li> <li>The splash screen closes and the 'real' UI is shown. The main window (splash screen) is now invalid.</li> <li>I still have the Process object, and I can query its handle, module, etc. But the main window handle is now invalid.</li> </ul> <p>I need to get the process's UI (or UI handle) at this point. Assume I cannot change the behavior of the process to make this any easier (or saner).</p> <p>I have looked around online but I'll admit I didn't look for more than an hour. Seemed like it should be somewhat trivial :-(</p>
[ { "answer_id": 79201, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 3, "selected": false, "text": "FindWindow FindWindowEx" }, { "answer_id": 79205, "author": "MB.", "author_id": 11961, "author_profile": "https://Stackoverflow.com/users/11961", "pm_score": 4, "selected": true, "text": "EnumWindowsProc GetWindowThreadProcessId IsWindowVisible GetWindowCaption GetWindowTextLength hWnd" }, { "answer_id": 79277, "author": "blackwing", "author_id": 9107, "author_profile": "https://Stackoverflow.com/users/9107", "pm_score": 1, "selected": false, "text": "MainWindowHandle FindWindow GetWindowThreadProcessId" }, { "answer_id": 4536066, "author": "Giova", "author_id": 554557, "author_profile": "https://Stackoverflow.com/users/554557", "pm_score": 2, "selected": false, "text": "public bool IsWindowActive(Int32 PID)\n{\n return IsWindowActive(Process.GetProcessById(PID));\n}\n\n[DllImport(\"user32.dll\")]\nprivate static extern\nIntPtr GetForegroundWindow();\n\npublic bool IsWindowActive(Process proc)\n{\n proc.Refresh();\n return proc.MainWindowHandle.Equals(GetForegroundWindow());\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14656/" ]
79,121
<p>So, im trying to write some code that utilizes Nvidia's CUDA architecture. I noticed that copying to and from the device was really hurting my overall performance, so now I am trying to move a large amount of data onto the device.</p> <p>As this data is used in numerous functions, I would like it to be global. Yes, I can pass pointers around, but I would really like to know how to work with globals in this instance. </p> <p>So, I have device functions that want to access a device allocated array.</p> <p>Ideally, I could do something like:</p> <pre><code>__device__ float* global_data; main() { cudaMalloc(global_data); kernel1&lt;&lt;&lt;blah&gt;&gt;&gt;(blah); //access global data kernel2&lt;&lt;&lt;blah&gt;&gt;&gt;(blah); //access global data again } </code></pre> <p>However, I havent figured out how to create a dynamic array. I figured out a work around by declaring the array as follows:</p> <pre><code>__device__ float global_data[REALLY_LARGE_NUMBER]; </code></pre> <p>And while that doesn't require a cudaMalloc call, I would prefer the dynamic allocation approach.</p>
[ { "answer_id": 79256, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "float* devPtr;\ncudaMalloc((void**)&devPtr, 256 * sizeof(*devPtr));\ncudaMemset(devPtr, 0, 256 * sizeof(*devPtr));\n __global__\nvoid kernel1(float *some_neat_data)\n{\n some_neat_data[threadIdx.x]++;\n}\n\n__global__\nvoid kernel2(float *potentially_that_same_neat_data)\n{\n potentially_that_same_neat_data[threadIdx.x] *= 0.3f;\n}\n float* devPtr;\ncudaMalloc((void**)&devPtr, 256 * sizeof(*devPtr));\ncudaMemset(devPtr, 0, 256 * sizeof(*devPtr));\n\nkernel1<<<1,128>>>(devPtr);\nkernel2<<<1,128>>>(devPtr);\n #include <algorithm>\n\n__constant__ float devPtr[1024];\n\n__global__\nvoid kernel1(float *some_neat_data)\n{\n some_neat_data[threadIdx.x] = devPtr[0] * devPtr[1];\n}\n\n__global__\nvoid kernel2(float *potentially_that_same_neat_data)\n{\n potentially_that_same_neat_data[threadIdx.x] *= devPtr[2];\n}\n\n\nint main(int argc, char *argv[])\n{\n float some_data[256];\n for (int i = 0; i < sizeof(some_data) / sizeof(some_data[0]); i++)\n {\n some_data[i] = i * 2;\n }\n cudaMemcpyToSymbol(devPtr, some_data, std::min(sizeof(some_data), sizeof(devPtr) ));\n float* otherDevPtr;\n cudaMalloc((void**)&otherDevPtr, 256 * sizeof(*otherDevPtr));\n cudaMemset(otherDevPtr, 0, 256 * sizeof(*otherDevPtr));\n\n kernel1<<<1,128>>>(otherDevPtr);\n kernel2<<<1,128>>>(otherDevPtr);\n\n return 0;\n}\n" }, { "answer_id": 79796, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "#include <algorithm>\n\n#define NDEBUG\n#define CUT_CHECK_ERROR(errorMessage) do { \\\n cudaThreadSynchronize(); \\\n cudaError_t err = cudaGetLastError(); \\\n if( cudaSuccess != err) { \\\n fprintf(stderr, \"Cuda error: %s in file '%s' in line %i : %s.\\n\", \\\n errorMessage, __FILE__, __LINE__, cudaGetErrorString( err) );\\\n exit(EXIT_FAILURE); \\\n } } while (0)\n\n\n__device__ float *devPtr;\n\n__global__\nvoid kernel1(float *some_neat_data)\n{\n devPtr = some_neat_data;\n}\n\n__global__\nvoid kernel2(void)\n{\n devPtr[threadIdx.x] *= .3f;\n}\n\n\nint main(int argc, char *argv[])\n{\n float* otherDevPtr;\n cudaMalloc((void**)&otherDevPtr, 256 * sizeof(*otherDevPtr));\n cudaMemset(otherDevPtr, 0, 256 * sizeof(*otherDevPtr));\n\n kernel1<<<1,128>>>(otherDevPtr);\n CUT_CHECK_ERROR(\"kernel1\");\n\n kernel2<<<1,128>>>();\n\n CUT_CHECK_ERROR(\"kernel2\");\n\n return 0;\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14621/" ]
79,126
<p>I'm building a function to extend the <code>Enum.Parse</code> concept that</p> <ul> <li>Allows a default value to be parsed in case that an Enum value is not found</li> <li>Is case insensitive</li> </ul> <p>So I wrote the following:</p> <pre><code>public static T GetEnumFromString&lt;T&gt;(string value, T defaultValue) where T : Enum { if (string.IsNullOrEmpty(value)) return defaultValue; foreach (T item in Enum.GetValues(typeof(T))) { if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item; } return defaultValue; } </code></pre> <p>I am getting a Error Constraint cannot be special class <code>System.Enum</code>.</p> <p>Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the <code>Parse</code> function and pass a type as an attribute, which forces the ugly boxing requirement to your code.</p> <p><strong>EDIT</strong> All suggestions below have been greatly appreciated, thanks.</p> <p>Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML)</p> <pre><code>public static class EnumUtils { public static T ParseEnum&lt;T&gt;(string value, T defaultValue) where T : struct, IConvertible { if (!typeof(T).IsEnum) throw new ArgumentException(&quot;T must be an enumerated type&quot;); if (string.IsNullOrEmpty(value)) return defaultValue; foreach (T item in Enum.GetValues(typeof(T))) { if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item; } return defaultValue; } } </code></pre> <p><strong>EDIT:</strong> (16th Feb 2015) Christopher Currens has posted <a href="https://stackoverflow.com/a/8086788">a compiler enforced type-safe generic solution in MSIL or F#</a> below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page.</p> <p><strong>EDIT 2:</strong> (13th Apr 2021) As this has now been addressed, and supported, since C# 7.3, I have changed the accepted answer, though full perusal of the top answers is worth it for academic, and historical, interest :)</p>
[ { "answer_id": 79148, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": 3, "selected": false, "text": "public static TValue ParseEnum<TValue>(string value, TValue defaultValue)\n where TValue : struct // enum \n{\n try\n {\n if (String.IsNullOrEmpty(value))\n return defaultValue;\n return (TValue)Enum.Parse(typeof (TValue), value);\n }\n catch(Exception ex)\n {\n return defaultValue;\n }\n}\n" }, { "answer_id": 79251, "author": "Bivoauc", "author_id": 14715, "author_profile": "https://Stackoverflow.com/users/14715", "pm_score": 4, "selected": false, "text": "public static T ParseEnum<T>(string enumString)\n where T : struct // enum \n {\n if (String.IsNullOrEmpty(enumString) || !typeof(T).IsEnum)\n throw new Exception(\"Type given must be an Enum\");\n try\n {\n\n return (T)Enum.Parse(typeof(T), enumString, true);\n }\n catch (Exception ex)\n {\n return default(T);\n }\n}\n" }, { "answer_id": 79319, "author": "Karg", "author_id": 12685, "author_profile": "https://Stackoverflow.com/users/12685", "pm_score": 4, "selected": false, "text": "internal sealed class GenericTypeThatRequiresAnEnum<T> {\n static GenericTypeThatRequiresAnEnum() {\n if (!typeof(T).IsEnum) {\n throw new ArgumentException(\"T must be an enumerated type\");\n }\n }\n}\n" }, { "answer_id": 79903, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 10, "selected": false, "text": "Enum IConvertible public T GetEnumFromString<T>(string value) where T : struct, IConvertible\n{\n if (!typeof(T).IsEnum) \n {\n throw new ArgumentException(\"T must be an enumerated type\");\n }\n\n //...\n}\n IConvertible" }, { "answer_id": 2661254, "author": "Sunny Rajwadi", "author_id": 319544, "author_profile": "https://Stackoverflow.com/users/319544", "pm_score": 3, "selected": false, "text": "public static class XmlEnumExtension\n{\n public static string ReadXmlEnumAttribute(this Enum value)\n {\n if (value == null) throw new ArgumentNullException(\"value\");\n var attribs = (XmlEnumAttribute[]) value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof (XmlEnumAttribute), true);\n return attribs.Length > 0 ? attribs[0].Name : value.ToString();\n }\n\n public static T ParseXmlEnumAttribute<T>(this string str)\n {\n foreach (T item in Enum.GetValues(typeof(T)))\n {\n var attribs = (XmlEnumAttribute[])item.GetType().GetField(item.ToString()).GetCustomAttributes(typeof(XmlEnumAttribute), true);\n if(attribs.Length > 0 && attribs[0].Name.Equals(str)) return item;\n }\n return (T)Enum.Parse(typeof(T), str, true);\n }\n}\n\npublic enum MyEnum\n{\n [XmlEnum(\"First Value\")]\n One,\n [XmlEnum(\"Second Value\")]\n Two,\n Three\n}\n\n static void Main()\n {\n // Parsing from XmlEnum attribute\n var str = \"Second Value\";\n var me = str.ParseXmlEnumAttribute<MyEnum>();\n System.Console.WriteLine(me.ReadXmlEnumAttribute());\n // Parsing without XmlEnum\n str = \"Three\";\n me = str.ParseXmlEnumAttribute<MyEnum>();\n System.Console.WriteLine(me.ReadXmlEnumAttribute());\n me = MyEnum.One;\n System.Console.WriteLine(me.ReadXmlEnumAttribute());\n}\n" }, { "answer_id": 3859812, "author": "Jeff", "author_id": 164438, "author_profile": "https://Stackoverflow.com/users/164438", "pm_score": 2, "selected": false, "text": "public static IEnumerable<TEnum> GetEnumValues()\n{\n Type enumType = typeof(TEnum);\n\n if(!enumType.IsEnum)\n throw new ArgumentException(\"Type argument must be Enum type\");\n\n Array enumValues = Enum.GetValues(enumType);\n return enumValues.Cast<TEnum>();\n}\n" }, { "answer_id": 4460247, "author": "Martin", "author_id": 394076, "author_profile": "https://Stackoverflow.com/users/394076", "pm_score": 4, "selected": false, "text": "public T LoadEnum<T>(string value, T defaultValue = default(T)) where T : struct, IComparable, IFormattable, IConvertible\n{\n if (Enum.IsDefined(typeof(T), value))\n {\n return (T)Enum.Parse(typeof(T), value, true);\n }\n return defaultValue;\n}\n" }, { "answer_id": 8086788, "author": "Christopher Currens", "author_id": 721276, "author_profile": "https://Stackoverflow.com/users/721276", "pm_score": 11, "selected": true, "text": "public static Dictionary<int, string> EnumNamedValues<T>() where T : System.Enum\n{\n var result = new Dictionary<int, string>();\n var values = Enum.GetValues(typeof(T));\n\n foreach (int item in values)\n result.Add(item, Enum.GetName(typeof(T), item));\n return result;\n}\n // license: http://www.apache.org/licenses/LICENSE-2.0.html\n.assembly MyThing{}\n.class public abstract sealed MyThing.Thing\n extends [mscorlib]System.Object\n{\n .method public static !!T GetEnumFromString<valuetype .ctor ([mscorlib]System.Enum) T>(string strValue,\n !!T defaultValue) cil managed\n {\n .maxstack 2\n .locals init ([0] !!T temp,\n [1] !!T return_value,\n [2] class [mscorlib]System.Collections.IEnumerator enumerator,\n [3] class [mscorlib]System.IDisposable disposer)\n // if(string.IsNullOrEmpty(strValue)) return defaultValue;\n ldarg strValue\n call bool [mscorlib]System.String::IsNullOrEmpty(string)\n brfalse.s HASVALUE\n br RETURNDEF // return default it empty\n \n // foreach (T item in Enum.GetValues(typeof(T)))\n HASVALUE:\n // Enum.GetValues.GetEnumerator()\n ldtoken !!T\n call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)\n call class [mscorlib]System.Array [mscorlib]System.Enum::GetValues(class [mscorlib]System.Type)\n callvirt instance class [mscorlib]System.Collections.IEnumerator [mscorlib]System.Array::GetEnumerator() \n stloc enumerator\n .try\n {\n CONDITION:\n ldloc enumerator\n callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()\n brfalse.s LEAVE\n \n STATEMENTS:\n // T item = (T)Enumerator.Current\n ldloc enumerator\n callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()\n unbox.any !!T\n stloc temp\n ldloca.s temp\n constrained. !!T\n \n // if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;\n callvirt instance string [mscorlib]System.Object::ToString()\n callvirt instance string [mscorlib]System.String::ToLower()\n ldarg strValue\n callvirt instance string [mscorlib]System.String::Trim()\n callvirt instance string [mscorlib]System.String::ToLower()\n callvirt instance bool [mscorlib]System.String::Equals(string)\n brfalse.s CONDITION\n ldloc temp\n stloc return_value\n leave.s RETURNVAL\n \n LEAVE:\n leave.s RETURNDEF\n }\n finally\n {\n // ArrayList's Enumerator may or may not inherit from IDisposable\n ldloc enumerator\n isinst [mscorlib]System.IDisposable\n stloc.s disposer\n ldloc.s disposer\n ldnull\n ceq\n brtrue.s LEAVEFINALLY\n ldloc.s disposer\n callvirt instance void [mscorlib]System.IDisposable::Dispose()\n LEAVEFINALLY:\n endfinally\n }\n \n RETURNDEF:\n ldarg defaultValue\n stloc return_value\n \n RETURNVAL:\n ldloc return_value\n ret\n }\n} \n T GetEnumFromString<T>(string valueString, T defaultValue) where T : Enum\n using MyThing;\n// stuff...\nprivate enum MyEnum { Yes, No, Okay }\nstatic void Main(string[] args)\n{\n Thing.GetEnumFromString(\"No\", MyEnum.Yes); // returns MyEnum.No\n Thing.GetEnumFromString(\"Invalid\", MyEnum.Okay); // returns MyEnum.Okay\n Thing.GetEnumFromString(\"AnotherInvalid\", 0); // compiler error, not an Enum\n}\n System.Enum .assembly MyThing{} ilasm.exe /DLL /OUTPUT=MyThing.netmodule\n /addmodule:{files} enum type MyThing =\n static member GetEnumFromString<'T when 'T :> Enum> str defaultValue: 'T =\n /// protect for null (only required in interop with C#)\n let str = if isNull str then String.Empty else str\n\n Enum.GetValues(typedefof<'T>)\n |> Seq.cast<_>\n |> Seq.tryFind(fun v -> String.Compare(v.ToString(), str.Trim(), true) = 0)\n |> function Some x -> x | None -> defaultValue\n FSharp.Core // works, result is inferred to have type StringComparison\nvar result = MyThing.GetEnumFromString(\"OrdinalIgnoreCase\", StringComparison.Ordinal);\n// type restriction is recognized by C#, this fails at compile time\nvar result = MyThing.GetEnumFromString(\"OrdinalIgnoreCase\", 42);\n" }, { "answer_id": 10273741, "author": "expert", "author_id": 226895, "author_profile": "https://Stackoverflow.com/users/226895", "pm_score": 1, "selected": false, "text": "where T : Enum public static T GetEnumFromString<T>(string strValue, T defaultValue)\n{\n // Check if it realy enum at runtime \n if (!typeof(T).IsEnum)\n throw new ArgumentException(\"Method GetEnumFromString can be used with enums only\");\n\n if (!string.IsNullOrEmpty(strValue))\n {\n IEnumerator enumerator = Enum.GetValues(typeof(T)).GetEnumerator();\n while (enumerator.MoveNext())\n {\n T temp = (T)enumerator.Current;\n if (temp.ToString().ToLower().Equals(strValue.Trim().ToLower()))\n return temp;\n }\n }\n\n return defaultValue;\n}\n" }, { "answer_id": 16736914, "author": "Yahoo Serious", "author_id": 422877, "author_profile": "https://Stackoverflow.com/users/422877", "pm_score": 5, "selected": false, "text": "ignoreCase defaultValue TryParse ParseOrDefault public abstract class ConstrainedEnumParser<TClass> where TClass : class\n// value type constraint S (\"TEnum\") depends on reference type T (\"TClass\") [and on struct]\n{\n // internal constructor, to prevent this class from being inherited outside this code\n internal ConstrainedEnumParser() {}\n // Parse using pragmatic/adhoc hard cast:\n // - struct + class = enum\n // - 'guaranteed' call from derived <System.Enum>-constrained type EnumUtils\n public static TEnum Parse<TEnum>(string value, bool ignoreCase = false) where TEnum : struct, TClass\n {\n return (TEnum)Enum.Parse(typeof(TEnum), value, ignoreCase);\n }\n public static bool TryParse<TEnum>(string value, out TEnum result, bool ignoreCase = false, TEnum defaultValue = default(TEnum)) where TEnum : struct, TClass // value type constraint S depending on T\n {\n var didParse = Enum.TryParse(value, ignoreCase, out result);\n if (didParse == false)\n {\n result = defaultValue;\n }\n return didParse;\n }\n public static TEnum ParseOrDefault<TEnum>(string value, bool ignoreCase = false, TEnum defaultValue = default(TEnum)) where TEnum : struct, TClass // value type constraint S depending on T\n {\n if (string.IsNullOrEmpty(value)) { return defaultValue; }\n TEnum result;\n if (Enum.TryParse(value, ignoreCase, out result)) { return result; }\n return defaultValue;\n }\n}\n\npublic class EnumUtils: ConstrainedEnumParser<System.Enum>\n// reference type constraint to any <System.Enum>\n{\n // call to parse will then contain constraint to specific <System.Enum>-class\n}\n WeekDay parsedDayOrArgumentException = EnumUtils.Parse<WeekDay>(\"monday\", ignoreCase:true);\nWeekDay parsedDayOrDefault;\nbool didParse = EnumUtils.TryParse<WeekDay>(\"clubs\", out parsedDayOrDefault, ignoreCase:true);\nparsedDayOrDefault = EnumUtils.ParseOrDefault<WeekDay>(\"friday\", ignoreCase:true, defaultValue:WeekDay.Sunday);\n TEnum TryParse ignoreCase default defaultValue ignoreCase public static class EnumUtils\n{\n public static TEnum ParseEnum<TEnum>(this string value,\n bool ignoreCase = true,\n TEnum defaultValue = default(TEnum))\n where TEnum : struct, IComparable, IFormattable, IConvertible\n {\n if ( ! typeof(TEnum).IsEnum) { throw new ArgumentException(\"TEnum must be an enumerated type\"); }\n if (string.IsNullOrEmpty(value)) { return defaultValue; }\n TEnum lResult;\n if (Enum.TryParse(value, ignoreCase, out lResult)) { return lResult; }\n return defaultValue;\n }\n}\n" }, { "answer_id": 17852186, "author": "niaher", "author_id": 111438, "author_profile": "https://Stackoverflow.com/users/111438", "pm_score": 1, "selected": false, "text": "using System;\n\ninternal static class EnumEnforcer\n{\n /// <summary>\n /// Makes sure that generic input parameter is of an enumerated type.\n /// </summary>\n /// <typeparam name=\"T\">Type that should be checked.</typeparam>\n /// <param name=\"typeParameterName\">Name of the type parameter.</param>\n /// <param name=\"methodName\">Name of the method which accepted the parameter.</param>\n public static void EnforceIsEnum<T>(string typeParameterName, string methodName)\n where T : struct, IConvertible\n {\n if (!typeof(T).IsEnum)\n {\n string message = string.Format(\n \"Generic parameter {0} in {1} method forces an enumerated type. Make sure your type parameter {0} is an enum.\",\n typeParameterName,\n methodName);\n\n throw new ArgumentException(message);\n }\n }\n\n /// <summary>\n /// Makes sure that generic input parameter is of an enumerated type.\n /// </summary>\n /// <typeparam name=\"T\">Type that should be checked.</typeparam>\n /// <param name=\"typeParameterName\">Name of the type parameter.</param>\n /// <param name=\"methodName\">Name of the method which accepted the parameter.</param>\n /// <param name=\"inputParameterName\">Name of the input parameter of this page.</param>\n public static void EnforceIsEnum<T>(string typeParameterName, string methodName, string inputParameterName)\n where T : struct, IConvertible\n {\n if (!typeof(T).IsEnum)\n {\n string message = string.Format(\n \"Generic parameter {0} in {1} method forces an enumerated type. Make sure your input parameter {2} is of correct type.\",\n typeParameterName,\n methodName,\n inputParameterName);\n\n throw new ArgumentException(message);\n }\n }\n\n /// <summary>\n /// Makes sure that generic input parameter is of an enumerated type.\n /// </summary>\n /// <typeparam name=\"T\">Type that should be checked.</typeparam>\n /// <param name=\"exceptionMessage\">Message to show in case T is not an enum.</param>\n public static void EnforceIsEnum<T>(string exceptionMessage)\n where T : struct, IConvertible\n {\n if (!typeof(T).IsEnum)\n {\n throw new ArgumentException(exceptionMessage);\n }\n }\n}\n" }, { "answer_id": 22636379, "author": "KarmaEDV", "author_id": 2620046, "author_profile": "https://Stackoverflow.com/users/2620046", "pm_score": 2, "selected": false, "text": "public static TEnum ParseToEnum<TEnum>(this string text) where TEnum : struct, IConvertible, IComparable, IFormattable\n{\n if (string.IsNullOrEmpty(text) || !typeof(TEnum).IsEnum)\n throw new ArgumentException(\"TEnum must be an Enum type\");\n\n try\n {\n var enumValue = (TEnum)Enum.Parse(typeof(TEnum), text.Trim(), true);\n return enumValue;\n }\n catch (Exception)\n {\n throw new ArgumentException(string.Format(\"{0} is not a member of the {1} enumeration.\", text, typeof(TEnum).Name));\n }\n}\n" }, { "answer_id": 28527552, "author": "Julien Lebosquain", "author_id": 183367, "author_profile": "https://Stackoverflow.com/users/183367", "pm_score": 8, "selected": false, "text": "public static TEnum Parse<TEnum>(string value)\n where TEnum : struct, Enum\n{\n ...\n}\n class struct public abstract class EnumClassUtils<TClass>\nwhere TClass : class\n{\n\n public static TEnum Parse<TEnum>(string value)\n where TEnum : struct, TClass\n {\n return (TEnum) Enum.Parse(typeof(TEnum), value);\n }\n\n}\n\npublic class EnumUtils : EnumClassUtils<Enum>\n{\n}\n EnumUtils.Parse<SomeEnum>(\"value\");\n" }, { "answer_id": 40357283, "author": "Basheer AL-MOMANI", "author_id": 4251431, "author_profile": "https://Stackoverflow.com/users/4251431", "pm_score": 1, "selected": false, "text": "to get integer value from enum public static int ToInt<T>(this T soure) where T : IConvertible//enum\n{\n if (typeof(T).IsEnum)\n {\n return (int) (IConvertible)soure;// the tricky part\n }\n //else\n // throw new ArgumentException(\"T must be an enumerated type\");\n return soure.ToInt32(CultureInfo.CurrentCulture);\n}\n MemberStatusEnum.Activated.ToInt()// using extension Method\n(int) MemberStatusEnum.Activated //the ordinary way\n" }, { "answer_id": 45274236, "author": "BatteryBackupUnit", "author_id": 684096, "author_profile": "https://Stackoverflow.com/users/684096", "pm_score": 1, "selected": false, "text": "Fody ExtraConstraints.Fody public void MethodWithEnumConstraint<[EnumConstraint] T>() {...}\n\npublic void MethodWithTypeEnumConstraint<[EnumConstraint(typeof(ConsoleColor))] T>() {...}\n public void MethodWithDelegateConstraint<[DelegateConstraint] T> ()\n{...}\n\npublic void MethodWithTypeDelegateConstraint<[DelegateConstraint(typeof(Func<int>))] T> ()\n{...}\n" }, { "answer_id": 47457596, "author": "uluorta", "author_id": 785915, "author_profile": "https://Stackoverflow.com/users/785915", "pm_score": 0, "selected": false, "text": "System.Enum public static class EnumUtils\n{\n public static Enum GetEnumFromString(string value, Enum defaultValue)\n {\n if (string.IsNullOrEmpty(value)) return defaultValue;\n foreach (Enum item in Enum.GetValues(defaultValue.GetType()))\n {\n if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;\n }\n return defaultValue;\n }\n}\n var parsedOutput = (YourEnum)EnumUtils.GetEnumFromString(someString, YourEnum.DefaultValue);\n" }, { "answer_id": 49432554, "author": "DiskJunky", "author_id": 1838819, "author_profile": "https://Stackoverflow.com/users/1838819", "pm_score": 5, "selected": false, "text": "public class MyGeneric<TEnum> where TEnum : System.Enum\n{ }\n public static Dictionary<int, string> EnumNamedValues<T>()\n where T : System.Enum\n{\n var result = new Dictionary<int, string>();\n var values = Enum.GetValues(typeof(T));\n\n foreach (int item in values)\n result.Add(item, Enum.GetName(typeof(T), item));\n return result;\n}\n" }, { "answer_id": 50270186, "author": "baumgarb", "author_id": 4587483, "author_profile": "https://Stackoverflow.com/users/4587483", "pm_score": 4, "selected": false, "text": " private static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum\n {\n // Your code goes here...\n }\n" }, { "answer_id": 50596283, "author": "Rodney P. Barbati", "author_id": 1588303, "author_profile": "https://Stackoverflow.com/users/1588303", "pm_score": -1, "selected": false, "text": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.function.Function;\n\n\npublic class EnumFromString {\n\n enum NumberEnum {One, Two, Three};\n enum LetterEnum {A, B, C};\n\n\n Map<String, Function<String, ? extends Enum>> enumsByName = new HashMap<>();\n\n public static void main(String[] args) {\n EnumFromString efs = new EnumFromString();\n\n System.out.print(\"\\nFirst string is NumberEnum.Two - enum is \" + efs.acceptEnumeratedValue(\"NumberEnum.Two\").name());\n System.out.print(\"\\nSecond string is LetterEnum.B - enum is \" + efs.acceptEnumeratedValue(\"LetterEnum.B\").name());\n\n }\n\n public EnumFromString() {\n enumsByName.put(\"NumberEnum\", s -> {return NumberEnum.valueOf(s);});\n enumsByName.put(\"LetterEnum\", s -> {return LetterEnum.valueOf(s);});\n }\n\n public Enum acceptEnumeratedValue(String enumDotValue) {\n\n int pos = enumDotValue.indexOf(\".\");\n\n String enumName = enumDotValue.substring(0, pos);\n String value = enumDotValue.substring(pos + 1);\n\n Enum enumeratedValue = enumsByName.get(enumName).apply(value);\n\n return enumeratedValue;\n }\n\n\n}\n" }, { "answer_id": 58731308, "author": "Cubelaster", "author_id": 1562834, "author_profile": "https://Stackoverflow.com/users/1562834", "pm_score": 1, "selected": false, "text": "public static class EnumExtensions\n {\n public static string GetDescription(this Enum @enum)\n {\n Type type = @enum.GetType();\n FieldInfo fi = type.GetField(@enum.ToString());\n DescriptionAttribute[] attrs =\n fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];\n if (attrs.Length > 0)\n {\n return attrs[0].Description;\n }\n return null;\n }\n }\n" }, { "answer_id": 69573641, "author": "Chris F Carroll", "author_id": 550314, "author_profile": "https://Stackoverflow.com/users/550314", "pm_score": 3, "selected": false, "text": "System.Enum Parse() TryParse() where struct where Enum bool IsValid<TE>(string attempted) where TE : Enum\n {\n return Enum.TryParse(attempted, out TE _);\n }\n bool Ok<TE>(string attempted) where TE : struct,Enum\n{\n return Enum.TryParse(attempted, out var _)\n}\n where struct,Enum where Enum" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ]
79,129
<p>For the life of me, I cannot get the SqlProfileProvider to work in an MVC project that I'm working on.</p> <p>The first interesting thing that I realized is that Visual Studio does not automatically generate the ProfileCommon proxy class for you. That's not a big deal since it's simpy a matter of extending the ProfileBase class. After creating a ProfileCommon class, I wrote the following Action method for creating the user profile.</p> <pre><code>[AcceptVerbs("POST")] public ActionResult CreateProfile(string company, string phone, string fax, string city, string state, string zip) { MembershipUser user = Membership.GetUser(); ProfileCommon profile = ProfileCommon.Create(user.UserName, user.IsApproved) as ProfileCommon; profile.Company = company; profile.Phone = phone; profile.Fax = fax; profile.City = city; profile.State = state; profile.Zip = zip; profile.Save(); return RedirectToAction("Index", "Account"); }</code></pre> <p>The problem that I'm having is that the call to ProfileCommon.Create() cannot cast to type ProfileCommon, so I'm not able to get back my profile object, which obviously causes the next line to fail since profile is null.</p> <p>Following is a snippet of my web.config:</p> <p><pre><code>&lt;profile defaultProvider="AspNetSqlProfileProvider" automaticSaveEnabled="false" enabled="true"&gt; &lt;providers&gt; &lt;clear/&gt; &lt;add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="/" /&gt; &lt;/providers&gt; &lt;properties&gt; &lt;add name="FirstName" type="string" /&gt; &lt;add name="LastName" type="string" /&gt; &lt;add name="Company" type="string" /&gt; &lt;add name="Phone" type="string" /&gt; &lt;add name="Fax" type="string" /&gt; &lt;add name="City" type="string" /&gt; &lt;add name="State" type="string" /&gt; &lt;add name="Zip" type="string" /&gt; &lt;add name="Email" type="string" &gt; &lt;/properties&gt; &lt;/profile&gt;</pre></code></p> <p>The MembershipProvider is working without a hitch, so I know that the connection string is good.</p> <p>Just in case it's helpful, here is my ProfileCommon class:</p> <pre><code>public class ProfileCommon : ProfileBase { public virtual string Company { get { return ((string)(this.GetPropertyValue("Company"))); } set { this.SetPropertyValue("Company", value); } } public virtual string Phone { get { return ((string)(this.GetPropertyValue("Phone"))); } set { this.SetPropertyValue("Phone", value); } } public virtual string Fax { get { return ((string)(this.GetPropertyValue("Fax"))); } set { this.SetPropertyValue("Fax", value); } } public virtual string City { get { return ((string)(this.GetPropertyValue("City"))); } set { this.SetPropertyValue("City", value); } } public virtual string State { get { return ((string)(this.GetPropertyValue("State"))); } set { this.SetPropertyValue("State", value); } } public virtual string Zip { get { return ((string)(this.GetPropertyValue("Zip"))); } set { this.SetPropertyValue("Zip", value); } } public virtual ProfileCommon GetProfile(string username) { return ((ProfileCommon)(ProfileBase.Create(username))); } }</code></pre> <p>Any thoughts on what I might be doing wrong? Have any of the rest of you successfully integrated a ProfileProvider with your ASP.NET MVC projects?</p> <p>Thank you in advance...</p>
[ { "answer_id": 80594, "author": "Mladen Mihajlovic", "author_id": 11421, "author_profile": "https://Stackoverflow.com/users/11421", "pm_score": 3, "selected": false, "text": "ProfileCommon profile = (ProfileCommon)ProfileCommon.Create(user.UserName, user.IsApproved) as ProfileCommon;\n" }, { "answer_id": 434793, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "<profile inherits=\"MySite.Models.ProfileCommon\" defaultProvider=\"....\n <properties> public virtual ProfileCommon GetProfile(string username) \n{ \n return Create(username) as ProfileCommon; \n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10792/" ]
79,133
<p>In other words:</p> <ol> <li>Log on as Bert (who is an administrator)</li> <li>Using fast user switching, log on as Ernie (Bert remains logged on)</li> <li>Switch back to Bert</li> <li>Bert logs Ernie off</li> </ol> <p>What is the best way to achieve step 4?</p>
[ { "answer_id": 42917620, "author": "Babak", "author_id": 4676, "author_profile": "https://Stackoverflow.com/users/4676", "pm_score": 3, "selected": true, "text": "sudo launchctl bootout user/$(id -u <username>) <username>" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4676/" ]
79,165
<p>I read the Git manual, FAQ, Git - SVN crash course, etc. and they all explain this and that, but nowhere can you find a simple instruction like:</p> <p>SVN repository in: <code>svn://myserver/path/to/svn/repos</code></p> <p>Git repository in: <code>git://myserver/path/to/git/repos</code></p> <pre><code>git-do-the-magic-svn-import-with-history \ svn://myserver/path/to/svn/repos \ git://myserver/path/to/git/repos </code></pre> <p>I don't expect it to be that simple, and I don't expect it to be a single command. But I do expect it not to try to explain anything - just to say what steps to take given this example.</p>
[ { "answer_id": 79178, "author": "jfm3", "author_id": 11138, "author_profile": "https://Stackoverflow.com/users/11138", "pm_score": 10, "selected": true, "text": "$ git svn clone http://svn/repo/here/trunk\n git-svn git-svn $ git svn --help\n" }, { "answer_id": 79188, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 8, "selected": false, "text": "~/authors.txt jmaddox = Jon Maddox <jon@gmail.com>\nbigpappa = Brian Biggs <bigpappa@gmail.com>\n mkdir repo && cd repo\ngit svn init http://subversion/repo --no-metadata\ngit config svn.authorsfile ~/authors.txt\ngit svn fetch\n git-svn git-core +svn git svn init file:///home/user/repoName --no-metadata\n" }, { "answer_id": 85456, "author": "EfForEffort", "author_id": 14113, "author_profile": "https://Stackoverflow.com/users/14113", "pm_score": 4, "selected": false, "text": "# Clone a repo (like git clone):\n git svn clone http://svn.foo.org/project -T trunk -b branches -t tags\n" }, { "answer_id": 86094, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 6, "selected": false, "text": "mkdir project\ncd project\ngit svn init http://svn.url\n git svn fetch -r42\n git svn rebase\n gitk\n git remote add origin git@github.com:user/project-name.git\n git config branch.master.remote origin\ngit config branch.master.merge refs/heads/master\n git_remote_branch" }, { "answer_id": 139428, "author": "Gregg Lind", "author_id": 15842, "author_profile": "https://Stackoverflow.com/users/15842", "pm_score": 2, "selected": false, "text": "svn-dcommit git stash; git svn dcommit ; git stash apply\n" }, { "answer_id": 3972103, "author": "cmcginty", "author_id": 64313, "author_profile": "https://Stackoverflow.com/users/64313", "pm_score": 11, "selected": false, "text": "users.txt user1 = First Last Name <email@address.com>\nuser2 = First Last Name <email@address.com>\n...\n svn log -q | awk -F '|' '/^r/ {gsub(/ /, \"\", $2); sub(\" $\", \"\", $2); print $2\" = \"$2\" <\"$2\">\"}' | sort -u > users.txt\n git svn clone --stdlayout --no-metadata --authors-file=users.txt svn://hostname/path dest_dir-tmp\n dest_dir-tmp --tags --branches --trunk git svn help svn:// http:// https:// /trunk /tag /branches --no-metadata git-svn-id: svn://svn.mycompany.com/myrepo/<branchname/trunk>@<RevisionNumber> <Repository UUID> users.txt cd dest_dir-tmp\ngit svn fetch\n git svn fetch\n trunk git branch -r\n git checkout -b local_branch remote_branch\n# It's OK if local_branch and remote_branch are the same names\n git checkout -b tag_v1 remotes/tags/v1\ngit checkout master\ngit tag v1 tag_v1\ngit branch -D tag_v1\n git clone dest_dir-tmp dest_dir\nrm -rf dest_dir-tmp\ncd dest_dir\n git checkout -b local_branch origin/remote_branch\n git remote rm origin\n" }, { "answer_id": 8262076, "author": "Alexander Kitaev", "author_id": 351457, "author_profile": "https://Stackoverflow.com/users/351457", "pm_score": 5, "selected": false, "text": "$ subgit install svn_repos\n...\nTRANSLATION SUCCESSFUL \n $ subgit configure svn_repos\n$ edit svn_repos/conf/subgit.conf (change mapping, add authors mapping, etc)\n$ subgit install svn_repos\n" }, { "answer_id": 9316931, "author": "Jason Huntley", "author_id": 1214542, "author_profile": "https://Stackoverflow.com/users/1214542", "pm_score": 2, "selected": false, "text": "/trunk\n /Project1\n /Project2\n/branches\n /Project1\n /Project2\n/tags\n /Project1\n /Project2\n /Project1\n /trunk\n /branches\n /tags\n/Project2\n /trunk\n /branches\n /tags\n Ex: ./migration https://svnurl.com/basepath project1\n Ex: ./migration https://svnurl.com/basepath .\n" }, { "answer_id": 19001024, "author": "thoutbeckers", "author_id": 2338613, "author_profile": "https://Stackoverflow.com/users/2338613", "pm_score": 3, "selected": false, "text": "#!/usr/bin/env bash\nauthors=$(svn log -q | grep -e '^r' | awk 'BEGIN { FS = \"|\" } ; { print $2 }' | sort | uniq)\nfor author in ${authors}; do\n echo \"${author} = NAME <USER@DOMAIN>\";\ndone\n authors git config user.name user.email git svn git svn clone --authors-file=authors --stdlayout svn://example.org/Folder/projectroot git svn rebase --continue svn copy git svn git svn clone git branch --set-upstream master git-svn\ngit svn rebase\n" }, { "answer_id": 24879012, "author": "Valarpirai", "author_id": 3863121, "author_profile": "https://Stackoverflow.com/users/3863121", "pm_score": 3, "selected": false, "text": "git\ngit-svn\n svn log -q | awk -F '|' '/^r/ {sub(\"^ \", \"\", $2); sub(\" $\", \"\", $2); print $2\" = \"$2\" <\"$2\">\"}' | sort -u > authors-transform.txt\n jwilkins = jwilkins <jwilkins>\n jwilkins = John Albin Wilkins <johnalbin@example.com>\n git svn clone [SVN repo URL] --no-metadata -A authors-transform.txt --stdlayout ~/temp\n cd ~/temp\ngit svn show-ignore > .gitignore\ngit add .gitignore\ngit commit -m 'Convert svn:ignore properties to .gitignore.'\n git init --bare ~/new-bare.git\ncd ~/new-bare.git\ngit symbolic-ref HEAD refs/heads/trunk\n cd ~/temp\ngit remote add bare ~/new-bare.git\ngit config remote.bare.push 'refs/remotes/*:refs/heads/*'\ngit push bare\n cd ~/new-bare.git\ngit branch -m trunk master\n cd ~/new-bare.git\ngit for-each-ref --format='%(refname)' refs/heads/tags |\ncut -d / -f 4 |\nwhile read ref\ndo\n git tag \"$ref\" \"refs/heads/tags/$ref\";\n git branch -D \"tags/$ref\";\ndone\n" }, { "answer_id": 25823518, "author": "leftclickben", "author_id": 1007512, "author_profile": "https://Stackoverflow.com/users/1007512", "pm_score": 2, "selected": false, "text": "svn.domain.com.au http git.domain.com.au dev-team ssh git@git.domain.com.au favourite-project dev-team users.txt username = First Last <address@domain.com.au> username bash\ngit svn clone --stdlayout --no-metadata -A users.txt \nhttp://svn.domain.com.au/svn/repository/favourite-project\ncd favourite-project\ngit remote add gitlab git@git.domain.com.au:dev-team/favourite-project.git\ngit push --set-upstream gitlab master\n git svn clone users.txt cd favourite-project git svn fetch trunk tags branches git svn clone trunk/ tags/ branches/ git svn clone" }, { "answer_id": 28364465, "author": "it3xl", "author_id": 390940, "author_profile": "https://Stackoverflow.com/users/390940", "pm_score": 4, "selected": false, "text": "subgit import --svn-url url://svn.serv/Bla/Bla directory/path/Local.git.Repo\n subgit import directory/path/Local.git.Repo\n start subgit import --svn-url url://svn.serv/Bla/Bla directory/path/Local.git.Repo\n start subgit import directory/path/Local.git.Repo\n $ git remote add origin url://your/repo.git\n git config --global http.postBuffer 1073741824\n git push origin --mirror\n git push origin --all\ngit push origin --tags\n" }, { "answer_id": 29173307, "author": "krlmlr", "author_id": 946850, "author_profile": "https://Stackoverflow.com/users/946850", "pm_score": 4, "selected": false, "text": "fast-export svn:ignore .gitignore reposurgeon" }, { "answer_id": 35410032, "author": "Ruslan Makrenko", "author_id": 4953065, "author_profile": "https://Stackoverflow.com/users/4953065", "pm_score": 0, "selected": false, "text": "svnadmin dump /path/to/repository > repo_name.svn_dump cd REPO_NAME_PARENT_FOLDER svnadmin load REPO_NAME_FOLDER < dumpfile.dump svnserve -d -R --root REPO_NAME_FOLDER Unable to open ... to URL: cd SOURCE_GIT_FOLDER git log\n git remote add origin https://fullurlpathtoyourrepo/reponame.git\ngit push -u origin --all # pushes up the repo and its refs for the first time\ngit push -u origin --tags # pushes up any tags\n" }, { "answer_id": 35605248, "author": "Pablo Belaustegui", "author_id": 5975111, "author_profile": "https://Stackoverflow.com/users/5975111", "pm_score": 3, "selected": false, "text": "git svn clone --username=yourSvnUsername -T trunk_subdir -t tags_subdir -b branches_subdir -r aRevisionNumber svn_url gitreponame\n cd gitreponame\ngit svn fetch\n git svn rebase\n cp .git/refs/remotes/origin/* .git/refs/heads/\n git for-each-ref refs/remotes/origin/tags | sed 's#^.*\\([[:xdigit:]]\\{40\\}\\).*refs/remotes/origin/tags/\\(.*\\)$#\\2 \\1#g' | while read p; do git tag -m \"tag from svn\" $p; done\n git remotes add newrepo git@github.com:aUser/aProjectName.git\ngit push newrepo refs/heads/*\ngit push --tags newrepo\n" }, { "answer_id": 36986911, "author": "Pankaj", "author_id": 926520, "author_profile": "https://Stackoverflow.com/users/926520", "pm_score": 3, "selected": false, "text": "git svn clone svn log -q <SVN_URL> | awk -F '|' '/^r/ {sub(\"^ \", \"\", $2); sub(\" $\", \"\", $2); print $2\" = \"$2\" <\"$2\">\"}' | sort -u > authors.txt svn log --stop-on-copy <SVN_URL> git svn clone -r<SVN_REV_NO>:HEAD --no-minimize-url --stdlayout --no-metadata --authors-file authors.txt <SVN_URL> $ git remote add origin https://github.com/pankaj0323/JDProjects.git\n$ git branch -a\n* master\n remotes/origin/MyDevBranch\n remotes/origin/tags/MyDevBranch-1.0\n remotes/origin/trunk\n$$ git checkout -b MyDevBranch origin/MyDevBranch\nBranch MyDevBranch set up to track remote branch MyDevBranch from origin.\nSwitched to a new branch 'MyDevBranch'\n$ git branch -a\n* MyDevBranch\n master\n remotes/origin/MyDevBranch\n remotes/origin/tags/MyDevBranch-1.0\n remotes/origin/trunk\n$\n $git checkout origin/tags/MyDevBranch-1.0\nNote: checking out 'origin/tags/MyDevBranch-1.0'.\nYou are in 'detached HEAD' state. You can look around, make experimental\nchanges and commit them, and you can discard any commits you make in this\nstate without impacting any branches by performing another checkout.\n\nIf you want to create a new branch to retain commits you create, you may\ndo so (now or later) by using -b with the checkout command again. Example:\n\n git checkout -b new_branch_name\n\nHEAD is now at 3041d81... Creating a tag\n$ git branch -a\n* (detached from origin/tags/MyDevBranch-1.0)\n MyDevBranch\n master\n remotes/origin/MyDevBranch\n remotes/origin/tags/MyDevBranch-1.0\n remotes/origin/trunk\n$ git tag -a MyDevBranch-1.0 -m \"creating tag\"\n$git tag\nMyDevBranch-1.0\n$\n $ git push origin master MyDevBranch MyDevBranch-1.0\nCounting objects: 14, done.\nDelta compression using up to 8 threads.\nCompressing objects: 100% (11/11), done.\nWriting objects: 100% (14/14), 2.28 KiB | 0 bytes/s, done.\nTotal 14 (delta 3), reused 0 (delta 0)\nTo https://github.com/pankaj0323/JDProjects.git\n * [new branch] master -> master\n * [new branch] MyDevBranch -> MyDevBranch\n * [new tag] MyDevBranch-1.0 -> MyDevBranch-1.0\n$\n sudo gem install svn2git $ svn2git <SVN_URL> --authors authors.txt --revision <SVN_REV_NO> $ git remote add origin https://github.com/pankaj0323/JDProjects.git\n$ git branch -a\n MyDevBranch\n* master\n remotes/svn/MyDevBranch\n remotes/svn/trunk\n$ git tag\n MyDevBranch-1.0\n$ git push origin master MyDevBranch MyDevBranch-1.0\n git svn clone" }, { "answer_id": 41449157, "author": "Pedro Vicente", "author_id": 4739800, "author_profile": "https://Stackoverflow.com/users/4739800", "pm_score": 0, "selected": false, "text": "git clone --bare #!/bin/bash\nfile=\"list.txt\"\nwhile IFS= read -r repo_name\ndo\n printf '%s\\n' \"$repo_name\"\n sudo git svn clone --shared --preserve-empty-dirs --authors-file=users.txt file:///programs/svn/$repo_name\n sudo git clone --bare /programs/git/$repo_name $repo_name.git\n sudo chown -R www-data:www-data $repo_name.git\n sudo rm -rf $repo_name\ndone <\"$file\"\n repo1_name\nrepo2_name\n (no author) = Prince Rogers <prince.rogers.nelson@payesley.park.org>" }, { "answer_id": 48636876, "author": "cljk", "author_id": 1574012, "author_profile": "https://Stackoverflow.com/users/1574012", "pm_score": 2, "selected": false, "text": "transfer.bat http://svn.my.address/svn/myrepo/trunk https://git.my.address/orga/myrepo @echo off \nSET FROM=%1 \nSET TO=%2 \nSET TMP=tmp_%random%\n\necho from: %FROM% \necho to: %TO% \necho tmp: %TMP%\n\npause\n\ngit svn clone --no-metadata --authors-file=users.txt %FROM% %TMP% \ncd %TMP% \ngit remote add origin %TO% \ngit push --set-upstream origin master\n\n\ncd .. \necho delete %TMP% ... \npause\n\nrmdir /s /q %TMP%\n User1 = User One <u.1@xxx.com>\n" }, { "answer_id": 48732137, "author": "Anand Tripathi", "author_id": 5230702, "author_profile": "https://Stackoverflow.com/users/5230702", "pm_score": -1, "selected": false, "text": "anand = Anand Tripathi <email_id>\ntrip = Tripathi Anand <email_id>\n svn2git <svn_repo_path> --nobranches --notags --notrunk --no-minimize-url --username <user_name> --verbose --authors <author.txt_path>\n\nIf no trunk and no tag and branch is present then have to execute the above command else if root is trunk then mention rootistrunk or trunk is present then --trunk <trunk_name>\n" }, { "answer_id": 63570098, "author": "dgates82", "author_id": 2209181, "author_profile": "https://Stackoverflow.com/users/2209181", "pm_score": 1, "selected": false, "text": "svn log -q | awk -F '|' '/^r/ {sub(\"^ \", \"\", $2); sub(\" $\", \"\", $2); print $2\" = \"$2\" <\"$2\">\"}' | sort -u > authors-transform.txt\n someuser = someuser <someuser>\n someuser = Some User <someuser@somewhere.com>\n git svn clone --stdlayout --no-metadata -r854:HEAD --authors-file=authors-transform.txt https://somesvnserver/somerepo/ temp\n cd temp\n git svn fetch\n git 1.0.0 origin/tags/1.0.0\n for brname in `git branch -r | grep tags | awk '{gsub(/^[^\\/]+\\//,\"\",$1); print $1}'`; do echo $brname; tname=${brname:5}; echo $tname; git tag $tname origin/tags/$tname; done\n git checkout -b branchname origin/branches/branchname\n for brname in `git branch -r | grep -v master | grep -v HEAD | grep -v trunk | grep -v tags | awk '{gsub(/^[^\\/]+\\//,\"\",$1); print $1}'`; do echo $brname; git checkout -b $brname origin/$brname; done\n cd ..\ngit clone temp temp2\ncd temp2\n git checkout -b WORKING\ngit branch -m develop\ngit push origin --delete WORKING\ngit push origin -u develop\n git remote set-url origin https://somebitbucketserver/somerepo.git\ngit push -u origin --all\ngit push origin --tags\n" }, { "answer_id": 68242281, "author": "Bharathiraja", "author_id": 2648257, "author_profile": "https://Stackoverflow.com/users/2648257", "pm_score": 0, "selected": false, "text": "SVN GIT GIT SVN <> #!/bin/bash\n\n######## Project name \nPROJECT_NAME=\"Helloworld\"\nEMAIL=\"example mail\"\n\n#Credientials Repo\nGIT_USER='<git username>'\nGIT_PWD='<git password>'\nSVN_USER='<svn username>'\nSVN_PWD='<svn password>'\n\n######## SVN repository to be migrated # Dont use https - error will be thrown\nBASE_SVN=\"<SVN URL>/Helloworld\"\n\n#Organization inside BASE_SVN\nBRANCHES=\"branches\"\nTAGS=\"tags\"\nTRUNK=\"trunk\"\n\n#Credientials\ngit config --global user.name '<git username>'\ngit config --global user.password '<git password>'\ngit config --global credential.helper 'cache --timeout=3600'\n\n######## GIT repository to migrate - Ensure already project created in Git\nGIT_URL=https://$GIT_USER:$GIT_PWD@<GIT URL>/Helloworld.git\n\n###########################\n#### Don't need to change from here\n###########################\n\n#Geral Configuration\nABSOLUTE_PATH=$(pwd)\nTMP=$ABSOLUTE_PATH/$PROJECT_NAME\n\n#Branchs Configuration\nSVN_BRANCHES=$BASE_SVN/$BRANCHES\nSVN_TAGS=$BASE_SVN/$TAGS\nSVN_TRUNK=$BASE_SVN/$TRUNK\n\nAUTHORS=$PROJECT_NAME\"-authors.txt\"\n\necho '[LOG] Starting migration of '$SVN_TRUNK\necho '[LOG] Using: '$(git --version)\necho '[LOG] Using: '$(svn --version | grep svn,)\n\nmkdir $TMP\necho\necho '[DIR] cd' $TMP\ncd $TMP\n\necho\necho '[LOG] Getting authors'\nsvn --username $SVN_USER --password $SVN_PWD log -q $BASE_SVN | awk -F '|' '/^r/ {sub(\"^ \", \"\", $2); sub(\" $\", \"\", $2); print $2\" = \"$2\" <\"$2\"@\"$EMAIL\">\"}' | sort -u >> $AUTHORS\n\necho\necho '[RUN] git svn clone --authors-file='$AUTHORS' --trunk='$TRUNK' --branches='$BRANCHES' --tags='$TAGS $BASE_SVN $TMP\ngit svn clone --authors-file=$AUTHORS --trunk=$TRUNK --branches=$BRANCHES --tags=$TAGS $BASE_SVN $TMP\n\n#Not working so no need to mention it\n#--stdlayout $PROJECT_NAME\necho\necho '[RUN] svn ls '$SVN_BRANCHES\nsvn ls $SVN_BRANCHES\n\necho \necho 'git branch -a'\ngit branch -a\n\necho\necho '[LOG] Getting first revision'\nFIRST_REVISION=$( svn log -r 1:HEAD --limit 1 $BASE_SVN | awk -F '|' '/^r/ {sub(\"^ \", \"\", $1); sub(\" $\", \"\", $1); print $1}' )\n\necho\necho '[RUN] git svn fetch -'$FIRST_REVISION':HEAD'\ngit svn fetch -$FIRST_REVISION:HEAD\n\n#Branches and Tags \necho\necho '[RUN] svn ls '$SVN_BRANCHES\nfor BRANCH in $(svn ls $SVN_BRANCHES); do\n echo git branch ${BRANCH%/} remotes/svn/${BRANCH%/}\n git branch ${BRANCH%/} remotes/svn/${BRANCH%/}\ndone\n\ngit for-each-ref --format=\"%(refname:short) %(objectname)\" refs/remotes/origin/tags | grep -v \"@\" | cut -d / -f 3- |\nwhile read ref\ndo\n echo git tag -a $ref -m 'import tag from svn'\n git tag -a $ref -m 'import tag from svn'\ndone\n\ngit for-each-ref --format=\"%(refname:short)\" refs/remotes/origin/tags | cut -d / -f 1- |\nwhile read ref\ndo\n git branch -rd $ref\ndone\n \necho\necho 'git tag'\ngit tag\n\necho\necho 'git show-ref --tags'\ngit show-ref --tags\n\necho\necho '[RUN] git remote add origin '$GIT_URL\ngit remote add origin $GIT_URL\n\necho\necho '[RUN] git push'\ngit push origin --all --force\ngit push origin --tags\n\n#echo git branch -d -r trunk\n#git branch -d -r trunk\n\ngit config --global credential.helper cache\necho 'Successful.'\n .git SVN .git/refs/heads SVN .git/refs/remotes/origin/<branches> .git/refs/heads master tags trunk branches tags" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14690/" ]
79,197
<p>What's a simple way to combine <strong>feed</strong> and <strong>feed2</strong>? I want the items from <strong>feed2</strong> to be added to <strong>feed</strong>. Also I want to avoid duplicates as <strong>feed</strong> might already have items when a question is tagged with both WPF and Silverlight.</p> <pre><code>Uri feedUri = new Uri("http://stackoverflow.com/feeds/tag/silverlight"); XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri); SyndicationFeed feed = SyndicationFeed.Load(reader); Uri feed2Uri = new Uri("http://stackoverflow.com/feeds/tag/wpf"); XmlReader reader2 = XmlReader.Create(feed2Uri.AbsoluteUri); SyndicationFeed feed2 = SyndicationFeed.Load(reader2); </code></pre>
[ { "answer_id": 79376, "author": "Frater", "author_id": 14746, "author_profile": "https://Stackoverflow.com/users/14746", "pm_score": 1, "selected": false, "text": "SyndicationFeed newFeed = feed.clone;\nforeach(SyndicationItem item in feed2.items)\n{\n if (!newFeed.contains(item))\n newFeed.items.Add(item);\n}\n" }, { "answer_id": 86322, "author": "Michael Brown", "author_id": 14359, "author_profile": "https://Stackoverflow.com/users/14359", "pm_score": 5, "selected": true, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Xml;\nusing System.ServiceModel.Syndication;\n\nnamespace FeedUnion\n{\n class Program\n {\n static void Main(string[] args)\n {\n Uri feedUri = new Uri(\"http://stackoverflow.com/feeds/tag/silverlight\"); \n SyndicationFeed feed;\n SyndicationFeed feed2;\n using(XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri))\n {\n feed= SyndicationFeed.Load(reader); \n }\n Uri feed2Uri = new Uri(\"http://stackoverflow.com/feeds/tag/wpf\"); \n using (XmlReader reader2 = XmlReader.Create(feed2Uri.AbsoluteUri))\n {\n feed2 = SyndicationFeed.Load(reader2);\n }\n SyndicationFeed feed3 = new SyndicationFeed(feed.Items.Union(feed2.Items));\n StringBuilder builder = new StringBuilder();\n using (XmlWriter writer = XmlWriter.Create(builder))\n {\n feed3.SaveAsRss20(writer);\n System.Console.Write(builder.ToString());\n System.Console.Read();\n }\n }\n }\n}\n" }, { "answer_id": 8916265, "author": "rasx", "author_id": 22944, "author_profile": "https://Stackoverflow.com/users/22944", "pm_score": 0, "selected": false, "text": " [TestMethod]\n public void ShouldCombineRssFeeds()\n {\n //reference: http://stackoverflow.com/questions/79197/combining-two-syndicationfeeds\n\n SyndicationFeed feed;\n SyndicationFeed feed2;\n\n var feedUri = new Uri(\"http://stackoverflow.com/feeds/tag/silverlight\");\n using(var reader = XmlReader.Create(feedUri.AbsoluteUri))\n {\n feed = SyndicationFeed.Load(reader);\n }\n\n Assert.IsTrue(feed.Items.Count() > 0, \"The expected feed items are not here.\");\n\n var feed2Uri = new Uri(\"http://stackoverflow.com/feeds/tag/wpf\");\n using(var reader2 = XmlReader.Create(feed2Uri.AbsoluteUri))\n {\n feed2 = SyndicationFeed.Load(reader2);\n }\n\n Assert.IsTrue(feed2.Items.Count() > 0, \"The expected feed items are not here.\");\n\n var feedsCombined = new SyndicationFeed(feed.Items.Union(feed2.Items));\n\n Assert.IsTrue(\n feedsCombined.Items.Count() == feed.Items.Count() + feed2.Items.Count(),\n \"The expected number of combined feed items are not here.\");\n\n var builder = new StringBuilder();\n using(var writer = XmlWriter.Create(builder))\n {\n feedsCombined.SaveAsRss20(writer);\n writer.Flush();\n writer.Close();\n }\n\n var xmlString = builder.ToString();\n\n Assert.IsTrue(new Func<bool>(\n () =>\n {\n var test = false;\n\n var xDoc = XDocument.Parse(xmlString);\n var count = xDoc.Root.Element(\"channel\").Elements(\"item\").Count();\n test = (count == feedsCombined.Items.Count());\n\n return test;\n }\n ).Invoke(), \"The expected number of RSS items are not here.\");\n }\n" }, { "answer_id": 17917480, "author": "Manjit", "author_id": 2629183, "author_profile": "https://Stackoverflow.com/users/2629183", "pm_score": 0, "selected": false, "text": " //Executed and Tested :) \n using (XmlReader reader = XmlReader.Create(strFeed))\n {\n rssData = SyndicationFeed.Load(reader);\n model.BlogFeed = rssData; ;\n }\n using (XmlReader reader = XmlReader.Create(strFeed1))\n {\n rssData1 = SyndicationFeed.Load(reader);\n model.BlogFeed = rssData1;\n }\n\n SyndicationFeed feed3 = new SyndicationFeed(rssData.Items.Union(rssData1.Items));\n model.BlogFeed = feed3; \n return View(model);\n" }, { "answer_id": 35239636, "author": "Pherekles", "author_id": 4565121, "author_profile": "https://Stackoverflow.com/users/4565121", "pm_score": 0, "selected": false, "text": "// create temporary List of SyndicationItem's\nList<SyndicationItem> tempItems = new List<SyndicationItem>();\n\n// add all feed items to the list\ntempItems.AddRange(feed.Items);\ntempItems.AddRange(feed2.Items);\n\n// remove duplicates with Linq 'Distinct()'-method depending on yourattributes\n\n// add list without duplicates to 'feed2'\nfeed2.Items = tempItems\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1133/" ]
79,215
<p>For example, if I have a page located in Views/Home/Index.aspx and a JavaScript file located in Views/Home/Index.js, how do you reference this on the aspx page?</p> <p>The example below doesn't work even though the compiler says the path is correct</p> <pre><code>&lt;script src="Index.js" type="text/javascript"&gt;&lt;/script&gt; </code></pre> <p>The exact same issue has been posted here in more detail: <a href="http://forums.asp.net/p/1319380/2619991.aspx" rel="nofollow noreferrer">http://forums.asp.net/p/1319380/2619991.aspx</a></p> <p>If this is not currently possible, will it be in the future? If not, how is everyone managing their javascript resources for large Asp.net MVC projects? Do you just create a folder structure in the Content folder that mirrors your View folder structure? YUCK!</p>
[ { "answer_id": 79246, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\" src=\"<%=VirtualPathUtility.ToAbsolute(\"~/Views/Home/Index.js\") %>\"></script>\n" }, { "answer_id": 80638, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "public static class JavaScriptExtensions\n{\n public static string JavaScript(this HtmlHelper html, string source)\n {\n TagBuilder tagBuilder = new TagBuilder(\"script\");\n tagBuilder.Attributes.Add(\"type\", \"text/javascript\");\n tagBuilder.Attributes.Add(\"src\", VirtualPathUtility.ToAbsolute(source));\n return tagBuilder.ToString(TagRenderMode.Normal);\n }\n}\n <%=Html.JavaScript(\"~/Content/MicrosoftAjax.js\")%>\n" }, { "answer_id": 8094695, "author": "Pablo Montilla", "author_id": 83169, "author_profile": "https://Stackoverflow.com/users/83169", "pm_score": 0, "selected": false, "text": "public class RouteHandler : IRouteHandler\n{\n public IHttpHandler \n GetHttpHandler(RequestContext requestContext)\n {\n var request = requestContext.HttpContext.Request;\n\n // Here you should probably make the 'Views' directory appear in the correct place.\n var path = request.MapPath(request.Path); \n if(File.Exists(path)) {\n // This is internal, you probably should make your own version.\n return new StaticFileHandler(requestContext);\n }\n else {\n return new MvcHandler(requestContext);\n }\n }\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10941/" ]
79,229
<p>In your experience, how often should Oracle database statistics be run? Our team of developers recently discovered that statistics hadn't been run our production box in over 2 1/2 months. That sounds like a long time to me, but I'm not a DBA.</p>
[ { "answer_id": 16741489, "author": "grokster", "author_id": 502441, "author_profile": "https://Stackoverflow.com/users/502441", "pm_score": 4, "selected": false, "text": "SELECT owner, table_name, last_analyzed FROM all_tables ORDER BY last_analyzed DESC NULLS LAST; --Tables.\nSELECT owner, index_name, last_analyzed FROM all_indexes ORDER BY last_analyzed DESC NULLS LAST; -- Indexes.\n SELECT * FROM dba_autotask_client WHERE client_name = 'auto optimizer stats collection';\n SELECT window_group_name, window_name FROM dba_scheduler_wingroup_members;\n SELECT window_name, start_time, duration FROM dba_autotask_schedule;\n EXEC dbms_stats.gather_schema_stats(ownname=>NULL, cascade=>TRUE); -- cascade=>TRUE means include Table Indexes too.\n -- Probably need to CONNECT / AS SYSDBA\nEXEC dbms_stats.gather_database_stats;\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
79,241
<p>When working with tables in Oracle, how do you know when you are setting up a good index versus a bad index?</p>
[ { "answer_id": 166669, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 0, "selected": false, "text": "WHERE CompanyCode = ? AND Amount BETWEEN 100 AND 200\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
79,244
<p>How to make sure that all derived C++/CLI classes will override the ICloneable::Clone() method of the base class?</p> <p>Do you think I should worry about this? Or this is not a responsibility of the base class' writer?</p> <p><strong>Amendment:</strong> Sorry, I forgot to mention that the base class is a non-abstract class.</p>
[ { "answer_id": 79327, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 2, "selected": false, "text": "public ref class ClonableBase abstract\n{\n public:\n virtual void Clone() = 0;\n}\n public ref class ClonableChild : public ClonableBase\n{\n public:\n virtual void Clone();\n}\n\nvoid ConableChild::Clone()\n{\n //some stuff here\n}\n" }, { "answer_id": 79437, "author": "metao", "author_id": 11484, "author_profile": "https://Stackoverflow.com/users/11484", "pm_score": 1, "selected": false, "text": "class Base\n{\n...\nvirtual void Clone() = 0;\n};\n class Base\n{\n...\nvirtual void Clone()\n{ \n ...\n doClone();\n ...\n};\n\n...\n\nprivate:\nvirtual void doClone() = 0;\n};\n" }, { "answer_id": 80068, "author": "Eric W", "author_id": 14972, "author_profile": "https://Stackoverflow.com/users/14972", "pm_score": 1, "selected": false, "text": "virtual void Clone()\n{\n throw gcnew NotSupportedException();\n}\n" }, { "answer_id": 80108, "author": "metamal", "author_id": 14385, "author_profile": "https://Stackoverflow.com/users/14385", "pm_score": 0, "selected": false, "text": "Object^ BaseClass::Clone()\n{\n if(this->GetType() != BaseClass::typeid)\n {\n throw gcnew System::NotImplementedException(\"The Clone() method is not implemented for \" + this->GetType()->ToString() + \"!\");\n }\n\n BaseClass^ base = gcnew BaseClass();\n ... // Copy the fields here\n return base;\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14385/" ]
79,258
<p>Is there a tool that will find for me all the css classes that I am referencing in my HTML that don't actually exist?</p> <p>ie. if I have &lt;ul class="topnav" /&gt; in my HTML and the topnav class doesn't exist in any of the referenced CSS files.</p> <p>This is similar to <a href="https://stackoverflow.com/questions/33242/how-can-i-find-unused-images-and-css-styles-in-a-website">SO#33242</a>, which asks how to find unused CSS styles. This isn't a duplicate, as that question asks which CSS classes are not used. This is the opposite problem.</p>
[ { "answer_id": 79433, "author": "mislav", "author_id": 11687, "author_profile": "https://Stackoverflow.com/users/11687", "pm_score": 3, "selected": true, "text": "function forItems(a, f) {\n for (var i = 0; i < a.length; i++) f(a.item(i))\n}\n\nfunction classExists(className) {\n var pattern = new RegExp('\\\\.' + className + '\\\\b'), found = false\n\n try {\n forItems(document.styleSheets, function(ss) {\n // decompose only screen stylesheets\n if (!ss.media.length || /\\b(all|screen)\\b/.test(ss.media.mediaText))\n forItems(ss.cssRules, function(r) {\n // ignore rules other than style rules\n if (r.type == CSSRule.STYLE_RULE && r.selectorText.match(pattern)) {\n found = true\n throw \"found\"\n }\n })\n })\n } catch(e) {}\n\n\n return found\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4640/" ]
79,264
<p>Is there a program or API I can code against to extract individual files from a Windows Vista Complete PC Backup image?</p> <p>I like the idea of having a complete image to restore from, but hate the idea that I have to make two backups, one for restoring individual files, and one for restoring my computer in the event of a catastrophic failure.</p>
[ { "answer_id": 79433, "author": "mislav", "author_id": 11687, "author_profile": "https://Stackoverflow.com/users/11687", "pm_score": 3, "selected": true, "text": "function forItems(a, f) {\n for (var i = 0; i < a.length; i++) f(a.item(i))\n}\n\nfunction classExists(className) {\n var pattern = new RegExp('\\\\.' + className + '\\\\b'), found = false\n\n try {\n forItems(document.styleSheets, function(ss) {\n // decompose only screen stylesheets\n if (!ss.media.length || /\\b(all|screen)\\b/.test(ss.media.mediaText))\n forItems(ss.cssRules, function(r) {\n // ignore rules other than style rules\n if (r.type == CSSRule.STYLE_RULE && r.selectorText.match(pattern)) {\n found = true\n throw \"found\"\n }\n })\n })\n } catch(e) {}\n\n\n return found\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2581/" ]
79,266
<p>When attempting to understand how a SQL statement is executing, it is sometimes recommended to look at the explain plan. What is the process one should go through in interpreting (making sense) of an explain plan? What should stand out as, "Oh, this is working splendidly?" versus "Oh no, that's not right."</p>
[ { "answer_id": 79300, "author": "convex hull", "author_id": 10747, "author_profile": "https://Stackoverflow.com/users/10747", "pm_score": 2, "selected": false, "text": "Seq Scan on my_table (cost=0.00..15558.92 rows=620092 width=78)\n" }, { "answer_id": 79326, "author": "dpollock", "author_id": 7884, "author_profile": "https://Stackoverflow.com/users/7884", "pm_score": 1, "selected": false, "text": "* Index or table scans: May indicate a need for better or additional indexes.\n* Bookmark Lookups: Consider changing the current clustered index,\n consider using a covering index, limit\n the number of columns in the SELECT\n statement.\n* Filter: Remove any functions in the WHERE clause, don't include wiews\n in your Transact-SQL code, may need\n additional indexes.\n* Sort: Does the data really need to be sorted? Can an index be used to\n avoid sorting? Can sorting be done at\n the client more efficiently? \n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
79,275
<p>I have a form like this:</p> <pre><code>&lt;form name="mine"&gt; &lt;input type=text name=one&gt; &lt;input type=text name=two&gt; &lt;input type=text name=three&gt; &lt;/form&gt; </code></pre> <p>When user types a value in 'one', I sometimes want to skip the field 'two', depending on what he typed. For example, if user types '123' and uses Tab to move to next field, I want to skip it and go to field three.</p> <p>I tried to use <code>OnBlur</code> and <code>OnEnter</code>, without success. </p> <p><strong>Try 1:</strong></p> <pre><code>&lt;form name="mine"&gt; &lt;input type=text name=one onBlur="if (document.mine.one.value='123') document.three.focus();&gt; &lt;input type=text name=two&gt; &lt;input type=text name=three&gt; &lt;/form&gt; </code></pre> <p><strong>Try 2:</strong></p> <pre><code>&lt;form name="mine"&gt; &lt;input type=text name=one&gt; &lt;input type=text name=two onEnter="if (document.mine.one.value='123') document.three.focus();&gt; &lt;input type=text name=three&gt; &lt;/form&gt; </code></pre> <p>but none of these works. Looks like the browser doesn't allow you to mess with focus while the focus is changing. </p> <p>BTW, all this tried with Firefox on Linux.</p>
[ { "answer_id": 79317, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": 3, "selected": true, "text": "<INPUT tabindex=\"3\" type=\"submit\" name=\"mySubmit\">\n" }, { "answer_id": 79345, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 0, "selected": false, "text": "<form name=\"mine\">\n <input type=\"text\" name=\"one\" onkeypress=\"if (mine.one.value == '123') mine.three.focus();\" />\n <input type=\"text\" name=\"two\">\n <input type=\"text\" name=\"three\">\n</form>\n" }, { "answer_id": 79347, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "onkeypress onblur onfocus onfocus" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14690/" ]
79,292
<p>Can databases (MySQL in particular, any SQL--MS, Oracle, Postgres--in general) do mass updates, and figure out on their own what the new value should be? Say for example I've got a database with information about a bunch of computers, and all of these computers have drives of various sizes--anywhere from 20 to 250 GB. Then one day we upgrade every single computer by adding a 120 GB hard drive. Is there a way to say something like</p> <pre><code>update computers set total_disk_space = (whatever that row's current total_disk_space is plus 120) </code></pre>
[ { "answer_id": 79305, "author": "Tom Leys", "author_id": 11440, "author_profile": "https://Stackoverflow.com/users/11440", "pm_score": 2, "selected": false, "text": "update computers set total_disk_space = total_disk_space + 120;\n" }, { "answer_id": 79313, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 3, "selected": false, "text": "Update Computers \nSet Total_Disk_Space = Total_Disk_Space + 120;\n Update Computers\nSet Total_Disk_Space = Total_Disk_Space + 120\nWhere PurchaseDate BETWEEN '1/1/2008' AND GETDATE();\n" }, { "answer_id": 79329, "author": "Matt Haley", "author_id": 14142, "author_profile": "https://Stackoverflow.com/users/14142", "pm_score": 2, "selected": false, "text": "UPDATE computers\nSET total_disk_space = total_disk_space + 120;\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14701/" ]
79,322
<p>The documentation with the module itself is pretty thin, and just tends to point to MOP.</p>
[ { "answer_id": 79569, "author": "Dave Rolsky", "author_id": 9832, "author_profile": "https://Stackoverflow.com/users/9832", "pm_score": 6, "selected": true, "text": "Moose::Meta Moose::Manual::Unsweetened" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11289/" ]
79,352
<p>I have a method that can return either a single object or a collection of objects. I want to be able to run object.collect on the result of that method whether or not it is a single object or a collection already. How can i do this?</p> <pre><code>profiles = ProfileResource.search(params) output = profiles.collect do | profile | profile.to_hash end </code></pre> <p>If profiles is a single object, I get a NoMethodError exception when I try to execute collect on that object.</p>
[ { "answer_id": 79416, "author": "Matt Haley", "author_id": 14142, "author_profile": "https://Stackoverflow.com/users/14142", "pm_score": 1, "selected": false, "text": "profiles = [ProfileResource.search(params)].flatten\noutput = profiles.collect do |profile|\n profile.to_hash\nend\n" }, { "answer_id": 79427, "author": "ctcherry", "author_id": 10322, "author_profile": "https://Stackoverflow.com/users/10322", "pm_score": 0, "selected": false, "text": "search ProfileResource" }, { "answer_id": 79457, "author": "Mike Tunnicliffe", "author_id": 13956, "author_profile": "https://Stackoverflow.com/users/13956", "pm_score": 4, "selected": true, "text": "profiles = ProfileResource.search(params)\nprofiles = [profiles] if !profiles.respond_to?(:collect)\noutput = profiles.collect do |profile|\n profile.to_hash\nend\n" }, { "answer_id": 79502, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "[*ProfileResource.search(params)].collect { |profile| profile.to_hash }\n" }, { "answer_id": 79506, "author": "Zakaria", "author_id": 3370, "author_profile": "https://Stackoverflow.com/users/3370", "pm_score": 0, "selected": false, "text": "profiles = [*ProfileResource.search(params)]\noutput = profiles.collect do | profile |\n profile.to_hash\nend\n" }, { "answer_id": 79512, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "profiles = ProfileResource.search(params)\noutput = Array(profiles).collect do |profile|\n profile.to_hash\nend\n" }, { "answer_id": 81655, "author": "Farrel", "author_id": 7889, "author_profile": "https://Stackoverflow.com/users/7889", "pm_score": 0, "selected": false, "text": "profiles = Array(ProfileResource.search(params))\noutput = profiles.collect do | profile |\n profile.to_hash\nend\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1486/" ]
79,360
<p>I've drawn an ellipse in the XZ plane, and set my perspective slightly up on the Y-axis and back on the Z, looking at the center of ellipse from a 45-degree angle, using gluPerspective() to set my viewing frustrum.</p> <p><a href="http://www.flickr.com/photos/rampion/2863703051/" rel="nofollow noreferrer" title="ellipse by rampion, on Flickr"><img src="https://farm4.static.flickr.com/3153/2863703051_a768ed86a9_m.jpg" width="240" height="187" alt="ellipse" /></a></p> <p>Unrotated, the major axis of the ellipse spans the width of my viewport. When I rotate 90-degrees about my line-of-sight, the major axis of the ellipse now spans the height of my viewport, thus deforming the ellipse (in this case, making it appear less eccentric).</p> <p><a href="http://www.flickr.com/photos/rampion/2863703073/" rel="nofollow noreferrer" title="rotated ellipse by rampion, on Flickr"><img src="https://farm4.static.flickr.com/3187/2863703073_24c6549d4b_m.jpg" width="240" height="187" alt="rotated ellipse" /></a></p> <p>What do I need to do to prevent this deformation (or at least account for it), so rotation about the line-of-sight preserves the perceived major axis of the ellipse (in this case, causing it to go beyond the viewport)?</p>
[ { "answer_id": 79459, "author": "Martin", "author_id": 2581, "author_profile": "https://Stackoverflow.com/users/2581", "pm_score": 2, "selected": false, "text": "void gluPerspective( GLdouble fovy,\n GLdouble aspect,\n GLdouble zNear,\n GLdouble zFar )\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9859/" ]
79,367
<p>I have a query:</p> <pre><code>SELECT * FROM Items WHERE column LIKE '%foo%' OR column LIKE '%bar%' </code></pre> <p>How do I order the results?</p> <p>Let's say I have rows that match 'foo' and rows that match 'bar' but I also have a row with 'foobar'.</p> <p>How do I order the returned rows so that the first results are the ones that matched more LIKEs? </p>
[ { "answer_id": 79393, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "select *, case when col like '%foo%' and col like '%bar%' then 2 end \nelse 1 end as ordcol \nfrom items \nwhere col like '%foo%' or col like '%bar%' order by ordcol\n" }, { "answer_id": 79395, "author": "Booji Boy", "author_id": 1433, "author_profile": "https://Stackoverflow.com/users/1433", "pm_score": 0, "selected": false, "text": "SELECT * FROM Items WHERE column LIKE '%foo%' OR column LIKE '%bar%'\norder by (select count(*) from items i where i.column= item.column) DESC \n column count(*) ORDER" }, { "answer_id": 79418, "author": "Mike Tunnicliffe", "author_id": 13956, "author_profile": "https://Stackoverflow.com/users/13956", "pm_score": 0, "selected": false, "text": "SELECT *\nFROM Items\nWHERE column LIKE '%foo%' OR column LIKE '%bar%'\nORDER BY CASE WHEN column LIKE '%foo%' AND column LIKE '%bar%' THEN 1 ELSE 0 END DESC\n" }, { "answer_id": 79422, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 1, "selected": false, "text": "UNION SELECT * FROM Items WHERE column LIKE '%foo%' AND column LIKE '%bar%'\nUNION\nSELECT * FROM Items WHERE column LIKE '%foo%' AND NOT (column LIKE '%bar%')\nUNION\nSELECT * FROM Items WHERE column LIKE '%bar%' AND NOT (column LIKE '%foo%');\n score SELECT\n *,\n (IF(column LIKE '%bar%', 1, 0) + IF(column LIKE '%foo%', 1, 0)) AS score\nFROM Items\nWHERE column LIKE '%foo%' OR column LIKE '%bar%'\nORDER BY score DESC;\n IF" }, { "answer_id": 79430, "author": "nicudotro", "author_id": 14635, "author_profile": "https://Stackoverflow.com/users/14635", "pm_score": 2, "selected": false, "text": "SELECT * FROM Items WHERE column LIKE '%foo%' OR column LIKE '%bar%' \nORDER BY \n(IF(column LIKE '%foo%',1,0) + IF(column LIKE '%bar%',1,0)) \nDESC\n IF ( condition, true_value, false_value )" }, { "answer_id": 79473, "author": "Jolyon", "author_id": 11740, "author_profile": "https://Stackoverflow.com/users/11740", "pm_score": 0, "selected": false, "text": "SELECT * FROM Items WHERE column LIKE '%foo%' AND column LIKE '%bar%';\nSELECT * FROM Items WHERE (column LIKE '%foo%' AND column NOT LIKE '%bar%') OR (column NOT LIKE '%foo%' AND LIKE '%bar%')" }, { "answer_id": 79497, "author": "Mark Nold", "author_id": 4134, "author_profile": "https://Stackoverflow.com/users/4134", "pm_score": 0, "selected": false, "text": "SELECT \n a.employee_id,\n a.surname,\n sum(a.counter)\nFROM\n\n (SELECT\n employee_id,\n surname,\n 1 as counter\n FROM\n MyTable\n WHERE\n surname like '%SMITH%'\n\n UNION ALL\n\n SELECT\n employee_id,\n surname,\n 1 as counter\n FROM\n MyTable\n WHERE\n surname like '%JO%'\n ) a\n\nGROUP BY \n a.employee_id,\n a.surname\nORDER BY 3,1,2\n" }, { "answer_id": 79598, "author": "Matt", "author_id": 4154, "author_profile": "https://Stackoverflow.com/users/4154", "pm_score": 0, "selected": false, "text": "SELECT 1 as rank, * FROM Items WHERE column LIKE '%foo%' AND column LIKE '%bar%'\nUNION\nSELECT 2 as rank, * FROM Items WHERE column LIKE '%foo%' AND column NOT LIKE '%bar%'\nUNION\nSELECT 2 as rank, * FROM Items WHERE column LIKE '%bar%' AND column NOT LIKE '%foo%'\nORDER BY rank\n" }, { "answer_id": 81772, "author": "Andy Irving", "author_id": 8553, "author_profile": "https://Stackoverflow.com/users/8553", "pm_score": 1, "selected": false, "text": "SELECT * FROM Items\nWHERE col LIKE '%foo%'\n OR col LIKE '%bar%'\nORDER BY CASE WHEN col LIKE '%foo%' THEN 1\n WHEN col LIKE '%bar%' THEN 2\n END\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
79,381
<p>I am wanting to access a website from a different port than 80 or 8080. Is this possible? I just want to view the website but through a different port. I do not have a router. I know this can be done because I have a browser that accessing websites through different ports, Called XB Browser by Xero Bank.</p> <hr> <p>Thanks for the answers. So, if I setup a proxy on one computer, I could have it go from my computer, to another computer that then returns the website to me. Would this bypass logging software?</p>
[ { "answer_id": 79464, "author": "etchasketch", "author_id": 14640, "author_profile": "https://Stackoverflow.com/users/14640", "pm_score": 3, "selected": false, "text": "ssh -L 22222:<target_website>:80 <home_computer>\n http://localhost:22222/\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14769/" ]
79,445
<p>I'd like to write a simple C# application to monitor the line-in audio and give me the current (well, the rolling average) beats per minute.</p> <p>I've seen <a href="http://www.gamedev.net/page/resources/_/technical/math-and-physics/beat-detection-algorithms-r1952" rel="noreferrer">this gamedev article</a>, and that was absolutely no help. I went through and tried to implement what he was doing but it just wasn't working.</p> <p>I know there have to be tons of solutions for this, because lots of DJ software does it, but I'm not having any luck in finding any open-source library or instructions on doing it myself.</p>
[ { "answer_id": 81666, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 5, "selected": false, "text": "double[] signal = stream.Take(1024);\n double[] real = new double[signal.Length];\ndouble[] imag = new double[signal.Length);\nFFT(signal, out real, out imag);\n for (i=0; i < real.Length; i++) real[i] = real[i] * real[i];\n for (i=0; i < imag.Length; i++) imag[i] = imag[i] * imag[i];\n double bassIntensity = 0;\nfor (i=8; i < 96; i++) bassIntensity += real[i];\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14758/" ]
79,455
<p>Given this example:</p> <pre><code>&lt;img class="a" /&gt; &lt;img /&gt; &lt;img class="a" /&gt; &lt;img class="a" id="active" /&gt; &lt;img class="a" /&gt; &lt;img class="a" /&gt; &lt;img /&gt; &lt;img class="a" /&gt; </code></pre> <p><em>(I've just used img tags as an example, that's not what it is in my code)</em></p> <p>Using jQuery, how would you select the img tags with class "a" that are adjacent to #active (the middle four, in this example)?</p> <p>You could do it fairly easily by looping over all the following and preceding elements, stopping when the filter condition fails, but I was wondering if jQuery could it natively?</p>
[ { "answer_id": 79767, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 0, "selected": false, "text": "$('#active ~ img.a').hide();\n" }, { "answer_id": 79861, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "$('#active ~ img.a')\n" }, { "answer_id": 79978, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 0, "selected": false, "text": "var next = $('#active').next('.a');\nvar prev = $('#active').prev('.a');\n" }, { "answer_id": 80302, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 3, "selected": true, "text": "// here's our active element.\nvar $active = $('#active');\n\n// here is the filter we'll be testing against.\nvar filter = \"img.a\";\n\n// $all will be the final jQuery object with all the consecutively matched elements.\n// start it out by populating it with the current object.\nvar $all = $active;\n\nfor ($curr = $active.prev(filter); $curr.length > 0; $curr = $curr.prev(filter)) {\n $all = $all.add($curr);\n}\nfor ($curr = $td.next(filter); $curr.length > 0; $curr = $curr.next(filter)) {\n $all = $all.add($curr);\n}\n $('#active')\n .nextAll()\n .each(hideConsecutive)\n .end()\n .prevAll()\n .each(hideConsecutive)\n;\nfunction hideConsecutive(index, element) {\n var $e = $(element);\n if (!$e.is(\".a\")) {\n return false; // this stops the each function.\n } else {\n $e.hide('slow');\n }\n}\n" }, { "answer_id": 763488, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": " var $all = \n (name == 'prev')\n ? $(this).prevAll()\n : $(this).nextAll();\n if (!matchExpr)\n return $all;\n\n var $notMatch = $($all).not(matchExpr).filter(':first');\n if ($all.index($notMatch) != -1)\n return $allConsecutive = $all.slice(0, $all.index($notMatch));\n\n return $all;\n};\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
79,461
<p>I have a <code>div</code> with two images and an <code>h1</code>. All of them need to be vertically aligned within the div, next to each other. One of the images needs to be <code>absolute</code> positioned within the <code>div</code>.</p> <p>What is the CSS needed for this to work on all common browsers?</p> <pre class="lang-html prettyprint-override"><code>&lt;div id=&quot;header&quot;&gt; &lt;img src=&quot;..&quot; &gt;&lt;/img&gt; &lt;h1&gt;testing...&lt;/h1&gt; &lt;img src=&quot;...&quot;&gt;&lt;/img&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 79513, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": -1, "selected": false, "text": "<div id=\"header\" style=\"display: table-cell; vertical-align:middle;\">\n .someClass\n{\n display: table-cell;\n vertical-align:middle;\n}\n" }, { "answer_id": 79550, "author": "Mike Tunnicliffe", "author_id": 13956, "author_profile": "https://Stackoverflow.com/users/13956", "pm_score": 2, "selected": false, "text": "#header > h1 { display: inline; }\n #header { position: relative; width: 20em; height: 20em; }\n#img-for-abs-positioning { position: absolute; top: 0; left: 0; }\n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n <html>\n <head>\n <title>Example of vertical positioning inside a div</title>\n <style type=\"text/css\">\n #header > h1 { display: inline; }\n #header { border: solid 1px red; \n position: relative; }\n #img-for-abs-positioning { position: absolute;\n bottom: -1em; right: 2em; }\n </style>\n </head>\n \n <body>\n <div id=\"header\">\n <img src=\"#\" alt=\"Image 1\" width=\"40\" height=\"40\" />\n <h1>Header</h1>\n <img src=\"#\" alt=\"Image 2\" width=\"40\" height=\"40\" \n id=\"img-for-abs-positioning\" />\n </div>\n </body>\n </html>" }, { "answer_id": 80036, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 4, "selected": false, "text": "H1 vertical-align #header h1 { display: inline; }\n#header img { vertical-align: middle; }\n H1 H1 <h1 id=header\">\n <img src=\"..\" ></img>\n testing...\n <img src=\"...\"></img>\n</h1>\n" }, { "answer_id": 84616, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 11, "selected": true, "text": "vertical-align vertical-align vertical-align: middle absolute height margin-top top line-height" }, { "answer_id": 5962720, "author": "Romain", "author_id": 305288, "author_profile": "https://Stackoverflow.com/users/305288", "pm_score": 6, "selected": false, "text": ".vcontainer {\n min-height: 10em;\n display: table-cell;\n vertical-align: middle;\n}\n" }, { "answer_id": 9967286, "author": "Anita Mandal", "author_id": 1146211, "author_profile": "https://Stackoverflow.com/users/1146211", "pm_score": 4, "selected": false, "text": "#outer {height: 400px; overflow: hidden; position: relative;}\n#outer[id] {display: table; position: static;}\n\n#middle {position: absolute; top: 50%;} /* For explorer only*/\n#middle[id] {display: table-cell; vertical-align: middle; width: 100%;}\n\n#inner {position: relative; top: -50%} /* For explorer only */\n/* Optional: #inner[id] {position: static;} */ <div id=\"outer\">\n <div id=\"middle\">\n <div id=\"inner\">\n any text\n any height\n any content, for example generated from DB\n everything is vertically centered\n </div>\n </div>\n</div>" }, { "answer_id": 10181095, "author": "abernier", "author_id": 133327, "author_profile": "https://Stackoverflow.com/users/133327", "pm_score": 5, "selected": false, "text": "div:before {content:\" \"; display:inline-block; height:100%; vertical-align:middle;}\ndiv p {display:inline-block;} <div style=\"height:100px; border:1px solid;\">\n <p style=\"border:1px dotted;\">I'm vertically centered.</p>\n</div>" }, { "answer_id": 16357586, "author": "user2346571", "author_id": 2346571, "author_profile": "https://Stackoverflow.com/users/2346571", "pm_score": 7, "selected": false, "text": "div.ext-box { display: table; width:100%;}\ndiv.int-box { display: table-cell; vertical-align: middle; } <div class=\"ext-box\">\n <div class=\"int-box\">\n <h2>Some txt</h2>\n <p>bla bla bla</p>\n </div>\n</div> .class #id" }, { "answer_id": 19131573, "author": "Joel Moses", "author_id": 2837597, "author_profile": "https://Stackoverflow.com/users/2837597", "pm_score": -1, "selected": false, "text": "<div>\n <table style=\"width: 100%; height: 100%\">\n <tr>\n <td style=\"width: 100%; height: 100%; vertical-align: middle;\">\n What ever you want vertically-aligned\n </td>\n </tr>\n </table>\n</div>\n" }, { "answer_id": 20149753, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "html,\n body {\n height: 100%;\n }\n body {\n margin: 0;\n }\n\n .table {\n display: table;\n width: auto;\n table-layout:auto;\n height: 100%;\n }\n .table:nth-child(even) {\n background: #a9edc3;\n }\n .table:nth-child(odd) {\n background: #eda9ce;\n }\n\n .tr {\n display: table-row;\n }\n .td {\n display: table-cell;\n width: 50%;\n vertical-align: middle;\n }\n" }, { "answer_id": 20920505, "author": "pr0gg3r", "author_id": 1159244, "author_profile": "https://Stackoverflow.com/users/1159244", "pm_score": -1, "selected": false, "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n<html>\n <head>\n <style type=\"text/css\">\n #style_center { position:relative; top:50%; left:50%; }\n #style_center_absolute { position:absolute; top:50px; left:50px; }\n <!--#style_center { position:relative; top:50%; left:50%; height:50px; margin-top:-25px; }-->\n </style>\n </head>\n\n <body>\n <div style=\"height:200px; width:200px; background:#00FF00\">\n <div id=\"style_center\">+</div>\n </div>\n </body>\n</html>\n" }, { "answer_id": 21202703, "author": "Shadoweb", "author_id": 1063653, "author_profile": "https://Stackoverflow.com/users/1063653", "pm_score": 4, "selected": false, "text": ".element {\n position: relative;\n top: 50%;\n transform: translateY(-50%);\n}\n .element {\n position: relative;\n top: 50%;\n -webkit-transform: translateY(-50%);\n -ms-transform: translateY(-50%);\n transform: translateY(-50%);\n}\n" }, { "answer_id": 24985086, "author": "Arsh", "author_id": 3882353, "author_profile": "https://Stackoverflow.com/users/3882353", "pm_score": 0, "selected": false, "text": "<style>\n.outer {\n font-size: 0;\n width: 400px;\n height: 400px;\n background: orange;\n text-align: center;\n display: inline-block;\n}\n\n.outer .emptyDiv {\n height: 100%;\n background: orange;\n visibility: collapse;\n}\n\n.outer .inner {\n padding: 10px;\n background: red;\n font: bold 12px Arial;\n}\n\n.verticalCenter {\n display: inline-block;\n *display: inline;\n zoom: 1;\n vertical-align: middle;\n}\n</style>\n\n<div class=\"outer\">\n <div class=\"emptyDiv verticalCenter\"></div>\n <div class=\"inner verticalCenter\">\n <p>Line 1</p>\n <p>Line 2</p>\n </div>\n</div>\n" }, { "answer_id": 25867805, "author": "danigonlinea", "author_id": 1196978, "author_profile": "https://Stackoverflow.com/users/1196978", "pm_score": 0, "selected": false, "text": "i div <div class=\"circle\">\n <i class=\"fa fa-plus icon\">\n</i></div>\n .circle {\n border-radius: 50%;\n color: blue;\n background-color: red;\n height:100px;\n width:100px;\n text-align: center;\n line-height: 100px;\n}\n\n.icon {\n font-size: 50px;\n vertical-align: middle;\n}\n" }, { "answer_id": 26356771, "author": "VuesomeDev", "author_id": 1725325, "author_profile": "https://Stackoverflow.com/users/1725325", "pm_score": 5, "selected": false, "text": "div .vcontainer {\n position: relative;\n top: 50%;\n transform: translateY(-50%);\n -webkit-transform: translateY(-50%);\n}\n" }, { "answer_id": 26364552, "author": "joan16v", "author_id": 1398876, "author_profile": "https://Stackoverflow.com/users/1398876", "pm_score": 4, "selected": false, "text": "<div>\n\n <table style=\"width:100%; height:100%;\">\n <tr>\n <td style=\"vertical-align:middle;\">\n BUTTON TEXT\n </td>\n </tr>\n </table>\n\n</div>\n" }, { "answer_id": 31078418, "author": "E. Serrano", "author_id": 1572964, "author_profile": "https://Stackoverflow.com/users/1572964", "pm_score": 8, "selected": false, "text": "align-self:start .container {\n display: flex;\n align-items: center;\n}\n .container {\n display: -ms-flexbox;\n display: -webkit-flex;\n display: flex;\n\n -ms-flex-align: center;\n -webkit-align-items: center;\n -webkit-box-align: center;\n align-items: center;\n}\n" }, { "answer_id": 31279382, "author": "BernieSF", "author_id": 1689852, "author_profile": "https://Stackoverflow.com/users/1689852", "pm_score": 0, "selected": false, "text": "<div style=\"width:70px; height:68px; float:right; display: table-cell; line-height: 68px\">\n <a href=\"javascript:void(0)\" style=\"margin-left: 4px; line-height: 2\" class=\"btn btn-primary\">Login</a>\n</div>\n" }, { "answer_id": 34320593, "author": "Henk-Martijn", "author_id": 4069967, "author_profile": "https://Stackoverflow.com/users/4069967", "pm_score": 3, "selected": false, "text": "<div class=\"circle\">\n <div class=\"content\">\n Some text\n </div>\n</div>\n .circle {\n /* Act as a table so we can center vertically its child */\n display: table;\n /* Set dimensions */\n height: 200px;\n width: 200px;\n /* Horizontal center text */\n text-align: center;\n /* Create a red circle */\n border-radius: 100%;\n background: red;\n}\n\n.content {\n /* Act as a table cell */\n display: table-cell;\n /* And now we can vertically center! */\n vertical-align: middle;\n /* Some basic markup */\n font-size: 30px;\n font-weight: bold;\n color: white;\n}\n <div class=\"container\">\n <div class=\"content\">\n\n <div class=\"centerhoriz\">\n\n <div class=\"circle\">\n <div class=\"content\">\n Some text\n </div><!-- content -->\n </div><!-- circle -->\n\n <div class=\"square\">\n <div class=\"content\">\n <div id=\"smallcircle\"></div>\n </div><!-- content -->\n </div><!-- square -->\n\n </div><!-- center-horiz -->\n\n </div><!-- content -->\n</div><!-- container -->\n .container {\n display: table;\n height: 500px;\n width: 300px;\n text-align: center;\n background: lightblue;\n}\n\n.centerhoriz {\n display: inline-block;\n}\n\n.circle {\n display: table;\n height: 200px;\n width: 200px;\n text-align: center;\n background: red;\n border-radius: 100%;\n margin: 10px;\n}\n\n.square {\n display: table;\n height: 200px;\n width: 200px;\n text-align: center;\n background: blue;\n margin: 10px;\n}\n\n.content {\n display: table-cell;\n vertical-align: middle;\n font-size: 30px;\n font-weight: bold;\n color: white;\n}\n\n#smallcircle {\n display: inline-block;\n height: 50px;\n width: 50px;\n background: green;\n border-radius: 100%;\n}\n" }, { "answer_id": 39904652, "author": "Dashrath", "author_id": 1510544, "author_profile": "https://Stackoverflow.com/users/1510544", "pm_score": 2, "selected": false, "text": "<div class=\"box\">\n <span><a href=\"#\">Some Text</a></span>\n</div>\n .box {\n display: block;\n background: #60D3E8;\n position: relative;\n width: 300px;\n height: 200px;\n text-align: center;\n}\n\n.box span {\n font: bold 20px/20px 'source code pro', sans-serif;\n position: absolute;\n left: 0;\n right: 0;\n top: calc(50% - 10px);\n}\n\na {\n color: white;\n text-decoration: none;\n}\n div height width" }, { "answer_id": 45458436, "author": "Shivam", "author_id": 1592107, "author_profile": "https://Stackoverflow.com/users/1592107", "pm_score": 2, "selected": false, "text": ".immediate-parent-of-text-containing-div {\n height: 50px; /* Or any fixed height that suits you. */\n}\n\n.text-containing-div {\n display: inline-grid;\n align-items: center;\n text-align: center;\n height: 100%;\n}\n" }, { "answer_id": 48523051, "author": "WasiF", "author_id": 4574281, "author_profile": "https://Stackoverflow.com/users/4574281", "pm_score": 5, "selected": false, "text": "d-flex align-items-center d-flex justify-content-center d-flex align-items-center justify-content-center .container {\n height: 180px;\n width:100%;\n background-color: blueviolet;\n}\n\n.container > div {\n background-color: white;\n padding: 1rem;\n} <link href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"\nrel=\"stylesheet\"/>\n\n<div class=\"d-flex align-items-center justify-content-center container\">\n <div>I am in Center</div>\n</div> .container {\n height: 180px;\n width:100%;\n background-color: blueviolet;\n}\n\n.container > div {\n background-color: white;\n padding: 1rem;\n}\n\n.center {\n display: flex;\n align-items: center;\n justify-content: center;\n} <div class=\"container center\">\n <div>I am in Center</div>\n</div>" }, { "answer_id": 51626821, "author": "Sameera Prasad Jayasinghe", "author_id": 5901608, "author_profile": "https://Stackoverflow.com/users/5901608", "pm_score": 7, "selected": false, "text": " .outer {\n display: flex;\n align-items: center; \n justify-content: center;\n }\n" }, { "answer_id": 55066555, "author": "Dennis Don", "author_id": 1367794, "author_profile": "https://Stackoverflow.com/users/1367794", "pm_score": 3, "selected": false, "text": "<div class=\"outdiv\">\n <div class=\"indiv\">\n <span>test1</span>\n <span>test2</span>\n </div>\n</div>\n .outdiv {\n display: flex;\n justify-content: center;\n align-items: center;\n}\n" }, { "answer_id": 57117215, "author": "Stephen", "author_id": 558721, "author_profile": "https://Stackoverflow.com/users/558721", "pm_score": 2, "selected": false, "text": "/* technique */\n\n.wrapper {\n display: inline-grid;\n grid-auto-flow: column;\n align-items: center;\n justify-content: center;\n}\n\n/* visual emphasis */\n\n.wrapper {\n border: 1px solid red;\n height: 180px;\n width: 400px;\n}\n\nimg {\n width: 100px;\n height: 80px;\n background: #fafafa;\n}\n\nimg:nth-child(2) {\n height: 120px;\n} <div class=\"wrapper\">\n <img src=\"https://source.unsplash.com/random/100x80/?bear\">\n <img src=\"https://source.unsplash.com/random/100x120/?lion\">\n <img src=\"https://source.unsplash.com/random/100x80/?tiger\">\n</div>" }, { "answer_id": 57247568, "author": "akhtarvahid", "author_id": 6544460, "author_profile": "https://Stackoverflow.com/users/6544460", "pm_score": 4, "selected": false, "text": "/* Absolute Positioning Method */\n.parent1 {\n background: darkcyan;\n width: 200px;\n height: 200px;\n position: relative;\n}\n.child1 {\n background: white;\n height: 30px;\n width: 30px;\n position: absolute;\n top: 50%;\n left: 50%;\n margin: -15px;\n}\n\n/* Flexbox Method */\n.parent2 {\n display: flex;\n justify-content: center;\n align-items: center;\n background: darkcyan;\n height: 200px;\n width: 200px;\n}\n.child2 {\n background: white;\n height: 30px;\n width: 30px;\n}\n\n/* Transform/Translate Method */\n.parent3 {\n position: relative;\n height: 200px;\n width: 200px;\n background: darkcyan;\n}\n.child3 {\n background: white;\n height: 30px;\n width: 30px;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n} <div class=\"parent1\">\n <div class=\"child1\"></div>\n</div>\n<hr />\n\n<div class=\"parent2\">\n <div class=\"child2\"></div>\n</div>\n<hr />\n\n<div class=\"parent3\">\n <div class=\"child3\"></div>\n</div>" }, { "answer_id": 64780990, "author": "HASSAN MD TAREQ", "author_id": 4802664, "author_profile": "https://Stackoverflow.com/users/4802664", "pm_score": 2, "selected": false, "text": "class=\"container d-flex\" class=\"m-auto\" <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css\" crossorigin=\"anonymous\">\n\n<div class=\"container d-flex mt-5\" style=\"height:110px; background-color: #333;\">\n <h2 class=\"m-auto\"><a href=\"https://hovermind.com/\">H➲VER➾M⇡ND</a></h2>\n</div>" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5232/" ]
79,466
<p>(sorry I should have been clearer with the code the first time I posted this. Hope this makes sense)</p> <p>File "size_specification.rb"</p> <pre><code>class SizeSpecification def fits? end end </code></pre> <p>File "some_module.rb"</p> <pre><code>require 'size_specification' module SomeModule def self.sizes YAML.load_file(File.dirname(__FILE__) + '/size_specification_data.yml') end end </code></pre> <p>File "size_specification_data.yml</p> <pre><code>--- - !ruby/object:SizeSpecification height: 250 width: 300 </code></pre> <p>Then when I call</p> <pre><code>SomeModule.sizes.first.fits? </code></pre> <p>I get an exception because "sizes" are Object's not SizeSpecification's so they don't have a "fits" function.</p>
[ { "answer_id": 80075, "author": "robertpostill", "author_id": 11219, "author_profile": "https://Stackoverflow.com/users/11219", "pm_score": 0, "selected": false, "text": "class SizeSpecification\n include SomeModule\n def fits? \n end\nend\n SizeSpecification::SomeModule.sizes\n SizeSpecification.sizes\n" }, { "answer_id": 94745, "author": "anshul", "author_id": 17674, "author_profile": "https://Stackoverflow.com/users/17674", "pm_score": 1, "selected": false, "text": "require 'yaml'\nrequire \"some_module\"\n\nSomeModule.sizes.first.fits?\n $ ruby --version\nruby 1.8.6 (2008-06-20 patchlevel 230) [i486-linux]\n$ ruby -w test.rb \n$\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14796/" ]
79,474
<p>I've set up Passenger in development (Mac OS X) and it works flawlessly. The only problem came later: now I have a custom <code>GEM_HOME</code> path and ImageMagick binaries installed in <code>"/usr/local"</code>. I can put them in one of the shell rc files that get sourced and this solves the environment variables for processes spawned from the console; but what about Passenger? The same application cannot find my gems when run this way.</p>
[ { "answer_id": 79615, "author": "Brian Phillips", "author_id": 7230, "author_profile": "https://Stackoverflow.com/users/7230", "pm_score": 1, "selected": false, "text": "SetEnv" }, { "answer_id": 80003, "author": "manveru", "author_id": 8367, "author_profile": "https://Stackoverflow.com/users/8367", "pm_score": 2, "selected": false, "text": "ENV['GEM_HOME'] = '/foo'\n" }, { "answer_id": 81255, "author": "Ben Scofield", "author_id": 6478, "author_profile": "https://Stackoverflow.com/users/6478", "pm_score": 5, "selected": true, "text": "#!/bin/bash\nexport ENV_VAR=value\n/usr/bin/ruby $*\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11687/" ]
79,490
<p>How can I get a history of uptimes for my debian box? After a reboot, I dont see an option for the uptime command to print a history of uptimes. If it matters, I would like to use these uptimes for graphing a page in php to show my webservers uptime lengths between boots.</p> <p>Update: Not sure if it is based on a length of time or if last gets reset on reboot but I only get the most recent boot timestamp with the last command. last -x also does not return any further info. Sounds like a script is my best bet.</p> <p>Update: Uptimed is the information I am looking for, not sure how to grep that info in code. Managing my own script for a db sounds like the best fit for an application.</p>
[ { "answer_id": 79515, "author": "roo", "author_id": 716, "author_profile": "https://Stackoverflow.com/users/716", "pm_score": 5, "selected": false, "text": "last" }, { "answer_id": 79540, "author": "etchasketch", "author_id": 14640, "author_profile": "https://Stackoverflow.com/users/14640", "pm_score": 6, "selected": true, "text": "uptime >> uptime.log\n" }, { "answer_id": 79553, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 6, "selected": false, "text": "<? system(\"/usr/local/bin/uprecords -a -B\"); ?>\n" }, { "answer_id": 79699, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "0,10,20,30,40,50 * * * *\n /bin/echo $(/bin/date +\\%Y-\\%m-\\%d) $(/usr/bin/uptime)\n >>/tmp/uptime.hist 2>&1\n" }, { "answer_id": 80135, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "last | grep reboot \n" }, { "answer_id": 18943901, "author": "sepehr", "author_id": 184176, "author_profile": "https://Stackoverflow.com/users/184176", "pm_score": 4, "selected": false, "text": "last #last reboot #last reboot\nreboot system boot **************** Sat Sep 21 03:31 - 08:27 (1+04:56) \nreboot system boot **************** Wed Aug 7 07:08 - 08:27 (46+01:19)\n" }, { "answer_id": 62146140, "author": "sebisnow", "author_id": 6207983, "author_profile": "https://Stackoverflow.com/users/6207983", "pm_score": 0, "selected": false, "text": "sudo grep \"May 28\" /var/log/syslog* | head\n sudo grep \"May 28\" /var/log/syslog* | tail\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/777/" ]
79,493
<p>I want to use Apple's or RedHat's built-in Apache but I want to use Perl 5.10 and mod_perl. What's the least intrusive way to accomplish this? I want the advantage of free security patching for the vendor's Apache, dav, php, etc., but I care a lot about which version of Perl I use and what's in my @INC path. I don't mind compiling my own mod_perl.</p>
[ { "answer_id": 80032, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 1, "selected": false, "text": "/opt/ #!/opt/bin/perl /opt/bin/perl /usr/bin/perl cpan2rpm" }, { "answer_id": 83080, "author": "Michael Cramer", "author_id": 1496728, "author_profile": "https://Stackoverflow.com/users/1496728", "pm_score": 4, "selected": true, "text": "export PATH=/usr/local/perl/5.10.0/bin:$PATH\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14783/" ]
79,496
<p>I am looking for a way to connect to Facebook by allowing the user to enter in their username and password and have our app connect to their account and get their contacts so that they can invite them to join their group on our site. I have written a Facebook app before, but this is not an app as much as it is a connector so that they can invite all their friends or just some to the site we are working on.</p> <p>I have seen several other sites do this and also connect to Yahoo, Gmail and Hotmail contacts. I don't think they are using Facebook Connect to do this since it is so new, but they may be. </p> <p>Any solution in any language is fine as I can port whatever example to use C#. I cannot find anything specifically on Google or Facebook to address this specific problem. Any help is appreciated. </p> <p>I saw a first answer get removed that had suggested I might need to scrape the friends page. The more I look around, this might be what I need to do. Any other way I think will require the person to add it as an app. I am wondering how a answer can get removed, maybe that user deleted it.</p>
[ { "answer_id": 1606882, "author": "Jon Hadley", "author_id": 161525, "author_profile": "https://Stackoverflow.com/users/161525", "pm_score": 3, "selected": false, "text": "def invite_friends(request): \n #HTML escape function for invitation content. \n from cgi import escape \n facebook_uid = request.facebook.uid \n\n # Convert the array of friends into a comma-delimeted string. \n exclude_ids = \",\".join([str(a) for a in request.facebook.friends.getAppUsers()]) \n\n # Prepare the invitation text that all invited users will receive. \n content = \"\"\"<fb:name uid=\"%s\" firstnameonly=\"true\" shownetwork=\"false\"/> wants to invite you to play Online board games, <fb:req-choice url=\"%s\" label=\"Put Online Gaming and Video Chat on your profile!\"/>\"\"\" % (facebook_uid, request.facebook.get_add_url()) \n\n invitation_content = escape(content, True) \n return render_to_response('facebook/invite_friends.fbml',\n {'content': invitation_content, 'exclude_ids': exclude_ids })\n <fb:request-form action=\"http://apps.facebook.com/livevideochat/?skipped=1\" \n method=\"POST\" invite=\"true\" type=\"Online Games\" \n content=\"{{ content }}\"> \n\n <fb:multi-friend-selector max=\"20\" \n actiontext=\"Here are your friends who aren't using Online Games and Live Video Chat. Invite them to play Games Online today!\" \n showborder=\"true\" rows=\"5\" exclude_ids=\"{{ exclude_ids }}\"> </fb:request-form>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11196/" ]
79,498
<p>I have determined that my JSON, coming from the server, is valid (making the ajax call manually), but I would really like to use JQuery. I have also determined that the "post" URL, being sent to the server, is correct, using firebug. However, the error callback is still being triggered (parse error). I also tried datatype: text.</p> <p>Are there other options that I should include?</p> <pre><code>$(function() { $("#submit").bind("click", function() { $.ajax({ type: "post", url: "http://myServer/cgi-bin/broker" , datatype: "json", data: {'start' : start,'end' : end}, error: function(request,error){ alert(error); }, success: function(request) { alert(request.length); } }); // End ajax }); // End bind }); // End eventlistener </code></pre>
[ { "answer_id": 79617, "author": "Adam Weber", "author_id": 9324, "author_profile": "https://Stackoverflow.com/users/9324", "pm_score": 5, "selected": true, "text": "contentType: \"application/json; charset=utf-8\"\n" }, { "answer_id": 9664708, "author": "Bohdan Hdal", "author_id": 801142, "author_profile": "https://Stackoverflow.com/users/801142", "pm_score": 1, "selected": false, "text": "myResult request success: function(request) {\n alert(myResult.length);\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
79,538
<p>I just installed Ubuntu 8.04 and I'm taking a course in Java so I figured why not install a IDE while I am installing it. So I pick my IDE of choice, Eclipse, and I make a very simple program, Hello World, to make sure everything is running smoothly. When I go to use Scanner for user input I get a very odd error:</p> <p><b>My code:</b><pre>import java.util.Scanner;</p> <p>class test { public static void main (String [] args) { Scanner sc = new Scanner(System.in); System.out.println("hi"); } }</pre></p> <p><b>The output:</b></p> <pre> Exception in thread "main" java.lang.Error: Unresolved compilation problems: Scanner cannot be resolved to a type Scanner cannot be resolved to a type at test.main(test.java:5) </pre>
[ { "answer_id": 473785, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "# update-alternatives --config javac System.out.println(\"Say thank you, Mr.\");\nScanner scanner = java.util.Scanner(System.in);\nString thanks = scanner.next();\nSystem.out.println(\"Your welcome.\");" }, { "answer_id": 60959558, "author": "boi yeet", "author_id": 12864849, "author_profile": "https://Stackoverflow.com/users/12864849", "pm_score": 0, "selected": false, "text": "int a=sc.nextInt(); String b=sc.nextLine(); Hello World!" }, { "answer_id": 68014889, "author": "ailar", "author_id": 16177997, "author_profile": "https://Stackoverflow.com/users/16177997", "pm_score": 0, "selected": false, "text": "package com.company;\n\nimport java.util.Scanner;\n\npublic class Main {\n\n public static void main(String[] args) {\n Scanner in = new Scanner(System.in);\n System.out.print(\"Input seconds: \");\n int num = in.nextInt();\n\n for (int i = 1; i <=num; i++) {\n\n if(i%10==3)\n {\n System.out.println(i);\n }\n }\n\n }\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/97220/" ]
79,602
<p>I am writing a web application that requires user interaction via email. I'm curious if there is a best practice or recommended source for learning about processing email. I am writing my application in Python, but I'm not sure what mail server to use or how to format the message or subject line to account for automated processing. I'm also looking for guidance on processing bouncebacks. </p>
[ { "answer_id": 79670, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 3, "selected": true, "text": "$ dig google.com txt\n...snip...\n;; ANSWER SECTION:\ngoogle.com. 300 IN TXT \"v=spf1 include:_netblocks.google.com ~all\"\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322887/" ]
79,612
<p>Looking for a <code>Linux application</code> <em>(or Firefox extension)</em> that will allow me to scrape an HTML mockup and keep the page's integrity.</p> <p>Firefox does an almost perfect job but doesn't grab images referenced in the CSS.</p> <p>The Scrapbook extension for Firefox gets everything, but flattens the directory structure. </p> <p>I wouldn't terribly mind if all folders became children of the <code>index</code> page.</p>
[ { "answer_id": 79645, "author": "Gilean", "author_id": 6305, "author_profile": "https://Stackoverflow.com/users/6305", "pm_score": 4, "selected": true, "text": "wget --mirror –w 2 –p --HTML-extension –-convert-links http://www.yourdomain.com\n" }, { "answer_id": 79657, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 1, "selected": false, "text": "wget -r man wget curl" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13320/" ]
79,632
<p>I have a two tables joined with a join table - this is just pseudo code:</p> <pre><code>Library Book LibraryBooks </code></pre> <p>What I need to do is if i have the id of a library, i want to get all the libraries that all the books that this library has are in.</p> <p>So if i have Library 1, and Library 1 has books A and B in them, and books A and B are in Libraries 1, 2, and 3, is there an elegant (one line) way todo this in rails?</p> <p>I was thinking:</p> <pre><code>l = Library.find(1) allLibraries = l.books.libraries </code></pre> <p>But that doesn't seem to work. Suggestions?</p>
[ { "answer_id": 79646, "author": "Jim Puls", "author_id": 6010, "author_profile": "https://Stackoverflow.com/users/6010", "pm_score": 2, "selected": false, "text": "l.books.map {|b| b.libraries}\n l.books.map {|b| b.libraries}.flatten.uniq\n" }, { "answer_id": 79770, "author": "bouchard", "author_id": 14843, "author_profile": "https://Stackoverflow.com/users/14843", "pm_score": 2, "selected": false, "text": "l.books.map{|b| b.libraries}.flatten.uniq\n" }, { "answer_id": 81287, "author": "Ben Scofield", "author_id": 6478, "author_profile": "https://Stackoverflow.com/users/6478", "pm_score": 2, "selected": false, "text": "l.books.map{|b| b.libraries}.flatten.uniq\n LibraryBook.find(:all, :conditions => ['book_id IN (?)', l.book_ids]).map(&:library_id).uniq\n" }, { "answer_id": 81752, "author": "Ryan Bigg", "author_id": 15245, "author_profile": "https://Stackoverflow.com/users/15245", "pm_score": 4, "selected": true, "text": "l = Library.find(:all, :include => :books)\nl.books.map { |b| b.library_ids }.flatten.uniq\n map(&:library_ids) map { |b| b.library_ids } :joins include :joins" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4322/" ]
79,669
<p>I need to copy about 40 databases from one server to another. The new databases should have new names, but all the same tables, data and indexes as the original databases. So far I've been: </p> <p>1) creating each destination database<br> 2) using the "<a href="http://msdn.microsoft.com/en-us/library/ms140052.aspx" rel="noreferrer">Tasks->Export Data</a>" command to create and populate tables for each database individually<br> 3) rebuilding all of the indexes for each database with a SQL script </p> <p>Only three steps per database, but I'll bet there's an easier way. Do any MS SQL Server experts out there have any advice?</p>
[ { "answer_id": 79691, "author": "Leon Bambrick", "author_id": 49, "author_profile": "https://Stackoverflow.com/users/49", "pm_score": 7, "selected": true, "text": "(on source server...)\nBACKUP DATABASE Northwind\n TO DISK = 'c:\\Northwind.bak'\n\n(target server...)\nRESTORE FILELISTONLY\n FROM DISK = 'c:\\Northwind.bak'\n\n(look at the device names... and determine where you want the mdf and\nldf files to go on this target server)\n\nRESTORE DATABASE TestDB\n FROM DISK = 'c:\\Northwind.bak'\n WITH MOVE 'Northwind' TO 'c:\\test\\testdb.mdf',\n MOVE 'Northwind_log' TO 'c:\\test\\testdb.ldf'\nGO\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13728/" ]
79,677
<p>I need to speed up a program for the Nintendo DS which doesn't have an FPU, so I need to change floating-point math (which is emulated and slow) to fixed-point.</p> <p>How I started was I changed floats to ints and whenever I needed to convert them, I used <strong>x>>8</strong> to convert the fixed-point variable x to the actual number and <strong>x&lt;&lt;8</strong> to convert to fixed-point. Soon I found out it was impossible to keep track of what needed to be converted and I also realized it would be difficult to change the precision of the numbers (8 in this case.)</p> <p>My question is, how should I make this easier and still fast? Should I make a FixedPoint class, or just a FixedPoint8 typedef or struct with some functions/macros to convert them, or something else? Should I put something in the variable name to show it's fixed-point?</p>
[ { "answer_id": 79701, "author": "Bart", "author_id": 4343, "author_profile": "https://Stackoverflow.com/users/4343", "pm_score": 3, "selected": false, "text": "#define SCALE(x) (x>>8)\n#define UNSCALE(x) (x<<8)\n\nxPositionUnscaled = UNSCALE(10);\nxPositionScaled = SCALE(xPositionUnscaled);\n xPositionScaled = SCALE(xPositionScaled);\n" }, { "answer_id": 79735, "author": "Antti Kissaniemi", "author_id": 2948, "author_profile": "https://Stackoverflow.com/users/2948", "pm_score": 5, "selected": false, "text": "FixedPoint8 typedef FixedPoint<short, 8> FixedPoint8;" }, { "answer_id": 79763, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "template <int precision = 8> class FixedPoint {\nprivate:\n int val_;\npublic:\n inline FixedPoint(int val) : val_ (val << precision) {};\n inline operator int() { return val_ >> precision; }\n // Other operators...\n};\n" }, { "answer_id": 79942, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 6, "selected": false, "text": "// From: https://github.com/eteran/cpp-utilities/edit/master/Fixed.h\n// See also: http://stackoverflow.com/questions/79677/whats-the-best-way-to-do-fixed-point-math\n/*\n * The MIT License (MIT)\n * \n * Copyright (c) 2015 Evan Teran\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#ifndef FIXED_H_\n#define FIXED_H_\n\n#include <ostream>\n#include <exception>\n#include <cstddef> // for size_t\n#include <cstdint>\n#include <type_traits>\n\n#include <boost/operators.hpp>\n\nnamespace numeric {\n\ntemplate <size_t I, size_t F>\nclass Fixed;\n\nnamespace detail {\n\n// helper templates to make magic with types :)\n// these allow us to determine resonable types from\n// a desired size, they also let us infer the next largest type\n// from a type which is nice for the division op\ntemplate <size_t T>\nstruct type_from_size {\n static const bool is_specialized = false;\n typedef void value_type;\n};\n\n#if defined(__GNUC__) && defined(__x86_64__)\ntemplate <>\nstruct type_from_size<128> {\n static const bool is_specialized = true;\n static const size_t size = 128;\n typedef __int128 value_type;\n typedef unsigned __int128 unsigned_type;\n typedef __int128 signed_type;\n typedef type_from_size<256> next_size;\n};\n#endif\n\ntemplate <>\nstruct type_from_size<64> {\n static const bool is_specialized = true;\n static const size_t size = 64;\n typedef int64_t value_type;\n typedef uint64_t unsigned_type;\n typedef int64_t signed_type;\n typedef type_from_size<128> next_size;\n};\n\ntemplate <>\nstruct type_from_size<32> {\n static const bool is_specialized = true;\n static const size_t size = 32;\n typedef int32_t value_type;\n typedef uint32_t unsigned_type;\n typedef int32_t signed_type;\n typedef type_from_size<64> next_size;\n};\n\ntemplate <>\nstruct type_from_size<16> {\n static const bool is_specialized = true;\n static const size_t size = 16;\n typedef int16_t value_type;\n typedef uint16_t unsigned_type;\n typedef int16_t signed_type;\n typedef type_from_size<32> next_size;\n};\n\ntemplate <>\nstruct type_from_size<8> {\n static const bool is_specialized = true;\n static const size_t size = 8;\n typedef int8_t value_type;\n typedef uint8_t unsigned_type;\n typedef int8_t signed_type;\n typedef type_from_size<16> next_size;\n};\n\n// this is to assist in adding support for non-native base\n// types (for adding big-int support), this should be fine\n// unless your bit-int class doesn't nicely support casting\ntemplate <class B, class N>\nB next_to_base(const N& rhs) {\n return static_cast<B>(rhs);\n}\n\nstruct divide_by_zero : std::exception {\n};\n\ntemplate <size_t I, size_t F>\nFixed<I,F> divide(const Fixed<I,F> &numerator, const Fixed<I,F> &denominator, Fixed<I,F> &remainder, typename std::enable_if<type_from_size<I+F>::next_size::is_specialized>::type* = 0) {\n\n typedef typename Fixed<I,F>::next_type next_type;\n typedef typename Fixed<I,F>::base_type base_type;\n static const size_t fractional_bits = Fixed<I,F>::fractional_bits;\n\n next_type t(numerator.to_raw());\n t <<= fractional_bits;\n\n Fixed<I,F> quotient;\n\n quotient = Fixed<I,F>::from_base(next_to_base<base_type>(t / denominator.to_raw()));\n remainder = Fixed<I,F>::from_base(next_to_base<base_type>(t % denominator.to_raw()));\n\n return quotient;\n}\n\ntemplate <size_t I, size_t F>\nFixed<I,F> divide(Fixed<I,F> numerator, Fixed<I,F> denominator, Fixed<I,F> &remainder, typename std::enable_if<!type_from_size<I+F>::next_size::is_specialized>::type* = 0) {\n\n // NOTE(eteran): division is broken for large types :-(\n // especially when dealing with negative quantities\n\n typedef typename Fixed<I,F>::base_type base_type;\n typedef typename Fixed<I,F>::unsigned_type unsigned_type;\n\n static const int bits = Fixed<I,F>::total_bits;\n\n if(denominator == 0) {\n throw divide_by_zero();\n } else {\n\n int sign = 0;\n\n Fixed<I,F> quotient;\n\n if(numerator < 0) {\n sign ^= 1;\n numerator = -numerator;\n }\n\n if(denominator < 0) {\n sign ^= 1;\n denominator = -denominator;\n }\n\n base_type n = numerator.to_raw();\n base_type d = denominator.to_raw();\n base_type x = 1;\n base_type answer = 0;\n\n // egyptian division algorithm\n while((n >= d) && (((d >> (bits - 1)) & 1) == 0)) {\n x <<= 1;\n d <<= 1;\n }\n\n while(x != 0) {\n if(n >= d) {\n n -= d;\n answer += x;\n }\n\n x >>= 1;\n d >>= 1;\n }\n\n unsigned_type l1 = n;\n unsigned_type l2 = denominator.to_raw();\n\n // calculate the lower bits (needs to be unsigned)\n // unfortunately for many fractions this overflows the type still :-/\n const unsigned_type lo = (static_cast<unsigned_type>(n) << F) / denominator.to_raw();\n\n quotient = Fixed<I,F>::from_base((answer << F) | lo);\n remainder = n;\n\n if(sign) {\n quotient = -quotient;\n }\n\n return quotient;\n }\n}\n\n// this is the usual implementation of multiplication\ntemplate <size_t I, size_t F>\nvoid multiply(const Fixed<I,F> &lhs, const Fixed<I,F> &rhs, Fixed<I,F> &result, typename std::enable_if<type_from_size<I+F>::next_size::is_specialized>::type* = 0) {\n\n typedef typename Fixed<I,F>::next_type next_type;\n typedef typename Fixed<I,F>::base_type base_type;\n\n static const size_t fractional_bits = Fixed<I,F>::fractional_bits;\n\n next_type t(static_cast<next_type>(lhs.to_raw()) * static_cast<next_type>(rhs.to_raw()));\n t >>= fractional_bits;\n result = Fixed<I,F>::from_base(next_to_base<base_type>(t));\n}\n\n// this is the fall back version we use when we don't have a next size\n// it is slightly slower, but is more robust since it doesn't\n// require and upgraded type\ntemplate <size_t I, size_t F>\nvoid multiply(const Fixed<I,F> &lhs, const Fixed<I,F> &rhs, Fixed<I,F> &result, typename std::enable_if<!type_from_size<I+F>::next_size::is_specialized>::type* = 0) {\n\n typedef typename Fixed<I,F>::base_type base_type;\n\n static const size_t fractional_bits = Fixed<I,F>::fractional_bits;\n static const size_t integer_mask = Fixed<I,F>::integer_mask;\n static const size_t fractional_mask = Fixed<I,F>::fractional_mask;\n\n // more costly but doesn't need a larger type\n const base_type a_hi = (lhs.to_raw() & integer_mask) >> fractional_bits;\n const base_type b_hi = (rhs.to_raw() & integer_mask) >> fractional_bits;\n const base_type a_lo = (lhs.to_raw() & fractional_mask);\n const base_type b_lo = (rhs.to_raw() & fractional_mask);\n\n const base_type x1 = a_hi * b_hi;\n const base_type x2 = a_hi * b_lo;\n const base_type x3 = a_lo * b_hi;\n const base_type x4 = a_lo * b_lo;\n\n result = Fixed<I,F>::from_base((x1 << fractional_bits) + (x3 + x2) + (x4 >> fractional_bits));\n\n}\n}\n\n/*\n * inheriting from boost::operators enables us to be a drop in replacement for base types\n * without having to specify all the different versions of operators manually\n */\ntemplate <size_t I, size_t F>\nclass Fixed : boost::operators<Fixed<I,F>> {\n static_assert(detail::type_from_size<I + F>::is_specialized, \"invalid combination of sizes\");\n\npublic:\n static const size_t fractional_bits = F;\n static const size_t integer_bits = I;\n static const size_t total_bits = I + F;\n\n typedef detail::type_from_size<total_bits> base_type_info;\n\n typedef typename base_type_info::value_type base_type;\n typedef typename base_type_info::next_size::value_type next_type;\n typedef typename base_type_info::unsigned_type unsigned_type;\n\npublic:\n static const size_t base_size = base_type_info::size;\n static const base_type fractional_mask = ~((~base_type(0)) << fractional_bits);\n static const base_type integer_mask = ~fractional_mask;\n\npublic:\n static const base_type one = base_type(1) << fractional_bits;\n\npublic: // constructors\n Fixed() : data_(0) {\n }\n\n Fixed(long n) : data_(base_type(n) << fractional_bits) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(unsigned long n) : data_(base_type(n) << fractional_bits) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(int n) : data_(base_type(n) << fractional_bits) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(unsigned int n) : data_(base_type(n) << fractional_bits) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(float n) : data_(static_cast<base_type>(n * one)) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(double n) : data_(static_cast<base_type>(n * one)) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(const Fixed &o) : data_(o.data_) {\n }\n\n Fixed& operator=(const Fixed &o) {\n data_ = o.data_;\n return *this;\n }\n\nprivate:\n // this makes it simpler to create a fixed point object from\n // a native type without scaling\n // use \"Fixed::from_base\" in order to perform this.\n struct NoScale {};\n\n Fixed(base_type n, const NoScale &) : data_(n) {\n }\n\npublic:\n static Fixed from_base(base_type n) {\n return Fixed(n, NoScale());\n }\n\npublic: // comparison operators\n bool operator==(const Fixed &o) const {\n return data_ == o.data_;\n }\n\n bool operator<(const Fixed &o) const {\n return data_ < o.data_;\n }\n\npublic: // unary operators\n bool operator!() const {\n return !data_;\n }\n\n Fixed operator~() const {\n Fixed t(*this);\n t.data_ = ~t.data_;\n return t;\n }\n\n Fixed operator-() const {\n Fixed t(*this);\n t.data_ = -t.data_;\n return t;\n }\n\n Fixed operator+() const {\n return *this;\n }\n\n Fixed& operator++() {\n data_ += one;\n return *this;\n }\n\n Fixed& operator--() {\n data_ -= one;\n return *this;\n }\n\npublic: // basic math operators\n Fixed& operator+=(const Fixed &n) {\n data_ += n.data_;\n return *this;\n }\n\n Fixed& operator-=(const Fixed &n) {\n data_ -= n.data_;\n return *this;\n }\n\n Fixed& operator&=(const Fixed &n) {\n data_ &= n.data_;\n return *this;\n }\n\n Fixed& operator|=(const Fixed &n) {\n data_ |= n.data_;\n return *this;\n }\n\n Fixed& operator^=(const Fixed &n) {\n data_ ^= n.data_;\n return *this;\n }\n\n Fixed& operator*=(const Fixed &n) {\n detail::multiply(*this, n, *this);\n return *this;\n }\n\n Fixed& operator/=(const Fixed &n) {\n Fixed temp;\n *this = detail::divide(*this, n, temp);\n return *this;\n }\n\n Fixed& operator>>=(const Fixed &n) {\n data_ >>= n.to_int();\n return *this;\n }\n\n Fixed& operator<<=(const Fixed &n) {\n data_ <<= n.to_int();\n return *this;\n }\n\npublic: // conversion to basic types\n int to_int() const {\n return (data_ & integer_mask) >> fractional_bits;\n }\n\n unsigned int to_uint() const {\n return (data_ & integer_mask) >> fractional_bits;\n }\n\n float to_float() const {\n return static_cast<float>(data_) / Fixed::one;\n }\n\n double to_double() const {\n return static_cast<double>(data_) / Fixed::one;\n }\n\n base_type to_raw() const {\n return data_;\n }\n\npublic:\n void swap(Fixed &rhs) {\n using std::swap;\n swap(data_, rhs.data_);\n }\n\npublic:\n base_type data_;\n};\n\n// if we have the same fractional portion, but differing integer portions, we trivially upgrade the smaller type\ntemplate <size_t I1, size_t I2, size_t F>\ntypename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator+(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {\n\n typedef typename std::conditional<\n I1 >= I2,\n Fixed<I1,F>,\n Fixed<I2,F>\n >::type T;\n\n const T l = T::from_base(lhs.to_raw());\n const T r = T::from_base(rhs.to_raw());\n return l + r;\n}\n\ntemplate <size_t I1, size_t I2, size_t F>\ntypename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator-(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {\n\n typedef typename std::conditional<\n I1 >= I2,\n Fixed<I1,F>,\n Fixed<I2,F>\n >::type T;\n\n const T l = T::from_base(lhs.to_raw());\n const T r = T::from_base(rhs.to_raw());\n return l - r;\n}\n\ntemplate <size_t I1, size_t I2, size_t F>\ntypename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator*(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {\n\n typedef typename std::conditional<\n I1 >= I2,\n Fixed<I1,F>,\n Fixed<I2,F>\n >::type T;\n\n const T l = T::from_base(lhs.to_raw());\n const T r = T::from_base(rhs.to_raw());\n return l * r;\n}\n\ntemplate <size_t I1, size_t I2, size_t F>\ntypename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator/(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {\n\n typedef typename std::conditional<\n I1 >= I2,\n Fixed<I1,F>,\n Fixed<I2,F>\n >::type T;\n\n const T l = T::from_base(lhs.to_raw());\n const T r = T::from_base(rhs.to_raw());\n return l / r;\n}\n\ntemplate <size_t I, size_t F>\nstd::ostream &operator<<(std::ostream &os, const Fixed<I,F> &f) {\n os << f.to_double();\n return os;\n}\n\ntemplate <size_t I, size_t F>\nconst size_t Fixed<I,F>::fractional_bits;\n\ntemplate <size_t I, size_t F>\nconst size_t Fixed<I,F>::integer_bits;\n\ntemplate <size_t I, size_t F>\nconst size_t Fixed<I,F>::total_bits;\n\n}\n\n#endif\n using namespace numeric;\ntypedef Fixed<16, 16> fixed;\nfixed f;\n" }, { "answer_id": 80281, "author": "ryan_s", "author_id": 13728, "author_profile": "https://Stackoverflow.com/users/13728", "pm_score": 3, "selected": false, "text": " #include \"stdio.h\"\n\n/* Declarations for fixed point stuff */\n\ntypedef int int_fixed;\n\n#define FRACT_BITS 8\n#define FIXED_POINT_ONE (1 << FRACT_BITS)\n#define MAKE_INT_FIXED(x) ((x) << FRACT_BITS)\n#define MAKE_FLOAT_FIXED(x) ((int_fixed)((x) * FIXED_POINT_ONE))\n#define MAKE_FIXED_INT(x) ((x) >> FRACT_BITS)\n#define MAKE_FIXED_FLOAT(x) (((float)(x)) / FIXED_POINT_ONE)\n\n#define FIXED_MULT(x, y) ((x)*(y) >> FRACT_BITS)\n#define FIXED_DIV(x, y) (((x)<<FRACT_BITS) / (y))\n\n/* tests */\nint main()\n{\n int_fixed fixed_x = MAKE_FLOAT_FIXED( 4.5f );\n int_fixed fixed_y = MAKE_INT_FIXED( 2 );\n\n int_fixed fixed_result = FIXED_MULT( fixed_x, fixed_y );\n printf( \"%.1f\\n\", MAKE_FIXED_FLOAT( fixed_result ) );\n\n fixed_result = FIXED_DIV( fixed_result, fixed_y );\n printf( \"%.1f\\n\", MAKE_FIXED_FLOAT( fixed_result ) );\n\n return 0;\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813/" ]
79,688
<p>What's the best way to calculate percentile rankings (e.g. the 90th percentile or the median score) in MSSQL 2005?</p> <p>I'd like to be able to select the 25th, median, and 75th percentiles for a single column of scores (preferably in a single record so I can combine with average, max, and min). So for example, table output of the results might be:</p> <pre><code>Group MinScore MaxScore AvgScore pct25 median pct75 ----- -------- -------- -------- ----- ------ ----- T1 52 96 74 68 76 84 T2 48 98 74 68 75 85 </code></pre>
[ { "answer_id": 79766, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "select @n = count(*) from tbl1\nselect @median = @n / 2\nselect @p75 = @n * 3 / 4\nselect @p90 = @n * 9 / 10\n\nselect top 1 score from (select top @median score from tbl1 order by score asc) order by score desc\n" }, { "answer_id": 79990, "author": "Matt", "author_id": 4154, "author_profile": "https://Stackoverflow.com/users/4154", "pm_score": 4, "selected": false, "text": "SELECT TOP N PERCENT FROM TheTable ORDER BY TheScore DESC\n -- Find the minimum score for all scores in the 90th percentile\nSELECT Min(subq.TheScore) FROM\n(SELECT TOP 10 PERCENT TheScore FROM TheTable\nORDER BY TheScore DESC) AS subq\n" }, { "answer_id": 342502, "author": "Soldarnal", "author_id": 3420, "author_profile": "https://Stackoverflow.com/users/3420", "pm_score": 1, "selected": false, "text": "CREATE PROCEDURE [dbo].[TestGetPercentile]\n\n@percentile as float,\n@resultval as float output\n\nAS\n\nBEGIN\n\nWITH scores(score, prev_rank, curr_rank, next_rank) AS (\n SELECT dblScore,\n (ROW_NUMBER() OVER ( ORDER BY dblScore ) - 1.0) / ((SELECT COUNT(*) FROM TestScores) + 1) [prev_rank],\n (ROW_NUMBER() OVER ( ORDER BY dblScore ) + 0.0) / ((SELECT COUNT(*) FROM TestScores) + 1) [curr_rank],\n (ROW_NUMBER() OVER ( ORDER BY dblScore ) + 1.0) / ((SELECT COUNT(*) FROM TestScores) + 1) [next_rank]\n FROM TestScores\n)\n\nSELECT @resultval = (\n SELECT TOP 1 \n CASE WHEN t1.score = t2.score\n THEN t1.score\n ELSE\n t1.score + (t2.score - t1.score) * ((@percentile - t1.curr_rank) / (t2.curr_rank - t1.curr_rank))\n END\n FROM scores t1, scores t2\n WHERE (t1.curr_rank = @percentile OR (t1.curr_rank < @percentile AND t1.next_rank > @percentile))\n AND (t2.curr_rank = @percentile OR (t2.curr_rank > @percentile AND t2.prev_rank < @percentile))\n)\n\nEND\n DECLARE @pct25 float;\nDECLARE @pct50 float;\nDECLARE @pct75 float;\n\nexec SurveyGetPercentile .25, @pct25 output\nexec SurveyGetPercentile .50, @pct50 output\nexec SurveyGetPercentile .75, @pct75 output\n\nSelect\n min(dblScore) as minScore,\n max(dblScore) as maxScore,\n avg(dblScore) as avgScore,\n @pct25 as percentile25,\n @pct50 as percentile50,\n @pct75 as percentile75\nFrom TestScores\n" }, { "answer_id": 6504968, "author": "Kay Aliu", "author_id": 818956, "author_profile": "https://Stackoverflow.com/users/818956", "pm_score": 1, "selected": false, "text": "DECLARE @Temp TABLE(Id INT IDENTITY(1,1), DATA DECIMAL(10,5))\n\nINSERT INTO @Temp VALUES(0)\nINSERT INTO @Temp VALUES(2)\nINSERT INTO @Temp VALUES(8)\nINSERT INTO @Temp VALUES(4)\nINSERT INTO @Temp VALUES(3)\nINSERT INTO @Temp VALUES(6)\nINSERT INTO @Temp VALUES(6)\nINSERT INTO @Temp VALUES(6) \nINSERT INTO @Temp VALUES(7)\nINSERT INTO @Temp VALUES(0)\nINSERT INTO @Temp VALUES(1)\nINSERT INTO @Temp VALUES(NULL)\n\n\n--50th percentile or median\nSELECT ((\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 50 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA\n ) AS A\n ORDER BY DATA DESC) + \n (\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 50 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA DESC\n ) AS A\n ORDER BY DATA ASC)) / 2.0\n\n\n--90th percentile \nSELECT ((\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 90 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA\n ) AS A\n ORDER BY DATA DESC) + \n (\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 10 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA DESC\n ) AS A\n ORDER BY DATA ASC)) / 2.0\n\n\n--75th percentile\nSELECT ((\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 75 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA\n ) AS A\n ORDER BY DATA DESC) + \n (\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 25 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA DESC\n ) AS A\n ORDER BY DATA ASC)) / 2.0\n" }, { "answer_id": 6512841, "author": "Elizabeth", "author_id": 819953, "author_profile": "https://Stackoverflow.com/users/819953", "pm_score": 3, "selected": false, "text": "SELECT SalesOrderID, \n OrderQty,\n RowNum = Row_Number() OVER(Order By OrderQty),\n Rnk = RANK() OVER(ORDER BY OrderQty),\n DenseRnk = DENSE_RANK() OVER(ORDER BY OrderQty),\n NTile4 = NTILE(4) OVER(ORDER BY OrderQty)\nFROM Sales.SalesOrderDetail \nWHERE SalesOrderID IN (43689, 63181)\n" }, { "answer_id": 12291090, "author": "Paul", "author_id": 1650451, "author_profile": "https://Stackoverflow.com/users/1650451", "pm_score": 2, "selected": false, "text": "SELECT\n Group,\n 75_percentile = MAX(case when NTILE(4) OVER(ORDER BY score ASC) = 3 then score else 0 end),\n 90_percentile = MAX(case when NTILE(10) OVER(ORDER BY score ASC) = 9 then score else 0 end) \nFROM TheScore\nGROUP BY Group\n" }, { "answer_id": 55066450, "author": "Debasmita", "author_id": 7025084, "author_profile": "https://Stackoverflow.com/users/7025084", "pm_score": 0, "selected": false, "text": "(Rank -1) /(total_rows -1) SELECT Name, marks, (rank_1-1)/((select count(*) as total_1 from table)-1)as percentile_rank\nfrom\n(\nSELECT Name,\n Marks,\n RANK() OVER (ORDER BY Marks) AS rank_1\n from table\n) as A\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3420/" ]
79,693
<p>How do you get all the classes in a namespace through reflection in C#?</p>
[ { "answer_id": 79706, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 5, "selected": false, "text": "using System.Reflection;\nusing System.Collections.Generic;\n//...\n\nstatic List<string> GetClasses(string nameSpace)\n{\n Assembly asm = Assembly.GetExecutingAssembly();\n\n List<string> namespacelist = new List<string>();\n List<string> classlist = new List<string>();\n\n foreach (Type type in asm.GetTypes())\n {\n if (type.Namespace == nameSpace)\n namespacelist.Add(type.Name);\n }\n\n foreach (string classname in namespacelist)\n classlist.Add(classname);\n\n return classlist;\n}\n using System.Linq;\nusing System.Reflection;\nusing System.Collections.Generic;\n//...\n\nstatic IEnumerable<string> GetClasses(string nameSpace)\n{\n Assembly asm = Assembly.GetExecutingAssembly();\n return asm.GetTypes()\n .Where(type => type.Namespace == nameSpace)\n .Select(type => type.Name);\n}\n" }, { "answer_id": 79712, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "Assembly.GetTypes() GetTypes()" }, { "answer_id": 79738, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 8, "selected": false, "text": "namespace string nspace = \"...\";\n\nvar q = from t in Assembly.GetExecutingAssembly().GetTypes()\n where t.IsClass && t.Namespace == nspace\n select t;\nq.ToList().ForEach(t => Console.WriteLine(t.Name));\n" }, { "answer_id": 79793, "author": "tsimon", "author_id": 1685, "author_profile": "https://Stackoverflow.com/users/1685", "pm_score": 4, "selected": false, "text": "// Setup event handler to resolve assemblies\nAppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve);\n\nAssembly a = System.Reflection.Assembly.ReflectionOnlyLoadFrom(filename);\na.GetTypes();\n// process types here\n\n// method later in the class:\nstatic Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)\n{\n return System.Reflection.Assembly.ReflectionOnlyLoad(args.Name);\n}\n" }, { "answer_id": 762978, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 2, "selected": false, "text": "//a simple combined code snippet \n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\n\nnamespace MustHaveAttributes\n{\n class Program\n {\n static void Main ( string[] args )\n {\n Console.WriteLine ( \" START \" );\n\n // what is in the assembly\n Assembly a = Assembly.Load ( \"MustHaveAttributes\" );\n Type[] types = a.GetTypes ();\n foreach (Type t in types)\n {\n\n Console.WriteLine ( \"Type is {0}\", t );\n }\n Console.WriteLine (\n \"{0} types found\", types.Length );\n\n #region Linq\n //#region Action\n\n\n //string @namespace = \"MustHaveAttributes\";\n\n //var q = from t in Assembly.GetExecutingAssembly ().GetTypes ()\n // where t.IsClass && t.Namespace == @namespace\n // select t;\n //q.ToList ().ForEach ( t => Console.WriteLine ( t.Name ) );\n\n\n //#endregion Action \n #endregion\n\n Console.ReadLine ();\n Console.WriteLine ( \" HIT A KEY TO EXIT \" );\n Console.WriteLine ( \" END \" );\n }\n } //eof Program\n\n\n class ClassOne\n {\n\n } //eof class \n\n class ClassTwo\n {\n\n } //eof class\n\n\n [System.AttributeUsage ( System.AttributeTargets.Class |\n System.AttributeTargets.Struct, AllowMultiple = true )]\n public class AttributeClass : System.Attribute\n {\n\n public string MustHaveDescription { get; set; }\n public string MusHaveVersion { get; set; }\n\n\n public AttributeClass ( string mustHaveDescription, string mustHaveVersion )\n {\n MustHaveDescription = mustHaveDescription;\n MusHaveVersion = mustHaveVersion;\n }\n\n } //eof class \n\n} //eof namespace \n" }, { "answer_id": 14234375, "author": "JoanComasFdz", "author_id": 383129, "author_profile": "https://Stackoverflow.com/users/383129", "pm_score": 3, "selected": false, "text": "string @namespace = \"...\";\n\nvar types = Assembly.GetExecutingAssembly().GetTypes()\n .Where(t => t.IsClass && t.Namespace == @namespace)\n .ToList();\n\ntypes.ForEach(t => Console.WriteLine(t.Name));\n" }, { "answer_id": 16504427, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 7, "selected": false, "text": "System.Collections.Generic AppDomain.CurrentDomain.GetAssemblies()\n .SelectMany(t => t.GetTypes())\n .Where(t => t.IsClass && t.Namespace == @namespace)\n" }, { "answer_id": 27598813, "author": "Ivo Stoyanov", "author_id": 2298241, "author_profile": "https://Stackoverflow.com/users/2298241", "pm_score": 3, "selected": false, "text": "var allClasses = Assembly.GetExecutingAssembly().GetTypes().Where(a => a.IsClass && a.Namespace != null && a.Namespace.Contains(@\"..your namespace...\")).ToList();\n" }, { "answer_id": 34869091, "author": "JWP", "author_id": 1522548, "author_profile": "https://Stackoverflow.com/users/1522548", "pm_score": 5, "selected": false, "text": "var assemblyName = \"Some.Assembly.Name\"\nvar nameSpace = \"Some.Namespace.Name\";\nvar className = \"ClassNameFilter\";\n\nvar asm = Assembly.Load(assemblyName);\nvar classes = asm.GetTypes().Where(p =>\n p.Namespace == nameSpace &&\n p.Name.Contains(className) \n).ToList();\n" }, { "answer_id": 35707879, "author": "Antonio Lopes", "author_id": 4837664, "author_profile": "https://Stackoverflow.com/users/4837664", "pm_score": 0, "selected": false, "text": "Type[] types = Assembly.Load(new AssemblyName(\"mynamespace.folder\")).GetTypes();\nforeach (var item in types)\n{\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
79,709
<p>I have a function inside a loop inside a function. The inner function acquires and stores a large vector of data in memory (as a global variable... I'm using "R" which is like "S-Plus"). The loop loops through a long list of data to be acquired. The outer function starts the process and passes in the list of datasets to be acquired.</p> <pre><code>for (dataset in list_of_datasets) { for (datachunk in dataset) { &lt;process datachunk&gt; &lt;store result? as vector? where?&gt; } } </code></pre> <p>I programmed the inner function to store each dataset before moving to the next, so all the work of the outer function occurs as side effects on global variables... a big no-no. Is this better or worse than collecting and returning a giant, memory-hogging vector of vectors? Is there a superior third approach?</p> <p>Would the answer change if I were storing the data vectors in a database rather than in memory? Ideally, I'd like to be able to terminate the function (or have it fail due to network timeouts) without losing all the information processed prior to termination.</p>
[ { "answer_id": 79827, "author": "leif", "author_id": 14257, "author_profile": "https://Stackoverflow.com/users/14257", "pm_score": 1, "selected": false, "text": "help(environment)\n\n# You might do something like this:\n\nouter <- function(datasets) {\n # create the return environment\n ret.env <- new.env()\n for(set in dataset) {\n tmp <- inner(set)\n # check for errors however you like here. You might have inner return a list, and\n # have the list contain an error component\n assign(set, tmp, envir=ret.env)\n }\n return(ret.env)\n}\n\n#The inner function might be defined like this\n\ninner <- function(dataset) {\n # I don't know what you are doing here, but lets pretend you are reading a data file\n # that is named by dataset\n filedata <- read.table(dataset, header=T)\n return(filedata)\n}\n" }, { "answer_id": 86804, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "outerfunc <- function(names) {\n templist <- list()\n for (aname in names) {\n templist[[aname]] <- innerfunc(aname)\n }\n templist\n}\n\ninnerfunc <- function(aname) {\n retval <- NULL\n if (\"one\" %in% aname) retval <- c(1)\n if (\"two\" %in% aname) retval <- c(1,2)\n if (\"three\" %in% aname) retval <- c(1,2,3)\n retval\n}\n\nnames <- c(\"one\",\"two\",\"three\")\n\nname_vals <- outerfunc(names)\n\nfor (name in names) assign(name, name_vals[[name]])\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
79,736
<p>This is my first real question of need for any of those Gridview experts out there in the .NET world.</p> <p>I an creating a Gridview from codebehind and I am holding a bunch of numerical data in the columns. Although, I do add the comma in the number fields from codebehind. When I load it to the Gridview, I have the sorting ability turned on, BUT the gridview chooses to ALPHA sort rather than sorting numerically because I add in those commas.</p> <p>So I need help. Anyone willing to give this one a shot? I need to change some of my columns in the gridview to numerical sort rather than the alpha sort it is using.</p>
[ { "answer_id": 97441, "author": "TonyOssa", "author_id": 3276, "author_profile": "https://Stackoverflow.com/users/3276", "pm_score": 0, "selected": false, "text": "[DllImport(\"Shlwapi.dll\", CharSet = CharSet.Unicode)]\nprivate static extern int StrCmpLogicalW(string psz1, string psz2);\n Array.Sort(tringArray, delegate(string left, string right)\n{\n return StrCmpLogicalW(left, right);\n});\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7644/" ]
79,737
<p>This question may be too product specifc but I'd like to know if anyone is exporting bug track data from HP Quality Center.</p> <p>HP Quality Center (QC) has an old school COM API but I'd rather use a web service or maybe even screen scraper to export the data into an excel spreadsheet.</p> <p>In any case, what's the best way to export bug tracking data from hosted HP Quality Center?</p>
[ { "answer_id": 80813, "author": "granth", "author_id": 11210, "author_profile": "https://Stackoverflow.com/users/11210", "pm_score": 4, "selected": true, "text": "TDAPIOLELib.TDConnection connection = new TDAPIOLELib.TDConnection(); \nconnection.InitConnectionEx(\"http://SERVER:8080/qcbin\"); \nconnection.Login(\"USERNAME\", \"PASSWORD\"); \nconnection.Connect(\"QCDOMAIN\", \"QCPROJECT\"); \nTDAPIOLELib.BugFactory bugFactory = connection.BugFactory as TDAPIOLELib.BugFactory; \nTDAPIOLELib.List bugList = bugFactory.NewList(\"\"); \nforeach (TDAPIOLELib.Bug bug in bugList) \n{ \n // View / Modify the properties \n // bug.ID, bug.Name, etc. \n // Save them when done \n // bug.Post(); \n}\n" }, { "answer_id": 217944, "author": "Tobias Kunze", "author_id": 6070, "author_profile": "https://Stackoverflow.com/users/6070", "pm_score": 0, "selected": false, "text": "Export/All Defects" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3048/" ]
79,745
<p>We have an application which needs to use Direct3D. Specifically, it needs at least DirectX 9.0c version 4.09.0000.0904. While this should be present on all newer XP machines it might not be installed on older XP machines. How can I programmatically (using C++) determine if it is installed? I want to be able to give an information message to the user that Direct3D will not be available.</p>
[ { "answer_id": 79817, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "DWORD dwVersion;\nDWORD dwRevision;\nif (DirectXSetupGetVersion(&dwVersion, &dwRevision))\n{\n printf(\"DirectX version is %d.%d.%d.%d\\n\",\n HIWORD(dwVersion), LOWORD(dwVersion),\n HIWORD(dwRevision), LOWORD(dwRevision));\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5022/" ]
79,754
<p>No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on.</p> <pre><code>IDLE 1.2.2 ==== No Subprocess ==== &gt;&gt;&gt; import unittest &gt;&gt;&gt; &gt;&gt;&gt; class Test(unittest.TestCase): def testA(self): a = 1 self.assertEqual(a,1) &gt;&gt;&gt; unittest.main() option -n not recognized Usage: idle.pyw [options] [test] [...] Options: -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output Examples: idle.pyw - run default set of tests idle.pyw MyTestSuite - run suite 'MyTestSuite' idle.pyw MyTestCase.testSomething - run MyTestCase.testSomething idle.pyw MyTestCase - run all 'test*' test methods in MyTestCase Traceback (most recent call last): File "&lt;pyshell#7&gt;", line 1, in &lt;module&gt; unittest.main() File "E:\Python25\lib\unittest.py", line 767, in __init__ self.parseArgs(argv) File "E:\Python25\lib\unittest.py", line 796, in parseArgs self.usageExit(msg) File "E:\Python25\lib\unittest.py", line 773, in usageExit sys.exit(2) SystemExit: 2 &gt;&gt;&gt; </code></pre>
[ { "answer_id": 79826, "author": "Allen", "author_id": 6043, "author_profile": "https://Stackoverflow.com/users/6043", "pm_score": 3, "selected": false, "text": "unittest.main() sys.argv unittest.main()" }, { "answer_id": 79833, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 5, "selected": true, "text": "unittest.main()\n unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(Test))\n" }, { "answer_id": 79932, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "unittest.py unittest.main() sys.exit() TextTestRunner" }, { "answer_id": 407950, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "try:\n sys.exit()\nexcept SystemExit:\n print('Simple as that, but you should really use a TestRunner instead')\n" }, { "answer_id": 3215505, "author": "dmeister", "author_id": 4194, "author_profile": "https://Stackoverflow.com/users/4194", "pm_score": 5, "selected": false, "text": "False sys.exit() unittest.main()" }, { "answer_id": 21262077, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 3, "selected": false, "text": "import unittest2 as unittest unittest unittest.main(exit=False) unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(Test))\n import sys # sys.stderr is used in below default args\n\ntest_loader = unittest.TestLoader()\nloaded_test_suite = test_loader.loadTestsFromTestCase(Test)\n # Default args:\ntext_test_runner = unittest.TextTestRunner(stream=sys.stderr,\n descriptions=True, \n verbosity=1)\ntext_test_runner.run(loaded_test_suite)\n unittest.main(exit=False)\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3176/" ]
79,764
<p>I know there have been a few threads on this before, but I have tried absolutely everything suggested (that I could find) and nothing has worked for me thus far...</p> <p>With that in mind, here is what I'm trying to do:</p> <p>First, I want to allow users to publish pages and give them each a subdomain of their choice (ex: <code>user.example.com</code>). From what I can gather, the best way to do this is to map <code>user.example.com</code> to <code>example.com/user</code> with mod_rewrite and <code>.htaccess</code> - is that correct?</p> <p>If that is correct, can somebody give me explicit instructions on how to do this?</p> <p>Also, I am doing all of my development locally, using MAMP, so if somebody could tell me how to set up my local environment to work in the same manner (I've read this is more difficult), I would greatly appreciate it. Honestly, I have been trying a everything to no avail, and since this is my first time doing something like this, I am completely lost.</p> <p><em>Some of these answers have been REALLY helpful, but for the system I have in mind, manually adding a subdomain for each user is not an option. What I'm really asking is how to do this on the fly, and redirect <code>wildcard.example.com</code> to <code>example.com/wildcard</code> -- the way Tumblr is set up is a perfect example of what I'd like to do.</em></p>
[ { "answer_id": 79811, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 5, "selected": true, "text": "http://myname.example.com http://example.com/something.aspx?name=myname *.example.com *.example.com *.example.com ryan.example.com bill.example.com name1.example.com name2.example.com nameN.example.com" }, { "answer_id": 80122, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 4, "selected": false, "text": "/etc/hosts 127.0.0.1 /etc/hosts 127.0.0.1 localhost vhost1.test.domain vhost2.test.domain\n /etc/hosts user.example.com example.com/user RewriteEngine On\nRewriteCond %{HTTP_HOST} ^subdomain\\.example\\.com\nRewriteRule ^(.*)$ http://example.com/subdomain$1 [R]\n .htaccess example.com/ .htaccess .htaccess .htaccess NameVirtualHost 127.0.0.1:80\n\n# Your \"default\" configuration must go first\n<VirtualHost 127.0.0.1:80>\n ServerName example.com\n ServerAlias www.example.com\n DocumentRoot /www/siteroot\n # etc.\n</VirtualHost>\n\n# First subdomain you want to redirect\n<VirtualHost 127.0.0.1:80>\n ServerName vhost1.example.com\n RewriteEngine On\n RewriteRule ^(.*)$ http://example.com/vhost1$1 [R]\n</VirtualHost>\n\n# Second subdomain you want to redirect\n<VirtualHost 127.0.0.1:80>\n ServerName vhost2.example.com\n RewriteEngine On\n RewriteRule ^(.*)$ http://example.com/vhost2$1 [R]\n</VirtualHost>\n" }, { "answer_id": 3381158, "author": "Arvind Gupta", "author_id": 407820, "author_profile": "https://Stackoverflow.com/users/407820", "pm_score": 1, "selected": false, "text": "* hosts ServerAlias example.com *.example.com <VirtualHost 127.0.0.1:80> \n DocumentRoot /var/www/ \n ServerName example.com \n ServerAlias example.com *.example.com \n</VirtualHost>\n" }, { "answer_id": 13572237, "author": "Beau", "author_id": 325758, "author_profile": "https://Stackoverflow.com/users/325758", "pm_score": 3, "selected": false, "text": "vcap.me resolves to 127.0.0.1\nwww.vcap.me resolves to 127.0.0.1\n 127.0.0.1.xip.io resolves to 127.0.0.1\nwww.127.0.0.1.xip.io resolves to 127.0.0.1\ndb.192.168.0.1.xip.io resolves to 192.168.0.1\n" }, { "answer_id": 40946135, "author": "Fery W", "author_id": 881743, "author_profile": "https://Stackoverflow.com/users/881743", "pm_score": 2, "selected": false, "text": "dnsmasq sudo apt-get install dnsmasq\n localhost.conf /etc/dnsmasq.d #file /etc/dnsmasq.d/localhost.conf\naddress=/localhost/127.0.0.1\n /etc/dhcp/dhclient.conf prepend domain-name-servers 127.0.0.1;\n sudo systemctl restart dnsmasq\nsudo dhclient\n dig whatever.localhost\n 127.0.0.0" }, { "answer_id": 51949318, "author": "Nicolay77", "author_id": 82782, "author_profile": "https://Stackoverflow.com/users/82782", "pm_score": 0, "selected": false, "text": "/etc/NetworkManager/NetworkManager.conf dns=dnsmasq [main] sudo editor /etc/NetworkManager/NetworkManager.conf\n [main]\nplugins=ifupdown,keyfile\ndns=dnsmasq\n...\n sudo rm /etc/resolv.conf\nsudo ln -s /var/run/NetworkManager/resolv.conf /etc/resolv.conf\n echo 'address=/.localhost/127.0.0.1' | sudo tee /etc/NetworkManager/dnsmasq.d/localhost-wildcard.conf\n sudo systemctl reload NetworkManager\n dig localdomain.localhost\n echo 'address=/.local-dev.workdomain.com/127.0.0.1' | sudo tee /etc/NetworkManager/dnsmasq.d/workdomain-wildcard.conf\n dig petproject.local-dev.workdomain.com\n\n;; ANSWER SECTION:\npetproject.local-dev.workdomain.com. 0 IN A 127.0.0.1\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14891/" ]
79,774
<p>Ok - a bit of a mouthful. So the problem I have is this - I need to store a Date for expiry where <em>only</em> the date part is required and I don't want any timezone conversion. So for example if I have an expiry set to "08 March 2008" I want that value to be returned to any client - no matter what their timezone is. The problem with remoting it as a DateTime is that it gets stored/sent as "08 March 2008 00:00", which means for clients connecting from any timezone West of me it gets converted and therefore flipped to "07 March 2008" Any suggestions for cleanly handling this scenario ? Obviously sending it as a string would work. anything else ? thanks, Ian</p>
[ { "answer_id": 79837, "author": "Timothy Carter", "author_id": 4660, "author_profile": "https://Stackoverflow.com/users/4660", "pm_score": 1, "selected": true, "text": "public struct Date\n{\n public int Month; //or string instead of int\n public int Day;\n public int Year;\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14871/" ]
79,780
<p>I've had a new found interest in building a small, efficient web server in C and have had some trouble parsing POST methods from the HTTP Header. Would anyone have any advice as to how to handle retrieving the name/value pairs from the "posted" data?</p> <pre><code>POST /test HTTP/1.1 Host: test-domain.com:7017 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Referer: http://test-domain.com:7017/index.html Cookie: __utma=43166241.217413299.1220726314.1221171690.1221200181.16; __utmz=43166241.1220726314.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none) Cache-Control: max-age=0 Content-Type: application/x-www-form-urlencoded Content-Length: 25 field1=asfd&amp;field2=a3f3f3 // ^-this </code></pre> <p>I see no tangible way to retrieve the bottom line as a whole and ensure that it works every time. I'm not a fan of hard-coding in anything.</p>
[ { "answer_id": 47447856, "author": "Oliver", "author_id": 2984198, "author_profile": "https://Stackoverflow.com/users/2984198", "pm_score": 0, "selected": false, "text": "/r/n Content-Length char* data char *data = \"f1=asfd&f2=a3f3f3\";\nchar f1[100], \nchar f2[100];\nsscanf(data, \"%s&%s\", &f1, &f2); // get the field tuples\n\nchar f1_name[50];\nchar f1_data[50];\nsscanf(f1, \"%s=%s\", f1_name, f1_data); \n\nchar f2_name[50];\nchar f2_data[50];\nsscanf(f2, \"%s=%s\", f2_name, f2_data); \n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14877/" ]
79,789
<p>I have a list of timesheet entries that show a start and stop time. This is sitting in a MySQL database. I need to create bar charts based on this data with the 24 hours of the day along the bottom and the amount of man-hours worked for each hour of the day.</p> <p>For example, if Alice worked a job from 15:30 to 19:30 and Bob worked from 12:15 to 17:00, the chart would look like this:</p> <p><a href="https://i.stack.imgur.com/HHrs0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HHrs0.png" alt="Example Chart"></a></p> <p>I have a WTFey solution right now that involves a spreadsheet going out to column DY or something like that. The needed resolution is 15-minute intervals.</p> <p>I'm assuming this is something best done in the database then exported for chart creation. Let me know if I'm missing any details. Thanks.</p>
[ { "answer_id": 80125, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "create an array named timetable with 24 entries\ninitialise timetable to zero\n\nfor each user in SQLtable\n firsthour = user.firsthour\n lasthour = user.lasthour\n\n firstminutes = 4 - (rounded down integer(user.firstminutes/15))\n lastminutes = rounded down integer(user.lastminutes/15)\n\n timetable(firsthour) = timetable(firsthour) + firstminutes\n timetable(lasthour) = timetable(lasthour) + lastminutes\n\n for index=firsthour+1 to lasthour-1\n timetable(index) = timetable(index) + 4\n next index\n\nnext user\n" }, { "answer_id": 80134, "author": "Mike Farmer", "author_id": 4082, "author_profile": "https://Stackoverflow.com/users/4082", "pm_score": 3, "selected": true, "text": "TIME_DIM\n -id\n -time_of_day\n -interval_15 \n -interval_30\n id time_of_day interval_15 interval_30\n1 00:00 00:00 00:00\n...\n30 00:23 00:15 00:00\n...\n100 05:44 05:30 05:30\n SELECT b.interval_15, count(*) \nFROM my_data_table a\nINNER JOIN time_dim b ON a.time_field = b.time\nWHERE a.date_field = now()\nGROUP BY b.interval_15\n" }, { "answer_id": 80155, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 0, "selected": false, "text": "results = []\nfor time in range(0, 24, .25):\n amount = mysql(\"select count(*) from User_Activity_Table where time >= start_time and time <= end_time\")\n results.append(amount)\n" }, { "answer_id": 81667, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 0, "selected": false, "text": "SELECT HOUR(times.from_time) AS 'TIME', count(*) / 4 AS 'HOURS'\nFROM times\n JOIN activity\n ON times.from_time >= activity.start_time AND \n times.to_time <= activity.end_time\nGROUP BY HOUR(times.from_time)\nORDER BY HOUR(times.from_time)\n TIME HOURS\n12 0.7500\n13 1.0000\n14 1.0000\n15 1.5000\n16 2.0000\n17 1.0000\n18 1.0000\n19 0.7500\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9867/" ]
79,797
<p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p> <p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p> <p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p> <p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/" rel="noreferrer">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
[ { "answer_id": 79808, "author": "Chuck Callebs", "author_id": 14877, "author_profile": "https://Stackoverflow.com/users/14877", "pm_score": 5, "selected": false, "text": "def local_to_utc(t):\n secs = time.mktime(t)\n return time.gmtime(secs)\n\ndef utc_to_local(t):\n secs = calendar.timegm(t)\n return time.localtime(secs)\n datetime.datetime t local_to_utc(t.timetuple())\n" }, { "answer_id": 79877, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 9, "selected": false, "text": "datetime.datetime pytz datetime.astimezone() from datetime import datetime \nimport pytz\n\nlocal = pytz.timezone(\"America/Los_Angeles\")\nnaive = datetime.strptime(\"2001-2-3 10:11:12\", \"%Y-%m-%d %H:%M:%S\")\nlocal_dt = local.localize(naive, is_dst=None)\nutc_dt = local_dt.astimezone(pytz.utc)\n strftime() utc_dt.strftime(\"%Y-%m-%d %H:%M:%S\")\n" }, { "answer_id": 79913, "author": "Tom", "author_id": 3715, "author_profile": "https://Stackoverflow.com/users/3715", "pm_score": 7, "selected": true, "text": "import time\ntime.strftime(\"%Y-%m-%d %H:%M:%S\", \n time.gmtime(time.mktime(time.strptime(\"2008-09-17 14:04:00\", \n \"%Y-%m-%d %H:%M:%S\"))))\n time calendar time.strptime time.mktime time.gmtime calendar.timegm time.localtime" }, { "answer_id": 1464261, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime(seconds))\n None" }, { "answer_id": 2175170, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 8, "selected": false, "text": ".utcnow() .utcfromtimestamp(xxx) >>> from datetime import timezone\n>>> \n>>> # alternative to '.utcnow()'\n>>> dt_now = datetime.datetime.now(datetime.timezone.utc)\n>>>\n>>> # alternative to '.utcfromtimestamp()'\n>>> dt_ts = datetime.fromtimestamp(1571595618.0, tz=timezone.utc)\n >>> import datetime\n>>> utc_datetime = datetime.datetime.utcnow()\n>>> utc_datetime.strftime(\"%Y-%m-%d %H:%M:%S\")\n'2010-02-01 06:59:19'\n pytz >>> # Obtain the UTC Offset for the current system:\n>>> UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now()\n>>> local_datetime = datetime.datetime.strptime(\"2008-09-17 14:04:00\", \"%Y-%m-%d %H:%M:%S\")\n>>> result_utc_datetime = local_datetime + UTC_OFFSET_TIMEDELTA\n>>> result_utc_datetime.strftime(\"%Y-%m-%d %H:%M:%S\")\n'2008-09-17 04:04:00'\n >>> UTC_OFFSET = 10\n>>> result_utc_datetime = local_datetime - datetime.timedelta(hours=UTC_OFFSET)\n>>> result_utc_datetime.strftime(\"%Y-%m-%d %H:%M:%S\")\n'2008-09-17 04:04:00'\n datetime.timezone import datetime\n\ntimezone_aware_dt = datetime.datetime.now(datetime.timezone.utc)\n" }, { "answer_id": 2347991, "author": "user235042", "author_id": 235042, "author_profile": "https://Stackoverflow.com/users/235042", "pm_score": 3, "selected": false, "text": "dt = datetime.strptime(\"2008-09-17 14:04:00\",\"%Y-%m-%d %H:%M:%S\")\nutc_struct_time = time.gmtime(time.mktime(dt.timetuple()))\nutc_dt = datetime.fromtimestamp(time.mktime(utc_struct_time))\nprint dt.strftime(\"%Y-%m-%d %H:%M:%S\")\n" }, { "answer_id": 4113872, "author": "Mohammad Efazati", "author_id": 471397, "author_profile": "https://Stackoverflow.com/users/471397", "pm_score": -1, "selected": false, "text": "time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime(seconds))\n None" }, { "answer_id": 4894920, "author": "Scipythonee", "author_id": 600738, "author_profile": "https://Stackoverflow.com/users/600738", "pm_score": 3, "selected": false, "text": "import time\n\nimport datetime\n\ndef Local2UTC(LocalTime):\n\n EpochSecond = time.mktime(LocalTime.timetuple())\n utcTime = datetime.datetime.utcfromtimestamp(EpochSecond)\n\n return utcTime\n\n>>> LocalTime = datetime.datetime.now()\n\n>>> UTCTime = Local2UTC(LocalTime)\n\n>>> LocalTime.ctime()\n\n'Thu Feb 3 22:33:46 2011'\n\n>>> UTCTime.ctime()\n\n'Fri Feb 4 05:33:46 2011'\n" }, { "answer_id": 8068619, "author": "Dantalion", "author_id": 384779, "author_profile": "https://Stackoverflow.com/users/384779", "pm_score": 2, "selected": false, "text": "def get_utc_from_local(date_time, local_tz=None):\n assert date_time.__class__.__name__ == 'datetime'\n if local_tz is None:\n local_tz = pytz.timezone(settings.TIME_ZONE) # Django eg, \"Europe/London\"\n local_time = local_tz.normalize(local_tz.localize(date_time))\n return local_time.astimezone(pytz.utc)\n\nimport pytz\nfrom datetime import datetime\n\nsummer_11_am = datetime(2011, 7, 1, 11)\nget_utc_from_local(summer_11_am)\n>>>datetime.datetime(2011, 7, 1, 10, 0, tzinfo=<UTC>)\n\nwinter_11_am = datetime(2011, 11, 11, 11)\nget_utc_from_local(winter_11_am)\n>>>datetime.datetime(2011, 11, 11, 11, 0, tzinfo=<UTC>)\n" }, { "answer_id": 8563126, "author": "Yarin", "author_id": 165673, "author_profile": "https://Stackoverflow.com/users/165673", "pm_score": 5, "selected": false, "text": "from datetime import *\nfrom dateutil import *\nfrom dateutil.tz import *\n\n# METHOD 1: Hardcode zones:\nutc_zone = tz.gettz('UTC')\nlocal_zone = tz.gettz('America/Chicago')\n# METHOD 2: Auto-detect zones:\nutc_zone = tz.tzutc()\nlocal_zone = tz.tzlocal()\n\n# Convert time string to datetime\nlocal_time = datetime.strptime(\"2008-09-17 14:02:00\", '%Y-%m-%d %H:%M:%S')\n\n# Tell the datetime object that it's in local time zone since \n# datetime objects are 'naive' by default\nlocal_time = local_time.replace(tzinfo=local_zone)\n# Convert time to UTC\nutc_time = local_time.astimezone(utc_zone)\n# Generate UTC time string\nutc_string = utc_time.strftime('%Y-%m-%d %H:%M:%S')\n" }, { "answer_id": 10040725, "author": "Paulius Sladkevičius", "author_id": 1316954, "author_profile": "https://Stackoverflow.com/users/1316954", "pm_score": 4, "selected": false, "text": "import pytz, datetime\nutc = pytz.utc\nfmt = '%Y-%m-%d %H:%M:%S'\namsterdam = pytz.timezone('Europe/Amsterdam')\n\ndt = datetime.datetime.strptime(\"2012-04-06 10:00:00\", fmt)\nam_dt = amsterdam.localize(dt)\nprint am_dt.astimezone(utc).strftime(fmt)\n'2012-04-06 08:00:00'\n" }, { "answer_id": 12059267, "author": "Cristian Salamea", "author_id": 218604, "author_profile": "https://Stackoverflow.com/users/218604", "pm_score": 2, "selected": false, "text": ">>> from time import strftime, gmtime, localtime\n>>> strftime('%H:%M:%S', gmtime()) #UTC time\n>>> strftime('%H:%M:%S', localtime()) # localtime\n" }, { "answer_id": 12186921, "author": "Shu Wu", "author_id": 1084497, "author_profile": "https://Stackoverflow.com/users/1084497", "pm_score": 4, "selected": false, "text": "from dateutil import tz\n\ndef datetime_to_utc(date):\n \"\"\"Returns date in UTC w/o tzinfo\"\"\"\n return date.astimezone(tz.gettz('UTC')).replace(tzinfo=None) if date.tzinfo else date\n" }, { "answer_id": 13084428, "author": "akaihola", "author_id": 15770, "author_profile": "https://Stackoverflow.com/users/15770", "pm_score": 5, "selected": false, "text": "ts = (d - epoch) / unit calendar.timegm(struct_time) calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple()) calendar.timegm(dt.utctimetuple()) calendar.timegm(dt.utctimetuple()) time.gmtime(t) stz.localize(dt, is_dst=None).utctimetuple() dt.utctimetuple() dt.utctimetuple() datetime.fromtimestamp(t, None) datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None) dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None) dt.astimezone(tz).replace(tzinfo=None) datetime.utcfromtimestamp(t) datetime.datetime(*struct_time[:6]) stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None) dt.astimezone(UTC).replace(tzinfo=None) datetime.fromtimestamp(t, tz) datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz) stz.localize(dt, is_dst=None) dt.replace(tzinfo=UTC)" }, { "answer_id": 42348504, "author": "Yash", "author_id": 2708266, "author_profile": "https://Stackoverflow.com/users/2708266", "pm_score": 2, "selected": false, "text": "arrowObj = arrow.Arrow.strptime('2017-02-20 10:00:00', '%Y-%m-%d %H:%M:%S' , 'US/Eastern')\n\narrowObj.to('UTC') or arrowObj.to('local') \n" }, { "answer_id": 48203190, "author": "spedy", "author_id": 2115494, "author_profile": "https://Stackoverflow.com/users/2115494", "pm_score": -1, "selected": false, "text": "pip install python-dateutil from dateutil.parser import tz\n\nmydt.astimezone(tz.gettz('UTC')).replace(tzinfo=None) \n" }, { "answer_id": 50138694, "author": "uclatommy", "author_id": 4015330, "author_profile": "https://Stackoverflow.com/users/4015330", "pm_score": 3, "selected": false, "text": ">>> utc_delta = datetime.utcnow()-datetime.now()\n>>> utc_time = datetime(2008, 9, 17, 14, 2, 0) + utc_delta\n>>> print(utc_time)\n2008-09-17 19:01:59.999996\n class to_utc():\n utc_delta = datetime.utcnow() - datetime.now()\n\n def __call__(cls, t):\n return t + cls.utc_delta\n >>> utc_converter = to_utc()\n>>> print(utc_converter(datetime(2008, 9, 17, 14, 2, 0)))\n2008-09-17 19:01:59.999996\n" }, { "answer_id": 53760225, "author": "franksands", "author_id": 289368, "author_profile": "https://Stackoverflow.com/users/289368", "pm_score": 1, "selected": false, "text": "import time\nimport calendar\n\nlocal_time = time.strptime(\"2018-12-13T09:32:00.000\", \"%Y-%m-%dT%H:%M:%S.%f\")\nlocal_seconds = time.mktime(local_time)\nutc_time = time.gmtime(local_seconds)\n" }, { "answer_id": 62237615, "author": "tobixen", "author_id": 1452887, "author_profile": "https://Stackoverflow.com/users/1452887", "pm_score": 2, "selected": false, "text": "from datetime import datetime\n## datetime.timezone works in newer versions of python\ntry:\n from datetime import timezone\n utc_tz = timezone.utc\nexcept:\n import pytz\n utc_tz = pytz.utc\n\ndef _to_utc_date_string(ts):\n # type (Union[date,datetime]]) -> str\n \"\"\"coerce datetimes to UTC (assume localtime if nothing is given)\"\"\"\n if (isinstance(ts, datetime)):\n try:\n ## in python 3.6 and higher, ts.astimezone() will assume a\n ## naive timestamp is localtime (and so do we)\n ts = ts.astimezone(utc_tz)\n except:\n ## in python 2.7 and 3.5, ts.astimezone() will fail on\n ## naive timestamps, but we'd like to assume they are\n ## localtime\n import tzlocal\n ts = tzlocal.get_localzone().localize(ts).astimezone(utc_tz)\n return ts.strftime(\"%Y%m%dT%H%M%SZ\")\n" }, { "answer_id": 62816943, "author": "Philipp", "author_id": 2782049, "author_profile": "https://Stackoverflow.com/users/2782049", "pm_score": 1, "selected": false, "text": "my_dt datetime.datetime.utcfromtimestamp(my_dt.timestamp())\n" }, { "answer_id": 62840310, "author": "Alperen", "author_id": 6900838, "author_profile": "https://Stackoverflow.com/users/6900838", "pm_score": 0, "selected": false, "text": "datetime from datetime import datetime\n\ndef to_utc(date):\n return datetime(*date.utctimetuple()[:6])\n datetime >>> date = datetime.strptime(\"11 Feb 2011 17:33:54 -0800\", \"%d %b %Y %H:%M:%S %z\")\n >>> to_utc(date)\ndatetime.datetime(2011, 2, 12, 1, 33, 54)\n >>> date.utctimetuple()\ntime.struct_time(tm_year=2011, tm_mon=2, tm_mday=12, tm_hour=1, tm_min=33, tm_sec=54, tm_wday=5, tm_yday=43, tm_isdst=0)\n>>> date.utctimetuple()[:6]\n(2011, 2, 12, 1, 33, 54)\n>>> datetime(*date.utctimetuple()[:6])\ndatetime.datetime(2011, 2, 12, 1, 33, 54)\n" }, { "answer_id": 64097432, "author": "FObersteiner", "author_id": 10197418, "author_profile": "https://Stackoverflow.com/users/10197418", "pm_score": 4, "selected": false, "text": "datetime.astimezone(tz=None) from datetime import datetime, timezone\ns = \"2008-09-17 14:02:00\"\n\n# to datetime object:\ndt = datetime.fromisoformat(s) # Python 3.7\n\n# I'm on time zone Europe/Berlin; CEST/UTC+2 during summer 2008\ndt = dt.astimezone()\nprint(dt)\n# 2008-09-17 14:02:00+02:00\n\n# ...and to UTC:\ndtutc = dt.astimezone(timezone.utc)\nprint(dtutc)\n# 2008-09-17 12:02:00+00:00\n .astimezone() tzinfo" }, { "answer_id": 64626046, "author": "Zisheng Ye", "author_id": 8102752, "author_profile": "https://Stackoverflow.com/users/8102752", "pm_score": 2, "selected": false, "text": "local_time datetime.datetime local_time.astimezone(datetime.timezone.utc)" }, { "answer_id": 69031527, "author": "Lalit Sharma", "author_id": 7756843, "author_profile": "https://Stackoverflow.com/users/7756843", "pm_score": 1, "selected": false, "text": "2021-09-02T19:02:00Z dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ') astimezone(pytz.utc) dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ') dt = dt.astimezone(pytz.utc) dt.strftime(\"%Y-%m-%d %H:%M:%S\") from datetime import datetime\nimport pytz\n\ndef converLocalToUTC(datetime, getString=True, format=\"%Y-%m-%d %H:%M:%S\"):\n dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ')\n dt = dt.astimezone(pytz.utc)\n \n if getString:\n return dt.strftime(format)\n return dt\n converLocalToUTC(\"2021-09-02T19:02:00Z\")" }, { "answer_id": 69261133, "author": "Bryce", "author_id": 11804374, "author_profile": "https://Stackoverflow.com/users/11804374", "pm_score": 2, "selected": false, "text": "from datetime import datetime\nfrom zoneinfo import ZoneInfo\n\n# Get timezone we're trying to convert from\nlocal_tz = ZoneInfo(\"America/New_York\")\n# UTC timezone\nutc_tz = ZoneInfo(\"UTC\")\n\ndt = datetime.strptime(\"2021-09-20 17:20:00\",\"%Y-%m-%d %H:%M:%S\")\ndt = dt.replace(tzinfo=local_tz)\ndt_utc = dt.astimezone(utc_tz)\n\nprint(dt.strftime(\"%Y-%m-%d %H:%M:%S\"))\nprint(dt_utc.strftime(\"%Y-%m-%d %H:%M:%S\"))\n dt.astimezone()" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3715/" ]
79,816
<p>I'd like a short smallest possible javascript routine that when a mousedown occurs on a button it first responds just like a mouseclick and then if the user keeps the button pressed it responds as if the user was continously sending mouseclicks and after a while with the button held down acts as if the user was accelerating their mouseclicks...basically think of it like a keypress repeat with acceleration in time.<br> i.e. user holds down mouse button (x=call function) - x___x___x___x__x__x_x_x_x_xxxxxxx</p>
[ { "answer_id": 79830, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 2, "selected": false, "text": "window.setTimeout x x window.clearTimeout" }, { "answer_id": 79862, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": -1, "selected": false, "text": "var isClicked = false;\nvar clickCounter = 100;\nfunction fnTrackClick(){\n if(isClicked){\n clickCounter--;\n setTimeout(clickCounter * 100, fnTrackClick);\n }\n}\n\n<input type=\"button\" value=\"blah\" onmousedown=\"isClicked=true;\" onmouseover=\"fnTrackClick();\" onmouseup=\"isClicked = false;\" />\n" }, { "answer_id": 79890, "author": "Glennular", "author_id": 14753, "author_profile": "https://Stackoverflow.com/users/14753", "pm_score": 2, "selected": false, "text": "var tid = 0;\nvar speed = 100;\n\nfunction toggleOn(){\n if(tid==0){\n tid=setInterval('ThingToDo()',speed);\n }\n}\nfunction toggleOff(){\n if(tid!=0){\n clearInterval(tid);\n tid=0;\n }\n}\nfunction ThingToDo{\n\n}\n" }, { "answer_id": 79970, "author": "neouser99", "author_id": 10669, "author_profile": "https://Stackoverflow.com/users/10669", "pm_score": 5, "selected": true, "text": "function holdit(btn, action, start, speedup) {\n var t;\n\n var repeat = function () {\n action();\n t = setTimeout(repeat, start);\n start = start / speedup;\n }\n\n btn.mousedown = function() {\n repeat();\n }\n\n btn.mouseup = function () {\n clearTimeout(t);\n }\n};\n\n/* to use */\nholdit(btn, function () { }, 1000, 2); /* x..1000ms..x..500ms..x..250ms..x */\n" }, { "answer_id": 43407325, "author": "Phuong Vu", "author_id": 1014112, "author_profile": "https://Stackoverflow.com/users/1014112", "pm_score": 0, "selected": false, "text": "$('button').clickAndHold(function (e, n) {\n console.log(\"Call me baby \", n);\n});\n" }, { "answer_id": 58237538, "author": "cskwg", "author_id": 4386189, "author_profile": "https://Stackoverflow.com/users/4386189", "pm_score": 0, "selected": false, "text": " function holdit( btn, method, start, speedup ) {\n var t, keep = start;\n var repeat = function () {\n var args = Array.prototype.slice.call( arguments );\n method.apply( this, args );\n t = setTimeout( repeat, start, args[0], args[1], args[2], args[3], args[4], args[5] );\n if ( start > keep / 20 ) start = start / speedup;\n }\n btn.onmousedown = btn.mousedown = repeat;\n //\n btn.onmouseout = btn.mouseout = btn.onmouseup = btn.mouseup = function () {\n clearTimeout( t );\n start = keep;\n }\n};\n" }, { "answer_id": 70521675, "author": "Daniel Cachro", "author_id": 17790036, "author_profile": "https://Stackoverflow.com/users/17790036", "pm_score": 0, "selected": false, "text": "let holdIt = (btn, action, start, speedup, limit) => {\n let t;\n let startValue = start;\n\n let repeat = () => {\n action();\n t = setTimeout(repeat, startValue);\n (startValue > limit) ? startValue /= speedup: startValue = limit;\n }\n\n btn.onmousedown = () => {\n repeat();\n }\n\n const stopActionEvents = ['mouseup', 'mouseout'];\n\n stopActionEvents.forEach(event => {\n btn.addEventListener(event, () => {\n clearTimeout(t);\n startValue = start;\n })\n });\n\n};\n\nholdIt(actionButton, functionToDo, 500, 2, 5);\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14907/" ]
79,843
<p>The situation is this:</p> <ul> <li>You have a Hibernate context with an object graph that has some lazy loading defined. </li> <li>You want to use the Hibernate objects in your UI as is without having to copy the data somewhere. </li> <li>There are different UI contexts that require different amounts of data. </li> <li>The data is too big to just eager load the whole graph each time.</li> </ul> <p>What is the best means to load all the appropriate objects in the object graph in a configurable way so that they can be accessed without having to go back to the database to load more data?</p> <p>Any help.</p>
[ { "answer_id": 79933, "author": "sirrocco", "author_id": 5246, "author_profile": "https://Stackoverflow.com/users/5246", "pm_score": 3, "selected": true, "text": "new ClientRepo().LoadClientBy(id)\n .WithOrders()\n .WithBonus()\n .OrderByName();\n" }, { "answer_id": 87117, "author": "Roland Schneider", "author_id": 16515, "author_profile": "https://Stackoverflow.com/users/16515", "pm_score": 1, "selected": false, "text": "Hibernate.initialize(Object entity, String propertyName)" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14893/" ]
79,856
<p>In a stored procedure, I need to get the count of the results of another stored procedure. Specifically, I need to know if it returns any results, or an empty set.</p> <p>I could create a temp table/table variable, exec the stored procedure into it, and then run a select count on that data. But I really don't care about the data itself, all I need is the count (or presence/absence of data). I was wondering if there is a more efficient way of getting just that information.</p> <p>I don't want to just copy the contents of the other stored procedure and rewrite it as a select count. The stored procedure changes too frequently for that to be workable.</p>
[ { "answer_id": 80158, "author": "Ricardo C", "author_id": 232589, "author_profile": "https://Stackoverflow.com/users/232589", "pm_score": 0, "selected": false, "text": "DECLARE @res AS TABLE (\n [EmpID] [int] NOT NULL,\n [EmpName] [varchar](30) NULL,\n [MgrID] [int] NULL\n)\n\nINSERT @res \nEXEC dbo.ProcFoo\n\nSELECT COUNT(*) FROM @res\n" }, { "answer_id": 82603, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 0, "selected": false, "text": "CREATE PROCEDURE subProcedure @param1, @param2, @Param3 tinyint OUTPUT\nAS\nBEGIN\n IF EXISTS(SELECT * FROM table1 WHERE we have something to work with)\n BEGIN\n -- The body of your sproc\n SET @Param3 = 1\n END\n ELSE\n SET @Param3 = 0\nEND\n DECLARE @ThereWasData tinyint\nexec subProcedure 'foo', 'bar', @ThereWasData OUTPUT\nIF @ThereWasData = 1 \n PRINT 'subProcedure had data'\nELSE\n PRINT 'subProcedure had NO data'\n" }, { "answer_id": 12804872, "author": "Rikki", "author_id": 1623728, "author_profile": "https://Stackoverflow.com/users/1623728", "pm_score": 0, "selected": false, "text": "Create Procedure [dbo].[GetResult] (\n @RowCount BigInt = -1 Output\n) As Begin\n\n /*\n You can do whatever else you should do here.\n */\n\n Select @RowCount = Count_Big(*)\n From dbo.SomeLargeOrSmallTable\n Where SomeColumn = 'Somefilters'\n ;\n\n /*\n You can do whatever else you should do here.\n */\n\n --Reporting how your procedure has done the statements. It's just a sample to show you how to work with the procedures. There are many ways for doing these things.\n Return @@Error;\n\nEnd;\n Declare @RowCount BigInt\n, @Result Int\n;\n\nExecute @Result = [dbo].[GetResult] @RowCount Out\n\nSelect @RowCount\n, @Result\n;\n" }, { "answer_id": 39282002, "author": "M.Hassan", "author_id": 3142139, "author_profile": "https://Stackoverflow.com/users/3142139", "pm_score": 0, "selected": false, "text": " create proc test\n as\n begin\n select top 10 * from customers\n end\n go\n\n\n create proc test2 (@n int out)\n as\n begin\n exec test\n set @n = @@rowcount\n --print @n\n end\n go\n\n declare @n1 int =0\n\n exec test2 @n1 out\n print @n1\n --output result: 10\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10630/" ]
79,891
<p>While we try to set up as many unit tests as time allows for our applications, I always find the amount of UI-level tests lacking. There are many options out there, but I'm not sure what would be a good place to start. </p> <p>What is your preferred unit testing tool for testing Swing applications? Why do you like it?</p>
[ { "answer_id": 1001008, "author": "Dema", "author_id": 407003, "author_profile": "https://Stackoverflow.com/users/407003", "pm_score": 2, "selected": false, "text": " Scenario: Dialog manipulation\n Given the frame \"SwingSet\" is visible\n And the frame \"SwingSet\" is the container\n When I click the menu \"File/About\"\n Then I should see the dialog \"About Swing!\"\n Given the dialog \"About Swing!\" is the container\n When I click the button \"OK\"\n Then I should not see the dialog \"About Swing!\"\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13812/" ]
79,918
<p>How are folks integrating various static analysis tools such as PMD, Checkstyle, and FindBugs so that they are used together in some uniform way? In particular, I'm interested in generating a single uniform report that includes warnings from all tools. Also, I want to be able to mark-up my code with reasonably consistent looking warning suppressions.</p> <p>My question here is not meant to address tool "overlap" where, say, PMD and Checkstyle are looking for the same things. That is another issue.</p> <p>Please see some of my <a href="https://stackoverflow.com/questions/4080/what-code-analysis-tools-do-you-use-for-your-java-projects#79845"> thoughts on the matter in an answer</a> to <a href="https://stackoverflow.com/questions/4080/what-code-analysis-tools-do-you-use-for-your-java-projects">a related question</a>.</p>
[ { "answer_id": 84051, "author": "Greg Mattes", "author_id": 13940, "author_profile": "https://Stackoverflow.com/users/13940", "pm_score": 0, "selected": false, "text": "/absolute-path/filename:line-number:column-number: warning(tool-name): message /project/src/com/example/Foo.java:425:9: warning(Checkstyle): Missing a Javadoc comment. SuppressWarnings" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13940/" ]
79,923
<ul> <li>What are the stack and heap?</li> <li>Where are they located physically in a computer's memory?</li> <li>To what extent are they controlled by the OS or language run-time?</li> <li>What is their scope?</li> <li>What determines their sizes?</li> <li>What makes one faster?</li> </ul>
[ { "answer_id": 79936, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 11, "selected": false, "text": "delete delete[] free new malloc int foo()\n{\n char *pBuffer; //<--nothing allocated yet (excluding the pointer itself, which is allocated here on the stack).\n bool b = true; // Allocated on the stack.\n if(b)\n {\n //Create 500 bytes on the stack\n char buffer[500];\n\n //Create 500 bytes on the heap\n pBuffer = new char[500];\n\n }//<-- buffer is deallocated here, pBuffer is not\n}//<--- oops there's a memory leak, I should have called delete[] pBuffer;\n" }, { "answer_id": 80094, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 7, "selected": false, "text": "void myfunction()\n{\n char big[10000000];\n // Do something that only uses for first 1K of big 99% of the time.\n}\n" }, { "answer_id": 80740, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 7, "selected": false, "text": "mmap() setrlimit(RLIMIT_STACK, ...) brk() sbrk()" }, { "answer_id": 1213360, "author": "Martin Liversage", "author_id": 98607, "author_profile": "https://Stackoverflow.com/users/98607", "pm_score": 10, "selected": false, "text": "new malloc malloc new" }, { "answer_id": 13308092, "author": "Snowcrash", "author_id": 343204, "author_profile": "https://Stackoverflow.com/users/343204", "pm_score": 9, "selected": false, "text": "public void Method1()\n{\n int i = 4;\n int y = 2;\n class1 cls1 = new class1();\n}\n Local Variables" }, { "answer_id": 13326916, "author": "davec", "author_id": 1763801, "author_profile": "https://Stackoverflow.com/users/1763801", "pm_score": 8, "selected": false, "text": "// Statically allocated in the data segment when the program/DLL is first loaded\n// Deallocated when the program/DLL exits\n// scope - can be accessed from anywhere in the code\nint someGlobalVariable;\n\n// Statically allocated in the data segment when the program is first loaded\n// Deallocated when the program/DLL exits\n// scope - can be accessed from anywhere in this particular code file\nstatic int someStaticVariable;\n\n// \"someArgument\" is allocated on the stack each time MyFunction is called\n// \"someArgument\" is deallocated when MyFunction returns\n// scope - can be accessed only within MyFunction()\nvoid MyFunction(int someArgument) {\n\n // Statically allocated in the data segment when the program is first loaded\n // Deallocated when the program/DLL exits\n // scope - can be accessed only within MyFunction()\n static int someLocalStaticVariable;\n\n // Allocated on the stack each time MyFunction is called\n // Deallocated when MyFunction returns\n // scope - can be accessed only within MyFunction()\n int someLocalVariable;\n\n // A *pointer* is allocated on the stack each time MyFunction is called\n // This pointer is deallocated when MyFunction returns\n // scope - the pointer can be accessed only within MyFunction()\n int* someDynamicVariable;\n\n // This line causes space for an integer to be allocated in the heap\n // when this line is executed. Note this is not at the beginning of\n // the call to MyFunction(), like the automatic variables\n // scope - only code within MyFunction() can access this space\n // *through this particular variable*.\n // However, if you pass the address somewhere else, that code\n // can access it too\n someDynamicVariable = new int;\n\n\n // This line deallocates the space for the integer in the heap.\n // If we did not write it, the memory would be \"leaked\".\n // Note a fundamental difference between the stack and heap\n // the heap must be managed. The stack is managed for us.\n delete someDynamicVariable;\n\n // In other cases, instead of deallocating this heap space you\n // might store the address somewhere more permanent to use later.\n // Some languages even take care of deallocation for you... but\n // always it needs to be taken care of at runtime by some mechanism.\n\n // When the function returns, someArgument, someLocalVariable\n // and the pointer someDynamicVariable are deallocated.\n // The space pointed to by someDynamicVariable was already\n // deallocated prior to returning.\n return;\n}\n\n// Note that someGlobalVariable, someStaticVariable and\n// someLocalStaticVariable continue to exist, and are not\n// deallocated until the program exits.\n int var1; // Has global scope and static allocation\nstatic int var2; // Has file scope and static allocation\n\nint main() {return 0;}\n from datetime import datetime\n\nclass Animal:\n _FavoriteFood = 'Undefined' # _FavoriteFood is statically allocated\n\n def PetAnimal(self):\n curTime = datetime.time(datetime.now()) # curTime is automatically allocatedion\n print(\"Thank you for petting me. But it's \" + str(curTime) + \", you should feed me. My favorite food is \" + self._FavoriteFood)\n\nclass Cat(Animal):\n _FavoriteFood = 'tuna' # Note since we override, Cat class has its own statically allocated _FavoriteFood variable, different from Animal's\n\nclass Dog(Animal):\n _FavoriteFood = 'steak' # Likewise, the Dog class gets its own static variable. Important to note - this one static variable is shared among all instances of Dog, hence it is not dynamic!\n\n\nif __name__ == \"__main__\":\n whiskers = Cat() # Dynamically allocated\n fido = Dog() # Dynamically allocated\n rinTinTin = Dog() # Dynamically allocated\n\n whiskers.PetAnimal()\n fido.PetAnimal()\n rinTinTin.PetAnimal()\n\n Dog._FavoriteFood = 'milkbones'\n whiskers.PetAnimal()\n fido.PetAnimal()\n rinTinTin.PetAnimal()\n\n# Output is:\n# Thank you for petting me. But it's 13:05:02.255000, you should feed me. My favorite food is tuna\n# Thank you for petting me. But it's 13:05:02.255000, you should feed me. My favorite food is steak\n# Thank you for petting me. But it's 13:05:02.255000, you should feed me. My favorite food is steak\n# Thank you for petting me. But it's 13:05:02.255000, you should feed me. My favorite food is tuna\n# Thank you for petting me. But it's 13:05:02.255000, you should feed me. My favorite food is milkbones\n# Thank you for petting me. But it's 13:05:02.256000, you should feed me. My favorite food is milkbones\n" }, { "answer_id": 28801420, "author": "shakurov", "author_id": 2212026, "author_profile": "https://Stackoverflow.com/users/2212026", "pm_score": 5, "selected": false, "text": "async/await async await" }, { "answer_id": 69523039, "author": "anshkun", "author_id": 3484350, "author_profile": "https://Stackoverflow.com/users/3484350", "pm_score": 0, "selected": false, "text": "brk() sbrk() alloca()" }, { "answer_id": 70050292, "author": "A. Hendry", "author_id": 8748308, "author_profile": "https://Stackoverflow.com/users/8748308", "pm_score": 3, "selected": false, "text": "new" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13161/" ]
79,928
<p>I want to run text through a filter to ensure it is all UTF-8 encoded. What is the recommended way to do this with PHP?</p>
[ { "answer_id": 83711, "author": "Tometzky", "author_id": 15862, "author_profile": "https://Stackoverflow.com/users/15862", "pm_score": 0, "selected": false, "text": "preg_match('/^.*$/Du', $value)\n preg_match('/^.*$/sDu', $value)\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/79928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]