qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
349,366
<p>I've notice an issue - it feels like a bug but I suspect a 'feature' - in SSMS in SQL Server 2008.</p> <p>I have various tabs open, for example an alter table script in one table and a SProc that queries that table in another tab, and when I execute my Alter Table script the changes are not reflected in Intellisense in the other tab.</p> <p>I can create new queries and the changes are still not reflected in Intellisense. If I open a new SSMS instance, the changes are reflected, until I make further changes, of course.</p> <p>However, if you over-rule Intellisense and push ahead with your modified tables and code, everything compiles without a grumble (as expected).</p> <p>Is this a bug? A feature? Is there a setting somewhere that alters this behaviour? I checked in the options but couldn't see anything</p>
[ { "answer_id": 1840118, "author": "Gabriel Guimarães", "author_id": 181969, "author_profile": "https://Stackoverflow.com/users/181969", "pm_score": 6, "selected": false, "text": "CTRL SHIFT R" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6898/" ]
349,369
<p>I want to send some strings in a list in a POST call. eg:</p> <pre><code> www.example.com/?post_data = A list of strings </code></pre> <p>The python code receives the data as a single string (Instead of a list of strings). How do I post it as a list of strings?</p>
[ { "answer_id": 349389, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "post_data= \",\".join( list_of_strings )\n" }, { "answer_id": 349776, "author": "Philippe F", "author_id": 13618, "author_profile": "https://Stackoverflow.com/users/13618", "pm_score": 1, "selected": false, "text": ">>> my_string_list= { 's1': 'I', \n... 's2': 'love', \n... 's3': 'python' \n... } \n >>> import urllib\n>>> print urllib.urlopen( 'http://www.google.fr/search', \n urllib.urlencode( my_string_list ) \n ).read()\n s3=python&s2=love&s1=I\n" }, { "answer_id": 351047, "author": "muhuk", "author_id": 42188, "author_profile": "https://Stackoverflow.com/users/42188", "pm_score": 0, "selected": false, "text": "django.utils.datastructures.MultiValueDict >>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']})\n>>> d['name']\n'Simon'\n>>> d.getlist('name')\n['Adrian', 'Simon']\n>>> d.get('lastname', 'nonexistent')\n'nonexistent'\n>>> d.setlist('lastname', ['Holovaty', 'Willison'])\n django.http.QueryDict MultiValueDict from django.http import QueryDict\n\nqs = 'post_data=a&post_data=b&post_data=c'\n\nquery_dict = QueryDict(qs)\n\nassert query_dict['post_data'] == 'c'\nassert query_dict.getlist('post_data') == ['a', 'b', 'c']\nassert query_dict.urlencode() == qs\n" }, { "answer_id": 2071413, "author": "Joelbitar", "author_id": 247004, "author_profile": "https://Stackoverflow.com/users/247004", "pm_score": 2, "selected": false, "text": "import urllib\n string_list = ['A', 'list', 'of', 'strings', 'and', 'öthér', '.&st,u?ff,']\n post_data = '&'.join('post_data[]='+urllib.quote(s) for s in string_list)\n urllib.urlopen('http://example.com/',post_data)\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2220518/" ]
349,375
<p>When it comes to putting the <strong>submit and reset buttons</strong> on your forms, <strong>what order do you use?</strong></p> <pre><code>[SUBMIT] [RESET] </code></pre> <p>or</p> <pre><code>[RESET] [SUBMIT] </code></pre> <p>This issue has come up countless times at work...</p> <p>So, in your opinion, which is the most usable for online users?</p> <p>I personally favor the latter, but some people tend to think otherwise.</p>
[ { "answer_id": 349423, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 0, "selected": false, "text": "confirm" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44084/" ]
349,383
<p>How is it possible to check if MOSS Standard or MOSS Enterprise is installed?</p>
[ { "answer_id": 456821, "author": "dahlbyk", "author_id": 54249, "author_profile": "https://Stackoverflow.com/users/54249", "pm_score": 2, "selected": false, "text": "SPFarm.Local.FeatureDefinitions 99ee0928-7342-4739-865d-35b61ea4eaf0 BDCAdminUILinks\ne4e6a041-bc5b-45cb-beab-885a27079f74 ExcelServer\na573867a-37ca-49dc-86b0-7d033a7ed2c8 PremiumSiteStapling\na10b6aa4-135d-4598-88d1-8d4ff5691d13 ipfsAdminLinks\ncdfa39c6-6413-4508-bccf-bf30368472b3 DataConnectionLibraryStapling\n" }, { "answer_id": 12693374, "author": "Still Learning", "author_id": 1694944, "author_profile": "https://Stackoverflow.com/users/1694944", "pm_score": 0, "selected": false, "text": "protected override void Render(HtmlTextWriter writer)\n {\n base.Render(writer);\n\n\n const string SHAREPOINT2010FOUNDATION = “BEED1F75-C398-4447-AEF1-E66E1F0DF91E”;\n const string SHAREPOINT2010STANDARD = “3FDFBCC8-B3E4-4482-91FA-122C6432805C”;\n const string SHAREPOINT2010ENTERPRISE = “D5595F62-449B-4061-B0B2-0CBAD410BB51″;\n\n SPFarm _spFarm = SPFarm.Local;\n\n\n IEnumerable<Guid> _guid = _spFarm.Products;\n foreach (var item in _guid)\n {\n\n string _skuID = item.ToString();\n writer.Write(“<div>\\n”);\n if (_skuID.Equals(SHAREPOINT2010STANDARD, StringComparison.CurrentCultureIgnoreCase))\n {\n writer.Write(“<span>” + _skuID + ” – You have SharePoint 2010 Standard Edition” + “</span>\\n”);\n }\n if (_skuID.Equals(SHAREPOINT2010ENTERPRISE,StringComparison.CurrentCultureIgnoreCase))\n {\n writer.Write(“<span>” + _skuID + ” – You have SharePoint 2010 Enterprise Edition” + “</span>\\n”);\n }\n if (_skuID.Equals(SHAREPOINT2010FOUNDATION, StringComparison.CurrentCultureIgnoreCase))\n {\n writer.Write(“<span>” + _skuID + ” – You have SharePoint 2010 Foundation” + “</span>\\n”);\n }\n\n writer.Write(“</div>\\n”);\n\n }\n }\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41291/" ]
349,387
<p>I am testing a couple of workflows for their workflow history cleanup time intervals. The workflow History needs to be retained for a specific number of days. I have implemented the solutions recommended <a href="http://mdablog.spaces.live.com/Blog/cns!B0C40902E1212960!796.entry" rel="nofollow noreferrer">here</a> </p> <p>My problem is that, now I need to test my code to see if the workflow history is getting cleaned up after the exact number of days. </p> <p>I came to know that the workflow history is cleanep up by a timer job called "Workflow Auto Cleanup" which runs daily.</p> <p>But in my case, the workflow History cleanup does not seem to run, because, in "Central Administration > Operations > Timer Job Definitions > Edit Timer Job" , the last run time is shown as "N\A"</p> <p>Is there anything I am missing here? What should I do to make this timer job run properly?</p> <p>Update: Checking the SharePoint logs gives this message: "Upgrade job definition already exists, waiting for the existing upgrade to complete"</p>
[ { "answer_id": 456821, "author": "dahlbyk", "author_id": 54249, "author_profile": "https://Stackoverflow.com/users/54249", "pm_score": 2, "selected": false, "text": "SPFarm.Local.FeatureDefinitions 99ee0928-7342-4739-865d-35b61ea4eaf0 BDCAdminUILinks\ne4e6a041-bc5b-45cb-beab-885a27079f74 ExcelServer\na573867a-37ca-49dc-86b0-7d033a7ed2c8 PremiumSiteStapling\na10b6aa4-135d-4598-88d1-8d4ff5691d13 ipfsAdminLinks\ncdfa39c6-6413-4508-bccf-bf30368472b3 DataConnectionLibraryStapling\n" }, { "answer_id": 12693374, "author": "Still Learning", "author_id": 1694944, "author_profile": "https://Stackoverflow.com/users/1694944", "pm_score": 0, "selected": false, "text": "protected override void Render(HtmlTextWriter writer)\n {\n base.Render(writer);\n\n\n const string SHAREPOINT2010FOUNDATION = “BEED1F75-C398-4447-AEF1-E66E1F0DF91E”;\n const string SHAREPOINT2010STANDARD = “3FDFBCC8-B3E4-4482-91FA-122C6432805C”;\n const string SHAREPOINT2010ENTERPRISE = “D5595F62-449B-4061-B0B2-0CBAD410BB51″;\n\n SPFarm _spFarm = SPFarm.Local;\n\n\n IEnumerable<Guid> _guid = _spFarm.Products;\n foreach (var item in _guid)\n {\n\n string _skuID = item.ToString();\n writer.Write(“<div>\\n”);\n if (_skuID.Equals(SHAREPOINT2010STANDARD, StringComparison.CurrentCultureIgnoreCase))\n {\n writer.Write(“<span>” + _skuID + ” – You have SharePoint 2010 Standard Edition” + “</span>\\n”);\n }\n if (_skuID.Equals(SHAREPOINT2010ENTERPRISE,StringComparison.CurrentCultureIgnoreCase))\n {\n writer.Write(“<span>” + _skuID + ” – You have SharePoint 2010 Enterprise Edition” + “</span>\\n”);\n }\n if (_skuID.Equals(SHAREPOINT2010FOUNDATION, StringComparison.CurrentCultureIgnoreCase))\n {\n writer.Write(“<span>” + _skuID + ” – You have SharePoint 2010 Foundation” + “</span>\\n”);\n }\n\n writer.Write(“</div>\\n”);\n\n }\n }\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1909/" ]
349,398
<p>Where can you get information on the ASP.NET State Service e.g. how it works, performance, behaviour characteristics etc. Have looked on internet but cant find in depth information or an article dedicated to the subject. Thanks</p>
[ { "answer_id": 349578, "author": "JSC", "author_id": 37311, "author_profile": "https://Stackoverflow.com/users/37311", "pm_score": 0, "selected": false, "text": "Session[\"Key\"]" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
349,410
<p>I have a registry value which is stored as a binary value (REG_BINARY) holding information about a filepath. The value is read out into an byte array. But how can I transform it into a readable string?</p> <p>I have read about system.text.encoding.ASCII.GetString(value) but this does not work. As far as I got to know the registry value is arbitrary binary data and not ASCII which is the reason for the method to produce useless data.</p> <p>Does anybody know how I can convert the data? </p> <p>Sample: (A piece of the entry)</p> <pre><code>01 00 00 00 94 00 00 00 14 00 00 00 63 00 3A 00 5C 00 70 00 72 00 6F 00 67 00 72 00 61 00 6D 00 6d 00 65 00 5C 00 67 00 65 00 6D 00 65 00 69 00 6E 00 73 00 61 00 6D 00 65 00 20 00 64 00 61 00 74 00 65 00 69 00 65 00 6E 00 5C </code></pre> <p>Due to the regedit this is supposed to be:</p> <pre><code>............c.:.\.p.r.o.g.r.a.m.m.e.\.g.e.m.e.i.n.s.a.m.e. .d.a.t.e.i.e.n.\ </code></pre> <p>The entry itself was created from Outlook. It's an entry for an disabled addin item (resiliency)</p>
[ { "answer_id": 349428, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "Encoding.Unicode.GetString(value) Encoding.Unicode.GetString(bytes, 12, bytes.Length-12)\n" }, { "answer_id": 349486, "author": "abatishchev", "author_id": 41956, "author_profile": "https://Stackoverflow.com/users/41956", "pm_score": 0, "selected": false, "text": "Function Microsoft.Win32.RegistryKey.GetValue(name as String) as Object\n System.Text.Encoding System.Text.Encoding.Unicode" }, { "answer_id": 2558404, "author": "Roberto", "author_id": 306600, "author_profile": "https://Stackoverflow.com/users/306600", "pm_score": 1, "selected": false, "text": "Dim encoding As System.Text.Encoding = System.Text.Encoding.Unicode\n For Each Val As String In ValueName\n data = k.GetValue(Val)\n ListRecent.Items.Add(Val & \": \" & encoding.GetString(data))\n Next\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25428/" ]
349,442
<p>I have a class with two methods defined in it.</p> <pre><code>public class Routines { public static method1() { /* set of statements */ } public static method2() { /* another set of statements.*/ } } </code></pre> <p>Now I need to call method1() from method2()</p> <p>Which one the following approaches is better? Or is this qualify as a question?</p> <pre><code>public static method2() { method1(); } </code></pre> <p>OR</p> <pre><code>public static method2() { Routines.method1(); } </code></pre>
[ { "answer_id": 349484, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "Routines.method1() method1() params void CallMethod()\n{\n Console.WriteLine(\"Calling Method()\");\n Method();\n Console.WriteLine(\"Calling Test.Method()\");\n Test.Method();\n}\n\nvoid Method(params string[] ignored)\n{\n Console.WriteLine (\" Instance method called\");\n}\n\nstatic void Method()\n{\n Console.WriteLine (\" Static method called\");\n}\n params" }, { "answer_id": 349511, "author": "Yuval Adam", "author_id": 24545, "author_profile": "https://Stackoverflow.com/users/24545", "pm_score": 3, "selected": false, "text": "public void method2()\n{\n method1();\n}\n public void method2()\n{\n this.method1();\n}\n" }, { "answer_id": 349641, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 5, "selected": true, "text": "Classname.method() this static" }, { "answer_id": 349664, "author": "Dennis C", "author_id": 40214, "author_profile": "https://Stackoverflow.com/users/40214", "pm_score": 0, "selected": false, "text": "public static method2() {\n Routines.method1();\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40614/" ]
349,446
<p>I am given a problem where I have been given N nodes in a graph that are interconnected to each other then given a matrix which lists down a node being connected to another (1 if it is, 0 if not). I am wondering how to best approach this problem. I think these are adjacency matrix? But how would I implement that ...</p> <p>Basically what I am trying to get out of these is find whether a particular node is connected to all other nodes in a given set 'S'. And whether selected items are clique or not...</p> <p>I'd appreciate any hints.</p>
[ { "answer_id": 349493, "author": "Piotr Lesnicki", "author_id": 38796, "author_profile": "https://Stackoverflow.com/users/38796", "pm_score": 2, "selected": false, "text": "M" }, { "answer_id": 349646, "author": "James", "author_id": 41039, "author_profile": "https://Stackoverflow.com/users/41039", "pm_score": 2, "selected": false, "text": "List<List<Integer>> false public boolean isClique(boolean[][] A, List<Integer> nodes){\n for(int i : nodes){\n for(int j : nodes){\n if(i != j){\n if(!A[i][j]) return false;\n }\n }\n }\n return true;\n}\n" }, { "answer_id": 350569, "author": "Mr.Ree", "author_id": 37946, "author_profile": "https://Stackoverflow.com/users/37946", "pm_score": 0, "selected": false, "text": "E.g: getValue( int i, int j ) { return array [ MIN(i,j) ] [ MAX(i,j) ] }\n" }, { "answer_id": 962330, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public class AdjacencyMatrix {\n\nprivate String [] nodes;\n\nprivate int [][] matrix;\n\npublic AdjacencyMatrix(String [] nodes,int [][] matrix){\n this.nodes = nodes;\n this.matrix = matrix;\n}\n\nboolean isSymmetric(){\n boolean sym = true;\n for(int i=0;i<matrix.length;i++){\n for(int j=i+1; j < matrix[0].length ; j++){\n if (matrix[i][j] != matrix[j][i]){\n sym = false;\n break;\n }\n }\n }\n return sym;\n}\n\npublic Graph createGraph(){\n Graph graph = new Graph();\n Node[] NODES = new Node[nodes.length];\n\n for (int i=0; i<nodes.length; i++){\n NODES[i] = new Node(nodes[i]);\n graph.addNode(NODES[i]);\n }\n\n for(int i=0;i<matrix.length;i++){ \n for(int j=i;j<matrix[0].length;j++){\n int distance = matrix[i][j];\n if (distance != 0){ \n graph.addEdge(new Edge(NODES[i], NODES[j], distance));\n } \n }\n }\n\n return graph;\n}\n\n\npublic long pathLength(int[] path){\n long sum = 0;\n for (int i=0; i<path.length - 1; i++){\n if (matrix[path[i]][path[i+1]] != 0)\n sum += matrix[path[i]][path[i+1]];\n else {\n sum = 0;\n break;\n }\n }\n\n return sum;\n}\n\n\npublic static void main(String[] args){\n String[] nodes = {\"A\", \"B\", \"C\", \"D\", \"E\"};\n int [][] matrix= { {0, 2, 2, 1, 0}, \n {2, 0, 1, 0, 0}, \n {2, 1, 0, 0, 1}, \n {1, 0, 0, 0, 4}, \n {0, 0, 1, 4, 7}};\n AdjacencyMatrix am = new AdjacencyMatrix(nodes, matrix);\n Graph graph = am.createGraph();\n int[] a = {0, 2, 4, 4, 3, 0};\n int[] b = {0, 1, 2, 4, 4, 3, 0};\n graph.writeGraph(); \n am.pathLength(a);\n am.pathLength(b);\n}\n\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44286/" ]
349,459
<p>Say I have a table called "xml" that stores XML files in a single column "data". How would I write a MySQL query that run an XPath and return only rows matching that XPath?</p>
[ { "answer_id": 350180, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": true, "text": "SELECT * FROM xml\nWHERE EXTRACTVALUE(data, '<xpath-expr>') != '';\n EXTRACTVALUE()" }, { "answer_id": 350226, "author": "ripper234", "author_id": 11236, "author_profile": "https://Stackoverflow.com/users/11236", "pm_score": 0, "selected": false, "text": "select * from xml where \n trim(both '\\r\\n' from ExtractValue(xml, '/some/xpath')) = 'value';\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
349,460
<p>I have this code:</p> <pre><code>SELECT idcallhistory3, callid, starttime, answertime, endtime, duration, is_answ, is_fail, is_compl, is_fromoutside, mediatype, from_no, to_no, callerid, dialednumber, lastcallerid, lastdialednumber, group_no, line_no FROM "public".callhistory3 WHERE (starttime &gt;= ?) AND (endtime &lt;= ?) AND (is_fromoutside = ?) AND (from_no = ?) AND (to_no = ?) </code></pre> <p>The problem is I need to pass one value for ? and get all the result without filter, some thing like *</p> <p>Any help?</p>
[ { "answer_id": 349473, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "WHERE (? IS NULL OR starttime >= ?)\n" }, { "answer_id": 349481, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "WHERE \n (@start is null OR starttime >= @start) AND \n (@end is null OR endtime <= @end) AND \n (@fromOutside is null OR is_fromoutside = @fromOutside) AND \n (@fromNo is null OR from_no = @fromNo) AND \n (@toNo is null OR to_no = @toNo)\n" }, { "answer_id": 349530, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "sp_ExecuteSql @cmd EXEC sp_ExecuteSQL @cmd, N'@someArg int', @actualArg\n @someArg @cmd @actualArg" }, { "answer_id": 349747, "author": "Jamal Hansen", "author_id": 2035722, "author_profile": "https://Stackoverflow.com/users/2035722", "pm_score": 2, "selected": false, "text": "SELECT idcallhistory3, callid, starttime, answertime, endtime, duration,\n is_answ, is_fail, is_compl, is_fromoutside, mediatype, from_no,\n to_no, callerid, dialednumber, lastcallerid, lastdialednumber,\n group_no, line_no\nFROM \"public\".callhistory3\nWHERE (starttime >= COALESCE(@starttime, starttime )) \n AND (endtime <= COALESCE(@endtime, endtime)) \n AND (is_fromoutside = COALESCE(@is_fromoutside, is_fromoutside)) \n AND (from_no = COALESCE(@from_no, from_no)) \n AND (COALESCE(to_no, -1) = COALESCE(@to_no, to_no, -1)) -- make nulls match\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
349,513
<p>I'm looking for a way to easily load test and benchmark some of our SQL (using ADO.NET, nothing fancy using LINQ or PLINQ) that has to be performant when running under high parallel load.</p> <p>I've thought of using the new parallel extensions CTP and specifically <code>Parallel.For</code> / <code>Parallel.ForEach</code> to simply run the SQL over 10k iterations or so - but I've not been able to find any data on what these have been optimized for.</p> <p>Essentially I'm worried that because database access is inherently I/O bound, it won't create sufficient load. Does anyone know if Parallel. For is intelligent enough to use > x threads (where x = # of CPUs) if the tasks it is executing are not totally CPU bound? I.e. does it behave in a similar manner to the managed thread pool?</p> <p>Would be rather cool if it was so!</p> <p><b>EDIT: As @CVertex has kindly referred to below, you can set the number of threads independently. Does anyone know if the parallel libraries by default are intelligent enough to keep adding threads if a job is I/O bound?</b></p>
[ { "answer_id": 349617, "author": "Mauricio Scheffer", "author_id": 21239, "author_profile": "https://Stackoverflow.com/users/21239", "pm_score": 0, "selected": false, "text": "PLINQ_DOP\nDOP stands for degree of parallelism. Setting this environment variable defines the number of threads for PLINQ to use. \nE.g. PLINQ_DOP=1 means single-threaded, while PLINQ_DOP=8 means PLINQ should use 8 threads. \nIf this is set to a value greater than the number of procs*cores available on the system, \nPLINQ will use more threads than processors. If one of them blocks, for instance, \nthis allows other threads to make forward progress.\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5777/" ]
349,520
<p>Is there any built-in utility or helper to parse <code>HttpContext.Current.User.Identity.Name</code>, e.g. <code>domain\user</code> to get separately domain name if exists and user?</p> <p>Or is there any other class to do so?</p> <p>I understand that it's very easy to call <code>String.Split("\")</code> but just interesting</p>
[ { "answer_id": 349654, "author": "Ian G", "author_id": 31765, "author_profile": "https://Stackoverflow.com/users/31765", "pm_score": 2, "selected": false, "text": "public static string GetDomain(string s)\n{\n int stop = s.IndexOf(\"\\\\\");\n return (stop > -1) ? s.Substring(0, stop + 1) : null;\n}\n\npublic static string GetLogin(string s)\n{\n int stop = s.IndexOf(\"\\\\\");\n return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : null;\n}\n" }, { "answer_id": 350142, "author": "Aen Sidhe", "author_id": 27337, "author_profile": "https://Stackoverflow.com/users/27337", "pm_score": 7, "selected": true, "text": "NullReferenceExcpetion public static class Extensions\n{\n public static string GetDomain(this IIdentity identity)\n {\n string s = identity.Name;\n int stop = s.IndexOf(\"\\\\\");\n return (stop > -1) ? s.Substring(0, stop) : string.Empty;\n }\n\n public static string GetLogin(this IIdentity identity)\n {\n string s = identity.Name;\n int stop = s.IndexOf(\"\\\\\");\n return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : string.Empty;\n }\n}\n IIdentity id = HttpContext.Current.User.Identity;\nid.GetLogin();\nid.GetDomain();\n" }, { "answer_id": 6285427, "author": "StarCub", "author_id": 109027, "author_profile": "https://Stackoverflow.com/users/109027", "pm_score": 4, "selected": false, "text": "System.Environment.UserDomainName System.Environment.UserName" }, { "answer_id": 15117237, "author": "Gruff Bunny", "author_id": 1141370, "author_profile": "https://Stackoverflow.com/users/1141370", "pm_score": 3, "selected": false, "text": "var components = User.Identity.Name.Split('\\\\');\n\nvar userName = components.Last() \n\nvar domainName = components.Reverse().Skip(1).FirstOrDefault()\n" }, { "answer_id": 17993778, "author": "Adam Cooper", "author_id": 2529475, "author_profile": "https://Stackoverflow.com/users/2529475", "pm_score": 0, "selected": false, "text": "public static class UserExtensions\n{\n public static string GetDomain(this IIdentity identity)\n {\n Regex.Match(identity.Name, \".*\\\\\\\\\").ToString()\n }\n\n public static string GetLogin(this IIdentity identity)\n {\n return Regex.Replace(identity.Name, \".*\\\\\\\\\", \"\");\n }\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41956/" ]
349,524
<p>In my SQL Server backend for my app, I want to create history tables for a bunch of my key tables, which will track a history of changes to the rows.</p> <p>My entire application uses Stored Procedures, there is no embedded SQL. The only connection to the database to modify these tables will be through the application and the SP interface. Traditionally, shops I've worked with have performed this task using triggers.</p> <p>If I have a choice between Stored Procedures and Triggers, which is better? Which is faster?</p>
[ { "answer_id": 363757, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 6, "selected": true, "text": "CREATE TABLE [AuditLog] (\n [AuditLogID] [int] IDENTITY (1, 1) NOT NULL ,\n [ChangeDate] [datetime] NOT NULL CONSTRAINT [DF_AuditLog_ChangeDate] DEFAULT (getdate()),\n [RowGUID] [uniqueidentifier] NOT NULL ,\n [ChangeType] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,\n [TableName] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,\n [FieldName] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,\n [OldValue] [varchar] (8000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,\n [NewValue] [varchar] (8000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,\n [Username] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,\n [Hostname] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,\n [AppName] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,\n [UserGUID] [uniqueidentifier] NULL ,\n [TagGUID] [uniqueidentifier] NULL ,\n [Tag] [varchar] (8000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL \n)\n CREATE TRIGGER LogInsert_Nodes ON dbo.Nodes\nFOR INSERT\nAS\n\n/* Load the saved context info UserGUID */\nDECLARE @SavedUserGUID uniqueidentifier\n\nSELECT @SavedUserGUID = CAST(context_info as uniqueidentifier)\nFROM master.dbo.sysprocesses\nWHERE spid = @@SPID\n\nDECLARE @NullGUID uniqueidentifier\nSELECT @NullGUID = '{00000000-0000-0000-0000-000000000000}'\n\nIF @SavedUserGUID = @NullGUID\nBEGIN\n SET @SavedUserGUID = NULL\nEND\n\n /*We dont' log individual field changes Old/New because the row is new.\n So we only have one record - INSERTED*/\n\n INSERT INTO AuditLog(\n ChangeDate, RowGUID, ChangeType, \n Username, HostName, AppName,\n UserGUID, \n TableName, FieldName, \n TagGUID, Tag, \n OldValue, NewValue)\n\n SELECT\n getdate(), --ChangeDate\n i.NodeGUID, --RowGUID\n 'INSERTED', --ChangeType\n USER_NAME(), HOST_NAME(), APP_NAME(), \n @SavedUserGUID, --UserGUID\n 'Nodes', --TableName\n '', --FieldName\n i.ParentNodeGUID, --TagGUID\n i.Caption, --Tag\n null, --OldValue\n null --NewValue\n FROM Inserted i\n CREATE TRIGGER LogUpdate_Nodes ON dbo.Nodes\nFOR UPDATE AS\n\n/* Load the saved context info UserGUID */\nDECLARE @SavedUserGUID uniqueidentifier\n\nSELECT @SavedUserGUID = CAST(context_info as uniqueidentifier)\nFROM master.dbo.sysprocesses\nWHERE spid = @@SPID\n\nDECLARE @NullGUID uniqueidentifier\nSELECT @NullGUID = '{00000000-0000-0000-0000-000000000000}'\n\nIF @SavedUserGUID = @NullGUID\nBEGIN\n SET @SavedUserGUID = NULL\nEND\n\n /* ParentNodeGUID uniqueidentifier */\n IF UPDATE (ParentNodeGUID)\n BEGIN\n INSERT INTO AuditLog(\n ChangeDate, RowGUID, ChangeType, \n Username, HostName, AppName,\n UserGUID, \n TableName, FieldName, \n TagGUID, Tag, \n OldValue, NewValue)\n SELECT \n getdate(), --ChangeDate\n i.NodeGUID, --RowGUID\n 'UPDATED', --ChangeType\n USER_NAME(), HOST_NAME(), APP_NAME(), \n @SavedUserGUID, --UserGUID\n 'Nodes', --TableName\n 'ParentNodeGUID', --FieldName\n i.ParentNodeGUID, --TagGUID\n i.Caption, --Tag\n d.ParentNodeGUID, --OldValue\n i.ParentNodeGUID --NewValue\n FROM Inserted i\n INNER JOIN Deleted d\n ON i.NodeGUID = d.NodeGUID\n WHERE (d.ParentNodeGUID IS NULL AND i.ParentNodeGUID IS NOT NULL)\n OR (d.ParentNodeGUID IS NOT NULL AND i.ParentNodeGUID IS NULL)\n OR (d.ParentNodeGUID <> i.ParentNodeGUID)\n END\n\n /* Caption varchar(255) */\n IF UPDATE (Caption)\n BEGIN\n INSERT INTO AuditLog(\n ChangeDate, RowGUID, ChangeType, \n Username, HostName, AppName,\n UserGUID, \n TableName, FieldName, \n TagGUID, Tag, \n OldValue, NewValue)\n SELECT \n getdate(), --ChangeDate\n i.NodeGUID, --RowGUID\n 'UPDATED', --ChangeType\n USER_NAME(), HOST_NAME(), APP_NAME(), \n @SavedUserGUID, --UserGUID\n 'Nodes', --TableName\n 'Caption', --FieldName\n i.ParentNodeGUID, --TagGUID\n i.Caption, --Tag\n d.Caption, --OldValue\n i.Caption --NewValue\n FROM Inserted i\n INNER JOIN Deleted d\n ON i.NodeGUID = d.NodeGUID\n WHERE (d.Caption IS NULL AND i.Caption IS NOT NULL)\n OR (d.Caption IS NOT NULL AND i.Caption IS NULL)\n OR (d.Caption <> i.Caption)\n END\n\n...\n\n/* ImageGUID uniqueidentifier */\nIF UPDATE (ImageGUID)\nBEGIN\n INSERT INTO AuditLog(\n ChangeDate, RowGUID, ChangeType, \n Username, HostName, AppName,\n UserGUID, \n TableName, FieldName, \n TagGUID, Tag, \n OldValue, NewValue)\n SELECT \n getdate(), --ChangeDate\n i.NodeGUID, --RowGUID\n 'UPDATED', --ChangeType\n USER_NAME(), HOST_NAME(), APP_NAME(), \n @SavedUserGUID, --UserGUID\n 'Nodes', --TableName\n 'ImageGUID', --FieldName\n i.ParentNodeGUID, --TagGUID\n i.Caption, --Tag\n (SELECT Caption FROM Nodes WHERE NodeGUID = d.ImageGUID), --OldValue\n (SELECT Caption FROM Nodes WHERE NodeGUID = i.ImageGUID) --New Value\n FROM Inserted i\n INNER JOIN Deleted d\n ON i.NodeGUID = d.NodeGUID\n WHERE (d.ImageGUID IS NULL AND i.ImageGUID IS NOT NULL)\n OR (d.ImageGUID IS NOT NULL AND i.ImageGUID IS NULL)\n OR (d.ImageGUID <> i.ImageGUID)\nEND\n CREATE TRIGGER LogDelete_Nodes ON dbo.Nodes\nFOR DELETE\nAS\n\n/* Load the saved context info UserGUID */\nDECLARE @SavedUserGUID uniqueidentifier\n\nSELECT @SavedUserGUID = CAST(context_info as uniqueidentifier)\nFROM master.dbo.sysprocesses\nWHERE spid = @@SPID\n\nDECLARE @NullGUID uniqueidentifier\nSELECT @NullGUID = '{00000000-0000-0000-0000-000000000000}'\n\nIF @SavedUserGUID = @NullGUID\nBEGIN\n SET @SavedUserGUID = NULL\nEND\n\n /*We dont' log individual field changes Old/New because the row is new.\n So we only have one record - DELETED*/\n\n INSERT INTO AuditLog(\n ChangeDate, RowGUID, ChangeType, \n Username, HostName, AppName,\n UserGUID, \n TableName, FieldName, \n TagGUID, Tag, \n OldValue,NewValue)\n\n SELECT\n getdate(), --ChangeDate\n d.NodeGUID, --RowGUID\n 'DELETED', --ChangeType\n USER_NAME(), HOST_NAME(), APP_NAME(), \n @SavedUserGUID, --UserGUID\n 'Nodes', --TableName\n '', --FieldName\n d.ParentNodeGUID, --TagGUID\n d.Caption, --Tag\n null, --OldValue\n null --NewValue\n FROM Deleted d\n CREATE PROCEDURE dbo.SaveContextUserGUID @UserGUID uniqueidentifier AS\n\n/* Saves the given UserGUID as the session's \"Context Information\" */\nIF @UserGUID IS NULL\nBEGIN\n PRINT 'Emptying CONTEXT_INFO because of null @UserGUID'\n DECLARE @BinVar varbinary(128)\n SET @BinVar = CAST( REPLICATE( 0x00, 128 ) AS varbinary(128) )\n SET CONTEXT_INFO @BinVar\n RETURN 0\nEND\n\nDECLARE @UserGUIDBinary binary(16) --a guid is 16 bytes\nSELECT @UserGUIDBinary = CAST(@UserGUID as binary(16))\nSET CONTEXT_INFO @UserGUIDBinary\n\n\n/* To load the guid back \nDECLARE @SavedUserGUID uniqueidentifier\n\nSELECT @SavedUserGUID = CAST(context_info as uniqueidentifier)\nFROM master.dbo.sysprocesses\nWHERE spid = @@SPID\n\nselect @SavedUserGUID AS UserGUID\n*/\n OldValue: Daimler Chrysler\nNewValue: Cerberus Capital Management\n" }, { "answer_id": 18529798, "author": "Jaycob Read", "author_id": 2652480, "author_profile": "https://Stackoverflow.com/users/2652480", "pm_score": 4, "selected": false, "text": "CREATE TABLE [dbo].[AUDIT_LOG_TRANSACTIONS](\n [AUDIT_LOG_TRANSACTION_ID] [int] IDENTITY(1,1) NOT NULL,\n [DATABASE] [nvarchar](128) NOT NULL,\n [TABLE_NAME] [nvarchar](261) NOT NULL,\n [TABLE_SCHEMA] [nvarchar](261) NOT NULL,\n [AUDIT_ACTION_ID] [tinyint] NOT NULL,\n [HOST_NAME] [varchar](128) NOT NULL,\n [APP_NAME] [varchar](128) NOT NULL,\n [MODIFIED_BY] [varchar](128) NOT NULL,\n [MODIFIED_DATE] [datetime] NOT NULL,\n [AFFECTED_ROWS] [int] NOT NULL,\n [SYSOBJ_ID] AS (object_id([TABLE_NAME])),\n PRIMARY KEY CLUSTERED \n (\n [AUDIT_LOG_TRANSACTION_ID] ASC\n )\n)\n CREATE TABLE [dbo].[AUDIT_LOG_DATA](\n [AUDIT_LOG_DATA_ID] [int] IDENTITY(1,1) NOT NULL,\n [AUDIT_LOG_TRANSACTION_ID] [int] NOT NULL,\n [PRIMARY_KEY_DATA] [nvarchar](1500) NOT NULL,\n [COL_NAME] [nvarchar](128) NOT NULL,\n [OLD_VALUE_LONG] [ntext] NULL,\n [NEW_VALUE_LONG] [ntext] NULL,\n [NEW_VALUE_BLOB] [image] NULL,\n [NEW_VALUE] AS (isnull(CONVERT([varchar](8000), [NEW_VALUE_LONG],0),CONVERT([varchar](8000),CONVERT([varbinary](8000),substring([NEW_VALUE_BLOB],(1),(8000)),0),0))),\n [OLD_VALUE] AS (CONVERT([varchar](8000),[OLD_VALUE_LONG],0)),\n [PRIMARY_KEY] AS ([PRIMARY_KEY_DATA]),\n [DATA_TYPE] [char](1) NOT NULL,\n [KEY1] [nvarchar](500) NULL,\n [KEY2] [nvarchar](500) NULL,\n [KEY3] [nvarchar](500) NULL,\n [KEY4] [nvarchar](500) NULL,\nPRIMARY KEY CLUSTERED \n (\n [AUDIT_LOG_DATA_ID] ASC\n)\n)\n CREATE TRIGGER [dbo].[tr_i_AUDIT_Audited_Table]\nON [dbo].[Audited_Table]\nFOR INSERT\nNOT FOR REPLICATION\nAs\nBEGIN\nDECLARE \n @IDENTITY_SAVE varchar(50),\n @AUDIT_LOG_TRANSACTION_ID Int,\n @PRIM_KEY nvarchar(4000),\n @ROWS_COUNT int\n\nSET NOCOUNT ON\nSelect @ROWS_COUNT=count(*) from inserted\nSet @IDENTITY_SAVE = CAST(IsNull(@@IDENTITY,1) AS varchar(50))\n\nINSERT\nINTO dbo.AUDIT_LOG_TRANSACTIONS\n(\n TABLE_NAME,\n TABLE_SCHEMA,\n AUDIT_ACTION_ID,\n HOST_NAME,\n APP_NAME,\n MODIFIED_BY,\n MODIFIED_DATE,\n AFFECTED_ROWS,\n [DATABASE]\n)\nvalues(\n 'Audited_Table',\n 'dbo',\n 2, -- ACTION ID For INSERT\n CASE \n WHEN LEN(HOST_NAME()) < 1 THEN ' '\n ELSE HOST_NAME()\n END,\n CASE \n WHEN LEN(APP_NAME()) < 1 THEN ' '\n ELSE APP_NAME()\n END,\n SUSER_SNAME(),\n GETDATE(),\n @ROWS_COUNT,\n 'Database_Name'\n)\n\nSet @AUDIT_LOG_TRANSACTION_ID = SCOPE_IDENTITY() \n\n--This INSERT INTO code is repeated for each columns that is audited. \n--Below are examples for only two columns\nINSERT INTO dbo.AUDIT_LOG_DATA\n(\n AUDIT_LOG_TRANSACTION_ID,\n PRIMARY_KEY_DATA,\n COL_NAME,\n NEW_VALUE_LONG,\n DATA_TYPE\n , KEY1\n)\nSELECT\n @AUDIT_LOG_TRANSACTION_ID,\n convert(nvarchar(1500), IsNull('[PK_Column]='+CONVERT(nvarchar(4000), NEW.[PK_Column], 0), '[PK_Column] Is Null')),\n 'Column1',\n CONVERT(nvarchar(4000), NEW.[Column1], 0),\n 'A'\n , CONVERT(nvarchar(500), CONVERT(nvarchar(4000), NEW.[PK_Column], 0))\nFROM inserted NEW\nWHERE NEW.[Column1] Is Not Null\n\n --value is inserted for each column that is selected for auditin\nINSERT INTO dbo.AUDIT_LOG_DATA\n(\n AUDIT_LOG_TRANSACTION_ID,\n PRIMARY_KEY_DATA,\n COL_NAME,\n NEW_VALUE_LONG,\n DATA_TYPE\n , KEY1\n)\nSELECT\n @AUDIT_LOG_TRANSACTION_ID,\n convert(nvarchar(1500), IsNull('[PK_Column]='+CONVERT(nvarchar(4000), NEW.[PK_Column], 0), '[PK_Column] Is Null')),\n 'Column2',\n CONVERT(nvarchar(4000), NEW.[Column2], 0),\n 'A'\n , CONVERT(nvarchar(500), CONVERT(nvarchar(4000), NEW.[PK_Column], 0))\n FROM inserted NEW\n WHERE NEW.[Column2] Is Not Null\nEnd\n" }, { "answer_id": 32413487, "author": "newdigate", "author_id": 4634140, "author_profile": "https://Stackoverflow.com/users/4634140", "pm_score": 1, "selected": false, "text": "CREATE TRIGGER [dbo].[tr_Employee_rev]\nON [dbo].[Employee]\nAFTER UPDATE, INSERT, DELETE\nAS\nBEGIN\n IF EXISTS(SELECT * FROM INSERTED) AND EXISTS (SELECT * FROM DELETED)\n BEGIN\n INSERT INTO [EmployeeRev](EmployeeID,Firstname,Initial,Surname,Birthdate,operation, updated, updatedby) SELECT inserted.ID, inserted.Firstname,inserted.Initial,inserted.Surname,inserted.Birthdate,'u', GetDate(), SYSTEM_USER FROM INSERTED\n END \n\n IF EXISTS (SELECT * FROM INSERTED) AND NOT EXISTS(SELECT * FROM DELETED)\n BEGIN\n INSERT INTO [EmployeeRev](EmployeeID,Firstname,Initial,Surname,Birthdate,operation, updated, updatedby) SELECT inserted.ID, inserted.Firstname,inserted.Initial,inserted.Surname,inserted.Birthdate,'i', GetDate(), SYSTEM_USER FROM INSERTED\n END\n\n IF EXISTS(SELECT * FROM DELETED) AND NOT EXISTS(SELECT * FROM INSERTED)\n BEGIN\n INSERT INTO [EmployeeRev](EmployeeID,Firstname,Initial,Surname,Birthdate,operation, updated, updatedby) SELECT deleted.ID, deleted.Firstname,deleted.Initial,deleted.Surname,deleted.Birthdate,'d', GetDate(), SYSTEM_USER FROM DELETED \n END\nEND\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24126/" ]
349,536
<p>I've got a potentially rather large list of objects I'd like to bind to a ListBox in WPF. However, I'd like to have the List load itself incrementally. How can I bind a ListBox to an IEnumerable that loads itself on-demand in such a way that the listbox only tries to enumerate as much as it needs for the display?</p>
[ { "answer_id": 349947, "author": "Cameron MacFarland", "author_id": 3820, "author_profile": "https://Stackoverflow.com/users/3820", "pm_score": 3, "selected": true, "text": "<ListBox \n VirtualizingStackPanel.IsVirtualizing=\"True\"\n ItemSource=\"...\"\n />\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3279/" ]
349,540
<p>Is there a way to sniff SQL queries sent to a SQL Server db on any level (above transport level)? Perhaps there's some kind of a tracer in ASP.NET or built-in log in SQL Server ? </p>
[ { "answer_id": 349585, "author": "Dave Harding", "author_id": 42697, "author_profile": "https://Stackoverflow.com/users/42697", "pm_score": 2, "selected": false, "text": "select db_id()\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
349,544
<p>There is <code>ConnectionManager</code> which waits for incoming connections. For each incoming connection it creates a <code>Connection</code> instance which handles the inbound and outbound traffic on this connection. Each <code>Connection</code> has a <code>Watchdog</code> which handles "bad connection" conditions and calls registered "Listerners". One "Listener" is the <code>ConnectionManager</code> which closes the connection and deletes the <code>Connection</code> instance which in turn deletes the corresponding Watchdog.</p> <p>Wait. A. Minute.</p> <p>The <code>Watchdog</code> calls the <code>ConnectionManager</code> which deletes the <code>Connection</code> which deletes the <code>Watchdog</code>? The Watchdog chases its own tail.</p> <p>I am completly blocked. How do I resolve this?</p> <hr> <p><strong>Solution</strong>: I will make the Listener thingy asynchronous, altough I don't know yet how to do that without too much pain. The <code>Watchdog</code> doesn't know about the <code>ConnectionManager</code>. It is fairly generic. Also the Win32-Thread-API doesn't have something like "join", so I might need to roll my own with <code>GetExitCodeThread()</code> and <code>STILL_ACTIVE</code>...</p> <p>Thanks, guys.</p>
[ { "answer_id": 349567, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 2, "selected": false, "text": "ConnectionManager ConnectionManager Watchdog Queue ConnectionManager\n | | |\nKill Connection---->| |\n | |<-------------------Get Message\n --- | |\n |-------------------->Process Message\n | |\n | Kill Connection\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8976/" ]
349,559
<p>I have a database with two main tables <code>notes</code> and <code>labels</code>. They have a many-to-many relationship (similar to how stackoverflow.com has questions with labels). What I am wondering is how can I search for a note using multiple labels using SQL? </p> <p>For example if I have a note "test" with three labels "one", "two", and "three" and I have a second note "test2" with labels "one" and "two" what is the SQL query that will find all the notes that are associated with labels "one" and "two"?</p>
[ { "answer_id": 349570, "author": "Kev", "author_id": 16777, "author_profile": "https://Stackoverflow.com/users/16777", "pm_score": 1, "selected": false, "text": "select * from notes a\ninner join notes_labels mm on (mm.note = a.id and mm.labeltext in ('one', 'two') )\n select * from notes a\nwhere exists (select 1 from notes_labels b where b.note = a.id and b.labeltext = 'one')\n and exists (select 1 from notes_labels c where c.note = a.id and c.labeltext = 'two')\n" }, { "answer_id": 349573, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 0, "selected": false, "text": "SELECT *\nFROM Notes n INNER JOIN NoteLabels nl\nON n.noteId = nl.noteId\nWHERE nl.labelId in (1, 2)\n" }, { "answer_id": 349579, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 0, "selected": false, "text": "notes labels inner join labels notes select * from ((labels l inner join labels_notes ln on l.labelid = ln.labelid) \ninner join notes n on ln.notesid = n.noteid) where" }, { "answer_id": 349582, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 0, "selected": false, "text": "SELECT DISTINCT n.id from notes as n, notes_labels as nl WHERE n.id = nl.noteid AND nl.text in (label1, label2);\n" }, { "answer_id": 349589, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 4, "selected": true, "text": "select * from notes\nwhere note_id in\n( select note_id from labels where label = 'One'\n intersect\n select note_id from labels where label = 'Two'\n)\n" }, { "answer_id": 349609, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 0, "selected": false, "text": "where exists where exists create table notes (\n NoteID int not null primary key\n ,NoteText varchar (max)\n)\ngo\n\ncreate table tags (\n TagID int not null primary key\n ,TagText varchar (100)\n)\ngo\n\ncreate table note_tag (\n NoteID int not null\n ,TagID int not null\n)\ngo\n\nalter table note_tag\n add constraint PK_NoteTag\n primary key clustered (TagID, NoteID)\ngo\n\ninsert notes values (1, 'Note A')\ninsert notes values (2, 'Note B')\ninsert notes values (3, 'Note C')\n\ninsert tags values (1, 'Tag1')\ninsert tags values (2, 'Tag2')\ninsert tags values (3, 'Tag3')\n\ninsert note_tag values (1, 1) -- Note A, Tag1\ninsert note_tag values (1, 2) -- Note A, Tag2\ninsert note_tag values (2, 2) -- Note B, Tag2\ninsert note_tag values (3, 1) -- Note C, Tag1\ninsert note_tag values (3, 3) -- Note C, Tag3\ngo\n\nselect n.NoteID\n ,n.NoteText\n from notes n\n where exists\n (select 1\n from note_tag nt\n join tags t\n on t.TagID = nt.TagID\n where n.NoteID = nt.NoteID\n and t.TagText in ('Tag1', 'Tag3'))\n\n\nNoteID NoteText\n----------- ----------------\n1 Note A\n3 Note C\n" }, { "answer_id": 349661, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 1, "selected": false, "text": "SELECT DISTINCT n.id, n.text\nFROM notes n\nINNER JOIN notes_labels nl ON n.id = nl.note_id\nINNER JOIN labels l ON nl.label_id = l.id\nWHERE l.label IN (?, ?)\n SELECT n.id, n.text\nFROM notes n\nINNER JOIN notes_labels nl ON n.id = nl.note_id\nINNER JOIN labels l ON nl.label_id = l.id\nWHERE l.label IN (?, ?)\nGROUP BY n.id, n.text\nHAVING COUNT(*) = 2;\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5004/" ]
349,576
<p>On Linux, how can I (programmatically) retrieve the following counters <em>on a per-interface basis</em>:</p> <ul> <li>Sent/received ethernet frames,</li> <li>Sent/received IPv4 packets,</li> <li>Sent/received IPv6 packets.</li> </ul>
[ { "answer_id": 349623, "author": "xahtep", "author_id": 42184, "author_profile": "https://Stackoverflow.com/users/42184", "pm_score": 4, "selected": true, "text": "iptables # input and output must be accounted for separately\n# ipv4, eth0\niptables -I INPUT -i eth0\niptables -I OUTPUT -o eth0\n# ipv6, eth0\nip6tables -I INPUT -i eth0\nip6tables -I OUTPUT -o eth0\n iptables -L -vxn\nip6tables -L -vxn\n -Z" }, { "answer_id": 349629, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 2, "selected": false, "text": "netstat /proc/net/raw /proc/net/tcp /proc/net/udp /sys" }, { "answer_id": 349638, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 2, "selected": false, "text": "netstat -i strace netstat -i" }, { "answer_id": 349645, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 2, "selected": false, "text": "ifconfig" }, { "answer_id": 352652, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 5, "selected": false, "text": "/sys/class/net/eth0/statistics /sys" }, { "answer_id": 511333, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "cat /proc/net/dev\n" }, { "answer_id": 23535501, "author": "Priyanka", "author_id": 3615333, "author_profile": "https://Stackoverflow.com/users/3615333", "pm_score": 1, "selected": false, "text": "netstat --statistics\n\nnstat -z\n\ncat /proc/net/dev_snmp6/eth0 gives ipv6 stats per interface\n" }, { "answer_id": 28697937, "author": "brotherrabbit", "author_id": 1217909, "author_profile": "https://Stackoverflow.com/users/1217909", "pm_score": 1, "selected": false, "text": "ethtool -S eth1" }, { "answer_id": 30335521, "author": "TumeloLilele", "author_id": 4917878, "author_profile": "https://Stackoverflow.com/users/4917878", "pm_score": -1, "selected": false, "text": "using System.Net.NetworkInformation;\n\nforeach (NetworkInterface ni in interfaces)\n{\n // perform your calculations\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21435/" ]
349,597
<p>Is anyone aware of a good resource <strong><em>online</em></strong> for detailed information on the use of ole excel objects(embeded workbooks, worksheets, etc...) in VB6? I'm maintaining an application that makes heavy use of these conrols and I'm having a lot of trouble getting them to work properly for the user's of this program. The scattered bits of Q&amp;A I can find online related to ole excel controls is very limited and not very definitive. Obviously, I have read through what there is on MSDN but I'm not finding it very helpful so I would like to find another good source of reference.</p> <p>Thanks</p>
[ { "answer_id": 381896, "author": "JeffK", "author_id": 5420, "author_profile": "https://Stackoverflow.com/users/5420", "pm_score": 3, "selected": true, "text": "' Start a new workbook in Excel '\n\nDim oExcel As Excel.Application\nDim oBook As Excel.Workbook\n\n' Launch an instance of Microsoft Excel '\nSet oExcel = new Excel.Application\nSet oBook = oExcel.Workbooks.Add\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10007/" ]
349,603
<p>I wanted to start with the use of Remoting under C# in a testdriven way, but I got stuck.</p> <p>One thing I found on the topic is this <a href="http://www.codeproject.com/KB/architecture/TddRemoting.aspx" rel="nofollow noreferrer">article by Marc Clifton</a>, but he seems to have the server running by starting it manually from the console.</p> <p>I try to have the server started (i.e. register the serving class) in the test fixture. I probably also have the usage of the interface wrong, but that will come later.</p> <p>I always get an Exception (sorry for the german message) that the channel is registered already. System.Runtime.Remoting.RemotingException : Der Channel tcp wurde bereits registriert.</p> <p>After commenting out the ChannelServices.RegisterChannell() line in the test method, it occurs for the call Activator.GetObject().</p> <p>I tried to put the StartServer() into a thread, but that did not help either. I found that creating a new AppDomain might be a possible way, but have not tried yet.</p> <p>Can you tell me, if my approach is inherently wrong? How can I fix it?</p> <pre><code>using System; using NUnit.Framework; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; namespace Bla.Tests.Remote { [TestFixture] public class VerySimpleProxyTest { int port = 8082; string proxyUri = "MyRemoteProxy"; string host = "localhost"; IChannel channel; [SetUp] public void SetUp() { StartServer(); } [TearDown] public void TearDown() { StopServer(); } [Test] public void UseRemoteService() { //IChannel clientChannel = new TcpClientChannel(); //ChannelServices.RegisterChannel(clientChannel, false); string uri = String.Format("tcp://{0}:{1}/{2}", host, port, proxyUri); IMyTestService remoteService = (IMyTestService)Activator.GetObject(typeof(IMyTestService), uri); Assert.IsTrue(remoteService.Ping()); //ChannelServices.UnregisterChannel(clientChannel); } private void StartServer() { channel = new TcpServerChannel(port); ChannelServices.RegisterChannel(channel, false); RemotingConfiguration.RegisterWellKnownServiceType(typeof(MyTestService), proxyUri, WellKnownObjectMode.Singleton); } private void StopServer() { ChannelServices.UnregisterChannel(channel); } } public interface IMyTestService { bool Ping(); } public class MyTestService : MarshalByRefObject, IMyTestService { public bool Ping() { return true; } } } </code></pre>
[ { "answer_id": 656400, "author": "Bas Bossink", "author_id": 74198, "author_profile": "https://Stackoverflow.com/users/74198", "pm_score": 1, "selected": false, "text": "ChannelServices.RegisterChannel" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32679/" ]
349,612
<pre><code>$(document).ready(function() { $("span.link").mouseover(function(e){ $(this.children).css("display","inline"); }); }); </code></pre> <p>I'm not a javascript expert, but I've cobbled together a few functions using jQuery. </p> <p>In this case, the stylesheet hides some controls. When the user mouses over, this function exposes those controls. </p> <p>This works on every browser but Firefox (on the Mac and Windows). Am I missing something obvious? </p> <p>Thanks for your help,</p> <p>Jason</p>
[ { "answer_id": 349627, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 4, "selected": true, "text": "$(function() {\n $(\"span.link\").mouseover(function(e){\n $(this).children().css(\"display\",\"inline\"); \n });\n});\n" }, { "answer_id": 394913, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 0, "selected": false, "text": "$(function() {\n $(\"span.link\").mouseover(function(e){\n $(this).children().addClass('inlineClass'); \n });\n});\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10461/" ]
349,613
<p>Hopefully an easy question, but I'd quite like a technical answer to this!</p> <p>What's the difference between:</p> <pre><code>i = 4 </code></pre> <p>and</p> <pre><code>Set i = 4 </code></pre> <p>in VBA? I know that the latter will throw an error, but I don't fully understand why.</p>
[ { "answer_id": 349624, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 6, "selected": false, "text": "Set Let Set object = New SomeObject\nSet object = FunctionReturningAnObjectRef(SomeArgument)\n\nLet i = 0\nLet i = FunctionReturningAValue(SomeArgument)\n\n' or, more commonly '\n\ni = 0\ni = FunctionReturningAValue(SomeArgument)\n" }, { "answer_id": 349636, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 8, "selected": true, "text": "set int i;\nint* ref_i;\n\ni = 4; // Assigning a value (in VBA: i = 4)\nref_i = &i; //assigning a reference (in VBA: set ref_i = i)\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4019/" ]
349,614
<p>i have the following javascript code:</p> <p><a href="http://www.nomorepasting.com/getpaste.php?pasteid=22561" rel="nofollow noreferrer">http://www.nomorepasting.com/getpaste.php?pasteid=22561</a></p> <p>Which works fine(the makewindows function has been changed to show it is a php variable), however the html contains unicode characters, and will only be assigned characters leading up to the first unicode character. If I make a small test file and echo out article_desc directly, all the html is output, although quetsions marks are displayed instead of the correct symbols. However json_encode seems to cut short the html, resulting in errors. </p> <p>edit: here is a dump straight from the mysql database of the html I am trying to display: </p> <p><a href="http://www.yousendit.com/download/TTZueEVYQzMrV3hMWEE9PQ" rel="nofollow noreferrer">http://www.yousendit.com/download/TTZueEVYQzMrV3hMWEE9PQ</a> </p> <p>it says utf-8 in the source. the actual page code generated from echoing out article_desc is here: </p> <p><a href="http://www.nomorepasting.com/getpaste.php?pasteid=22566" rel="nofollow noreferrer">http://www.nomorepasting.com/getpaste.php?pasteid=22566</a> </p> <p>it is definitely the same record, so I am unsure why it seems to very different.</p> <p>edit: this was fixed by calling: mysql_query('SET NAMES utf8'); </p>
[ { "answer_id": 350797, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 2, "selected": false, "text": "json_encode" }, { "answer_id": 459118, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "json_encode( utf8_encode( $Content ) );\n" }, { "answer_id": 4873500, "author": "SandRock", "author_id": 282105, "author_profile": "https://Stackoverflow.com/users/282105", "pm_score": 2, "selected": false, "text": "$conf->db->params['charset'] = 'UTF8';\n $pdoParams = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8;');\n$conf->db->params['driver_options'] = $pdoParams;\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1246613/" ]
349,626
<p>I want to get virtual path of a web page from a web service. Is there any way to do this?. suppose i have an aspx page like aa, i want to get full path as a url for that page from my web service.</p> <p>Regards, Harsh Suman</p>
[ { "answer_id": 349662, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "HttpContext.Current .Request HttpContext.Current" }, { "answer_id": 349871, "author": "Ron Todosichuk", "author_id": 43294, "author_profile": "https://Stackoverflow.com/users/43294", "pm_score": 0, "selected": false, "text": "string path = HttpContext.Current.Request.ApplicationPath;\n string path = HttpContext.Current.Request.Url.OriginalString;\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
349,652
<p>I'm getting a strange effect in Jena 2.5.5 (on Linux) where I am playing around with the inference API. The following code is a stripped down version. I am creating an initially empty Model and a generic rule reasoner. I add a reflexivity rule for a certain statement. I attach the reasoner to the model to get an InfModel. Then I create the matching statement and add it to the Model. </p> <p>Result: InfModel contains both the statement and its reverse. So far so good, that's what it's supposed to do.</p> <p>Now, when I <code>System.out.println()</code> the InfModel prior to adding the matching statement to Model, the result is completely different: the rule seems not to fire and thus, InfModel will end up not containing the reverse of the original statement.</p> <p>How does writing the model to the console change the functionality of the code? Is this behavior documented?</p> <pre><code>import java.util.*; import com.hp.hpl.jena.rdf.model.*; import com.hp.hpl.jena.reasoner.rulesys.*; /** * Describe class &lt;code&gt;RuleTest&lt;/code&gt; here. */ public class RuleTest { public static void main(String[] args) throws Exception { /* create model */ Model model = ModelFactory.createDefaultModel(); /* output model */ System.out.println("original model : " + model); System.out.println("-----"); /* collect rules */ List&lt;Rule&gt; rules = new ArrayList&lt;Rule&gt;(); Rule rule = Rule.parseRule("[ (subject predicate object) -&gt; (object predicate subject) ]."); rules.add(rule); /* create rule reasoner */ GenericRuleReasoner reasoner = new GenericRuleReasoner(rules); /* attach reasoner to model */ InfModel infModel = ModelFactory.createInfModel(reasoner, model); /* output model */ //-----------------------------------------------// // commenting the following line in/out changes // // the output of (*) below in Jena 2.5.5 ?!?!?! // //-----------------------------------------------// //System.out.println("inference model: " + infModel); System.out.println("====="); /* add facts to original model */ Resource s = model.createResource("subject"); Property p = model.createProperty("predicate"); RDFNode o = model.createResource("object"); Statement stmt = model.createStatement(s, p, o); model.add(stmt); /* output models */ System.out.println("original model : " + model); System.out.println("-----"); System.out.println("inference model: " + infModel); // (*) } } </code></pre>
[ { "answer_id": 18987508, "author": "Joshua Taylor", "author_id": 1281433, "author_profile": "https://Stackoverflow.com/users/1281433", "pm_score": 0, "selected": false, "text": "original model : <ModelCom {} | >\n-----\n=====\noriginal model : <ModelCom {subject @predicate object} | [subject, predicate, object]>\n-----\ninference model: <ModelCom {object @predicate subject; subject @predicate object} | [object, predicate, subject] [subject, predicate, object]>\n original model : <ModelCom {} | >\n-----\ninference model: <ModelCom {} | >\n=====\noriginal model : <ModelCom {subject @predicate object} | [subject, predicate, object]>\n-----\ninference model: <ModelCom {subject @predicate object} | [subject, predicate, object]>\n model infModel model infModel.rebind(); model model.add(stmt);\ninfModel.rebind();\n original model : <ModelCom {} | >\n-----\n=====\noriginal model : <ModelCom {subject @predicate object} | [subject, predicate, object]>\n-----\ninference model: <ModelCom {object @predicate subject; subject @predicate object} | [object, predicate, subject] [subject, predicate, object]>\n original model : <ModelCom {} | >\n-----\ninference model: <ModelCom {} | >\n=====\noriginal model : <ModelCom {subject @predicate object} | [subject, predicate, object]>\n-----\ninference model: <ModelCom {object @predicate subject; subject @predicate object} | [object, predicate, subject] [subject, predicate, object]>\n infModel model model infModel infModel model model model infModel model rebind() model" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
349,653
<p>The following doesn't work, because it doesn't wait until the process is finished:</p> <pre><code>import subprocess p = subprocess.Popen('start /WAIT /B MOZILL~1.LNK', shell=True) p.wait() </code></pre> <p>Any idea how to run a shortcut and wait that the subprocess returns ?</p> <p><strong>Edit:</strong> originally I was trying this without the <strong>shell</strong> option in my post, which caused Popen to fail. In effect, <code>start</code> is not an executable but a shell command. This was fixed thanks to Jim.</p>
[ { "answer_id": 349697, "author": "JimB", "author_id": 32880, "author_profile": "https://Stackoverflow.com/users/32880", "pm_score": 3, "selected": true, "text": "p = subprocess.Popen('start /B MOZILL~1.LNK', shell=True)\np.wait()\n p.pid os.waitpid()" }, { "answer_id": 349793, "author": "rob", "author_id": 43927, "author_profile": "https://Stackoverflow.com/users/43927", "pm_score": 0, "selected": false, "text": "p = subprocess.Popen('start /B MOZILL~1.LNK /WAIT', shell=True)\np.wait()\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28165/" ]
349,655
<p>I've created a database in Visual Studio 2008 in an App_Data folder of a MVC Web Application project. This results in an mdf file for the database that can be explored in the Server Explorer tab. You can create a SQL script for changes you do to the database.</p> <p>So I'm wondering how you run these sql change scripts to an mdf-file in Visual Studio 2008? Or am I forced to do this via the SQL Management Studio Express application?</p>
[ { "answer_id": 349670, "author": "Neil Barnwell", "author_id": 26414, "author_profile": "https://Stackoverflow.com/users/26414", "pm_score": 3, "selected": true, "text": "CREATE DATABASE [databaseName]\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3713/" ]
349,657
<p>I have a problem. </p> <p>I'm working on another guy's code and there is a JFrame with lots of JSeparators(he used them as borders for 'panels') now I'm replacing them for a JBorderedPanel class that follows the same border style of the whole application.</p> <p>The problem is that some of his separators are not clear to determine where they are in the code, there are lots of jSeparator#, replace with for any number between 0 and 999.</p> <p>Is there any way to determine which variable correspond to which border other than testing all jSeparators one by one?</p> <p>In before 'Don't replace them!' I'm obligated to replace them. I wouldn't be doing this if I could.</p> <p>Thanks in advance.</p>
[ { "answer_id": 349690, "author": "Bombe", "author_id": 43582, "author_profile": "https://Stackoverflow.com/users/43582", "pm_score": 1, "selected": false, "text": "MouseListener JSeparator" }, { "answer_id": 349735, "author": "Diones", "author_id": 2605, "author_profile": "https://Stackoverflow.com/users/2605", "pm_score": 0, "selected": false, "text": "public JSeparator getJSeparatorArvore01() {\n if (jSeparatorArvore01 == null) {\n jSeparatorArvore01 = new JSeparator();\n jSeparatorArvore01.setLocation(new Point(14, 38));\n jSeparatorArvore01.setSize(new Dimension(72, 10));\n }\n return jSeparatorArvore01;\n}\n" }, { "answer_id": 349803, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 2, "selected": false, "text": "public void installListeners (java.awt.Container parent) {\n for (Component child: parent.getComponents()) {\n if (child instanceof JSeparator) {\n child.addMouseListener (...\n hover(event);\n }\n }\n if (child instanceof java.awt.Container) {\n installListeners ((java.awt.Container)child);\n }\n }\n}\n hover() public void hover (MouseEvent event) {\n for (Field f: getClass().getFields()) {\n if (f.get(this) == event.getSource()) {\n System.out.println(f.getname());\n break;\n }\n }\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
349,659
<h1>Duplicate from : <a href="https://stackoverflow.com/questions/16432/c-string-output-format-or-concat">String output: format or concat in C#?</a></h1> <p>Especially in C# world using String.Format for everything is really common, normally as VB.NET developer unless I have to* I don't String.Format, </p> <p>I prefer normal string concatenation, such as:</p> <pre><code>V1 = V2 &amp; "test-x" &amp; V3 &amp; "-;" </code></pre> <p>to me it's better than this:</p> <pre><code>V1 = String.Format("{0} test-x {1} -;", V2, V3) </code></pre> <p>Am I missing something? Or is this just a personal preference?</p> <p><strong>Reasons to Use String.Format (From The Answers)</strong> (<em>I'll try to keep this up to date</em>)</p> <ul> <li>Localization is so much easier if you use String Format</li> <li>Obviously it's easier to change the format of input</li> <li>It's more readable (<em>however this is personal</em>)</li> <li>Better Performance </li> </ul> <p>**Sometimes I need to change the style or replacing stuff dynamically then I use String.Format*</p>
[ { "answer_id": 349688, "author": "Neil Barnwell", "author_id": 26414, "author_profile": "https://Stackoverflow.com/users/26414", "pm_score": 1, "selected": false, "text": "StringBuilder.AppendLine(string.Format(\"Some text {0}.\", \"here\"));\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40322/" ]
349,668
<p>I've recently used our company's spare laptop (that has a general user set up) while mine was being repaired. I've checked the "Remember password" option in SQL Server Management Studio when logging in to the database. </p> <p>I need to clear the login and password information that I have used to prevent the next person that will use the laptop from using my login names and passwords. How can I do this?</p>
[ { "answer_id": 1220687, "author": "Robin Luiten", "author_id": 103491, "author_profile": "https://Stackoverflow.com/users/103491", "pm_score": 9, "selected": false, "text": "C:\\Users\\%username%\\AppData\\Roaming\\Microsoft\\SQL Server Management Studio\\14.0\\SqlStudio.bin C:\\Users\\%username%\\AppData\\Roaming\\Microsoft\\SQL Server Management Studio\\13.0\\SqlStudio.bin C:\\Users\\%username%\\AppData\\Roaming\\Microsoft\\SQL Server Management Studio\\12.0\\SqlStudio.bin C:\\Users\\%username%\\AppData\\Roaming\\Microsoft\\SQL Server Management Studio\\11.0\\SqlStudio.bin C:\\Users\\%username%\\AppData\\Roaming\\Microsoft\\Microsoft SQL Server\\100\\Tools\\Shell\\SqlStudio.bin C:\\Users\\%username%\\AppData\\Roaming\\Microsoft\\Microsoft SQL Server\\90\\Tools\\Shell\\mru.dat AppData" }, { "answer_id": 52227566, "author": "Neil", "author_id": 3685882, "author_profile": "https://Stackoverflow.com/users/3685882", "pm_score": 5, "selected": false, "text": "SqlStudio.bin Microsoft.SqlServer.Management.UserSettings.SqlStudio C:\\Program Files (x86)\\Microsoft SQL Server\\130\\Tools\\Binn\\ManagementStudio\\Microsoft.SqlServer.Management.UserSettings.dll using System.IO;\nusing System.Runtime.Serialization.Formatters.Binary;\nusing Microsoft.SqlServer.Management.UserSettings;\n\nclass Program\n{\n static void Main(string[] args)\n {\n var settingsFile = new FileInfo(@\"C:\\Users\\%username%\\AppData\\Roaming\\Microsoft\\SQL Server Management Studio\\13.0\\SqlStudio.bin\");\n\n // Backup our original file just in case...\n File.Copy(settingsFile.FullName, settingsFile.FullName + \".backup\");\n\n BinaryFormatter fmt = new BinaryFormatter();\n\n SqlStudio settings = null;\n\n using(var fs = settingsFile.Open(FileMode.Open))\n {\n settings = (SqlStudio)fmt.Deserialize(fs);\n }\n\n // The structure of server types / servers / connections requires us to loop\n // through multiple nested collections to find the connection to be removed.\n // We start here with the server types\n\n var serverTypes = settings.SSMS.ConnectionOptions.ServerTypes;\n\n foreach (var serverType in serverTypes)\n {\n foreach (var server in serverType.Value.Servers)\n {\n // Will store the connection for the provided server which should be removed\n ServerConnectionSettings removeConn = null;\n\n foreach (var conn in server.Connections)\n {\n if (conn.UserName == \"adminUserThatShouldBeRemoved\")\n {\n removeConn = conn;\n break;\n }\n }\n\n if (removeConn != null)\n {\n server.Connections.RemoveItem(removeConn);\n }\n }\n }\n\n using (var fs = settingsFile.Open(FileMode.Create))\n {\n fmt.Serialize(fs, settings);\n }\n }\n}\n" }, { "answer_id": 55914665, "author": "gluecks", "author_id": 11377342, "author_profile": "https://Stackoverflow.com/users/11377342", "pm_score": 6, "selected": false, "text": "C:\\Users\\*********\\AppData\\Roaming\\Microsoft\\SQL Server Management Studio\\18.0\\UserSettings.xml <Element>.......</Element>" }, { "answer_id": 56294225, "author": "Weihui Guo", "author_id": 4271117, "author_profile": "https://Stackoverflow.com/users/4271117", "pm_score": 3, "selected": false, "text": "SqlStudio.bin UserSettings.xml C:\\Users\\userName\\AppData\\Roaming\\Microsoft\\SQL Server Management Studio\\18.0 <Element> UserSettings.xml Control Panel\\All Control Panel Items\\Credential Manager\\Windows Credentials" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
349,702
<p>I'm trying to learn bash string handling. How do I create a bash script which is equivalent to this Java code snippet?</p> <pre><code>String symbols = "abcdefg12345_"; for (char i : symbols.toCharArray()) { for (char j : symbols.toCharArray()) { System.out.println(new StringBuffer().append(i).append(j)); } } </code></pre> <p>The output of the above code snippet starts with:</p> <pre><code>aa ab ac ad ae af </code></pre> <p>And ends with:</p> <pre><code>_g _1 _2 _3 _4 _5 __ </code></pre> <p>My goal is to have a list of allowed characters (not necessarily the ones above) and print out all the permutations of length 2. If it is possible I would like a solution which relies solely on bash and doesn't require anything else installed.</p> <p><strong>Edit:</strong> Just a little follow up question: Is there a way to do this with a string without spaces separating sub-strings? Like LIST="abcdef12345_"?</p>
[ { "answer_id": 349712, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 4, "selected": true, "text": "echo {a,b,c,d,e,f,g,1,2,3,4,5,_}{a,b,c,d,e,f,g,1,2,3,4,5,_}\n LIST=\"a b c d e f 1 2 3 4 5 _\";\nfor a in $LIST ; do\n for b in $LIST ; do\n echo $a$b;\n done;\ndone\n" }, { "answer_id": 349716, "author": "Bombe", "author_id": 43582, "author_profile": "https://Stackoverflow.com/users/43582", "pm_score": 0, "selected": false, "text": "for i in a b c d e f g 1 2 3 4 5 _; do\n for j in a b c d e f g 1 2 3 4 5 _; do\n echo $i$j\n done\ndone\n man bash" }, { "answer_id": 349859, "author": "Tuminoid", "author_id": 40657, "author_profile": "https://Stackoverflow.com/users/40657", "pm_score": 0, "selected": false, "text": " for i in `echo {a,b,c,d,e,f,g,1,2,3,4,5,_}{a,b,c,d,e,f,g,1,2,3,4,5,_}`; do echo $i; done\n" }, { "answer_id": 349888, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 0, "selected": false, "text": "tr echo {a,b,c,d,e,f,g,1,2,3,4,5,_}{a,b,c,d,e,f,g,1,2,3,4,5,_} | tr \" \" \"\\n\"\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
349,705
<p>As in the subject, how can one get the total width of an element, including its border and padding, using jQuery? I've got the jQuery dimensions plugin, and running <code>.width()</code> on my <code>760px-wide</code>, <code>10px padding</code> DIV returns <code>760</code>.</p> <p>Perhaps I'm doing something wrong, but if my element manifests itself as <code>780 pixels wide</code> and Firebug tells me that there's <code>10px padding</code> on it, but calling <code>.width()</code> only gives 760, I'd be hard pressed to see how.</p> <p>Thanks for any suggestions.</p>
[ { "answer_id": 349719, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 9, "selected": true, "text": "border padding margin true width dimensions jQuery Core width var theDiv = $(\"#theDiv\");\nvar totalWidth = theDiv.width();\ntotalWidth += parseInt(theDiv.css(\"padding-left\"), 10) + parseInt(theDiv.css(\"padding-right\"), 10); //Total Padding Width\ntotalWidth += parseInt(theDiv.css(\"margin-left\"), 10) + parseInt(theDiv.css(\"margin-right\"), 10); //Total Margin Width\ntotalWidth += parseInt(theDiv.css(\"borderLeftWidth\"), 10) + parseInt(theDiv.css(\"borderRightWidth\"), 10); //Total Border Width\n" }, { "answer_id": 673622, "author": "James", "author_id": 21677, "author_profile": "https://Stackoverflow.com/users/21677", "pm_score": 8, "selected": false, "text": "outerHeight outerWidth $(elem).outerWidth(); // Returns the width + padding + borders\n true $(elem).outerWidth( true ); // Returns the width + padding + borders + margins\n" }, { "answer_id": 7111006, "author": "Cherven", "author_id": 278822, "author_profile": "https://Stackoverflow.com/users/278822", "pm_score": 0, "selected": false, "text": " var getInt = function (string) {\n if (typeof string == \"undefined\" || string == \"\")\n return 0;\n var tempInt = parseInt(string);\n\n if (!(tempInt <= 0 || tempInt > 0))\n return 0;\n return tempInt;\n }\n\n var liWidth = $(this).width();\n liWidth += getInt($(this).css(\"padding-left\"));\n liWidth += getInt($(this).css(\"padding-right\"));\n liWidth += getInt($(this).css(\"border-left-width\"));\n liWidth += getInt($(this).css(\"border-right-width\"));\n" }, { "answer_id": 12610621, "author": "bladnman", "author_id": 473501, "author_profile": "https://Stackoverflow.com/users/473501", "pm_score": 2, "selected": false, "text": "function getTotalWidthOfObject(object) {\n\n if(object == null || object.length == 0) {\n return 0;\n }\n\n var value = object.width();\n value += parseInt(object.css(\"padding-left\"), 10) + parseInt(object.css(\"padding-right\"), 10); //Total Padding Width\n value += parseInt(object.css(\"margin-left\"), 10) + parseInt(object.css(\"margin-right\"), 10); //Total Margin Width\n value += parseInt(object.css(\"borderLeftWidth\"), 10) + parseInt(object.css(\"borderRightWidth\"), 10); //Total Border Width\n return value;\n}\n\nfunction getTotalHeightOfObject(object) {\n\n if(object == null || object.length == 0) {\n return 0;\n }\n\n var value = object.height();\n value += parseInt(object.css(\"padding-top\"), 10) + parseInt(object.css(\"padding-bottom\"), 10); //Total Padding Width\n value += parseInt(object.css(\"margin-top\"), 10) + parseInt(object.css(\"margin-bottom\"), 10); //Total Margin Width\n value += parseInt(object.css(\"borderTopWidth\"), 10) + parseInt(object.css(\"borderBottomWidth\"), 10); //Total Border Width\n return value;\n}\n" }, { "answer_id": 14023108, "author": "user1798002", "author_id": 1798002, "author_profile": "https://Stackoverflow.com/users/1798002", "pm_score": 0, "selected": false, "text": "$(document).ready(function(){ \n$(\"div.width\").append($(\"div.width\").width()+\" px\");\n$(\"div.innerWidth\").append($(\"div.innerWidth\").innerWidth()+\" px\"); \n$(\"div.outerWidth\").append($(\"div.outerWidth\").outerWidth()+\" px\"); \n});\n\n\n<div class=\"width\">Width of this div container without including padding is: </div> \n<div class=\"innerWidth\">width of this div container including padding is: </div> \n<div class=\"outerWidth\">width of this div container including padding and margin is: </div>\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
349,724
<p>A recent <a href="https://stackoverflow.com/questions/349659/stringformat-or-not">question came up</a> about using String.Format(). Part of my answer included a suggestion to use StringBuilder.AppendLine(string.Format(...)). Jon Skeet suggested this was a bad example and proposed using a combination of AppendLine and AppendFormat.</p> <p>It occurred to me I've never really settled myself into a "preferred" approach for using these methods. I think I might start using something like the following but am interested to know what other people use as a "best practice":</p> <pre><code>sbuilder.AppendFormat("{0} line", "First").AppendLine(); sbuilder.AppendFormat("{0} line", "Second").AppendLine(); // as opposed to: sbuilder.AppendLine( String.Format( "{0} line", "First")); sbuilder.AppendLine( String.Format( "{0} line", "Second")); </code></pre>
[ { "answer_id": 349736, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "AppendFormat AppendLine AppendLine(string.Format(...))" }, { "answer_id": 349762, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "sbuilder.AppendFormat(\"{0} line\\n\", \"First\");\n" }, { "answer_id": 349771, "author": "Coderer", "author_id": 26286, "author_profile": "https://Stackoverflow.com/users/26286", "pm_score": 0, "selected": false, "text": "sbuilder.AppendFormat(\"{0} line\\n\", first);\n" }, { "answer_id": 350286, "author": "Chris", "author_id": 44360, "author_profile": "https://Stackoverflow.com/users/44360", "pm_score": 2, "selected": false, "text": "sbuilder.AppendFormat(\"{0} line\", \"First\");\nsbuilder.AppendLine();\nsbuilder.AppendFormat(\"{0} line\", \"Second\");\nsbuilder.AppendLine();\n sbuilder.Append(\"First\");\nsbuilder.AppendLine(\" line\");\nsbuilder.Append(\"Second\");\nsbuilder.AppendLine(\" line\");\n" }, { "answer_id": 350468, "author": "AdamSane", "author_id": 805, "author_profile": "https://Stackoverflow.com/users/805", "pm_score": 4, "selected": false, "text": "sbuilder.AppendLine( String.Format( \"{0} line\", \"First\"));\n public static string Format(IFormatProvider provider, string format, params object[] args)\n{\n if ((format == null) || (args == null))\n {\n throw new ArgumentNullException((format == null) ? \"format\" : \"args\");\n }\n StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8));\n builder.AppendFormat(provider, format, args);\n return builder.ToString();\n}\n" }, { "answer_id": 18729210, "author": "docmanhattan", "author_id": 864435, "author_profile": "https://Stackoverflow.com/users/864435", "pm_score": 4, "selected": false, "text": "public static StringBuilder AppendLine(this StringBuilder builder, string format, params object[] args)\n{\n builder.AppendFormat(format, args).AppendLine();\n return builder;\n}\n AppendLine(string.Format(...)) .AppendLine() var builder = new StringBuilder();\n\nbuilder\n .AppendLine(\"This is a test.\")\n .AppendLine(\"This is a {0}.\", \"test\");\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26414/" ]
349,729
<p>I am using <a href="http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.getallnetworkinterfaces.aspx" rel="nofollow noreferrer">NetworkInterface.GetAllNetworkInterfaces()</a> to get all the interfaces on a PC. However, this appears to only return "active" interfaces. How can I find "inactive" network interfaces, such as unconnected VPNs, disabled NICs, etc. in .NET. </p> <p>I would like to find them by their name in "Control Panel" -> "Network Connections". So, for example, if I have a VPN called "My Work" I would like to be able to find it using the name "My Work".</p> <p>Using Win32_NetworkAdapterConfiguration does not seem to be an option as it does not return the name shown in "Network Connections" (as far as I can see).</p> <p>Many thanks,</p> <p>RB.</p>
[ { "answer_id": 349766, "author": "Paul Nearney", "author_id": 24071, "author_profile": "https://Stackoverflow.com/users/24071", "pm_score": 1, "selected": false, "text": "using System.Management;\n\nstring query = \"SELECT * FROM Win32_NetworkAdapterConfiguration\";\nManagementObjectSearcher moSearch = new ManagementObjectSearcher(query);\nManagementObjectCollection moCollection = moSearch.Get();\n\n// Every record in this collection is a network interface\nforeach (ManagementObject mo in moCollection)\n{\n // Do what you need to here....\n}\n" }, { "answer_id": 350056, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 2, "selected": false, "text": "Dim p As New Process\n\np.StartInfo.UseShellExecute = False\np.StartInfo.RedirectStandardOutput = True\np.StartInfo.RedirectStandardError = True\np.StartInfo.FileName = \"rasdial.exe\"\np.StartInfo.Arguments = \"\"\"Company HQ\"\"\"\np.Start()\nIf Not p.WaitForExit(My.Settings.VpnTimeout) Then\n Throw New Exception( _\nString.Format(\"Connecting to \"\"{0}\"\" VPN failed after {1}ms\", sVpn, My.Settings.VpnTimeout))\nEnd If\n\nIf p.ExitCode <> 0 Then\n Throw New Exception( _\nString.Format(\"Failed connecting to \"\"{0}\"\" with exit code {1}. Errors {2}\", sVpn, p.ExitCode, p.StandardOutput.ReadToEnd.Replace(vbCrLf, \"\")))\nEnd If\n" }, { "answer_id": 682168, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "RasDialer dialer = new RasDialer();\nReadOnlyCollection<RasConnection> connections = dialer.GetActiveConnections();\n\nforeach (RasConnection connection in connections)\n{\n // Do what you want to with the connections.\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15393/" ]
349,742
<p>I frequently make use of <code>Request.QueryString[]</code> variables.</p> <p>In my <code>Page_load</code> I often do things like:</p> <pre><code> int id = -1; if (Request.QueryString["id"] != null) { try { id = int.Parse(Request.QueryString["id"]); } catch { // deal with it } } DoSomethingSpectacularNow(id); </code></pre> <p>It all seems a bit clunky and rubbish. How do you deal with your <code>Request.QueryString[]</code>s?</p>
[ { "answer_id": 349748, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 5, "selected": false, "text": "if (!int.TryParse(Request.QueryString[\"id\"], out id))\n{\n // error case\n}\n" }, { "answer_id": 349749, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "int id;\nif (!int.TryParse(Request.QueryString[\"id\"], out id))\n{\n id = -1;\n}\n" }, { "answer_id": 349753, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "if(!string.IsNullOrEmpty(Request.QueryString[\"id\"]))\n{\n//querystring contains id\n}\n" }, { "answer_id": 349760, "author": "dr. evil", "author_id": 40322, "author_profile": "https://Stackoverflow.com/users/40322", "pm_score": 1, "selected": false, "text": "GetIntegerFromQuerystring(val) GetIntegerFromPost(val) .... Dim X as Integer = GetIntegerFromQuerystring(\"id\")\nIf x = -1 Then Exit Sub\n" }, { "answer_id": 349764, "author": "M4N", "author_id": 19635, "author_profile": "https://Stackoverflow.com/users/19635", "pm_score": 4, "selected": false, "text": "public static int QueryString(string paramName, int defaultValue)\n{\n int value;\n if (!int.TryParse(Request.QueryString[paramName], out value))\n return defaultValue;\n return value;\n}\n int id = QueryString(\"id\", 0);\n" }, { "answer_id": 349772, "author": "annakata", "author_id": 13018, "author_profile": "https://Stackoverflow.com/users/13018", "pm_score": 1, "selected": false, "text": "private T GetValue<T>(string[] keys)\n{\n return GetValue<T>(keys, default(T));\n}\n\nprivate T GetValue<T>(string[] keys, T vDefault)\n{\n T x = vDefault;\n\n string v = null;\n\n for (int i = 0; i < keys.Length && String.IsNullOrEmpty(v); i++)\n {\n v = this.source[keys[i]];\n }\n\n if (!String.IsNullOrEmpty(v))\n {\n try\n {\n x = (typeof(T).IsSubclassOf(typeof(Enum))) ? (T)Enum.Parse(typeof(T), v) : (T)Convert.ChangeType(v, typeof(T));\n }\n catch(Exception e)\n {\n //do whatever you want here\n }\n }\n\n return x;\n}\n" }, { "answer_id": 349781, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 1, "selected": false, "text": "public class QueryString\n{\n static NameValueCollection QS\n {\n get\n {\n if (HttpContext.Current == null)\n throw new ApplicationException(\"No HttpContext!\");\n\n return HttpContext.Current.Request.QueryString;\n }\n }\n\n public static int Int(string key)\n {\n int i; \n if (!int.TryParse(QS[key], out i))\n i = -1; // Obviously Change as you see fit.\n return i;\n }\n\n // ... Other types omitted.\n}\n\n// And to Use..\nvoid Test()\n{\n int i = QueryString.Int(\"test\");\n}\n" }, { "answer_id": 349784, "author": "terjetyl", "author_id": 29519, "author_profile": "https://Stackoverflow.com/users/29519", "pm_score": 3, "selected": false, "text": "int? id = Request[\"id\"].ToInt();\nif(id.HasValue)\n{\n\n}\n public static int? ToInt(this string input) \n{\n int val;\n if (int.TryParse(input, out val))\n return val;\n return null;\n}\n\npublic static DateTime? ToDate(this string input)\n{\n DateTime val;\n if (DateTime.TryParse(input, out val))\n return val;\n return null;\n}\n\npublic static decimal? ToDecimal(this string input)\n{\n decimal val;\n if (decimal.TryParse(input, out val))\n return val;\n return null;\n}\n" }, { "answer_id": 349818, "author": "Bryan Watts", "author_id": 37815, "author_profile": "https://Stackoverflow.com/users/37815", "pm_score": 7, "selected": true, "text": "int id = request.QueryString.GetValue<int>(\"id\");\nDateTime date = request.QueryString.GetValue<DateTime>(\"date\");\n TypeDescriptor public static T GetValue<T>(this NameValueCollection collection, string key)\n{\n if(collection == null)\n {\n throw new ArgumentNullException(\"collection\");\n }\n\n var value = collection[key];\n\n if(value == null)\n {\n throw new ArgumentOutOfRangeException(\"key\");\n }\n\n var converter = TypeDescriptor.GetConverter(typeof(T));\n\n if(!converter.CanConvertFrom(typeof(string)))\n {\n throw new ArgumentException(String.Format(\"Cannot convert '{0}' to {1}\", value, typeof(T)));\n }\n\n return (T) converter.ConvertFrom(value);\n}\n" }, { "answer_id": 1590461, "author": "W3Max", "author_id": 146070, "author_profile": "https://Stackoverflow.com/users/146070", "pm_score": 1, "selected": false, "text": "public static T GetValue<T>(this NameValueCollection collection, string key)\n {\n if (collection == null)\n {\n return default(T);\n }\n\n var value = collection[key];\n\n if (value == null)\n {\n return default(T);\n }\n\n var type = typeof(T);\n\n if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))\n {\n type = Nullable.GetUnderlyingType(type);\n }\n\n var converter = TypeDescriptor.GetConverter(type);\n\n if (!converter.CanConvertTo(value.GetType()))\n {\n return default(T);\n }\n\n return (T)converter.ConvertTo(value, type);\n }\n Request.QueryString.GetValue<int?>(paramName) ?? 10;\n" }, { "answer_id": 3825327, "author": "AutomationNation", "author_id": 461061, "author_profile": "https://Stackoverflow.com/users/461061", "pm_score": 4, "selected": false, "text": "List<string> keys = new List<string>(Request.QueryString.AllKeys);\n keys.Contains(\"someKey\")\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31765/" ]
349,743
<p>My homepage (or welcome page) will consist of data from two models (lets call them authors and posts). I am new to rails and not sure what is the best way to accomplish this.</p> <p>Should I create a new controller called welcome which gathers data from the authors and posts and then display them in the welcome index view? Or should I have a welcome view under the post model which also gets data from authors? Or any other way to accomplish this?</p> <p>I understand how to do all this technically but just unsure what is the best practice method using the rails framework.</p>
[ { "answer_id": 349800, "author": "Robert K", "author_id": 24950, "author_profile": "https://Stackoverflow.com/users/24950", "pm_score": 7, "selected": true, "text": "Static routes.rb # Place at the end of the routing!\nmap.root :controller => 'MyController', :action => :index\n map.root :controller => 'static', :action => :index\n class MainController < ApplicationController\n def index\n @posts = Posts.find(:all, :limit => 10, :order => 'date_posted', :include => :user)\n end\nend\n" }, { "answer_id": 6486205, "author": "irakli", "author_id": 784635, "author_profile": "https://Stackoverflow.com/users/784635", "pm_score": 3, "selected": false, "text": "root :to => \"welcome#index\"\n class WelcomeController < ApplicationController\n def index\n @posts = Posts.find(:all, :limit => 10, :order => 'date_posted', :include => :user)\n end\nend\n" }, { "answer_id": 11003820, "author": "user664833", "author_id": 664833, "author_profile": "https://Stackoverflow.com/users/664833", "pm_score": 7, "selected": false, "text": "config/routes.rb welcome#index welcome#index rails generate controller Welcome index\n config/routes.rb get \"welcome/index\" root 'welcome#index' root :to => 'welcome#index' < 4 public/index.html < 4 PagesController pages#main pages#home pages#about pages#contact pages#terms pages#privacy static_pages#home static_pages#help" }, { "answer_id": 12984736, "author": "Naoise Golden", "author_id": 357452, "author_profile": "https://Stackoverflow.com/users/357452", "pm_score": 3, "selected": false, "text": "static $ rails generate controller static\n app/controllers/static_controller.rb class StaticController < ApplicationController\n def index \n end\nend\n app/views/index.html.erb config/routes.rb MyApp::Application.routes.draw do\n match 'home', :to => \"static#index\"\n root :to => \"static#index\"\nend\n /home /" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50718/" ]
349,769
<p>Is it possible to return an XElement from a webservice (in C#/asp.net)?</p> <p>Try a simple web service that returns an XElement:</p> <pre><code>[WebMethod] public XElement DoItXElement() { XElement xe = new XElement("hello", new XElement("message", "Hello World") ); return xe; } </code></pre> <p>This compiles fine but if you try and run it you get </p> <pre>Cannot use wildcards at the top level of a schema.</pre> <p>I found <a href="http://blog.bksanders.com/index.php/tag/linq-to-xml/" rel="nofollow noreferrer">this post implying that this is a bug</a> in .net.</p> <p>So... Can I return an XElement from a web service? If so, how?</p> <p>Thanks.</p>
[ { "answer_id": 40387725, "author": "Abacus", "author_id": 1078031, "author_profile": "https://Stackoverflow.com/users/1078031", "pm_score": 0, "selected": false, "text": "[System.Runtime.CompilerServices.Extension()]\npublic XmlElement ToXmlElement(XElement value)\n{\n var xmlDoc = new XmlDocument();\n xmlDoc.LoadXml(value.ToString());\n return xmlDoc.DocumentElement;\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3099/" ]
349,779
<p>I am writing an application which opens USB devices and transfer some data. I am following the UsbSimpleNotificationExample from the Developer Examples. The example adds notifications and assigns callbacks for a unique Vendor ID and Product ID. But for my application I have multiple PIDs and a single VIDs. How can I add a dictionary entry with single Vid and more than one PIDs? If I use CFDictionarySetValue with 2 PIDs, the 2nd Pid call overwrites the first dictionary value. I am not able to match IOServiceAddMatchingNotification callbacks properly due to this. What are the other options I can try? </p>
[ { "answer_id": 22538012, "author": "Chris Marshall", "author_id": 879365, "author_profile": "https://Stackoverflow.com/users/879365", "pm_score": 0, "selected": false, "text": "CFMutableDictionaryRef matchingDict = IOServiceMatching ( kIOUSBDeviceClassName );\nif ( matchingDict )\n{\n UInt32 usbVendor = k_MyVendorID;\n CFNumberRef refVendorId = CFNumberCreate ( kCFAllocatorDefault, kCFNumberIntType, &usbVendor );\n CFDictionarySetValue ( matchingDict, CFSTR ( kUSBVendorID ), refVendorId );\n CFRelease ( refVendorID );\n CFDictionarySetValue ( matchingDict, CFSTR ( kUSBProductID ), CFSTR ( \"*\" ) ); // This is a wildcard, so we find any device.\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
349,787
<p>In a software-project written in java you often have resources, that are part of the project and should be included on the classpath. For instance some templates or images, that should be accessible through the classpath (getResource). These files should be included into a produced JAR-file.</p> <p>It's clear that these resources should be added to the revision-control-system. But in which directory you put these files? Parallel to the java-source-files or in another directory that also reproduces the needed package-structure?</p>
[ { "answer_id": 349897, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 2, "selected": false, "text": "project/src\nproject/resources\nproject/classes\nproject/lib\nproject/dist\n" }, { "answer_id": 6644514, "author": "Ondra Žižka", "author_id": 145989, "author_profile": "https://Stackoverflow.com/users/145989", "pm_score": 0, "selected": false, "text": ".html META-INF WEB-INF <build>\n <resources>\n <resource>\n <directory>src/main/resources</directory>\n </resource>\n <!-- Web - Wicket -->\n <resource>\n <filtering>false</filtering>\n <directory>src/main/java</directory>\n <includes><include>**</include></includes>\n <excludes><exclude>**/*.java</exclude></excludes>\n </resource>\n </resources>\n\n <testResources>\n <testResource>\n <directory>src/test/resources</directory>\n </testResource>\n <!-- Web - Wicket -->\n <testResource>\n <filtering>false</filtering>\n <directory>src/main/java</directory>\n <includes><include>**</include></includes>\n <excludes><exclude>**/*.java</exclude></excludes>\n </testResource>\n </testResources>\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21005/" ]
349,802
<p>Is it possible for me to create and destroy a TXMLDocument by myself in Borland C++ Builder? I've tried but borland keeps telling me that TXMLDocument is (and must be) an IDE managed component. </p> <p>Also, the only reason that I want to do this is that TXMLDocument sort of crashes: I get the TXMLDocument and 'Gets' a workbook from it, sets some document properties (the xml is saved as an Excel-file later), and the I add some styles. Ok, then I add a worksheet and then all the cells that I want with proper formatting and then I save it. At this point everything is OK. </p> <p>Then I want to save another Excel-file. Since the IDE doesn't let me delete and recreate the TXMLDocument I try to delete just the worksheet form it. When I try this (in debug mode) the IDE goes in to line step mode in the CPU tab (showing some assembler):</p> <pre><code>ntdll.DbgBreakPoint: 77A07DFE CC int 3 77A07DFF C3 ret </code></pre>
[ { "answer_id": 349857, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 3, "selected": true, "text": "_di_IXMLDocument Doc = NewXMLDocument(); \n" }, { "answer_id": 1427403, "author": "enzo1959", "author_id": 173747, "author_profile": "https://Stackoverflow.com/users/173747", "pm_score": 0, "selected": false, "text": "#include <oxmldom.hpp>\n#include <XMLDoc.hpp>\n#include <xmldom.hpp>\n#include <XMLIntf.hpp>\n\n\n try\n {\n CoInitialize(0);\n _di_IXMLDocument xmlDoc;\n xmlDoc = LoadXMLData( s1 );\n s1 = xmlDoc->XML->Text;\n CoUninitialize();\n mylog( Fun + String::Format( \"ANSW-MSG-XML %s \", ARRAYOFCONST(( s1 ))));\n }\n catch ( Exception & ex )\n {\n mylog( Fun + String::Format( \"PARSEXML:ERRORE %s \\nmsg:%s\",\n ARRAYOFCONST(( ex.Message, cmdMsg ))));\n }\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2079/" ]
349,811
<p>How to arrange a Makefile to compile a kernel module with multiple .c files?</p> <p>Here is my current Makefile. It was auto generated by <a href="http://www.kdevelop.org/" rel="noreferrer">KDevelop</a></p> <pre><code>TARGET = nlb-driver OBJS = nlb-driver.o MDIR = drivers/misc EXTRA_CFLAGS = -DEXPORT_SYMTAB CURRENT = $(shell uname -r) KDIR = /lib/modules/$(CURRENT)/build PWD = $(shell pwd) DEST = /lib/modules/$(CURRENT)/kernel/$(MDIR) obj-m += $(TARGET).o default: make -C $(KDIR) M=$(PWD) modules $(TARGET).o: $(OBJS) $(LD) $(LD_RFLAG) -r -o $@ $(OBJS) ifneq (,$(findstring 2.4.,$(CURRENT))) install: su -c "cp -v $(TARGET).o $(DEST) &amp;&amp; /sbin/depmod -a" else install: su -c "cp -v $(TARGET).ko $(DEST) &amp;&amp; /sbin/depmod -a" endif clean: -rm -f *.o *.ko .*.cmd .*.flags *.mod.c make -C $(KDIR) M=$(PWD) clean -include $(KDIR)/Rules.make </code></pre>
[ { "answer_id": 349973, "author": "ctuffli", "author_id": 26683, "author_profile": "https://Stackoverflow.com/users/26683", "pm_score": 2, "selected": false, "text": "OBJS = nlb-driver.o\nOBJS += file1.o\nOBJS += file2.o\n...\n $(TARGET).o: nlb-driver.o file1.o file2.o\n $(LD) $(LD_RFLAG) -r -o $@ $(OBJS)\n OBJS = nlb-driver.o file1.o file2.o\n" }, { "answer_id": 43600027, "author": "Mateusz Piotrowski", "author_id": 4694621, "author_profile": "https://Stackoverflow.com/users/4694621", "pm_score": 3, "selected": false, "text": "monter_main.c monter_main.h monter_cdev.c monter_cdev.h monter_pci.c monter_pci.h monter_main.c monter.c monter.ko KDIR ?= /lib/modules/`uname -r`/build\n\ndefault:\n $(MAKE) -C $(KDIR) M=$$PWD\n\ninstall:\n $(MAKE) -C $(KDIR) M=$$PWD modules_install\n\nclean:\n $(MAKE) -C $(KDIR) M=$$PWD clean\n obj-m := monter.o\nmonter-objs := monter_main.o monter_cdev.o monter_pci.o\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1100/" ]
349,822
<p>When using the following function (compare 2 user's group membership), I get results that do not make sense.</p> <pre><code>function Compare-ADUserGroups &lt;br&gt; { #requires -pssnapin Quest.ActiveRoles.ADManagement param ( [string] $FirstUser = $(Throw "logonname required."), [string] $SecondUser = $(Throw "logonname required.") ) $a = (Get-QADUser $FirstUser).MemberOf $b = (Get-QADUser $SecondUser).MemberOf $c = Compare-Object -referenceObject $a -differenceObject $b $c | Sort-Object InputObject } </code></pre> <p>When I call this (Compare-ADUserGroups User1 User2), I get a result set similar to the following:</p> <ul> <li>CN=[All Users],OU=adm,DC=OSUMC,DC=EDU &lt;=</li> <li>CN=[All Users],OU=adm,DC=OSUMC,DC=EDU =></li> <li>CN=Extended Users,OU=MSG,DC=OSUMC,DC=EDU &lt;=</li> <li>CN=Extended Users,OU=MSG,DC=OSUMC,DC=EDU =></li> <li>CN=LCS2005,OU=Distribution Lists,DC=OSUMC,DC=EDU &lt;=</li> <li>CN=LCS2005,OU=Distribution Lists,DC=OSUMC,DC=EDU =></li> </ul> <p>I would expect these to not show given that they are equal and I am not using the -IncludeEqual parameter. Any ideas on why these are showing up?</p>
[ { "answer_id": 34658760, "author": "Alban", "author_id": 1911082, "author_profile": "https://Stackoverflow.com/users/1911082", "pm_score": 1, "selected": false, "text": "#requires -version 2\n<#\n .SYNOPSIS\n Compare les groupe entre 2 users\n .DESCRIPTION\n Affiche sur 2 colones les les groupes AD des 2 users a comparer et met en evidance les goupes mamquants de chaque user\n .PARAMETER user1\n Nom complet de l'utilisateur 1 a comparer\n ex : domain.adds\\UserName\n .PARAMETER user2\n Nom complet de l'utilisateur 2 a comparer\n .EXAMPLE\n .\\Compare-QadUsersGrp.ps1 $(whoami) $($UserNames)\n .EXAMPLE\n Start-Process -WindowStyle hidden powershell -ArgumentList \"-WindowStyle Normal .\\Compare-QadUsersGrp.ps1 $(whoami) $($UserNames)\"\n#>\n\n\nparam( \n [string]$SessionName1 = 'Domain\\testalb',\n [string]$SessionName2 = 'Domain\\testalb2'\n)\n\n$currentRunner = $false\n$version = '0.60'\n$source = \"Script Compare-Sessions (alopez)\"\n$lanStorage = \"c:\"\n\n add-content \"$lanStorage\\Get-TSAdmin_Usage-Log.txt\" -value \"[$(Get-Date -Format 'yyyy/MM/dd HH:mm:ss')] $(whoami) - $($version) Compare-Sessions - $SessionName1 vs $SessionName2\"\n\n############################################### Zone liée a l'affichage (refresh) ################################################\n\n function Refresh-Tabs {\n $loadBar.Visible = $true\n $loadBar.Value = 0\n\n $ListCompared = Get-vsGrps\n\n $loadBar.Value = 90\n $SrvForm.height = 178 + $ListCompared.count * 22\n\n $DefaultColor = 'DarkBlue'\n Set-DataGridView -DataGridView $Grille -AlternativeRowColor -ForeColor $DefaultColor -BackColor 'AliceBlue'\n\n Load-DataGridView -DataGridView $Grille -Item (ConvertTo-DataTable -InputObject ($ListCompared | ?{$_}))\n $Grille.Columns[\"$SessionName2\"].Width=320\n $Grille.Columns[\"$SessionName2\"].HeaderCell.Style.Alignment = 'MiddleRight'\n #$Grille.Columns[\"$SessionName2\"].AutoSizeMode = $true\n $Grille.Columns[\"$SessionName2\"].DefaultCellStyle.Alignment = 'MiddleRight'\n $Grille.Columns['#'].Width=20\n $Grille.Columns[\"$SessionName1\"].Width=330\n #$Grille.Columns[\"$SessionName2\"].AutoSizeMode = $true\n\n $Grille.Columns['DN'].Width = 0\n Find-DataGridViewValue -DataGridView $Grille -Value '==' -FindingColumns '#' -RowForeColor Gray\n Find-DataGridViewValue -DataGridView $Grille -Value '=>' -FindingColumns '#' -RowForeColor Green\n #Find-DataGridViewValue -DataGridView $Grille -Value '<=' -FindingColumns '#' -RowForeColor Blue\n\n $loadBar.Value = 100\n $loadBar.Visible = $false\n\n }\n\n function Set-DataGridView {\n PARAM (\n [ValidateNotNull()]\n [Parameter(Mandatory = $true)]\n [System.Windows.Forms.DataGridView]$DataGridView,\n\n [Parameter(ParameterSetName = \"AlternativeRowColor\")]\n [Switch]$AlternativeRowColor,\n\n [Parameter(Mandatory = $true, ParameterSetName = \"AlternativeRowColor\")]\n [System.Drawing.Color]$ForeColor,\n\n [Parameter(Mandatory = $true, ParameterSetName = \"AlternativeRowColor\")]\n [System.Drawing.Color]$BackColor,\n\n [Parameter(ParameterSetName = \"Proper\")]\n [Switch]$ProperFormat\n )\n PROCESS\n {\n\n $DataGridView.DefaultCellStyle.ForeColor = $DefaultColor\n\n if ($psboundparameters['AlternativeRowColor']) { # les ligne PAIRES\n $DataGridView.AlternatingRowsDefaultCellStyle.ForeColor = $ForeColor\n $DataGridView.AlternatingRowsDefaultCellStyle.BackColor = $BackColor\n }\n\n\n if ($psboundparameters['ProperFormat']) {\n #$Font = New-Object -TypeName System.Drawing.Font -ArgumentList \"Segoi UI\", 10\n $Font = New-Object -TypeName System.Drawing.Font -ArgumentList \"Consolas\", 10\n #[System.Drawing.FontStyle]::Bold\n\n $DataGridView.ColumnHeadersBorderStyle = 'Raised'\n $DataGridView.BorderStyle = 'Fixed3D'\n $DataGridView.SelectionMode = 'FullRowSelect'\n $DataGridView.AllowUserToResizeRows = $false\n $datagridview.DefaultCellStyle.font = $Font\n }\n } \n }\n\n function ConvertTo-DataTable {\n <#\n .SYNOPSIS\n Converts objects into a DataTable.\n .DESCRIPTION\n Converts objects into a DataTable, which are used for DataBinding.\n .PARAMETER InputObject\n The input to convert into a DataTable.\n .PARAMETER Table\n The DataTable you wish to load the input into.\n .PARAMETER RetainColumns\n This switch tells the function to keep the DataTable's existing columns.\n .PARAMETER FilterWMIProperties\n This switch removes WMI properties that start with an underline.\n .EXAMPLE\n $DataTable = ConvertTo-DataTable -InputObject (Get-Process)\n #>\n [OutputType([System.Data.DataTable])]\n param(\n [ValidateNotNull()]\n $InputObject, \n [ValidateNotNull()]\n [System.Data.DataTable]\n $Table,\n [switch] $RetainColumns,\n [switch] $FilterWMIProperties\n )\n\n if($Table -eq $null) {\n $Table = New-Object System.Data.DataTable\n }\n\n if($InputObject-is [System.Data.DataTable]) {\n $Table = $InputObject\n } else {\n if(-not $RetainColumns -or $Table.Columns.Count -eq 0) {\n #Clear out the Table Contents\n $Table.Clear()\n\n if($InputObject -eq $null){ return } #Empty Data\n\n $object = $null\n #find the first non null value\n foreach($item in $InputObject) {\n if($item -ne $null) {\n $object = $item\n break\n }\n }\n\n if($object -eq $null) { return } #All null then empty\n\n #Get all the properties in order to create the columns\n foreach ($prop in $object.PSObject.Get_Properties()) {\n if(-not $FilterWMIProperties -or -not $prop.Name.StartsWith('__')) #filter out WMI properties\n {\n #Get the type from the Definition string\n $type = $null\n\n if($prop.Value -ne $null) {\n try{ $type = $prop.Value.GetType() } catch {}\n }\n\n if($type -ne $null) # -and [System.Type]::GetTypeCode($type) -ne 'Object')\n {\n [void]$table.Columns.Add($prop.Name, $type) \n }\n else #Type info not found\n { \n [void]$table.Columns.Add($prop.Name) \n }\n }\n }\n\n if($object -is [System.Data.DataRow]) {\n foreach($item in $InputObject) { \n $Table.Rows.Add($item)\n }\n return @(,$Table)\n }\n } else {\n $Table.Rows.Clear() \n }\n\n foreach($item in $InputObject) { \n $row = $table.NewRow()\n\n if($item) {\n foreach ($prop in $item.PSObject.Get_Properties()) {\n if($table.Columns.Contains($prop.Name)) {\n $row.Item($prop.Name) = $prop.Value\n }\n }\n }\n [void]$table.Rows.Add($row)\n }\n }\n\n return @(,$Table) \n }\n\n function Load-DataGridView {\n <#\n .SYNOPSIS\n This functions helps you load items into a DataGridView.\n .DESCRIPTION\n Use this function to dynamically load items into the DataGridView control.\n .PARAMETER DataGridView\n The ComboBox control you want to add items to.\n .PARAMETER Item\n The object or objects you wish to load into the ComboBox's items collection.\n .PARAMETER DataMember\n Sets the name of the list or table in the data source for which the DataGridView is displaying data.\n #>\n Param (\n [ValidateNotNull()]\n [Parameter(Mandatory=$true)]\n [System.Windows.Forms.DataGridView]\n $DataGridView,\n [ValidateNotNull()]\n [Parameter(Mandatory=$true)]\n $Item,\n [Parameter(Mandatory=$false)]\n [string]\n $DataMember\n )\n $DataGridView.SuspendLayout()\n $DataGridView.DataMember = $DataMember\n\n if ($Item -is [System.ComponentModel.IListSource] -or $Item -is [System.ComponentModel.IBindingList] -or $Item -is [System.ComponentModel.IBindingListView] ) {\n $DataGridView.DataSource = $Item\n } else {\n $array = New-Object System.Collections.ArrayList\n\n if ($Item -is [System.Collections.IList]) {\n $array.AddRange($Item)\n } else { \n $array.Add($Item) \n }\n $DataGridView.DataSource = $array\n }\n $DataGridView.ResumeLayout()\n }\n\n function Find-DataGridViewValue {\n # https://github.com/lazywinadmin/WinFormPS/blob/master/WinFormPS.psm1\n <#\n .SYNOPSIS\n The Find-DataGridViewValue function helps you to find a specific value and select the cell, row or to set a fore and back color.\n\n .DESCRIPTION\n The Find-DataGridViewValue function helps you to find a specific value and select the cell, row or to set a fore and back color.\n\n .PARAMETER DataGridView\n Specifies the DataGridView Control to use\n\n .PARAMETER RowBackColor\n Specifies the back color of the row to use\n\n .PARAMETER RowForeColor\n Specifies the fore color of the row to use\n\n .PARAMETER SelectCell\n Specifies to select only the cell when the value is found\n\n .PARAMETER SelectRow\n Specifies to select the entire row when the value is found\n\n .PARAMETER FindingColumns\n Specifies the column(s) to search Value or NotValue\n\n .PARAMETER Value\n Specifies the value to search\n\n .PARAMETER NotValue\n Specifies the value to not match in all column (param FindingColumns is recomanded)\n\n .EXAMPLE\n PS C:\\> Find-DataGridViewValue -DataGridView $Grille -Value $textbox1.Text\n\n This will find the value and select the cell(s)\n\n .EXAMPLE\n PS C:\\> Find-DataGridViewValue -DataGridView $Grille -Value $textbox1.Text -RowForeColor 'Red' -RowBackColor 'Black'\n\n This will find the value and color the fore and back of the row\n .EXAMPLE\n PS C:\\> Find-DataGridViewValue -DataGridView $Grille -Value $textbox1.Text -SelectRow\n\n This will find the value and select the entire row\n\n .NOTES\n Francois-Xavier Cat\n @lazywinadm\n www.lazywinadmin.com\n #>\n [CmdletBinding(DefaultParameterSetName = \"Cell\")]\n PARAM (\n [ValidateNotNull()]\n [Parameter(Mandatory = $true)]\n [System.Windows.Forms.DataGridView]$DataGridView,\n $Value,\n $NotValue,\n [string[]]$FindingColumns,\n #[Parameter(ParameterSetName = \"Cell\")]\n [Switch]$SelectCell,\n #[Parameter(ParameterSetName = \"Row\")]\n [Switch]$SelectRow,\n #[Parameter(ParameterSetName = \"Column\")]\n #[Switch]$SelectColumn,\n [Parameter(ParameterSetName = \"RowColor\")]\n [system.Drawing.Color]$RowForeColor,\n [Parameter(ParameterSetName = \"RowColor\")]\n [system.Drawing.Color]$RowBackColor\n )\n\n PROCESS\n {\n $DataGridView.ClearSelection()\n ForEach ($Col in $DataGridView.Columns) {\n if ($FindingColumns -contains $Col.Name -or !$FindingColumns) {\n ForEach ($Row in $DataGridView.Rows) {\n $CurrentCell = $dataGridView.Rows[$Row.index].Cells[$Col.index]\n\n if ((-not $CurrentCell.Value.Equals([DBNull]::Value)) -and ( ($Value -and ($CurrentCell.Value.ToString() -like \"$Value\")) -or ($NotValue -and ($CurrentCell.Value.ToString() -notlike \"$NotValue\")) ))\n {\n # Append-RichtextboxStatus -ComputerName $textboxSocieteName.Text -Source \"Find $Value$NotValue\" -Message \"Colonne:$($col.name) ligne:$($row.index)\"\n # Row Selection\n IF ($PSBoundParameters['SelectRow'])\n {\n $dataGridView.Rows[$Row.index].Selected = $true\n }\n\n # Row Fore Color\n IF ($PSBoundParameters['RowForeColor'])\n {\n $dataGridView.Rows[$Row.index].DefaultCellStyle.ForeColor = $RowForeColor\n }\n\n # Row Back Color\n IF ($PSBoundParameters['RowBackColor'])\n {\n $dataGridView.Rows[$Row.index].DefaultCellStyle.BackColor = $RowBackColor\n }\n # Cell Selection\n ELSEIF (-not ($PSBoundParameters['SelectRow']) -and -not ($PSBoundParameters['RowForeColor']) -and -not ($PSBoundParameters['SelectColumn']))\n {\n $CurrentCell.Selected = $true\n }\n }#IF not empty and contains value\n }\n }\n }\n }#PROCESS\n }\n############################################### Zone liée aux actions sur les objects ############################################\n\n $CommonObject = [hashtable]::Synchronized( @{\n })\n\n function Get-vsGrps {\n Add-PSSnapin 'Quest.ActiveRoles.ADManagement'\n\n $loadBar.Value = 10\n $User1 = Get-QADUser -identity $SessionName1\n $loadBar.Value = 20\n $User2 = Get-QADUser -identity $SessionName2\n $loadBar.Value = 30\n $ListCompared = Compare-Object $User1.memberof $User2.memberof -IncludeEqual | %{\n #$_.InputObject=(Get-QADGroup $_.InputObject).Name\n #$_.InputObject = ($_.InputObject -split(','))[0] -replace('CN=','')\n [pscustomobject][ordered]@{\n \"$SessionName2\" = $(\n if ($_.SideIndicator -eq '==' -or $_.SideIndicator -eq '=>') {\n ($_.InputObject -split(','))[0] -replace('CN=','')\n } else {\n ''\n }\n )\n '#' = $_.SideIndicator\n \"$SessionName1\" = $(\n if ($_.SideIndicator -eq '==' -or $_.SideIndicator -eq '<=') {\n ($_.InputObject -split(','))[0] -replace('CN=','')\n } else {\n ''\n }\n )\n DN = $_.InputObject\n }\n } | Sort-Object DN\n $loadBar.Value = 40\n $ListCompared\n }\n\n function Toggle-Group {\n $loadBar.Value = 0\n $loadBar.Visible = $true\n $loadBar.Value = 50\n\n $line = $Grille.CurrentCell.RowIndex\n $col = $Grille.CurrentCell.ColumnIndex\n $DN = $Grille.currentrow.Cells[3].value\n $Grp = ($DN -split(','))[0] -replace('CN=','')\n\n if (@(0,2) -contains $col -and $edit.Checked) {\n $user = $Grille.columns[$Col].HeaderText\n if ($Grille.CurrentCell.value -eq '' -or $Grille.CurrentCell.value -like \" Supp ($Grp) ! \") {\n add-QADGroupMember -identity $DN -member $user\n retour-email -title \"$user : Add '$Grp'\" -msg \"Add $DN\"\n $Grille.CurrentCell.value = \" Add ($Grp) ! \"\n $Grille.CurrentCell.Style.ForeColor = 'Magenta'\n }\n else {\n Remove-QADGroupMember -identity $DN -member $user\n retour-email -title \"$user : Supp '$Grp'\" -msg \"Supp $DN\"\n $Grille.CurrentCell.value = \" Supp ($Grp) ! \"\n $Grille.CurrentCell.Style.ForeColor = 'Red'\n }\n $Grille.currentrow.Cells[1].value = \"><\"\n $Grille.currentrow.Cells[1].style.ForeColor = 'Red'\n }\n\n $loadBar.Value = 100\n $loadBar.Visible = $false\n }\n\n function retour-email {\n param (\n [string] $email = $script:currentRunner,\n [switch] $force = $edit.Checked,\n [string] $title = '.',\n [string] $msg = '.'\n )\n if ( $email -and $force) {\n Send-MailMessage -To $email -from 'Script@mydomain.com' -Subject \"$title\" -SmtpServer mySmtpServer -BodyAsHtml -Body \"$msg\"\n }\n add-content \"$lanStorage\\Get-TSAdmin_Usage-Log.txt\" -value \"[$(Get-Date -Format 'yyyy/MM/dd HH:mm:ss')] $(whoami) - $($version) Compare-Sessions - $title\"\n }\n\n\n############################################### Zone GUI / Interface - formulaire ###############################################\n\n#requires -version 2\n\nAdd-Type -AssemblyName 'System.Drawing'\nAdd-Type -AssemblyName 'System.Windows.Forms'\n[System.Windows.Forms.Application]::EnableVisualStyles()\n\n# permet de faire les requette serveur apres ouverture du formulaire\n $timerOnload = New-Object System.Windows.Forms.Timer \n $timerOnload.Interval = 500\n $timerOnload.add_Tick({\n Refresh-Tabs\n\n $script:currentRunner = (whoami | Get-QADUser).email\n\n $edit.Text = \"Edit Mode, with email return ($($script:currentRunner))\"\n $timerOnload.Enabled = $false\n })\n $timerOnload.Enabled = $true\n $timerOnload.Start()\n# \n\n#region $SrvForm\n$SrvForm = New-Object -TypeName 'System.Windows.Forms.Form'\n$SrvForm.Name = 'SrvForm'\n$SrvForm.MaximumSize = New-Object -TypeName 'System.Drawing.Size' -ArgumentList @(0, 1200)\n$SrvForm.MinimumSize = New-Object -TypeName 'System.Drawing.Size' -ArgumentList @(670, 180)\n$SrvForm.Size = New-Object -TypeName 'System.Drawing.Size' -ArgumentList @(670, 350)\n$SrvForm.Padding = New-Object -TypeName 'System.Windows.Forms.Padding' -ArgumentList @(1,1,1,0)\n$SrvForm.KeyPreview = $True\n$SrvForm.Add_KeyDown({ if ($_.KeyCode -eq 'Escape') {$SrvForm.Close()} })\n$SrvForm.Add_KeyDown({ if ($_.KeyCode -eq 'F5') {\n Refresh-Tabs\n }\n })\n$icon1 = & {\n $iconString = 'AAABAAEAJCEAAAEAGAAcDwAAFgAAACgAAAAkAAAAQgAAAAEAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACGhoaTk5OZmZmdnZ2enp6bm5sAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPT0+QkJCenp6AgIAAAAAAAAAAAAAAAAAAAACOjo6cnJyrq6u3t7e7u7u4uLiysrKurq6hoaGIiIgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABxcXGrq6vPz8/b29u5ubmLi4sAAAAAAAAAAACFhYWcnJy2trbLy8vX19fb29vZ2dnU1NTMzMzCwsKjo6OQkJCFhYUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAgIAAABnZ2eoqKi6urrQ0NDf39/c3Ny8vLyHh4cAAAAAAACcnJy3t7d+fn5dXV11dXXp6env7+/s7Ozm5ube3t7KysqqqqqXl5eKiooAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABOTk6ampqoqKi4uLjHx8fOzs7e3t7c3NzGxsaoqKiRkZGmpqZwcHAAAAAAAAAAAADc3Nz8/Pz5+fn39/fx8fHl5eXDw8Ovr6+Xl5eGhoYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWFhaEhISbm5unp6e0tLS8vLzDw8PLy8vZ2dng4ODQ0NC9vb1WVlZmZmZJSUlAQECFhYX8/Pz////////9/f37+/v29vbT09PDw8OsrKyNjY0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAbGxuFhYWenp6jo6OsrKy0tLS7u7vCwsLHx8fPz8/V1dVKSkqKiorQ0NDo6Oj29vb+/v7////////////////+/v79/f3f39/Q0NC0tLQYGBh+fn7IyMimpqYAAAAAAAAAAAAAAAAAAAAAAAAAAAADAwNPT0+MjIympqagoKCUlJSVlZWqqqqioqJbW1u2tra2trbX19ft7e37+/v////////////////////////////l5eXb29s2NjasrKz////4+Pjo6OjExMQAAAAAAAAAAAA5OTnAwMDa2trFxcWgoKBfX19MTExTU1NaWlp2dnaTk5M7OzuxsbGzs7O5ubnMzMzx8fH09fTk5OT////////////////////////k5OTCwsIuLi7////////q6uro6Ojd3d2Ojo4AAAAAAABoaGjU1NTg29vw9PXs8vLo7Ozf4OHU1NTJycm6urq0tLRUVFSdnZ2urq6zs7PS0tLs7OzT09P5+/v1+Pn3+/z8///////////////j4+OqqqpLS0v////9/f3m5ubo6Ojo6OiysrIAAAAAAAB2dnbW2dmsaGKMDQCqPy7CcWPVpJvcv7nbyMTd09He3t/c4OFZWlq0tre7vb7T09P09PT////hwrrlnovSg2i7aki/i3TXyMHx9fbl5+ifn6A5OTn////6+vrn5+fo6Ojq6uq9vb0AAAAAAACBgYHY3NytWlCdHQemIAiuJAizJgm3LA68Oh3ARivCUDbHa1WrdGacUTepXkCsmJD3+/zh0s7urZ3suqrVlXe9ZTWxSxKwQwusRhWtYD2MYU4IBwf39/f+/v7n5+fo6Ojn5+exsbEAAAAAAACLi4va39+uSDisKRCyKAy2Kgy7MhO7Lg3ANxfCORjEOhrEOhm/OBSyRROySxauTh3CpJbfppHz0Mfs0MXVpYe9cT2yWRyyWByyVhuyUhmkRhUNDAuZmZn////u7u7o6OjY2NiXl5cAAAAJCQmRkZHc4+WxNx+3Mxe5LhC6LA2/NBPDORnENRPJQSDKQiDLQyLGQx+ySheyVRqzWR7Hek3it6Ly39rs187VqYq9dD+yXB2yXB2yWR2yVhu3ThZpKA0ZGxzb29v////19fXNzc0AAAAAAABFRUWVlZXc5ea1Kg29Ox6+Nhi+Lw3DMxDKRSPIOBPORSLPSifRSyjKSiSySxeyVhuzXSDGhVniv6vy497s1szVpoi9cT2yWRyyVhuyUhmySRKrUCe7o5mUlZYeHh62trbj4+MAAAAAAAAAAABjY2OdnZ3Y1NS6LA3DQiXFQCDDMg7HMg7ORCLRSCXPORLWUS3XUi/SUCuzRBOzTRazVh3GfVPjs5/z1MzsxrrVmXq9ZjWxShKvTBm6bUnStKjs8vXf4ODR0dDAwMChoaHNzc0AAAAAAAAAAABoaGipqqrSvbi/NhfHSSvLSSrHNBDLNg/PORPZWDXVQBjYSiLeWjbeWjbMVjOgUS+tRRTDYzvckXjqq5zkn4zMfGC2aEjDlIDq39r7+fn////7+/vb29vKysqysrK5ubnDw8MAAAAAAAAAAABpaWm1trfNopnFQiTMTzLQUzTMOhXPOBDSORDbUy7fWzbbPhPiXjjjYj3jYj2qrK3Ey87Y3+Ln7O7w9fbx9vf4/f/////////////////+/v75+fnW1tbDw8OlpaXHx8eurq4AAAAAAAAAAABpaWnAwsPKiXvLTjDQVTfTWTrUSSXTOQ/XPBHdSyLkZD/jUSfiRxroakXnaES/i3zBwcHd3d3w8PD6+vr+/v7////+/v7////+/v79/f36+vrv7+/MzMy3t7eRkZHl5eW8vLwAAAAAAAAAAABqamrLzs/Icl7QWDvTWz7YXz/aXDrWOQ7bPhLfQhXpa0bqaUPmRBLqXzXscErZeFyvrq7Nzc3j4+Px8fH4+Pj7+/v8/Pz7+/v6+vr29vbw8PDa2tq6urqcnJzf39/Nzc0AAAAAAAAAAAA8PDxsbGzU2NnHYEjTYETXYUTbZUbfaknaQRXfQBLiQRHrYDbwdlHuYTbsSRfwdlHudlG1kIW1tbXPz8/g4ODp6enu7u7v7+/v7+/r6+vm5ubc3Ny7u7uYmJjOzs7Ly8sAAAAAAAAAAAAAAABYWFhycnLY29vJWD3VZkvaZ0rdakvibk7gTyXiQRPmRBTrSRjze1X2fFbyUB7xWiryflrve1ixkYiurq7JycnT09PY2Nja2trZ2dnW1tbOzs6lpaVdXV1WVlbY2NgAAAAAAAAAAAAAAAAAAABdXV2BgYHU0tLMWj7YbFHcbVDfcFHkclPkXznkQxPpRhTuSBT2cEX5glv5b0P0TBb0c0rygF7rfl12Sj1PT0+VlZW9vb3ExMS3t7eDg4M3NzcODg4MDAwQEBACAgIAAAAAAAAAAAAAAAAAAABfX1+Ojo7RyMfOY0jZcFbdclXhdFfld1nnbUnlRRTqRxTwSRX2YC/8iGL9imT4ViHzVSPziGbwhGTsg2SrYEoxGxYSCggIBQUCAQEHAwIgISEbGxscHBwAAAAAAAAAAAAAAAAAAAAAAAAAAABfX1+YmJjOv7vSa1LadFvfd1ziel3mfV/pelvlRRfqRxTwShX2Thf8jGj+jmn7hl/xRxHwaD3xi2ztiGrqhmrlhGrPeWTBc1+6YUqGSzy6vLwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABbW1ukpKTMtrHUcVnbeGDfe2LjfmPngWXqhmnmTSDpRRPuSRXzSBL4b0P7knD4j2/yYjTrRhTvgmHtjHDqi3DninHkiXHgiXLZaE2KWkzCxMUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABWVlaxsLHKsKrWdl/cfWXgf2fjgmjnhmrqiW3oZ0LmQhDqRxTuSRXxSxb4knL2k3TziGboQxHnWjHtk3jqj3bnj3fkjnfijXjWX0KLbmXBwsMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABcXFy7u7vKrKbWd2HcgmvghGzjhm7niW/pjHHrhmniPg7nRRTqRhTsSBXye1b0lnjzmn/qaELfOgrnd1jqln7nk3zkkX3ikn7TVDaNhYG/wMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABkZGS/v7/KpZ3We2bdhnHgiHLjinTmjXXoj3brk3rgSBziQhPlRBTnRBTrXzXymX7xmX/vlnzfSB3ZQhfnj3fnloHlloLil4TLRieRmpm+vr4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABqamrBw8TIkYXUcVrafGXegGnhhG3kiXHojXXrk3riXDbfQBLhQRPiQhPiQRLvmIDvn4junojkclLVOhDbZETnn4zlnIrjm4q2Qyijqam7u7sAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABtbW3Fx8e3nJaobmCpaVisYk+uXEawVT2zTzS1SSq1PBm3MQrCMwrNNgvWNgjhSR7mWjPlYTzjZ0bTMwjOMAjccVbdfmfcgmyiOyK1urm3t7cAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABsbGzAwMDMzc7O0tLQ1NTT19jU2dvW3N7Y3+Hb4uTc5efd5unV3uDM1tjEzs+8xce3vLy2sK20paC0npeylIuthnuqe26nb2KOZlrJy8uysrIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABRUVGwsLCxsbGqqqqmpqasrKyxsbG3t7e8vLzAwMDExMTIyMjLy8vPz8/S0tLV1dXX2NjV1tbT1NTS09TR0tLO0NDMzc7KzMzJysvExMSzs7MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///f/8AAAAP+fwD/wAAAA/g+AD/AAAAD8B4AH8AAAAPgBAAPwAAAA+AAAAfAAAADwAAAAMAAAAPwAAAAQAAAA4AAAABAAAADAAAAAAAAAAMAAAAAAAAAAwAAAABAAAADAAAAAEAAAAMAAAAAQAAAAwAAAADAAAADAAAAAMAAAAIAAAABwAAAAgAAAAHAAAACAAAAAcAAAAIAAAADwAAAAgAAAAfAAAACAAAAB8AAAAIAAAAPwAAAAgAAAD/AAAACAAAAf8AAAAIAAAB/wAAAAgAAAH/AAAAAAAAAf8AAAAAAAAB/wAAAAAAAAH/AAAAAAAAA/8AAAAAAAAD/wAAAA/8AAP/AAAAA='\n $iconStream = New-Object -TypeName 'System.IO.MemoryStream' -ArgumentList @(,([System.Convert]::FromBase64String($iconString)))\n $icon = New-Object -TypeName 'System.Drawing.Icon' -ArgumentList $iconStream\n $iconStream.Dispose()\n return $icon\n}\n$SrvForm.text = \"$SessionName2 vs $SessionName1\"\n$SrvForm.Icon = $icon1\n$SrvForm.Topmost = $True\n$SrvForm.Topmost = $false\n\n$SrvForm.SuspendLayout()\n\n #region $groupBox1\n $groupBox1 = New-Object -TypeName 'System.Windows.Forms.GroupBox'\n $groupBox1.Text = 'Comparatif des groupes (direct)'\n $groupBox1.Dock = [System.Windows.Forms.DockStyle]::Fill\n $groupBox1.SuspendLayout()\n\n #region $Grille\n $Grille = New-Object -TypeName 'System.Windows.Forms.DataGridView'\n $Grille.Name = 'Grille'\n $Grille.Dock = [System.Windows.Forms.DockStyle]::Fill\n $Grille.ReadOnly = $true\n $Grille.SelectionMode = [System.Windows.Forms.DataGridViewSelectionMode]::FullRowSelect\n $Grille.RowHeadersVisible = $false\n $Grille.AllowUserToAddRows = $false\n $Grille.AllowUserToResizeRows = $false\n $Grille.AllowUserToDeleteRows = $false\n $Grille.PerformLayout()\n\n #endregion $Grille\n\n [System.Void]$groupBox1.Controls.Add($Grille)\n\n #region $aide\n $aide = New-Object -TypeName 'System.Windows.Forms.Label'\n $aide.Name = 'aide'\n $aide.Text = 'Double-click sur un groupe ajoute ou supprime le groupe pour cet utilisateurs'\n $aide.Visible = $false\n $aide.ForeColor = [System.Drawing.Color]::Red\n $aide.Dock = [System.Windows.Forms.DockStyle]::Bottom\n $aide.TextAlign = [System.Drawing.ContentAlignment]::MiddleRight\n #endregion $aide\n\n [System.Void]$groupBox1.Controls.Add($aide)\n\n $groupBox1.ResumeLayout($false)\n $groupBox1.PerformLayout()\n #endregion $groupBox1\n\n [System.Void]$SrvForm.Controls.Add($groupBox1)\n\n #region $panel1\n $panel1 = New-Object -TypeName 'System.Windows.Forms.Panel'\n $panel1.Size = New-Object -TypeName 'System.Drawing.Size' -ArgumentList @(0, 30)\n $panel1.Padding = New-Object -TypeName 'System.Windows.Forms.Padding' -ArgumentList @(4)\n $panel1.Dock = [System.Windows.Forms.DockStyle]::Bottom\n $panel1.SuspendLayout()\n\n #region $edit\n $edit = New-Object -TypeName 'System.Windows.Forms.CheckBox'\n $edit.Name = 'edit'\n $edit.Text = 'Mode Edition, avec retour par email de chaque modif'\n $edit.Checked = $false\n $edit.Width = 480\n $edit.Dock = [System.Windows.Forms.DockStyle]::Left\n #endregion $edit\n\n [System.Void]$panel1.Controls.Add($edit)\n\n #region $button1\n $button1 = New-Object -TypeName 'System.Windows.Forms.Button'\n $button1.Text = 'Retour Email complet'\n $button1.Width = 150\n $button1.Dock = [System.Windows.Forms.DockStyle]::Right\n #endregion $button1\n\n [System.Void]$panel1.Controls.Add($button1)\n\n $panel1.ResumeLayout($false)\n $panel1.PerformLayout()\n #endregion $panel1\n\n [System.Void]$SrvForm.Controls.Add($panel1)\n\n #region $statusStrip1\n $statusStrip1 = New-Object -TypeName 'System.Windows.Forms.StatusStrip'\n $statusStrip1.SuspendLayout()\n\n #region $LabelVersion\n $LabelVersion = New-Object -TypeName 'System.Windows.Forms.ToolStripStatusLabel'\n $LabelVersion.Text = 'V0.00'\n $LabelVersion.Spring = $true\n $LabelVersion.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft\n #endregion $LabelVersion\n\n [System.Void]$statusStrip1.Items.Add($LabelVersion)\n\n #region $loadBar\n $loadBar = New-Object -TypeName 'System.Windows.Forms.ToolStripProgressBar'\n $loadBar.Style = [System.Windows.Forms.ProgressBarStyle]::Continuous\n $loadBar.Value = 100\n $loadBar.Visible = $true\n #endregion $loadBar\n\n [System.Void]$statusStrip1.Items.Add($loadBar)\n\n $statusStrip1.ResumeLayout($false)\n $statusStrip1.PerformLayout()\n #endregion $statusStrip1\n\n [System.Void]$SrvForm.Controls.Add($statusStrip1)\n\n############################################### Zone personalisation du formilaire ##############################################\n\n$LabelVersion.Text = \"[PID:$pid] $($script:MyInvocation.MyCommand) - V $Version\"\n\n$button1.add_click({\n retour-email -title \"$SessionName2 vs $SessionName1\" -msg (Get-vsGrps | ConvertTo-Html)\n })\n\n$Grille.add_DoubleClick({\n Toggle-group\n })\n\n$Grille.add_ColumnHeaderMouseClick({\n Find-DataGridViewValue -DataGridView $Grille -Value '==' -FindingColumns '#' -RowForeColor Gray\n Find-DataGridViewValue -DataGridView $Grille -Value '=>' -FindingColumns '#' -RowForeColor Green\n })\n\n$edit.Add_CheckStateChanged({\n $aide.visible = $edit.Checked\n })\n\n$SrvForm.ResumeLayout($false)\n$SrvForm.PerformLayout()\n#endregion $SrvForm\n\n#region GUI Startup\n$SrvForm.ShowDialog()\n#endregion GUI Startup\n\n#$powershell.Dispose()\n#$runspace.close()\n$timerOnload.stop()\n\nGet-vsGrps\n" }, { "answer_id": 46814742, "author": "JamieSee", "author_id": 1015164, "author_profile": "https://Stackoverflow.com/users/1015164", "pm_score": 0, "selected": false, "text": "Get-QADUser # Compare the group memberships of 2 Active Directory Users or the user memberships of 2 Active Directory Groups.\n# Requires the ActiveDirectory PowerShell module from the Microsoft's Remote Server Administration Tools.\n\nImport-Module ActiveDirectory\n\nfunction Get-ComparisonResult ($name1, $name2, $sideIndicator)\n{\n $comparisonResult = $null\n\n switch ($_.SideIndicator)\n {\n '<=' { $comparisonResult = \"$($name1) Only\" }\n '==' { $comparisonResult = \"$($name1) and $($name2)\" }\n '=>' { $comparisonResult = \"$($name2) Only\" }\n }\n\n return $comparisonResult\n}\n\nfunction Compare-ADUserGroupMembership($userName1, $userName2)\n{\n $userComparisonResultColumn = @{ name = 'Comparison Result'; expression = { Get-ComparisonResult $user1.DisplayName $user2.DisplayName $_.SideIndicator } }\n $groupNameColumn = @{ name = 'Group Name'; expression = { (Get-ADGroup $_.InputObject).Name } }\n\n $user1 = Get-ADUser $userName1 -Properties memberOf, displayName\n $user2 = Get-ADUser $userName2 -Properties memberOf, displayName\n\n $userGroupComparison = Compare-Object -IncludeEqual $user1.MemberOf $user2.MemberOf | Select $userComparisonResultColumn, $groupNameColumn\n\n return $userGroupComparison\n}\n\nfunction Compare-ADGroupMembership($groupName1, $groupName2)\n{\n $groupComparisonResultColumn = @{ name = 'Comparison Result'; expression = { Get-ComparisonResult $groupName1 $groupName2 $_.SideIndicator } }\n $userNameColumn = @{ name = 'User Name'; expression = { $_.InputObject.name } }\n\n $groupMembers1 = Get-ADGroupMember $groupName1\n $groupMembers2 = Get-ADGroupMember $groupName2\n\n $groupMemberComparison = Compare-Object -IncludeEqual $groupMembers1 $groupMembers2 | Select $groupComparisonResultColumn, $userNameColumn\n\n return $groupMemberComparison\n}\n\nCompare-ADUserGroupMembership 'userone' 'usertwo' | ft -AutoSize\nCompare-ADGroupMembership 'Group One' 'Group Two' | ft -AutoSize\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
349,842
<p>I want to do some functional testing on a (restful) webservice. The testsuite contains a bunch of test cases, each of which performs a couple of HTTP requests on the webservice.</p> <p>Naturally, the webservice has to run or the tests will fail. :-)</p> <p>Starting the webservice takes a couple of minutes (it does some heavy data lifting), so I want to start it as infrequently as possible (at least all test cases that only GET resources from the service could share one).</p> <p>So is there a way to do set up me the bomb in a test suite, before the tests are run like in a @BeforeClass method of a test case?</p>
[ { "answer_id": 349863, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 1, "selected": false, "text": "@BeforeSuite @AfterSuite" }, { "answer_id": 352576, "author": "Dan Vinton", "author_id": 21849, "author_profile": "https://Stackoverflow.com/users/21849", "pm_score": 0, "selected": false, "text": "<target name=\"start.webservice\"><!-- starts the webservice... --></target>\n<target name=\"stop.webservice\"><!-- stops the webservice... --></target>\n<target name=\"unit.test\"><!-- just runs the tests... --></target>\n\n<target name=\"run.test.suite\" \n depends=\"start.webservice, unit.test, stop.webservice\"/>\n" }, { "answer_id": 7638935, "author": "Sled", "author_id": 254477, "author_profile": "https://Stackoverflow.com/users/254477", "pm_score": 5, "selected": false, "text": "@ClassRule import org.junit.*;\nimport org.junit.rules.ExternalResource;\nimport org.junit.runners.Suite;\nimport org.junit.runner.RunWith;\n\n\n@RunWith( Suite.class )\n@Suite.SuiteClasses( { \n RuleTest.class,\n} )\npublic class RuleSuite{\n\n private static int bCount = 0;\n private static int aCount = 0;\n\n @ClassRule\n public static ExternalResource testRule = new ExternalResource(){\n @Override\n protected void before() throws Throwable{\n System.err.println( \"before test class: \" + ++bCount );\n sss = \"asdf\";\n };\n\n @Override\n protected void after(){\n System.err.println( \"after test class: \" + ++aCount );\n };\n };\n\n\n public static String sss;\n}\n import static org.junit.Assert.*;\n\nimport org.junit.ClassRule;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.ExternalResource;\n\npublic class RuleTest {\n\n @Test\n public void asdf1(){\n assertNotNull( \"A value should've been set by a rule.\", RuleSuite.sss );\n }\n\n @Test\n public void asdf2(){\n assertEquals( \"This value should be set by the rule.\", \"asdf\", RuleSuite.sss );\n }\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
349,845
<p>Environment: Rails 2.2.2, Oracle 10g</p> <p>Most of the columns declared "date" in my ActiveRecord models are exactly that: dates: they don't care about time at all.</p> <p>So with a model declared thus:#</p> <pre><code>class MyDateOnlyModel &lt; ActiveRecord::Migration def self.up create_table :my_date_only_model do |t| t.date :effective_date t.timestamps end end end </code></pre> <p>writing a test like this:</p> <pre><code>test_date = Date.new(2008,12,05) MyDateOnlyModel.create!(:effective_date =&gt; test_date) assert_equal test_date, MyDateOnlyModel.find(:first).effective_date </code></pre> <p>should pass, shouldn't it? (Assuming I didn't mess anything up transcribing the above, of course)</p> <p>But it doesn't - not quite. I get this:</p> <pre><code>&lt;Fri, 05 Dec 2008&gt; expected but was &lt;Fri, 05 Dec 2008 00:00:00 UTC +00:00&gt;. </code></pre> <p>So I put a date into the database and got ... well what <em>did</em> I get?</p> <pre><code>puts MyDateOnlyModel.find(:first).eff_date.class </code></pre> <p>tells me I actually got a <code>ActiveSupport::TimeWithZone</code>. Which wasn't what I wanted at all.</p> <p>Is there a simple way to tell ActiveRecord that some (not all) columns are <code>Date</code>s and only <code>Date</code>s?</p> <p>UPDATE: more complaining...</p> <p>Yes, I could use to_date:</p> <pre><code>assert_equal test_date, MyDateOnlyModel.find(:first).effective_date.to_date </code></pre> <p>works fine. But that's what I'm trying to avoid. I asked AR to make me a date, I want a date back.</p> <p>And I could add a method to my class, effective_date_as_date - that works too. But surely it's not impossible to just get a date, dagnabbit.</p> <p><strong>PRE-ACCEPTANCE UPDATE</strong></p> <p>Eventually I realised why this was a particular problem with Oracle: there is no distinction between DATE and DATETIME, so ActiveRecord can't figure out unaided whether a time of zero means midnight (possibly with time zone corrections) or just the date. Bah. Stupid Oracle. So I'm going to have either to go down the plugin route, change my database (tempting, so very tempting) or continue with the to_date/to_time mess I have at present.</p>
[ { "answer_id": 349863, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 1, "selected": false, "text": "@BeforeSuite @AfterSuite" }, { "answer_id": 352576, "author": "Dan Vinton", "author_id": 21849, "author_profile": "https://Stackoverflow.com/users/21849", "pm_score": 0, "selected": false, "text": "<target name=\"start.webservice\"><!-- starts the webservice... --></target>\n<target name=\"stop.webservice\"><!-- stops the webservice... --></target>\n<target name=\"unit.test\"><!-- just runs the tests... --></target>\n\n<target name=\"run.test.suite\" \n depends=\"start.webservice, unit.test, stop.webservice\"/>\n" }, { "answer_id": 7638935, "author": "Sled", "author_id": 254477, "author_profile": "https://Stackoverflow.com/users/254477", "pm_score": 5, "selected": false, "text": "@ClassRule import org.junit.*;\nimport org.junit.rules.ExternalResource;\nimport org.junit.runners.Suite;\nimport org.junit.runner.RunWith;\n\n\n@RunWith( Suite.class )\n@Suite.SuiteClasses( { \n RuleTest.class,\n} )\npublic class RuleSuite{\n\n private static int bCount = 0;\n private static int aCount = 0;\n\n @ClassRule\n public static ExternalResource testRule = new ExternalResource(){\n @Override\n protected void before() throws Throwable{\n System.err.println( \"before test class: \" + ++bCount );\n sss = \"asdf\";\n };\n\n @Override\n protected void after(){\n System.err.println( \"after test class: \" + ++aCount );\n };\n };\n\n\n public static String sss;\n}\n import static org.junit.Assert.*;\n\nimport org.junit.ClassRule;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.ExternalResource;\n\npublic class RuleTest {\n\n @Test\n public void asdf1(){\n assertNotNull( \"A value should've been set by a rule.\", RuleSuite.sss );\n }\n\n @Test\n public void asdf2(){\n assertEquals( \"This value should be set by the rule.\", \"asdf\", RuleSuite.sss );\n }\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1060/" ]
349,852
<p>I'm extracting an interface that I would like to retain the original name. The actual class will get a "Impl" suffix, in accordance with our naming conventions. I want to know how to best reflect that in subversion so that the history "AppPropertiesImpl.java" covers its life as "AppProperties.java". As for the new "AppProperties.java", I'm thinking it could be either a new file or a copy of the old. Any idea how to pull this off?</p> <p>Here's what I have now:</p> <p>AppProperties.java</p> <pre><code>public class AppProperties { public static final CONSTANT_ONE = "CONSTANT_ONE"; private String propertyOne; public String getPropertyOne() { return propertyOne; } public String setPropertyOne(String propertyOne) { this.propertyOne = propertyOne; } } </code></pre> <p>And I want to end up with:</p> <p>AppProperties.java</p> <pre><code>public interface AppProperties { public static final CONSTANT_ONE = "CONSTANT_ONE"; String getPropertyOne(); String setPropertyOne(String propertyOne); } </code></pre> <p>AppPropertiesImpl.java</p> <pre><code>public class AppPropertiesImpl implements AppProperties { private String propertyOne; public String getPropertyOne() { return propertyOne; } public String setPropertyOne(String propertyOne) { this.propertyOne; } } </code></pre>
[ { "answer_id": 349863, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 1, "selected": false, "text": "@BeforeSuite @AfterSuite" }, { "answer_id": 352576, "author": "Dan Vinton", "author_id": 21849, "author_profile": "https://Stackoverflow.com/users/21849", "pm_score": 0, "selected": false, "text": "<target name=\"start.webservice\"><!-- starts the webservice... --></target>\n<target name=\"stop.webservice\"><!-- stops the webservice... --></target>\n<target name=\"unit.test\"><!-- just runs the tests... --></target>\n\n<target name=\"run.test.suite\" \n depends=\"start.webservice, unit.test, stop.webservice\"/>\n" }, { "answer_id": 7638935, "author": "Sled", "author_id": 254477, "author_profile": "https://Stackoverflow.com/users/254477", "pm_score": 5, "selected": false, "text": "@ClassRule import org.junit.*;\nimport org.junit.rules.ExternalResource;\nimport org.junit.runners.Suite;\nimport org.junit.runner.RunWith;\n\n\n@RunWith( Suite.class )\n@Suite.SuiteClasses( { \n RuleTest.class,\n} )\npublic class RuleSuite{\n\n private static int bCount = 0;\n private static int aCount = 0;\n\n @ClassRule\n public static ExternalResource testRule = new ExternalResource(){\n @Override\n protected void before() throws Throwable{\n System.err.println( \"before test class: \" + ++bCount );\n sss = \"asdf\";\n };\n\n @Override\n protected void after(){\n System.err.println( \"after test class: \" + ++aCount );\n };\n };\n\n\n public static String sss;\n}\n import static org.junit.Assert.*;\n\nimport org.junit.ClassRule;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.ExternalResource;\n\npublic class RuleTest {\n\n @Test\n public void asdf1(){\n assertNotNull( \"A value should've been set by a rule.\", RuleSuite.sss );\n }\n\n @Test\n public void asdf2(){\n assertEquals( \"This value should be set by the rule.\", \"asdf\", RuleSuite.sss );\n }\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4893/" ]
349,855
<p>I want to automate the process of gathering code metrics on a .NET solution. Is there any way of getting msbuild to run the Code Metrics feature included in VS2008 Development Edition? </p> <p>I may end up using <a href="http://www.campwoodsw.com/sourcemonitor.html" rel="noreferrer">SourceMonitor</a>, but I would like to know if there is a way to use the VS code metrics engine from the command line.</p>
[ { "answer_id": 422171, "author": "shackett", "author_id": 52194, "author_profile": "https://Stackoverflow.com/users/52194", "pm_score": 3, "selected": false, "text": " \n\n<!-- The directory where FxCop is installed. -->\n<FxCopDirectory>C:\\Program Files\\Microsoft FxCop 1.36</FxCopDirectory>\n\n<!-- The FxCop console executable.. -->\n<FxCopCmd>$(FxCopDirectory)\\FxCopCmd</FxCopCmd>\n\n<Target Name=\"CodeAnalysis>\n<!-- Once to get XML for metrics. -->\n<Exec Command=\"&quot;$(FxCopCmd)&quot; /p:&quot;$(BuildDirectory)\\FxCop\\RuleSet.FxCop&quot; /out:$(BuildResults)\\FxCop.xml /summary /verbose /f:$(Binaries)\\@(CodeAnalysis, ' /f:$(Binaries)\\')\" />\n\n<!-- Once to report with the build results. -->\n<Exec Command=\"&quot;$(FxCopCmd)&quot; /p:&quot;$(BuildDirectory)\\FxCop\\RuleSet.FxCop&quot; /out:$(BuildResults)\\FxCop.html /summary /verbose /applyoutXsl:$(MSBuildTasks)\\CodeAnalysisReport.xsl /f:$(Binaries)\\@(CodeAnalysis, ' /f:$(Binaries)\\')\" />\n\n<!-- Update the FxCop report so that it is fully expanded by default. -->\n<FileUpdate Regex=\"&lt;body\\s\"\n ReplacementText=\"&lt;body onLoad=&quot;ExpandAll();&quot; \"\n Files=\"$(BuildResults)\\FxCop.html\" />\n</Target>\n\n\n <!-- The directory where FxCop is installed. -->\n<FxCopDirectory>C:\\Program Files\\Microsoft FxCop 1.36</FxCopDirectory>\n\n<!-- The FxCop console executable.. -->\n<FxCopCmd>$(FxCopDirectory)\\FxCopCmd</FxCopCmd>\n\n<Target Name=\"CodeAnalysis>\n<!-- Once to get XML for metrics. -->\n<Exec Command=\"&quot;$(FxCopCmd)&quot; /p:&quot;$(BuildDirectory)\\FxCop\\RuleSet.FxCop&quot; /out:$(BuildResults)\\FxCop.xml /summary /verbose /f:$(Binaries)\\@(CodeAnalysis, ' /f:$(Binaries)\\')\" />\n\n<!-- Once to report with the build results. -->\n<Exec Command=\"&quot;$(FxCopCmd)&quot; /p:&quot;$(BuildDirectory)\\FxCop\\RuleSet.FxCop&quot; /out:$(BuildResults)\\FxCop.html /summary /verbose /applyoutXsl:$(MSBuildTasks)\\CodeAnalysisReport.xsl /f:$(Binaries)\\@(CodeAnalysis, ' /f:$(Binaries)\\')\" />\n\n<!-- Update the FxCop report so that it is fully expanded by default. -->\n<FileUpdate Regex=\"&lt;body\\s\"\n ReplacementText=\"&lt;body onLoad=&quot;ExpandAll();&quot; \"\n Files=\"$(BuildResults)\\FxCop.html\" />\n</Target>\n /// <summary>\n/// Gather metrics for code analysis.\n/// </summary>\nprivate static void GatherCodeAnalysisMetrics()\n{\n string file = @\"$(BuildResults)\\FxCop.xml\";\n if (!File.Exists(file)) return;\n System.Xml.XmlDocument document = new System.Xml.XmlDocument();\n document.Load(file);\n System.Xml.XmlNodeList list = document.SelectNodes(\"//Message\");\n codeAnalysisWarnings = list.Count;\n\n Console.WriteLine(\"Code analysis warnings: \" + codeAnalysisWarnings);\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7532/" ]
349,858
<p>I'm trying to get a UIDatePicker with a UIButton to show up in a UIActionSheet. Unfortunately it gets cropped off and the entire Date Picker is not visible. I have not even attempted to add the UIButton yet. Can anyone suggest on getting the entire view to fit properly? I'm not sure how to add the proper dimensions as UIActionSheet seems to lack an <code>-initWithFrame:</code> type constructor.</p> <pre><code>UIActionSheet *menu = [[UIActionSheet alloc] initWithTitle:@"Date Picker" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:nil]; // Add the picker UIDatePicker *pickerView = [[UIDatePicker alloc] init]; pickerView.datePickerMode = UIDatePickerModeDate; [menu addSubview:pickerView]; [menu showInView:self.view]; [pickerView release]; [menu release]; </code></pre> <p>I've also tried with something similar to:</p> <pre><code>UIActionSheet *menu = [[UIActionSheet alloc] initWithFrame:CGRectMake(200.0, 200.0, 100.0f, 100.0f)]; </code></pre> <p>The coords are ofcourse not realistic, but they don't seem to affect the position/size of the UIActionSheet.</p>
[ { "answer_id": 353779, "author": "thbonk", "author_id": 44123, "author_profile": "https://Stackoverflow.com/users/44123", "pm_score": 6, "selected": true, "text": " UIActionSheet *menu = [[UIActionSheet alloc] initWithTitle:@\"Date Picker\" \n delegate:self\n cancelButtonTitle:@\"Cancel\"\n destructiveButtonTitle:nil\n otherButtonTitles:nil];\n\n // Add the picker\n UIDatePicker *pickerView = [[UIDatePicker alloc] init];\n pickerView.datePickerMode = UIDatePickerModeDate;\n [menu addSubview:pickerView];\n [menu showInView:self.view]; \n [menu setBounds:CGRectMake(0,0,320, 500)];\n\n CGRect pickerRect = pickerView.bounds;\n pickerRect.origin.y = -100;\n pickerView.bounds = pickerRect;\n\n [pickerView release];\n [menu release];\n" }, { "answer_id": 1530259, "author": "Ajay Sawant", "author_id": 185463, "author_profile": "https://Stackoverflow.com/users/185463", "pm_score": 4, "selected": false, "text": "[menu sendSubviewToBack:pickerView];\n" }, { "answer_id": 2676583, "author": "Oscar Peli", "author_id": 310826, "author_profile": "https://Stackoverflow.com/users/310826", "pm_score": 3, "selected": false, "text": "NSString *title = UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation) ? @\"\\n\\n\\n\\n\\n\\n\\n\\n\\n\" : @\"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\" ;\nUIActionSheet *actionSheet = [[UIActionSheet alloc] \n initWithTitle:[NSString stringWithFormat:@\"%@%@\", title, NSLocalizedString(@\"SelectADateKey\", @\"\")]\n delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@\"Ok\", nil];\n[actionSheet showInView:self.view];\nUIDatePicker *datePicker = [[[UIDatePicker alloc] init] autorelease];\ndatePicker.datePickerMode = UIDatePickerModeDate;\n[actionSheet addSubview:datePicker];\n" }, { "answer_id": 3185950, "author": "Dmitry", "author_id": 145792, "author_profile": "https://Stackoverflow.com/users/145792", "pm_score": 3, "selected": false, "text": " UIActionSheet *menu = [[UIActionSheet alloc] initWithTitle:@\"Date Picker\" \n delegate:self\n cancelButtonTitle:@\"Cancel\"\n destructiveButtonTitle:nil\n otherButtonTitles:@\"OK\",nil]; \n// Add the picker\nUIDatePicker *pickerView = [[UIDatePicker alloc] init];\npickerView.datePickerMode = UIDatePickerModeTime;\n[menu addSubview:pickerView];\n[menu showInView:_mainView]; \n\nCGRect menuRect = menu.frame;\nmenuRect.origin.y -= 214;\nmenuRect.size.height = 300;\nmenu.frame = menuRect;\n\n\nCGRect pickerRect = pickerView.frame;\npickerRect.origin.y = 174;\npickerView.frame = pickerRect;\n\n[pickerView release];\n[menu release]; \n" }, { "answer_id": 3447813, "author": "Stefan", "author_id": 141281, "author_profile": "https://Stackoverflow.com/users/141281", "pm_score": 2, "selected": false, "text": "\n[actionSheet showInView:self.parentViewController.tabBarController.view];\n" }, { "answer_id": 3815355, "author": "Jakob Egger", "author_id": 322427, "author_profile": "https://Stackoverflow.com/users/322427", "pm_score": 4, "selected": false, "text": "UIActionSheet *menu = [[UIActionSheet alloc] initWithTitle:@\"Date Picker\" \n delegate:self\n cancelButtonTitle:@\"Cancel\"\n destructiveButtonTitle:nil\n otherButtonTitles:@\"OK\",nil]; \n// Add the picker\nUIDatePicker *pickerView = [[UIDatePicker alloc] init];\npickerView.datePickerMode = UIDatePickerModeTime;\n[menu addSubview:pickerView];\n[menu showInView:_mainView]; \n\nCGRect menuRect = menu.frame;\nCGFloat orgHeight = menuRect.size.height;\nmenuRect.origin.y -= 214; //height of picker\nmenuRect.size.height = orgHeight+214;\nmenu.frame = menuRect;\n\n\nCGRect pickerRect = pickerView.frame;\npickerRect.origin.y = orgHeight;\npickerView.frame = pickerRect;\n\n[pickerView release];\n[menu release]; \n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40882/" ]
349,861
<p>I have a script that animates a small DIV popping up on the page. It all works fine in IE, and in FF if I remove the DOCTYPE, but when the DOCTYPE is XHTML/Transitional, in Firefox, the width does not change. </p> <pre><code>this.container.style.visibility = "visible"; alert("this.container.style.width before = " + this.container.style.width) this.container.style.width = this.width; alert("this.container.style.width after = " + this.container.style.width); this.container.style.height = this.height; </code></pre> <p>In IE, and in FF with no DOCTYPE, the first alert says 0, and the second says 320 (which is the width set elsewhere in the code) </p> <p>in FF, with the DOCTYPE to XHTML/Transitional, both alerts show 0. Any idea what's going on here? I'm thinking I may need to explicitly set positions on the DIVs in Transitional, but I'm not sure. </p>
[ { "answer_id": 349900, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 5, "selected": true, "text": "this.container.style.visibility = \"visible\";\nalert(\"this.container.style.width before = \" + this.container.style.width);\nthis.container.style.width = this.width + 'px';\nalert(\"this.container.style.width after = \" + this.container.style.width);\nthis.container.style.height = this.height + 'px';\n\n//Note the 'px' above\n" }, { "answer_id": 15542162, "author": "user1531241", "author_id": 1531241, "author_profile": "https://Stackoverflow.com/users/1531241", "pm_score": -1, "selected": false, "text": "document.getElementById(\"td\").style.visibility=\"hidden\";\ndocument.getElementById(\"td\").style.display=\"none\";\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8349/" ]
349,875
<p>Is it possible to display the text in a TextBlock vertically so that all letters are stacked upon each other (not rotated with LayoutTransform)?</p>
[ { "answer_id": 349954, "author": "Micah", "author_id": 17744, "author_profile": "https://Stackoverflow.com/users/17744", "pm_score": 4, "selected": false, "text": "<TextBlock TextAlignment=\"Center\" FontSize=\"14\" FontWeight=\"Bold\" Width=\"10\" TextWrapping=\"Wrap\">THIS IS A TEST</TextBlock>\n" }, { "answer_id": 351184, "author": "Christoffer Lette", "author_id": 11808, "author_profile": "https://Stackoverflow.com/users/11808", "pm_score": 2, "selected": false, "text": "TextBlock TextAlignment Center <TextBlock Name=\"textBlock1\" TextAlignment=\"Center\" Text=\"Stacked!\" />\n NewLine textBlock1.Text =\n String.Join(\n Environment.NewLine,\n textBlock1.Text.Select(c => new String(c, 1)).ToArray());\n System.Linq" }, { "answer_id": 351917, "author": "Boyan", "author_id": 38106, "author_profile": "https://Stackoverflow.com/users/38106", "pm_score": 0, "selected": false, "text": "<TextBlock x:Name=\"VertTextBlock\" Text=\"Vertical Text\" Loaded=\"VertTextBlock_Loaded\"></TextBlock>\n TextBlock tb = sender as TextBlock;\nStringBuilder sb = new StringBuilder(tb.Text);\nint len = tb.Text.Length * 2;\n\nfor (int i = 1; i < len; i += 2)\n{\n sb.Insert(i, '\\n');\n}\n\ntb.Text = sb.ToString();\n" }, { "answer_id": 1397748, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<linebreak/> can be used to show data in two lines\n" }, { "answer_id": 2090382, "author": "esko22", "author_id": 253632, "author_profile": "https://Stackoverflow.com/users/253632", "pm_score": 5, "selected": false, "text": " <TabControl TabStripPlacement=\"Left\">\n <TabItem Header=\"Tab 1\">\n <TabItem.LayoutTransform>\n <RotateTransform Angle=\"-90\"></RotateTransform> \n </TabItem.LayoutTransform>\n <TextBlock> Some Text for tab 1</TextBlock>\n </TabItem>\n <TabItem Header=\"Tab 2\">\n <TabItem.LayoutTransform>\n <RotateTransform Angle=\"-90\"></RotateTransform>\n </TabItem.LayoutTransform>\n <TextBlock> Some Text for tab 2</TextBlock>\n </TabItem>\n </TabControl>\n" }, { "answer_id": 2090964, "author": "Ray Burns", "author_id": 199245, "author_profile": "https://Stackoverflow.com/users/199245", "pm_score": 7, "selected": true, "text": "<ItemsControl\n ItemsSource=\"Text goes here, or you could use a binding to a string\" />\n" }, { "answer_id": 3823627, "author": "denis morozov", "author_id": 452941, "author_profile": "https://Stackoverflow.com/users/452941", "pm_score": 1, "selected": false, "text": "<TextBlock TextWrapping=\"Wrap\" MaxWidth=\"8\" TextAlignment=\"Center\" Text=\"stack\" />\n" }, { "answer_id": 3926764, "author": "TWood", "author_id": 368310, "author_profile": "https://Stackoverflow.com/users/368310", "pm_score": 2, "selected": false, "text": "xmlns:s=\"clr-namespace:System;assembly=mscorlib\"\n <s:String x:Key=\"SortString\">Sort</s:String>\n <ItemsControl ItemsSource=\"{Binding Source={StaticResource SortString}}\" Margin=\"5,-1,0,0\" /> \n" }, { "answer_id": 5001446, "author": "Venkat", "author_id": 485221, "author_profile": "https://Stackoverflow.com/users/485221", "pm_score": 2, "selected": false, "text": "<TextBlock Height=\"14\"\n x:Name=\"TextBlock1\"\n Text=\"Vertical Bottom to Up\" Margin=\"73,0,115,0\" RenderTransformOrigin=\"0.5,0.5\" >\n <TextBlock.RenderTransform>\n <TransformGroup>\n <ScaleTransform/>\n <SkewTransform/>\n <RotateTransform Angle=\"-90\"/>\n <TranslateTransform/>\n </TransformGroup>\n </TextBlock.RenderTransform>\n </TextBlock>\n" }, { "answer_id": 12787278, "author": "Ugo Robain", "author_id": 609692, "author_profile": "https://Stackoverflow.com/users/609692", "pm_score": 1, "selected": false, "text": "<ItemsControl Grid.Row=\"1\"\n Grid.Column=\"0\"\n ItemsSource=\"YOUR TEXT HERE\"\n HorizontalAlignment=\"Center\"\n VerticalAlignment=\"Center\">\n\n <ItemsControl.ItemTemplate>\n <DataTemplate>\n <TextBlock Text=\"{Binding}\"\n HorizontalAlignment=\"Center\"/>\n </DataTemplate>\n </ItemsControl.ItemTemplate>\n\n</ItemsControl>\n" }, { "answer_id": 17970665, "author": "lunatix", "author_id": 1556915, "author_profile": "https://Stackoverflow.com/users/1556915", "pm_score": 4, "selected": false, "text": "<Label Grid.Column=\"0\" Content=\"Your Text Here\" HorizontalContentAlignment=\"Center\">\n <Label.LayoutTransform>\n <TransformGroup>\n <RotateTransform Angle=\"90\" />\n <ScaleTransform ScaleX=\"-1\" ScaleY=\"-1\"/>\n </TransformGroup>\n </Label.LayoutTransform>\n</Label>\n" }, { "answer_id": 61056034, "author": "Chelaru Alexandru", "author_id": 13235273, "author_profile": "https://Stackoverflow.com/users/13235273", "pm_score": 0, "selected": false, "text": "<Application x:Class=\"Some.App\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:commands=\"clr-namespace:Deridiam.Helper.Commands\"\n xmlns:i=\"http://schemas.microsoft.com/xaml/behaviors\"\n ShutdownMode=\"OnMainWindowClose\"\n StartupUri=\"Views/MainWindow.xaml\">\n<Application.Resources>\n\n <commands:HorizontalToVertical x:Key=\"HorizontalToVertical_Command\"></commands:HorizontalToVertical>\n\n <ControlTemplate x:Key=\"VerticalCell\" TargetType=\"ContentControl\">\n <TextBlock Text=\"{TemplateBinding Content}\" Foreground=\"Black\"\n TextAlignment=\"Center\" FontWeight=\"Bold\" VerticalAlignment=\"Center\"\n TextWrapping=\"Wrap\" Margin=\"0\" FontSize=\"10\"> \n <i:Interaction.Triggers>\n <i:EventTrigger EventName=\"Loaded\">\n <i:InvokeCommandAction Command=\"{Binding ConvertToVerticalCmd, Source={StaticResource HorizontalToVertical_Command}}\" \n CommandParameter=\"{Binding RelativeSource={RelativeSource AncestorType={x:Type TextBlock}}}\" />\n </i:EventTrigger>\n </i:Interaction.Triggers>\n </TextBlock>\n </ControlTemplate>\n\n</Application.Resources>\n namespace Deridiam.Helper.Commands\n{\npublic class HorizontalToVertical\n{\n private ICommand _convertToVerticalCommand;\n\n public ICommand ConvertToVerticalCmd =>\n _convertToVerticalCommand ?? (_convertToVerticalCommand = new RelayCommand(\n x =>\n {\n var tBlock = x as TextBlock;\n var horizontalText = tBlock.Text;\n tBlock.Text = \"\";\n\n horizontalText.Select(c => c).ToList().ForEach(c =>\n {\n if (c.ToString() == \" \")\n {\n tBlock.Inlines.Add(\"\\n\");\n //tBlock.Inlines.Add(\"\\n\");\n }\n\n else\n {\n tBlock.Inlines.Add((new Run(c.ToString())));\n tBlock.Inlines.Add(new LineBreak());\n }\n\n\n });\n }));\n}\n}\n <ContentControl Width=\"15\" Content=\"Vertical Text\" Template=\"{StaticResource VerticalCell}\">\n</ContentControl>\n" }, { "answer_id": 67739609, "author": "Celso Lívero", "author_id": 5605739, "author_profile": "https://Stackoverflow.com/users/5605739", "pm_score": 0, "selected": false, "text": "<ItemsControl ItemsSource=\"{Binding SomeStringProperty, FallbackValue=Group 1}\" Margin=\"5\"\n TextElement.FontSize=\"16\" \n TextElement.FontWeight=\"Bold\" \n TextBlock.TextAlignment=\"Center\"\n HorizontalAlignment=\"Center\" \n VerticalAlignment=\"Center\" >\n<ItemsControl.ItemsPanel>\n <ItemsPanelTemplate>\n <WrapPanel Orientation=\"Vertical\" />\n </ItemsPanelTemplate>\n</ItemsControl.ItemsPanel>\n<ItemsControl.ItemTemplate>\n <DataTemplate >\n <TextBlock Text=\"{Binding }\" HorizontalAlignment=\"Center\" />\n </DataTemplate>\n</ItemsControl.ItemTemplate>\n" }, { "answer_id": 68094601, "author": "EldHasp", "author_id": 13349759, "author_profile": "https://Stackoverflow.com/users/13349759", "pm_score": -1, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Markup;\n\nnamespace Converters\n{\n [ValueConversion(typeof(object), typeof(string))]\n public class InsertLineBreakConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (parameter != null)\n value = parameter;\n\n if (value == null)\n return null;\n\n if (!(value is string str))\n str = value.ToString();\n\n return string.Join(Environment.NewLine, (IEnumerable<char>) str);\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n\n public static InsertLineBreakConverter Instance { get; } = new InsertLineBreakConverter();\n }\n\n public class InsertLineBreakConverterExtension : MarkupExtension\n {\n public override object ProvideValue(IServiceProvider serviceProvider)\n => InsertLineBreakConverter.Instance;\n }\n}\n <TextBlock Text=\"{Binding Property, Converter={cnvs:InsertLineBreakConverter}}\"/> \n <TextBlock Text=\"{Binding Converter={cnvs:InsertLineBreakConverter}, ConverterParameter='Some Text'}\"/>\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11499/" ]
349,878
<p>OK since I am in a holding pattern on this issue perhaps someone has seen these symptoms and can provide some sage advice. (Note: I have learned only enough Active Directory information to build this feature and I only have read access to the Active Directory.)</p> <p>I updated the company intranet to allow the automatic entry/modification of employee phone/address information; it uses a web service to connect to the company Active Directory so I can call it from multiple locations in the main application. </p> <p>The AD has two domains (A and B) in the same forest. Each domain has an ‘ADS update user’ group and an ‘ADSupdate’ account (which belongs to ‘ADS update user’).</p> <p>Problem: Entries in Domain A update fine for Local Development Servers, Test Servers, and Production Servers. Entries in Domain B update only when run from Local Development Servers. When you run the same code (verified multiple times) on either Test or Production you get a (General access denied error).</p> <p>The domain name is stored in the employee record so the exact same code is called for all employees.</p> <p>All Local Development Servers, Test, and Production servers reside in Domain A.</p> <p>This has the Active Directory Admin for Domain B stumped and to be honest I am thankful that the Local Development Servers are able to update the Active Directory entries in domain B. It proves that the code works at least in one location</p> <p>I have looked at machine permissions, permissions on the group and user, and IIS and I can spot no significant differences. Any help would be appreciated…</p>
[ { "answer_id": 349954, "author": "Micah", "author_id": 17744, "author_profile": "https://Stackoverflow.com/users/17744", "pm_score": 4, "selected": false, "text": "<TextBlock TextAlignment=\"Center\" FontSize=\"14\" FontWeight=\"Bold\" Width=\"10\" TextWrapping=\"Wrap\">THIS IS A TEST</TextBlock>\n" }, { "answer_id": 351184, "author": "Christoffer Lette", "author_id": 11808, "author_profile": "https://Stackoverflow.com/users/11808", "pm_score": 2, "selected": false, "text": "TextBlock TextAlignment Center <TextBlock Name=\"textBlock1\" TextAlignment=\"Center\" Text=\"Stacked!\" />\n NewLine textBlock1.Text =\n String.Join(\n Environment.NewLine,\n textBlock1.Text.Select(c => new String(c, 1)).ToArray());\n System.Linq" }, { "answer_id": 351917, "author": "Boyan", "author_id": 38106, "author_profile": "https://Stackoverflow.com/users/38106", "pm_score": 0, "selected": false, "text": "<TextBlock x:Name=\"VertTextBlock\" Text=\"Vertical Text\" Loaded=\"VertTextBlock_Loaded\"></TextBlock>\n TextBlock tb = sender as TextBlock;\nStringBuilder sb = new StringBuilder(tb.Text);\nint len = tb.Text.Length * 2;\n\nfor (int i = 1; i < len; i += 2)\n{\n sb.Insert(i, '\\n');\n}\n\ntb.Text = sb.ToString();\n" }, { "answer_id": 1397748, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<linebreak/> can be used to show data in two lines\n" }, { "answer_id": 2090382, "author": "esko22", "author_id": 253632, "author_profile": "https://Stackoverflow.com/users/253632", "pm_score": 5, "selected": false, "text": " <TabControl TabStripPlacement=\"Left\">\n <TabItem Header=\"Tab 1\">\n <TabItem.LayoutTransform>\n <RotateTransform Angle=\"-90\"></RotateTransform> \n </TabItem.LayoutTransform>\n <TextBlock> Some Text for tab 1</TextBlock>\n </TabItem>\n <TabItem Header=\"Tab 2\">\n <TabItem.LayoutTransform>\n <RotateTransform Angle=\"-90\"></RotateTransform>\n </TabItem.LayoutTransform>\n <TextBlock> Some Text for tab 2</TextBlock>\n </TabItem>\n </TabControl>\n" }, { "answer_id": 2090964, "author": "Ray Burns", "author_id": 199245, "author_profile": "https://Stackoverflow.com/users/199245", "pm_score": 7, "selected": true, "text": "<ItemsControl\n ItemsSource=\"Text goes here, or you could use a binding to a string\" />\n" }, { "answer_id": 3823627, "author": "denis morozov", "author_id": 452941, "author_profile": "https://Stackoverflow.com/users/452941", "pm_score": 1, "selected": false, "text": "<TextBlock TextWrapping=\"Wrap\" MaxWidth=\"8\" TextAlignment=\"Center\" Text=\"stack\" />\n" }, { "answer_id": 3926764, "author": "TWood", "author_id": 368310, "author_profile": "https://Stackoverflow.com/users/368310", "pm_score": 2, "selected": false, "text": "xmlns:s=\"clr-namespace:System;assembly=mscorlib\"\n <s:String x:Key=\"SortString\">Sort</s:String>\n <ItemsControl ItemsSource=\"{Binding Source={StaticResource SortString}}\" Margin=\"5,-1,0,0\" /> \n" }, { "answer_id": 5001446, "author": "Venkat", "author_id": 485221, "author_profile": "https://Stackoverflow.com/users/485221", "pm_score": 2, "selected": false, "text": "<TextBlock Height=\"14\"\n x:Name=\"TextBlock1\"\n Text=\"Vertical Bottom to Up\" Margin=\"73,0,115,0\" RenderTransformOrigin=\"0.5,0.5\" >\n <TextBlock.RenderTransform>\n <TransformGroup>\n <ScaleTransform/>\n <SkewTransform/>\n <RotateTransform Angle=\"-90\"/>\n <TranslateTransform/>\n </TransformGroup>\n </TextBlock.RenderTransform>\n </TextBlock>\n" }, { "answer_id": 12787278, "author": "Ugo Robain", "author_id": 609692, "author_profile": "https://Stackoverflow.com/users/609692", "pm_score": 1, "selected": false, "text": "<ItemsControl Grid.Row=\"1\"\n Grid.Column=\"0\"\n ItemsSource=\"YOUR TEXT HERE\"\n HorizontalAlignment=\"Center\"\n VerticalAlignment=\"Center\">\n\n <ItemsControl.ItemTemplate>\n <DataTemplate>\n <TextBlock Text=\"{Binding}\"\n HorizontalAlignment=\"Center\"/>\n </DataTemplate>\n </ItemsControl.ItemTemplate>\n\n</ItemsControl>\n" }, { "answer_id": 17970665, "author": "lunatix", "author_id": 1556915, "author_profile": "https://Stackoverflow.com/users/1556915", "pm_score": 4, "selected": false, "text": "<Label Grid.Column=\"0\" Content=\"Your Text Here\" HorizontalContentAlignment=\"Center\">\n <Label.LayoutTransform>\n <TransformGroup>\n <RotateTransform Angle=\"90\" />\n <ScaleTransform ScaleX=\"-1\" ScaleY=\"-1\"/>\n </TransformGroup>\n </Label.LayoutTransform>\n</Label>\n" }, { "answer_id": 61056034, "author": "Chelaru Alexandru", "author_id": 13235273, "author_profile": "https://Stackoverflow.com/users/13235273", "pm_score": 0, "selected": false, "text": "<Application x:Class=\"Some.App\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:commands=\"clr-namespace:Deridiam.Helper.Commands\"\n xmlns:i=\"http://schemas.microsoft.com/xaml/behaviors\"\n ShutdownMode=\"OnMainWindowClose\"\n StartupUri=\"Views/MainWindow.xaml\">\n<Application.Resources>\n\n <commands:HorizontalToVertical x:Key=\"HorizontalToVertical_Command\"></commands:HorizontalToVertical>\n\n <ControlTemplate x:Key=\"VerticalCell\" TargetType=\"ContentControl\">\n <TextBlock Text=\"{TemplateBinding Content}\" Foreground=\"Black\"\n TextAlignment=\"Center\" FontWeight=\"Bold\" VerticalAlignment=\"Center\"\n TextWrapping=\"Wrap\" Margin=\"0\" FontSize=\"10\"> \n <i:Interaction.Triggers>\n <i:EventTrigger EventName=\"Loaded\">\n <i:InvokeCommandAction Command=\"{Binding ConvertToVerticalCmd, Source={StaticResource HorizontalToVertical_Command}}\" \n CommandParameter=\"{Binding RelativeSource={RelativeSource AncestorType={x:Type TextBlock}}}\" />\n </i:EventTrigger>\n </i:Interaction.Triggers>\n </TextBlock>\n </ControlTemplate>\n\n</Application.Resources>\n namespace Deridiam.Helper.Commands\n{\npublic class HorizontalToVertical\n{\n private ICommand _convertToVerticalCommand;\n\n public ICommand ConvertToVerticalCmd =>\n _convertToVerticalCommand ?? (_convertToVerticalCommand = new RelayCommand(\n x =>\n {\n var tBlock = x as TextBlock;\n var horizontalText = tBlock.Text;\n tBlock.Text = \"\";\n\n horizontalText.Select(c => c).ToList().ForEach(c =>\n {\n if (c.ToString() == \" \")\n {\n tBlock.Inlines.Add(\"\\n\");\n //tBlock.Inlines.Add(\"\\n\");\n }\n\n else\n {\n tBlock.Inlines.Add((new Run(c.ToString())));\n tBlock.Inlines.Add(new LineBreak());\n }\n\n\n });\n }));\n}\n}\n <ContentControl Width=\"15\" Content=\"Vertical Text\" Template=\"{StaticResource VerticalCell}\">\n</ContentControl>\n" }, { "answer_id": 67739609, "author": "Celso Lívero", "author_id": 5605739, "author_profile": "https://Stackoverflow.com/users/5605739", "pm_score": 0, "selected": false, "text": "<ItemsControl ItemsSource=\"{Binding SomeStringProperty, FallbackValue=Group 1}\" Margin=\"5\"\n TextElement.FontSize=\"16\" \n TextElement.FontWeight=\"Bold\" \n TextBlock.TextAlignment=\"Center\"\n HorizontalAlignment=\"Center\" \n VerticalAlignment=\"Center\" >\n<ItemsControl.ItemsPanel>\n <ItemsPanelTemplate>\n <WrapPanel Orientation=\"Vertical\" />\n </ItemsPanelTemplate>\n</ItemsControl.ItemsPanel>\n<ItemsControl.ItemTemplate>\n <DataTemplate >\n <TextBlock Text=\"{Binding }\" HorizontalAlignment=\"Center\" />\n </DataTemplate>\n</ItemsControl.ItemTemplate>\n" }, { "answer_id": 68094601, "author": "EldHasp", "author_id": 13349759, "author_profile": "https://Stackoverflow.com/users/13349759", "pm_score": -1, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Markup;\n\nnamespace Converters\n{\n [ValueConversion(typeof(object), typeof(string))]\n public class InsertLineBreakConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (parameter != null)\n value = parameter;\n\n if (value == null)\n return null;\n\n if (!(value is string str))\n str = value.ToString();\n\n return string.Join(Environment.NewLine, (IEnumerable<char>) str);\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n\n public static InsertLineBreakConverter Instance { get; } = new InsertLineBreakConverter();\n }\n\n public class InsertLineBreakConverterExtension : MarkupExtension\n {\n public override object ProvideValue(IServiceProvider serviceProvider)\n => InsertLineBreakConverter.Instance;\n }\n}\n <TextBlock Text=\"{Binding Property, Converter={cnvs:InsertLineBreakConverter}}\"/> \n <TextBlock Text=\"{Binding Converter={cnvs:InsertLineBreakConverter}, ConverterParameter='Some Text'}\"/>\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30934/" ]
349,884
<p>I need to simple way to allow an end user to restart tomcat from a web page served from apache on the same box.</p> <p>We're trying to make it easy for our QC department to deploy a new version of our webapp to apache. We're using samba, but we need an easy way for them to stop / start the tomcat server before/after the deployment.</p> <p>This would only be for internal qc boxes. Is there an existing solution for this? or would it be easier to write a few quick php application to handle this?</p>
[ { "answer_id": 351676, "author": "derobert", "author_id": 27727, "author_profile": "https://Stackoverflow.com/users/27727", "pm_score": 4, "selected": true, "text": "/etc/init.d/tomcat restart #!/usr/bin/perl\nuse CGI;\nuse IPC::Run3;\nmy $CGI = new CGI;\n\nmy $output;\nif (defined $CGI->param('go') && 'restart' eq $CGI->param('go')) {\n run3 [ qw(sudo /etc/init.d/tomcat5.5 restart) ], \\undef, \\$output, \\$output;\n}\n\nprint <<EOF\nContent-type: text/html\n\nBlah, blah, blah, HTML form, displays $output at some point.\nEOF\n ALL ALL=(root) NOPASSWD: /etc/init.d/tomcat5.5 restart\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
349,886
<p>So I have an Oracle instance, and I know it's running on this system, I've su'd to the oracle user, and I'm trying to connect using "/ as sysdba". However, when I do connect, it says the instance is idle. I know the database is up and opened, because my application's talking to it. My paths (ORACLE_HOME, etc.) might be incorrect: any idea which incorrect setting might result in this?</p> <pre><code>% sqlplus "/ as sysdba" SQL*Plus: Release 10.2.0.3.0 - Production on Mon Dec 8 09:23:22 2008 Copyright (c) 1982, 2006, Oracle. All Rights Reserved. Connected to an idle instance. 09:23:22 SQL&gt; Disconnected % ps -ef | grep smon oracle 6961 1 0 Nov 05 ? 1:24 ora_smon_ORA003 % </code></pre>
[ { "answer_id": 350432, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 2, "selected": false, "text": "sqlplus \"/@ConnectIdentifier as sysdba\"\n" }, { "answer_id": 351521, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": 4, "selected": false, "text": "ORACLE_HOME=/opt/oracle\nORACLE_HOME=/opt/oracle/\n" }, { "answer_id": 637415, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "export ORACLE_SID=your sid here\nsqlplus /nolog\nstartup\n" }, { "answer_id": 8219075, "author": "Edmael", "author_id": 1058680, "author_profile": "https://Stackoverflow.com/users/1058680", "pm_score": 1, "selected": false, "text": "init.ora init.ora startup spfile=\"C:\\location\";" }, { "answer_id": 54039797, "author": "Anwar Husain", "author_id": 9913386, "author_profile": "https://Stackoverflow.com/users/9913386", "pm_score": 2, "selected": false, "text": "sqlplus sys/sys as sysdba SQL> startup\n Total System Global Area 467652608 bytes\nFixed Size 2214416 bytes\nVariable Size 352323056 bytes\nDatabase Buffers 104857600 bytes\nRedo Buffers 8257536 bytes\nDatabase mounted.\nDatabase opened.\n" }, { "answer_id": 56832011, "author": "J.Col", "author_id": 10989288, "author_profile": "https://Stackoverflow.com/users/10989288", "pm_score": 0, "selected": false, "text": "shutdown abort\n startup\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
349,889
<p>I just wrote the following C++ function to programmatically determine how much RAM a system has installed. It works, but it seems to me that there should be a simpler way to do this. Am I missing something?</p> <pre><code>getRAM() { FILE* stream = popen(&quot;head -n1 /proc/meminfo&quot;, &quot;r&quot;); std::ostringstream output; int bufsize = 128; while( !feof(stream) &amp;&amp; !ferror(stream)) { char buf[bufsize]; int bytesRead = fread(buf, 1, bufsize, stream); output.write(buf, bytesRead); } std::string result = output.str(); std::string label, ram; std::istringstream iss(result); iss &gt;&gt; label; iss &gt;&gt; ram; return ram; } </code></pre> <p>First, I'm using <code>popen(&quot;head -n1 /proc/meminfo&quot;)</code> to get the first line of the meminfo file from the system. The output of that command looks like</p> <blockquote> <p>MemTotal: 775280 kB</p> </blockquote> <p>Once I've got that output in an <code>istringstream</code>, it's simple to tokenize it to get at the information I want. Is there a simpler way to read in the output of this command? Is there a standard C++ library call to read in the amount of system RAM?</p>
[ { "answer_id": 349970, "author": "Bombe", "author_id": 43582, "author_profile": "https://Stackoverflow.com/users/43582", "pm_score": 1, "selected": false, "text": "top procps /proc/meminfo" }, { "answer_id": 350039, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "popen() head -n1 int GetRamInKB(void)\n{\n FILE *meminfo = fopen(\"/proc/meminfo\", \"r\");\n if(meminfo == NULL)\n ... // handle error\n\n char line[256];\n while(fgets(line, sizeof(line), meminfo))\n {\n int ram;\n if(sscanf(line, \"MemTotal: %d kB\", &ram) == 1)\n {\n fclose(meminfo);\n return ram;\n }\n }\n\n // If we got here, then we couldn't find the proper line in the meminfo file:\n // do something appropriate like return an error code, throw an exception, etc.\n fclose(meminfo);\n return -1;\n}\n" }, { "answer_id": 350046, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 7, "selected": true, "text": "sysinfo #include <sys/sysinfo.h>\n\n int sysinfo(struct sysinfo *info);\n\n struct sysinfo {\n long uptime; /* Seconds since boot */\n unsigned long loads[3]; /* 1, 5, and 15 minute load averages */\n unsigned long totalram; /* Total usable main memory size */\n unsigned long freeram; /* Available memory size */\n unsigned long sharedram; /* Amount of shared memory */\n unsigned long bufferram; /* Memory used by buffers */\n unsigned long totalswap; /* Total swap space size */\n unsigned long freeswap; /* swap space still available */\n unsigned short procs; /* Number of current processes */\n unsigned long totalhigh; /* Total high memory size */\n unsigned long freehigh; /* Available high memory size */\n unsigned int mem_unit; /* Memory unit size in bytes */\n char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding for libc5 */\n };\n sysinfo std::ifstream std::string unsigned long get_mem_total() {\n std::string token;\n std::ifstream file(\"/proc/meminfo\");\n while(file >> token) {\n if(token == \"MemTotal:\") {\n unsigned long mem;\n if(file >> mem) {\n return mem;\n } else {\n return 0;\n }\n }\n // Ignore the rest of the line\n file.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n }\n return 0; // Nothing found\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
349,892
<p>I have a logging table which has three columns. One column is a unique identifier, One Column is called "Name" and the other is "Status".<br> Values in the Name column can repeat so that you might see Name "Joe" in multiple rows. Name "Joe" might have a row with a status "open", another row with a status "closed", another with "waiting" and maybe one for "hold". I would like to, using a defined precedence in this highest to lowest order:("Closed","Hold","Waiting" and "Open") pull the highest ranking row for each Name and ignore the others. Anyone know a simple way to do this? </p> <p>BTW, not every Name will have all status representations, so "Joe" might only have a row for "waiting" and "hold", or maybe just "waiting".</p>
[ { "answer_id": 349903, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 3, "selected": true, "text": "Status | Order\n---------------\nClosed | 1\nHold | 2\nWaiting | 3\nOpen | 4\n Status_Precedence.Status ORDER BY Status_Precedence.Order" }, { "answer_id": 349926, "author": "Ta01", "author_id": 7280, "author_profile": "https://Stackoverflow.com/users/7280", "pm_score": 2, "selected": false, "text": "Select Name, Status, Case Status \n When 'Closed' then 1\n When 'Hold' then 2\n When 'Waiting' then 3\n When 'Open' Then 4\n END\n as StatusID\n\n From Logging\nOrder By StatusId -- Order based on Case\n" }, { "answer_id": 350228, "author": "madcolor", "author_id": 13954, "author_profile": "https://Stackoverflow.com/users/13954", "pm_score": 0, "selected": false, "text": "SELECT * from [TABLE] tb\nLEFT JOIN Status_Precedence sp ON tb.Status = sp.Status\nWHERE sp.Rank = (SELECT MIN(sp2.rank)\n FROM[Table] tb2\n LEFT JOIN Status_Precedence sp2 ON tb2.Status = sp2.Status\n WHERE tb.Status = tb2.Status)\norder by tb.[name]\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13954/" ]
349,896
<p>I'm trying to make a function that has a list of lists, it multiplies the sum of the inner list with the outer list. So far i can sum a list, i've made a function sumlist([1..n],X) that will return X = (result). But i cannot get another function to usefully work with that function, i've tried both is and = to no avail.</p>
[ { "answer_id": 351501, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 1, "selected": false, "text": "[L1,...,Ln] S1*..*Sn Si Li i plus mult plus(N,M,R) R N+M sum sum(L,S) S L L S 0 sum([],0).\n L [N|L2] S N S2 L2 sum(L2,S2) L2 plus(N,S2,S) sum([N|L2],S) :- sum(L2,S2), plus(N,S2,S).\n p p(L,R) R S1 Sn L=[L1,...,Ln] sum(Li,Si) i L R 1 p([],1).\n L [LL|L2] R LL L2 S sum(LL,S) p([LL|L2],R) :- sum(LL,S), p(L2,P), mult(S,P,R).\n sumlist([1,..,n],X) X = (result) (result) X sumlist([1,...,n],X) p(X) :- q(X) p(X) :- r(X)" }, { "answer_id": 353572, "author": "Kaarel", "author_id": 12547, "author_profile": "https://Stackoverflow.com/users/12547", "pm_score": 2, "selected": false, "text": "prodsumlist([], 1).\n\nprodsumlist([Head | Tail], Result) :-\n sumlist(Head, Sum_Of_Head),\n prodsumlist(Tail, ProdSum_Of_Tail),\n Result is Sum_Of_Head * ProdSum_Of_Tail.\n sumlist/2 ?- prodsumlist([[1, 2], [3], [-4]], Result).\nResult = -36.\n" }, { "answer_id": 1635507, "author": "pfctdayelise", "author_id": 54056, "author_profile": "https://Stackoverflow.com/users/54056", "pm_score": 0, "selected": false, "text": "prodsumlist(List, Result) :-\n xprodsumlist(List,1,Result).\n\nxprodsumlist([],R,R).\n\nxprodsumlist([Head|Rest],Sofar,Result) :-\n sumlist(Head, Sum_Of_Head),\n NewSofar is Sofar * Sum_Of_Head,\n xprodsumlist(Rest, NewSofar, Result).\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42789/" ]
349,904
<p>Recently I used a class that inherits from a collection instead of having the collection instantiated within the class, is this acceptable or does it create unseen problems further down the road? Examples below for the sake of clarity:</p> <pre><code>public class Cars : List&lt;aCar&gt; </code></pre> <p>instead of something like:</p> <pre><code>public class Cars { List&lt;aCar&gt; CarList = new List&lt;aCar&gt;(); } </code></pre> <p>Any thoughts?</p>
[ { "answer_id": 349950, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "IEnumerable<T> IList<T> List<T>" }, { "answer_id": 350257, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 1, "selected": false, "text": "public class CarList<T> : List<T> where T : Car {\n // some added functionality\n}\n public class CarList<T> : IList<T> where T : Car {\n private IList<T> innerList;\n public CarList() { this.innerList = new List<T>(); }\n\n // implementation of IList<T>\n\n // some added functionality\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4098/" ]
349,918
<p>I am using a third-party DLL. For some particular cases, a function in the DLL is throwing an exception. Is it possible to debug the DLL in the Visual Studio?</p> <p>After <a href="https://stackoverflow.com/questions/349918/debugging-a-third-party-dll-in-visual-studio/349925#349925">the answer from Andrew Rollings</a>, I am able to view the code, but is there any easy way to debug through the code in Visual Studio?</p>
[ { "answer_id": 350332, "author": "Robert Gowland", "author_id": 20570, "author_profile": "https://Stackoverflow.com/users/20570", "pm_score": 2, "selected": false, "text": "Trace.WriteLine System.Diagnostics.Debugger.Break() System.Diagnostics.Debugger.Break()" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41968/" ]
349,927
<p>According to <em>Cocoa Programming for Mac OS X, 3rd Edition</em>, on page 245 (chapter 17), you will usually create views in Interface Builder. However, it is possible to create them in code, a la:</p> <pre><code>NSView *superview = [window contentView]; NSRect frame = NSMakeRect(10, 10, 200, 100); NSButton *button = [[NSButton alloc] initWithFrame:frame]; [button setTitle:@"Click me!"]; [superview addSubview:button]; [button release]; </code></pre> <p>That’s all well and good, but how would I wire up said control’s outlets to actions in code? (In .NET, this is an easy thing; add a delegate ... I’m hoping it’s similarly easy in Cocoa/Obj-C.)</p>
[ { "answer_id": 350104, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 6, "selected": true, "text": "[button setTarget: self];\n[button setAction: @selector(myButtonWasHit:)];\n" }, { "answer_id": 350910, "author": "Mike Abdullah", "author_id": 28768, "author_profile": "https://Stackoverflow.com/users/28768", "pm_score": 4, "selected": false, "text": "[button setTarget:nil];\n[button setAction:@selector(myAction:)];\n" }, { "answer_id": 29488689, "author": "User", "author_id": 930450, "author_profile": "https://Stackoverflow.com/users/930450", "pm_score": 2, "selected": false, "text": "button.target = self\nbutton.action = \"myAction:\"\n func myAction(sender: NSButton) {\n println(\"click!\")\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14048/" ]
349,931
<p>Please tell me how do I print a bit, like <code>printf("%d",bit);</code>.</p>
[ { "answer_id": 349937, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 4, "selected": false, "text": "printf(\"%d\", bit & 0x1);\n" }, { "answer_id": 349960, "author": "Keltia", "author_id": 16143, "author_profile": "https://Stackoverflow.com/users/16143", "pm_score": 2, "selected": false, "text": "void print_bit(n, m)\n{\n printf(\"%d\", n & (1 << (m - 1)));\n}\n - 1" }, { "answer_id": 349967, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 3, "selected": false, "text": "#define IsBitSet(val, bit) ((val) & (1 << (bit)))\n\n/* ... your code ... */\n\nprintf (\"%c\", IsBitSet(bit, 0) ? '1' : '0');\n struct foo { int b:1; } myFoo;\n\nprintf(\"%c\", myFoo.b ? '1' : '0');\n" }, { "answer_id": 352301, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 1, "selected": false, "text": "bool b = true;\nstd::cout << b;\n _Bool b = 1;\nprintf(\"%d\", b);\n" }, { "answer_id": 6649522, "author": "Sajjad Mohammadadeh", "author_id": 641120, "author_profile": "https://Stackoverflow.com/users/641120", "pm_score": 1, "selected": false, "text": "union bitshow {\n unsigned bit1:1;\n int i;\n};\n\nint main() {\n union bitshow bit;\n cin >> bit.i;\n cout << bit.bit1;\n return 0;\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
349,933
<p>I have a user table like this</p> <pre><code>user_id | community_id | registration_date -------------------------------------------- 1 | 1 | 2008-01-01 2 | 1 | 2008-05-01 3 | 2 | 2008-01-28 4 | 2 | 2008-07-22 5 | 3 | 2008-01-11 </code></pre> <p>For each community, I would like to get the time that the 3rd user registered. I can easily do this for a single community using MySql's 'limit' SQL extension. For example, for community with ID=2</p> <pre><code>select registration_date from user order by registration_date where community_id = 2 limit 2, 1 </code></pre> <p>Alternatively, I can get the date that the first user registered for all communities via:</p> <pre><code>select community_id, min(registration_date) from user group by 1 </code></pre> <p>But I can't figure out how to get the registration date of the 3rd user for <em>all</em> communities in a single SQL statement.</p> <p>Cheers, Don</p>
[ { "answer_id": 350001, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "select \n registration_date, community_id \nfrom \n user outer \nwhere \n user_id IN (\n select \n user_id \n from \n user inner \n where \n inner.community_id = outer.community_id \n order by \n registration_date \n limit 2,1\n )\norder by registration_date\n" }, { "answer_id": 350007, "author": "chadgh", "author_id": 18992, "author_profile": "https://Stackoverflow.com/users/18992", "pm_score": 0, "selected": false, "text": "SELECT registration_date\nFROM user\nORDER BY registration_date\nLIMIT n\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
349,938
<p>Is there a programmatic way to extract equations (and possibly images) from an MS Word document? I've googled all over, but have yet to find anything that I can sink my teeth into and work from. If possible, I'd like to be able to do this with VB.NET or C#, but I can pick up enough of any language to hack out a DLL. Thanks!</p> <p><strong>EDIT:</strong> Right now I'm looking at extracting the equations from Word 2003, but if converting it to 2007/Open XML is required, that's fine.</p>
[ { "answer_id": 350030, "author": "Dirk Vollmar", "author_id": 40347, "author_profile": "https://Stackoverflow.com/users/40347", "pm_score": 3, "selected": false, "text": "\"C:\\Program Files\\Microsoft Office\\Office12\\wordconv.exe\" -oice -nme input\\_file output_file" }, { "answer_id": 350118, "author": "xahtep", "author_id": 42184, "author_profile": "https://Stackoverflow.com/users/42184", "pm_score": 4, "selected": true, "text": "InlineShapes Document ThisDocument.InlineShapes.Items(1).Select\nSelection.Copy\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4252/" ]
349,948
<p>I had a class with some common error handling code, and I wanted to pass in the method and arguments to call, but I couldn't quite come up with the syntax. What I want to do is roughly this:</p> <pre><code>private void InvokeHelper(Delegate method, params object[] args) { bool retry = false; do { try { method.DynamicInvoke(args); retry = false; } catch (MyException ex) { retry = HandleException(ex); } } while (retry); } </code></pre> <p>and then be able to do things like:</p> <pre><code>InvokeHelper(foo.MethodA, a, b, c); InvokeHelper(foo.MethodB, x, y ); </code></pre> <p>This gets a compiler error converting foo.MethodA and foo.MethodB into System.Delegate. I came up with the workaround below (and I actually like it better because then I get type checking on my arguments to my methods), but I'm curious if there's a way to do what I was originally trying to do? I know I could use <code>foo.GetType().GetMethod("MethodA")</code> and invoke that, but I was trying to avoid reflection. I mainly just want to understand how methods are dynamically invoked in .net.</p> <p>Workaround:</p> <pre><code>private delegate void EmptyDelegate(); private void InvokeHelper(EmptyDelegate method) { bool retry = false; do { try { method.Invoke(); retry = false; } catch (MyException ex) { retry = HandleException(ex); } } while (retry); } </code></pre> <p>then call:</p> <pre><code>InvokeHelper(delegate() { foo.MethodA(a, b, c); }); InvokeHelper(delegate() { foo.MethodB(x, y); }); </code></pre>
[ { "answer_id": 350043, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "private void InvokeHelper(Delegate method, params object[] args)\n InvokeHelper(foo.MethodA, new object[] { a, b, c});\n parms InvokeHelper(foo.MethodA, a, b, c);\n private void InvokeHelper(Action method)\n InvokeHelper(()=> MyMethodToInvoke(a, b, c));\n" }, { "answer_id": 350062, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": " private void InvokeHelper(Action method)\n {\n bool retry = false;\n\n do\n {\n try\n {\n method();\n retry = false;\n }\n catch (MyException ex)\n {\n retry = HandleException(ex);\n }\n } while (retry);\n }\n\n public void Test()\n {\n FooClass foo = new FooClass();\n InvokeHelper( () => foo.MethodA(1, \"b\", 3) );\n InvokeHelper( () => foo.MethodB(2, \"y\"));\n }\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9323/" ]
349,951
<p>We have a stored procedure that runs nightly that in turn kicks off a number of other procedures. Some of those procedures could logically be run in parallel with some of the others. </p> <ul> <li>How can I indicate to SQL Server whether a procedure should be run in parallel or serial &mdash; ie: kicked off of asynchronously or blocking? </li> <li>What would be the implications of running them in parallel, keeping in mind that I've already determined that the processes won't be competing for table access or locks- just total disk io and memory. For the most part they don't even use the same tables.</li> <li>Does it matter if some of those procedures are the <em>same</em> procedure, just with different parameters?</li> <li>If I start a pair or procedures asynchronously, is there a good system in SQL Server to then wait for both of them to finish, or do I need to have each of them set a flag somewhere and check and poll the flag periodically using <code>WAITFOR DELAY</code>?</li> </ul> <p>At the moment we're still on SQL Server 2000.</p> <p>As a side note, this matters because the main procedure is kicked off in response to the completion of a data dump into the server from a mainframe system. The mainframe dump takes all but about 2 hours each night, and we have no control over it. As a result, we're constantly trying to find ways to reduce processing times.</p>
[ { "answer_id": 4648502, "author": "BradC", "author_id": 21398, "author_profile": "https://Stackoverflow.com/users/21398", "pm_score": 5, "selected": true, "text": "sp_start_job xp_sqlagent_enum_jobs sp_oacreate sp_oamethod Parallel_AddSql Parallel_Execute" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
349,953
<p>I am converting a linux script from <a href="http://www.perlmonks.org/index.pl?node_id=217166" rel="nofollow noreferrer">http://www.perlmonks.org/index.pl?node_id=217166</a> specifically this:</p> <pre><code>#!/usr/bin/perl -w use strict; use Getopt::Std; use File::Find; @ARGV &gt; 0 and getopts('a:', \my %opt) or die &lt;&lt; "USAGE"; # Deletes any old files from the directory tree(s) given and # removes empty directories en passant. usage: $0 [-a maxage] directory [directory ...] -a maximum age in days, default is 120 USAGE my $max_age_days = $opt{a} || 120; find({ wanted =&gt; sub { unlink if -f $_ and -M _ &gt; $max_age_days }, postprocess =&gt; sub { rmdir $File::Find::dir }, }, @ARGV); </code></pre> <p>my attempt is:</p> <pre><code>#!/usr/bin/perl -w use strict; use Getopt::Std; use File::Find; @ARGV &gt; 0 and getopts('a:', \my %opt) or die &lt;&lt; "USAGE"; # Deletes any old files from the directory tree(s) given and # removes empty directories en passant. usage: $0 [-a maxage] directory [directory ...] -a maximum age in days, default is 120 USAGE my $max_age_days = $opt{a} || 120; find({ wanted =&gt; sub { unlink if -f $_ and -M _ &gt; $max_age_days }, # postprocess =&gt; sub { rmdir $File::Find::dir }, postprocess =&gt; sub { my $expr = "$File::Find::dir"; $expr =~ s/\//\\/g; # replace / with \ print "rmdir $expr\n"; `rmdir $expr`; }, }, @ARGV); </code></pre> <p>However I get an error when the script tries to remove a directory saying that the directory is in use by another process (when it isn't). Any ideas? I'm running the script on Windows Server 2003 SP2 64-bit using ActiveState 5.10.</p> <p>Thanks!</p>
[ { "answer_id": 349998, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 5, "selected": true, "text": "no_chdir" }, { "answer_id": 359798, "author": "Mark Allison", "author_id": 38211, "author_profile": "https://Stackoverflow.com/users/38211", "pm_score": 1, "selected": false, "text": "#!/usr/bin/perl -w\nuse strict;\nuse warnings;\nuse Getopt::Std;\nuse File::Find;\nuse Win32::OLE;\n\n@ARGV > 0 and getopts('a:', \\my %opt) or die << \"USAGE\";\nDeletes any old files from the directory tree(s) given and\nremoves empty directories en passant.\nusage: $0 [-a maxage] directory [directory ...]\n -a maximum age in days, default is 30\nUSAGE\n\nmy $max_age_days = $opt{a} || 30;\nmy @dir_list = undef;\n\nfind({\n wanted => sub { if (-f $_ and -M _ > $max_age_days) {\n unlink $_ or LogError (\"$0: Could not delete $_ ($!)\")}},\n postprocess => sub {push(@dir_list,$File::Find::dir)},\n}, @ARGV);\n\nif (@dir_list) {foreach my $thisdir (@dir_list) { rmdir $thisdir if defined ($thisdir)}}\n\n############\nsub LogError {\n my ($strDescr) = @_;\n use constant EVENT_SUCCESS => 0;\n use constant EVENT_ERROR => 1;\n use constant EVENT_WARNING => 3;\n use constant EVENT_INFO => 4;\n\n my $objWSHShell = Win32::OLE->new('WScript.Shell');\n $objWSHShell->LogEvent(EVENT_ERROR, $strDescr);\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38211/" ]
349,957
<p>I'm having an issue with an ObservableCollection getting new items but not reflecting those changes in a ListView. I have enough quirks in the way I'm implementing this that I'm having a hard time determining what the problem is.</p> <p>My ObservableCollection is implemented thusly:</p> <pre><code>public class MessageList : ObservableCollection&lt;LobbyMessage&gt; { public MessageList(): base() { Add(new LobbyMessage() { Name = "System", Message = "Welcome!" }); } } </code></pre> <p>I store the collection in a static property (so that its easily accessible from multiple user controls):</p> <pre><code>static public MessageList LobbyMessages { get; set; } </code></pre> <p>In the OnLoad event of my main NavigationWindow I have the following line:</p> <pre><code>ChatHelper.LobbyMessages = new MessageList(); </code></pre> <p>My XAML in the UserControl where the ListView is located reads as:</p> <pre><code> &lt;ListBox IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Mode=OneWay}" x:Name="ListBoxChatMessages" d:UseSampleData="True" ItemTemplate="{DynamicResource MessageListTemplate}" IsEnabled="True"&gt; &lt;ListBox.DataContext&gt; &lt;Magrathea_Words_Tools:MessageList/&gt; &lt;/ListBox.DataContext&gt; &lt;/ListBox&gt; </code></pre> <p>The initial message that I added in the constructor appears in the UI just fine.</p> <p>Now, the way I add new items to the collection is from a CallBack coming from a WCF service. I had this code working in a WinForms application and it was neccessary to marshall the callback to the UI thread so I left that code in place. Here is an abbreviated version of the method:</p> <pre><code>Helper.Context = SynchronizationContext.Current; #region IServiceMessageCallback Members /// &lt;summary&gt; /// Callback handler for when the service has a message for /// this client /// &lt;/summary&gt; /// &lt;param name="serviceMessage"&gt;&lt;/param&gt; public void OnReceivedServiceMessage(ServiceMessage serviceMessage) { // This is being called from the WCF service on it's own thread so // we have to marshall the call back to this thread. SendOrPostCallback callback = delegate { switch (serviceMessage.MessageType) { case MessageType.ChatMessage: ChatHelper.LobbyMessages.Add( new LobbyMessage() { Name = serviceMessage.OriginatingPlayer.Name, Message = serviceMessage.Message }); break; default: break; } }; Helper.Context.Post(callback, null); } </code></pre> <p>While debugging I can see the collection getting updated with messages from the service but the UI is not reflecting those additions.</p> <p>Any ideas about what I'm missing to get the ListView to reflect those new items in the collection?</p>
[ { "answer_id": 352879, "author": "Sailing Judo", "author_id": 42620, "author_profile": "https://Stackoverflow.com/users/42620", "pm_score": 3, "selected": true, "text": "ListBoxChatMessages.ItemsSource = ChatHelper.LobbyMessages.Messages;\n <ListBox IsSynchronizedWithCurrentItem=\"True\" \n ItemsSource=\"{Binding Mode=OneWay}\" Background=\"#FF1F1F1F\" \n Margin=\"223,18.084,15.957,67.787\" x:Name=\"ListBoxChatMessages\" \n ItemTemplate=\"{DynamicResource MessageListTemplate}\" \n IsEnabled=\"True\"/>\n" }, { "answer_id": 22963753, "author": "Scott Nimrod", "author_id": 492701, "author_profile": "https://Stackoverflow.com/users/492701", "pm_score": 0, "selected": false, "text": "<viewModels:LocationsViewModel x:Key=\"viewModel\" />\n.\n.\n. \n<ListView\n DataContext=\"{StaticResource viewModel}\"\n ItemsSource=\"{Binding Locations}\"\n IsItemClickEnabled=\"True\"\n ItemClick=\"GroupSection_ItemClick\"\n ContinuumNavigationTransitionInfo.ExitElementContainer=\"True\">\n\n <ListView.ItemTemplate>\n <DataTemplate>\n <StackPanel Orientation=\"Horizontal\">\n <TextBlock Text=\"{Binding Name}\" Margin=\"0,0,10,0\" Style=\"{ThemeResource ListViewItemTextBlockStyle}\" />\n <TextBlock Text=\"{Binding Latitude, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}\" Style=\"{ThemeResource ListViewItemTextBlockStyle}\" Margin=\"0,0,5,0\"/>\n <TextBlock Text=\"{Binding Longitude, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}\" Style=\"{ThemeResource ListViewItemTextBlockStyle}\" Margin=\"5,0,0,0\" />\n </StackPanel>\n </DataTemplate>\n </ListView.ItemTemplate>\n</ListView>\n\npublic class LocationViewModel : BaseViewModel\n{\n ObservableCollection<Location> _locations = new ObservableCollection<Location>();\n public ObservableCollection<Location> Locations\n {\n get\n {\n return _locations;\n }\n set\n {\n if (_locations != value)\n {\n _locations = value;\n OnNotifyPropertyChanged();\n }\n }\n }\n}\n\npublic class Location : BaseViewModel\n{\n int _locationId = 0;\n public int LocationId\n {\n get\n {\n return _locationId;\n }\n set\n {\n if (_locationId != value)\n {\n _locationId = value;\n OnNotifyPropertyChanged();\n }\n }\n }\n\n string _name = null;\n public string Name\n {\n get\n {\n return _name;\n }\n set\n {\n if (_name != value)\n {\n _name = value;\n OnNotifyPropertyChanged();\n }\n }\n }\n\n float _latitude = 0;\n public float Latitude \n { \n get\n {\n return _latitude;\n }\n set\n {\n if (_latitude != value)\n {\n _latitude = value;\n OnNotifyPropertyChanged();\n }\n }\n }\n\n float _longitude = 0;\n public float Longitude\n {\n get\n {\n return _longitude;\n }\n set\n {\n if (_longitude != value)\n {\n _longitude = value;\n OnNotifyPropertyChanged();\n }\n }\n }\n}\n\npublic class BaseViewModel : INotifyPropertyChanged\n{\n #region Events\n public event PropertyChangedEventHandler PropertyChanged;\n #endregion\n\n protected void OnNotifyPropertyChanged([CallerMemberName] string memberName = \"\")\n {\n if (PropertyChanged != null)\n {\n PropertyChanged(this, new PropertyChangedEventArgs(memberName));\n }\n }\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42620/" ]
349,978
<p>I have just imported a WAR file from an external site, which is basically a servlet into Eclipse IDE (the project runs on Apache-Tomcat). </p> <p>When I import it it has a folder called <strong>Web App Libraries</strong>. So here are a few of my newbie questions:</p> <ol> <li><p>I am unsure about what the exact purpose is of this folder is? What does it do, why would you choose to have it in your project? </p></li> <li><p>I see that it has a folder called <strong>Improted Classes</strong> and foobar.class files inside it - why?<br> <em>(These seemed to be mirrored in <strong>Web Content</strong> folder - although here you can modify the code as they are foobar.java.)</em></p></li> <li><p>There are references to foobar.jar files too - these are also mirrored in <strong>WEB-INF/lib</strong> folder too - why?</p></li> </ol> <p>I know these are basic type questions but I'm just getting to grips with Java and website dev, so apologies if they sound a bit dumb! - BTW if anyone knows any good online resource to understand more about project file structures like this, then let me know. I just need to get to grips with this stuff asap - as the project deadline is fairly soon.</p> <p>Cheers.</p> <p>Here's a screenshot just to help you visualise:</p> <p><img src="https://rantincsharp.files.wordpress.com/2008/12/eclipserestlet.gif" alt="alt text"></p>
[ { "answer_id": 350076, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 1, "selected": false, "text": "Project Name/\n JavaSource/ or src/ // holds all the Java Source Files, Servlets, Struts Actions\n WebContent/ // Nice root folder to hold web content files\n content files and folders\n WEB-INF/ // Web App Config folder\n lib/ // Libraries (but not tomcat ones)\n web.xml\n classes/ // Where your compiled Java goes, and configs (log4j.properties)\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5175/" ]
349,980
<p>I need to format an integer representation of bytes into something friendly, and I'm hoping that there's a utility function in Ruby or in Rails that will do that formatting for me (to perpetuate my laziness, of course.)</p> <p>I'm looking for something that would look like:</p> <pre><code>format_bytes(1024) -&gt; "1 KB" format_bytes(1048576) -&gt; "1 MB" </code></pre> <p>Looks like there's some stuff in ActiveSupport to do it the other way around, but I haven't found a way to do it in this direction.</p> <p>If there isn't one that exists, does anyone have a particularly elegant solution?</p>
[ { "answer_id": 350083, "author": "mwilliams", "author_id": 23909, "author_profile": "https://Stackoverflow.com/users/23909", "pm_score": 6, "selected": true, "text": "require 'action_view'\ninclude ActionView::Helpers::NumberHelper\nnumber_to_human_size(123) # => 123 Bytes\nnumber_to_human_size(1234) # => 1.2 KB\nnumber_to_human_size(12345) # => 12.1 KB\nnumber_to_human_size(1234567) # => 1.2 MB\nnumber_to_human_size(1234567890) # => 1.1 GB\nnumber_to_human_size(1234567890123) # => 1.1 TB\nnumber_to_human_size(1234567, :precision => 2) # => 1.18 MB\nnumber_to_human_size(483989, :precision => 0) # => 473 KB\nnumber_to_human_size(1234567, :precision => 2, :separator => ',') # => 1,18 MB\n" }, { "answer_id": 3145769, "author": "Tim Peters", "author_id": 180800, "author_profile": "https://Stackoverflow.com/users/180800", "pm_score": 1, "selected": false, "text": "require 'actionpack'\n" }, { "answer_id": 28503362, "author": "facundofarias", "author_id": 3009370, "author_profile": "https://Stackoverflow.com/users/3009370", "pm_score": 1, "selected": false, "text": "number_to_human_size(123) # => 123 Bytes\nnumber_to_human_size(1234) # => 1.2 KB\nnumber_to_human_size(12345) # => 12.1 KB\nnumber_to_human_size(1234567) # => 1.2 MB\nnumber_to_human_size(1234567890) # => 1.1 GB\nnumber_to_human_size(1234567890123) # => 1.1 TB\nnumber_to_human_size(1234567, :precision => 2) # => 1.18 MB\nnumber_to_human_size(483989, :precision => 0) # => 473 KB\nnumber_to_human_size(1234567, :precision => 2, :separator => ',') # => 1,18 MB\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/650/" ]
349,997
<pre><code>$pee = preg_replace( '|&lt;p&gt;|', "$1&lt;p&gt;", $pee ); </code></pre> <p>This regular expression is from the Wordpress source code (formatting.php, wpautop function); I'm not sure what it does, can anyone help?</p> <p>Actually I'm trying to port this function to Python...if anyone knows of an existing port already, that would be much better as I'm really bad with regex.</p>
[ { "answer_id": 350026, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 2, "selected": false, "text": "<p>" }, { "answer_id": 350033, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": -1, "selected": false, "text": "\"|<p>|\" \n \"$1<p>\"\n \"<p>\" \n \"test<p>\"\n" }, { "answer_id": 350087, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 2, "selected": false, "text": "\"|<p>|\"\n \"<p>\" \n \"$1<p>\" \n" }, { "answer_id": 350182, "author": "Argelbargel", "author_id": 2992, "author_profile": "https://Stackoverflow.com/users/2992", "pm_score": 2, "selected": false, "text": "| / / /(.\\*)\\/(.\\*)\\// #/(.\\*)/(.\\*)/# | $1 \"(.*)<p>\"\n $0 $1 &lt;p&gt; $1 &lt;p&gt; &lt;p&gt; $1" }, { "answer_id": 350806, "author": "Scott Reynen", "author_id": 10837, "author_profile": "https://Stackoverflow.com/users/10837", "pm_score": 0, "selected": false, "text": "$pee = preg_replace('!<p>([^<]+)\\s*?(</(?:div|address|form)[^>]*>)!', \"<p>$1</p>$2\", $pee);\n" }, { "answer_id": 365221, "author": "Jan Goyvaerts", "author_id": 33358, "author_profile": "https://Stackoverflow.com/users/33358", "pm_score": 0, "selected": false, "text": "$pee = preg_replace( '/<p>/', \"<p>\", $pee );\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/349997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18494/" ]
350,018
<p>What is the best way to combine both hashes into %hash1? I always know that %hash2 and %hash1 always have unique keys. I would also prefer a single line of code if possible. </p> <pre><code>$hash1{'1'} = 'red'; $hash1{'2'} = 'blue'; $hash2{'3'} = 'green'; $hash2{'4'} = 'yellow'; </code></pre>
[ { "answer_id": 350038, "author": "dreftymac", "author_id": 42223, "author_profile": "https://Stackoverflow.com/users/42223", "pm_score": 9, "selected": true, "text": "undef false" }, { "answer_id": 350190, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 5, "selected": false, "text": "my %new_hash = %hash1; # make a copy; leave %hash1 alone\n\nforeach my $key2 ( keys %hash2 )\n {\n if( exists $new_hash{$key2} )\n {\n warn \"Key [$key2] is in both hashes!\";\n # handle the duplicate (perhaps only warning)\n ...\n next;\n }\n else\n {\n $new_hash{$key2} = $hash2{$key2};\n }\n }\n foreach my $key2 ( keys %hash2 )\n {\n if( exists $hash1{$key2} )\n {\n warn \"Key [$key2] is in both hashes!\";\n # handle the duplicate (perhaps only warning)\n ...\n next;\n }\n else\n {\n $hash1{$key2} = $hash2{$key2};\n }\n }\n @hash1{ keys %hash2 } = values %hash2;\n" }, { "answer_id": 46246279, "author": "JeanieJ", "author_id": 4951877, "author_profile": "https://Stackoverflow.com/users/4951877", "pm_score": 3, "selected": false, "text": "$hash_ref1 = {%$hash_ref1, %$hash_ref2};\n $hash_ref1 = ($hash_ref1, $hash_ref2);\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2356/" ]
350,027
<p>I'm trying to set a WPF image's source in code. The image is embedded as a resource in the project. By looking at examples I've come up with the below code. For some reason it doesn't work - the image does not show up. </p> <p>By debugging I can see that the stream contains the image data. So what's wrong?</p> <pre><code>Assembly asm = Assembly.GetExecutingAssembly(); Stream iconStream = asm.GetManifestResourceStream("SomeImage.png"); PngBitmapDecoder iconDecoder = new PngBitmapDecoder(iconStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); ImageSource iconSource = iconDecoder.Frames[0]; _icon.Source = iconSource; </code></pre> <p>The icon is defined something like this: <code>&lt;Image x:Name="_icon" Width="16" Height="16" /&gt;</code></p>
[ { "answer_id": 350059, "author": "Arcturus", "author_id": 900, "author_profile": "https://Stackoverflow.com/users/900", "pm_score": 3, "selected": false, "text": "VisualBrush brush = new VisualBrush { TileMode = TileMode.None };\n\nbrush.Visual = frame;\n\nbrush.AlignmentX = AlignmentX.Center;\nbrush.AlignmentY = AlignmentY.Center;\nbrush.Stretch = Stretch.Uniform;\n GeometryDrawing drawing = new GeometryDrawing();\n\ndrawing.Brush = brush;\n\n// Brush this in 1, 1 ratio\nRectangleGeometry rect = new RectangleGeometry { Rect = new Rect(0, 0, 1, 1) };\ndrawing.Geometry = rect;\n new DrawingImage(drawing);\n <Image>\n <Image.Source>\n <BitmapImage UriSource=\"/yourassembly;component/YourImage.PNG\"></BitmapImage>\n </Image.Source>\n</Image>\n BitmapImage image = new BitmapImage { UriSource=\"/yourassembly;component/YourImage.PNG\" };\n" }, { "answer_id": 530382, "author": "Andrew Myhre", "author_id": 5152, "author_profile": "https://Stackoverflow.com/users/5152", "pm_score": 4, "selected": false, "text": "Assembly asm = Assembly.GetExecutingAssembly();\nStream iconStream = asm.GetManifestResourceStream(\"SomeImage.png\");\nBitmapImage bitmap = new BitmapImage();\nbitmap.BeginInit();\nbitmap.StreamSource = iconStream;\nbitmap.EndInit();\n_icon.Source = bitmap;\n" }, { "answer_id": 1108739, "author": "awe", "author_id": 109392, "author_profile": "https://Stackoverflow.com/users/109392", "pm_score": 3, "selected": false, "text": "if (File.Exists(imagePath))\n{\n // Create image element to set as icon on the menu element\n Image icon = new Image();\n BitmapImage bmImage = new BitmapImage();\n bmImage.BeginInit();\n bmImage.UriSource = new Uri(imagePath, UriKind.Absolute);\n bmImage.EndInit();\n icon.Source = bmImage;\n icon.MaxWidth = 25;\n item.Icon = icon;\n}\n Image < &lt; <MenuItem Name=\"mnuFileSave\" Header=\"Save\" Command=\"ApplicationCommands.Save\">\n <MenuItem.Icon>\n <Label VerticalAlignment=\"Center\" HorizontalAlignment=\"Center\" FontFamily=\"Wingdings\">&lt;</Label>\n </MenuItem.Icon>\n</MenuItem>\n" }, { "answer_id": 1332287, "author": "Simon", "author_id": 53158, "author_profile": "https://Stackoverflow.com/users/53158", "pm_score": 8, "selected": false, "text": "var uriSource = new Uri(@\"/WpfApplication1;component/Images/Untitled.png\", UriKind.Relative);\nfoo.Source = new BitmapImage(uriSource);\n" }, { "answer_id": 1651397, "author": "Jared Harley", "author_id": 42471, "author_profile": "https://Stackoverflow.com/users/42471", "pm_score": 10, "selected": true, "text": "Image finalImage = new Image();\nfinalImage.Width = 80;\n...\nBitmapImage logo = new BitmapImage();\nlogo.BeginInit();\nlogo.UriSource = new Uri(\"pack://application:,,,/AssemblyName;component/Resources/logo.png\");\nlogo.EndInit();\n...\nfinalImage.Source = logo;\n finalImage.Source = new BitmapImage(\n new Uri(\"pack://application:,,,/AssemblyName;component/Resources/logo.png\"));\n application:/// AssemblyShortName[;Version][;PublicKey];component/Path application: Resource" }, { "answer_id": 2014989, "author": "Alex B", "author_id": 159726, "author_profile": "https://Stackoverflow.com/users/159726", "pm_score": 6, "selected": false, "text": "string packUri = \"pack://application:,,,/AssemblyName;component/Images/icon.png\";\n_image.Source = new ImageSourceConverter().ConvertFromString(packUri) as ImageSource;\n" }, { "answer_id": 2068983, "author": "Mark Mullin", "author_id": 116328, "author_profile": "https://Stackoverflow.com/users/116328", "pm_score": 2, "selected": false, "text": "<UserControl.Resources>\n <ResourceDictionary>\n <ImageBrush x:Key=\"PosterBrush\" ImageSource=\"..\\Resources\\Images\\EmptyPoster.jpg\" Stretch=\"UniformToFill\"/>\n\n </ResourceDictionary>\n </UserControl.Resources>\n ImageBrush posterBrush = (ImageBrush)Resources[\"PosterBrush\"];\n" }, { "answer_id": 2511158, "author": "Siarhei Kuchuk", "author_id": 212746, "author_profile": "https://Stackoverflow.com/users/212746", "pm_score": 2, "selected": false, "text": "<Button Width=\"200\" Height=\"70\">\n <Button.Content>\n <StackPanel>\n <Image Width=\"20\" Height=\"20\">\n <Image.Source>\n <BitmapImage UriSource=\"/Company.ProductAssembly;component/Icons/ClickMe.png\"></BitmapImage>\n </Image.Source>\n </Image>\n <TextBlock HorizontalAlignment=\"Center\">Click me!</TextBlock>\n </StackPanel>\n </Button.Content>\n</Button>\n" }, { "answer_id": 2616419, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "static ImageSource PngStreamToImageSource (Stream pngStream) {\n var decoder = new PngBitmapDecoder(pngStream,\n BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);\n return decoder.Frames[0];\n}\n" }, { "answer_id": 3175152, "author": "JoanComasFdz", "author_id": 383129, "author_profile": "https://Stackoverflow.com/users/383129", "pm_score": 2, "selected": false, "text": "Properties.Resources.ResourceManager.GetURI(\"my_image\");\n // Convert the image in resources to a Stream\nStream ms = new MemoryStream()\nProperties.Resources.MyImage.Save(ms, ImageFormat.Png);\n\n// Create a BitmapImage with the stream.\nBitmapImage bitmap = new BitmapImage();\nbitmap.BeginInit();\nbitmap.StreamSource = ms;\nbitmap.EndInit();\n\n// Set as source\nSource = bitmap;\n" }, { "answer_id": 3178260, "author": "Bharat Thanki", "author_id": 383512, "author_profile": "https://Stackoverflow.com/users/383512", "pm_score": 3, "selected": false, "text": "Uri iconUri = new Uri(\"pack://application:,,,/ImageNAme.ico\", UriKind.RelativeOrAbsolute);\nNotifyIcon.Icon = BitmapFrame.Create(iconUri);\n" }, { "answer_id": 4423017, "author": "A Bothe", "author_id": 539729, "author_profile": "https://Stackoverflow.com/users/539729", "pm_score": 6, "selected": false, "text": "MyMenuItem.ImageSource = \n new BitmapImage(new Uri(\"Resource/icon.ico\",UriKind.Relative));\n" }, { "answer_id": 4985549, "author": "Payson Welch", "author_id": 552591, "author_profile": "https://Stackoverflow.com/users/552591", "pm_score": 4, "selected": false, "text": " this.Icon = new BitmapImage(new Uri(\"Icon.ico\", UriKind.Relative));\n" }, { "answer_id": 8164760, "author": "Hasan", "author_id": 721594, "author_profile": "https://Stackoverflow.com/users/721594", "pm_score": 4, "selected": false, "text": "var uriSource = new Uri(\"image path here\");\nimage1.Source = new BitmapImage(uriSource);\n" }, { "answer_id": 29575996, "author": "maulik kansara", "author_id": 4776259, "author_profile": "https://Stackoverflow.com/users/4776259", "pm_score": 2, "selected": false, "text": "Assembly asm = Assembly.GetExecutingAssembly();\nStream iconStream = asm.GetManifestResourceStream(asm.GetName().Name + \".\" + \"Desert.jpg\");\nBitmapImage bitmap = new BitmapImage();\nbitmap.BeginInit();\nbitmap.StreamSource = iconStream;\nbitmap.EndInit();\nimage1.Source = bitmap;\n" }, { "answer_id": 30138786, "author": "IlPADlI", "author_id": 2430943, "author_profile": "https://Stackoverflow.com/users/2430943", "pm_score": 4, "selected": false, "text": "internal static class ResourceAccessor\n{\n public static Uri Get(string resourcePath)\n {\n var uri = string.Format(\n \"pack://application:,,,/{0};component/{1}\"\n , Assembly.GetExecutingAssembly().GetName().Name\n , resourcePath\n );\n\n return new Uri(uri);\n }\n}\n new BitmapImage(ResourceAccessor.Get(\"Images/1.png\"))\n" }, { "answer_id": 43976263, "author": "Hollyroody", "author_id": 3587698, "author_profile": "https://Stackoverflow.com/users/3587698", "pm_score": 3, "selected": false, "text": "MyImage.Source = MyImage.FindResource(\"MyImageKeyDictionary\") as ImageSource;\n" }, { "answer_id": 64308241, "author": "Donovan Phoenix", "author_id": 4854335, "author_profile": "https://Stackoverflow.com/users/4854335", "pm_score": 0, "selected": false, "text": "img.Source = new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + @\"\\Images\\image.jpg\", UriKind.Absolute));\n" }, { "answer_id": 68168084, "author": "VinaCaptcha", "author_id": 2580101, "author_profile": "https://Stackoverflow.com/users/2580101", "pm_score": -1, "selected": false, "text": "Image.Source = new BitmapImage(new Uri(\"Resources/processed.png\", UriKind.Relative));\n UriKind.Relative // relative path\nUriKind.Absolute // exactly path\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22621/" ]
350,047
<p>I would like to run a job through cron that will be executed every second Tuesday at given time of day. For every Tuesday is easy:</p> <pre><code>0 6 * * Tue </code></pre> <p>But how to make it on "every second Tuesday" (or if you prefer - every second week)? I would not like to implement any logic in the script it self, but keep the definition only in cron.</p>
[ { "answer_id": 350061, "author": "xahtep", "author_id": 42184, "author_profile": "https://Stackoverflow.com/users/42184", "pm_score": 7, "selected": true, "text": "crontab 0 6 * * Tue expr `date +\\%W` \\% 2 > /dev/null || /scripts/fortnightly.sh\n" }, { "answer_id": 15022838, "author": "jimmyb", "author_id": 1279587, "author_profile": "https://Stackoverflow.com/users/1279587", "pm_score": -1, "selected": false, "text": "0 6 * * Tue/2\n" }, { "answer_id": 19276777, "author": "Björn", "author_id": 228450, "author_profile": "https://Stackoverflow.com/users/228450", "pm_score": 3, "selected": false, "text": "0 0 8 ? 1/1 TUE#1 *\n 0 0 8 ? 1/1 TUE#3 *\n" }, { "answer_id": 19278657, "author": "pilcrow", "author_id": 132382, "author_profile": "https://Stackoverflow.com/users/132382", "pm_score": 6, "selected": false, "text": "0 6 * * Tue expr `date +\\%s` / 604800 \\% 2 >/dev/null || /scripts/fortnightly.sh\n date" }, { "answer_id": 20226758, "author": "isaac", "author_id": 3038065, "author_profile": "https://Stackoverflow.com/users/3038065", "pm_score": -1, "selected": false, "text": "0 0 1-7,15-21,29-31 * 5\n" }, { "answer_id": 33227955, "author": "notorious.dds", "author_id": 5321658, "author_profile": "https://Stackoverflow.com/users/5321658", "pm_score": 3, "selected": false, "text": "0 6 * * Tue expr \\( `date +\\%s` / 604800 + 1 \\) \\% 2 > /dev/null || /scripts/fortnightly.sh\n" }, { "answer_id": 41255622, "author": "dxdc", "author_id": 4626770, "author_profile": "https://Stackoverflow.com/users/4626770", "pm_score": 1, "selected": false, "text": "%W TZ_OFFSET=$( date +%z | perl -ne '$_ =~ /([+-])(\\d{2})(\\d{2})/; print eval($1.\"60**2\") * ($2 + $3/60);' )\nDAY_PARITY=$(( ( `date +%s` + ${TZ_OFFSET} ) / 86400 % 2 ))\n if [ ${DAY_PARITY} -eq 1 ]; then\n...\nelse\n...\nfi\n" }, { "answer_id": 53326544, "author": "Paul Lemmons", "author_id": 8208327, "author_profile": "https://Stackoverflow.com/users/8208327", "pm_score": 2, "selected": false, "text": "0 6 * * 1 expr \\( `date +\\%s` / 86400 - `date --date='2018-03-19' +\\%s` / 86400 \\) \\% 14 == 0 > /dev/null && /scripts/fortnightly.sh\n" }, { "answer_id": 68191811, "author": "Bhupendra Bisht", "author_id": 10069435, "author_profile": "https://Stackoverflow.com/users/10069435", "pm_score": 3, "selected": false, "text": "0 0 1-7,15-21 * 2\n" }, { "answer_id": 68192038, "author": "Wolfack", "author_id": 4482269, "author_profile": "https://Stackoverflow.com/users/4482269", "pm_score": 0, "selected": false, "text": "0 0 1-7,15-21 * 2\n" }, { "answer_id": 68946240, "author": "Scottie H", "author_id": 10980232, "author_profile": "https://Stackoverflow.com/users/10980232", "pm_score": 1, "selected": false, "text": "\\<minute\\> \\<hour\\> * * \\<Day of Week\\> expr \\\\( $( date+\\\\%s ) \\\\/ 604800 \\\\% 2 \\\\) > /dev/null && \\<command to run on odd weeks\\> || \\<command to run on even weeks\\>\n crontab -e */2 1 + */2 1,15 2-8 date +%W 2,16 date +%s date +%N date +%s.%N date +\"%s / 604800 % 2\" | bc expr $( date +%s ) / 604800 % 2 $ expr 1 % 2 && echo Odd || echo Even\n1\nOdd \n$ expr 2 % 2 && echo Odd || echo Even \n0 \nEven\n 15 3 * * TUE expr \\\\( $( date+\\\\%s ) \\\\/ 604800 \\\\% 2 \\\\) > /dev/null\n && || expr \\\\( $( date+\\\\%s ) \\\\/ 604800 \\\\% 2 \\\\) > /dev/null && \\<command_O\\> || \\<command_E\\>\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42201/" ]
350,081
<p>In the application I'm working on porting to the web, we currently dynamically access different tables at runtime from run to run, based on a "template" string that is specified. I would like to move the burden of doing that back to the database now that we are moving to SQL server, so I don't have to mess with a dynamic GridView. I thought of writing a Table-valued UDF with a parameter for the table name and one for the query WHERE clause.</p> <p>I entered the following for my UDF but obviously it doesn't work. Is there any way to take a varchar or string of some kind and get a table reference that can work in the FROM clause?</p> <pre><code>CREATE FUNCTION TemplateSelector ( @template varchar(40), @code varchar(80) ) RETURNS TABLE AS RETURN ( SELECT * FROM @template WHERE ProductionCode = @code ) </code></pre> <p>Or some other way of getting a result set similar in concept to this. Basically all records in the table indicated by the varchar @template with the matching ProductionCode of the @code.</p> <p>I get the error "Must declare the table variable "@template"", so SQL server probably things I'm trying to select from a table variable.</p> <p>On Edit: Yeah I don't need to do it in a function, I can run Stored Procs, I've just not written any of them before.</p>
[ { "answer_id": 350107, "author": "Harper Shelby", "author_id": 21196, "author_profile": "https://Stackoverflow.com/users/21196", "pm_score": 3, "selected": true, "text": "CREATE PROCEDURE TemplateSelector \n( \n @template varchar(40),\n @code varchar(80)\n)\n\nAS\nEXEC('SELECT * FROM ' + @template + ' WHERE ProductionCode = ' + @code)\n" }, { "answer_id": 350263, "author": "Tony Peterson", "author_id": 26140, "author_profile": "https://Stackoverflow.com/users/26140", "pm_score": 0, "selected": false, "text": "SELECT * FROM TEMPLATENAME WHERE ProductionCode = @code\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26140/" ]
350,095
<p>Is there a way to programmatically, through a batch file (or powershell script), put all folders in <code>c:\Program Files</code> into the system variable <code>PATH</code>? I'm dependent on the command line and really want to just start a program from the command line.</p> <p>Yes, I'm jealous of Linux shells.</p>
[ { "answer_id": 350121, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 3, "selected": false, "text": "@echo off\n\nFOR /D %%G IN (%1\\*) DO PATH \"%%G\";%path%\n" }, { "answer_id": 350273, "author": "Rob Williams", "author_id": 26682, "author_profile": "https://Stackoverflow.com/users/26682", "pm_score": 3, "selected": false, "text": "PATH PATH PATH bin bin PATH bin SetLocal %ProgramFiles% PATH PATH" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
350,101
<p>Ok time to show my complete lack of knowladge for all things web forms but here goes. I am extending the Panel control and OnPreRender sticking some additional controls inside of it (lets just say 1 textbox for simplicity). From here I am just letting the Panels Render method do its thing. </p> <p>The issue I am having is that obviously every time this control is rerendered it is just sticks that same TextBox in the panel again with the value I am coding in the OnPreRender method. Now I dont actually want to repopulate the panel every time, </p> <p>I want to stick the textbox contorl in there on first load and have them reloaded from the control/viewstate caches. In this case with my example of just sticking a single textbox in the panel, if the value of the textbox changes and a postback occurs I want that value to to remain the changed value. </p> <p>Really basic webforms stuff I know, but I have never had to create custom controls in my time. ANy help appreciated. </p> <p>Chris. </p>
[ { "answer_id": 350197, "author": "Programmin Tool", "author_id": 21691, "author_profile": "https://Stackoverflow.com/users/21691", "pm_score": 1, "selected": false, "text": "public class SomeControl : WebControl, INamingContainer\n{\n private TextBox someTextBox;\n\n protected override void CreateChildControls()\n {\n base.CreateChildControls();\n\n someTextBox= new TextBox();\n someTextBox.ID = \"tbxMain\";\n\n Controls.Add(textboxToCheck);\n }\n}\n public class SomeControl : WebControl, INamingContainer\n{\n private TextBox someTextBox;\n\n protected override void CreateChildControls()\n {\n base.CreateChildControls();\n\n someTextBox= new TextBox();\n someTextBox.ID = \"tbxMain\";\n\n Controls.Add(textboxToCheck);\n }\n\n public String CssClass { get; set; }\n}\n someTextBox.CssClass = CssClass;\n set\n { \n EnsureChildControls();\n someTextbox.CssClass = value;\n }\n protected override void OnPreRender(EventArgs e)\n{\n someTextbox.CssClass = CssClass;\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/425/" ]
350,120
<p>Does someone knows if it's possible to dynamically create a call chain and invoke it?</p> <p>Lets say I have two classes A &amp; B:</p> <pre><code>public class A public function Func() as B return new B() end function end class public class B public function Name() as string return "a string"; end function end class </code></pre> <p>I want to be able to get <em>MethodInfo</em> for both <em>Func()</em> &amp; <em>Name()</em> and invoke them dynamically so that I can get a call similar to <em>A.Func().Name()</em>.</p> <p>I know I can use <em>Delegate.CreateDelegate</em> to create a delegate I can invoke from the two <em>MethodInfo</em> objects but this way I can only call the two functions separately and not as part of a call chain.</p> <p>I would like two solutions one for .NET 3.5 using expression tree and if possible a solution that is .NET 2.0 compatible as well</p>
[ { "answer_id": 350178, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "// I assume you've already got fMethodInfo and nameMethodInfo.\nExpression fCall = Expression.Call(null, fMethodInfo);\nExpression nameCall = Expression.Call(fCall, nameMethodInfo);\nExpression<Func<string>> lambda = Expression.Lambda<Func<string>>(nameCall, null);\nFunc<string> compiled = lambda.Compile();\n" }, { "answer_id": 352209, "author": "Dror Helper", "author_id": 11361, "author_profile": "https://Stackoverflow.com/users/11361", "pm_score": 0, "selected": false, "text": "Expression ctorCall = Expression.Constructor(A)\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11361/" ]
350,124
<p>I'm looking to write an automated monitor script to programmatically retrieve information from another user's Exchange 2003 inbox. I have working C++ code to log into MAPI and connect to my own inbox. I can also use the Control Panel->Mail applet to configure another user's mailbox into my profile, and my code can access that way. However, this was done on my desktop with Outlook installed, which provides a richer mail profile editor.</p> <p>Since this will run on a server, I'd prefer not to install Outlook at all. Instead, I can install the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=E17E7F31-079A-43A9-BFF2-0A110307611E&amp;displaylang=en" rel="nofollow noreferrer">MAPI client</a>. I then create a simple MAPI app that pops up the mail profile wizard using <code>MAPILogonEx()</code> with the <code>MAPI_LOGON_UI</code> flag. However, the basic MAPI client doesn't have the features to configure another user's mailbox. As a requirement, I can only run this script as the service account of the monitoring application, so I cannot tell it to run as the account whose mailbox I want.</p> <p>Is it still possible to connect to another user's mailbox (assuming permissions are already granted) using the basic MAPI client? Or is it absolutely necessary to install Outlook for this functionality?</p>
[ { "answer_id": 350581, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "CreateStoreEntryID IID_IExchangeManageStore CreateStoreEntryID LPEXCHANGEMANAGESTORE mapiObject = NULL;\n\nstore->QueryInterface( IID_IExchangeManageStore, (LPVOID *) &mapiObject);\n\nmapiObject->CreateStoreEntryID( server, mailbox, OPENSTORE_TAKE_OWNERSHIP | \n OPENSTORE_USE_ADMIN_PRIVILEGE, &len, &buffer);\n\n//Call OpenEntry on the entry id\n CreateStoreEntryID microsoft.public.win32.programmer.messaging" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3347/" ]
350,126
<p>I am trying to write a textbox that will search on 5 DB columns and will return every result of a given search, ex. "Red" would return: red ball, Red Williams, etc. Any examples or similar things people have tried. My example code for the search.</p> <p>Thanks.</p> <pre><code> ItemMasterDataContext db = new ItemMasterDataContext(); string s = txtSearch.Text.Trim(); var q = from p in db.ITMSTs where p.IMITD1.Contains(s) || p.IMITD2.Contains(s) || p.IMMFNO.Contains(s) || p.IMITNO.Contains(s) || p.IMVNNO.Contains(s) select p; lv.DataSource = q; lv.DataBind(); </code></pre>
[ { "answer_id": 350189, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "IQueryable<ITMST> lv.DataSource = q.ToList();\n" }, { "answer_id": 357340, "author": "Perpetualcoder", "author_id": 37494, "author_profile": "https://Stackoverflow.com/users/37494", "pm_score": 1, "selected": true, "text": "using(var db = new ItemMasterDataContext())\n{\n var s = txtSearch.Text.Trim();\n var result = from p in db.ITMSTs select p;\n\n if( result.Any(p=>p.IMITD1.Contains(s))\n lv.DataSource = result.Where(p=>p.IMITD1.Contains(s))\n else if ( result.Any(p=>p.IMITD2.Contains(s))\n lv.DataSource = result.Where(p=>p.IMITD1.Contains(s))\n\n lv.DataBind();\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37126/" ]
350,129
<p>How do I check to see if a particular value has already been assigned to Smarty and if not assign a (default) value?</p> <p>Answer:</p> <pre><code>if ($this-&gt;cismarty-&gt;get_template_vars('test') === null) { $this-&gt;cismarty-&gt;assign('test', 'Default value'); } </code></pre>
[ { "answer_id": 350162, "author": "Andy", "author_id": 26693, "author_profile": "https://Stackoverflow.com/users/26693", "pm_score": 5, "selected": true, "text": "if ($smarty->get_template_vars('foo') === null) \n{\n $smarty->assign('foo', 'some value');\n}\n if ($smarty->getTemplateVars('foo') === null) \n{\n $smarty->assign('foo', 'some value');\n}\n $smarty->getTemplateVars" }, { "answer_id": 350174, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 0, "selected": false, "text": "if (!isset($smarty['foo'])) \n{\n $smarty->assign('foo', 'some value');\n}\n" }, { "answer_id": 350245, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 1, "selected": false, "text": "get_template_vars() if ($smarty->get_template_vars('test') === null) {\n echo \"'test' is not assigned or is null\";\n}\n $tmp = $smarty->get_template_vars();\nif (!array_key_exists('test', $tmp)) {\n echo \"'test' is not assigned\";\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3238/" ]
350,131
<p>Are there any performance benefits to me not using the gridview in asp.net for simple tables querying from a stored procedure and instead writing the html in server code myself. I'm sure my code would certainly be more concise in output.</p>
[ { "answer_id": 350206, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "Dim tab As New Table\nFor Each row In DataTable.Rows\n Dim tabRow as New TableRow\n For Each col In row.Columns\n dim tabCol as New TableColumn\n tabCol .Text = row(col)\n tabRow.Controls.Add(tabCol )\n Next\n tab.Rows.Add(tabRow)\nNext \nPage.Controls.Add(tab)\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16989/" ]
350,140
<p>So I'm basically a beginner when it comes to Vim, nonetheless I do know the basic things (open files, edit, move around, basic grep, .vimrc, etc)</p> <p>I would submit this link first</p> <p><a href="http://weblog.jamisbuck.org/2008/11/17/vim-follow-up" rel="nofollow noreferrer">http://weblog.jamisbuck.org/2008/11/17/vim-follow-up</a></p> <p>If you scroll down to where it says "NERD___tree", it explains what it is and gives a link to the home page. I have already gotten NERD_tree installed, so far so good.</p> <p>Only thing is, this guy (JamisBuck) adds a line to the .vimrc file to streamline it's usage (I'm guessing to toggle between NERD_tree and the actual file, because as far as I can tell, there is no quick way to do it other than typing in:</p> <pre><code>:NERDTree </code></pre> <p>Every time which is less than desirable. The follwing is the code he adds to the .vimrc file:</p> <pre><code>map &lt;leader&gt;d :execute 'NERDTreeToggle ' . getcwd()&lt;CR&gt; </code></pre> <p>He doesn't explain exactly what is is and/or how to use it, so If someone could give me a short explanation and/or point me towards a resource to learn more about this, that would be appreciated.</p>
[ { "answer_id": 350159, "author": "mat", "author_id": 42083, "author_profile": "https://Stackoverflow.com/users/42083", "pm_score": 4, "selected": true, "text": ":help leader map <leader>d \\d" }, { "answer_id": 350171, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 3, "selected": false, "text": "<Leader>\n map <leader>d :execute 'NERDTreeToggle ' . getcwd()<CR>\n I’ve got my <Leader> character (:h mapleader) mapped to the comma \n(since it’s easier to reach than the backspace character).\n\nlet mapleader = \",\"\n" }, { "answer_id": 350540, "author": "Jeremy Cantrell", "author_id": 18866, "author_profile": "https://Stackoverflow.com/users/18866", "pm_score": 2, "selected": false, "text": ":execute 'NERDTreeToggle ' . getcwd()<CR>\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44346/" ]
350,141
<p>In Unix/Linux, how do you find out what group a given user is in via command line?</p>
[ { "answer_id": 350144, "author": "Bombe", "author_id": 43582, "author_profile": "https://Stackoverflow.com/users/43582", "pm_score": 10, "selected": true, "text": "groups\n groups user\n" }, { "answer_id": 350145, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 7, "selected": false, "text": "id userid\n" }, { "answer_id": 29615844, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 4, "selected": false, "text": "id -Gn [user]\n groups [user] id -p [user] -G --groups -n --name -ugG -p" }, { "answer_id": 61593888, "author": "Namasivayam Chinnapillai", "author_id": 12886837, "author_profile": "https://Stackoverflow.com/users/12886837", "pm_score": 0, "selected": false, "text": "sh collection.sh\n\n#!/bin/bash\n\nHOSTNAME=`hostname -s`\n\nfor i in `cat /etc/passwd| grep -vE \"nologin|shutd|hal|sync|root|false\"|awk -F':' '{print$1}' | sed 's/[[:space:]]/,/g'`; do groups $i; done|sed s/\\:/\\,/g|tr -d ' '|sed -e \"s/^/$HOSTNAME,/\"> /tmp/\"$HOSTNAME\"_inventory.txt\n\nsudo cat /etc/sudoers| grep -v \"^#\"|awk '{print $1}'|grep -v Defaults|sed '/^$/d;s/[[:blank:]]//g'>/tmp/\"$HOSTNAME\"_sudo.txt\n\npaste -d , /tmp/\"$HOSTNAME\"_inventory.txt /tmp/\"$HOSTNAME\"_sudo.txt|sed 's/,[[:blank:]]*$//g' >/tmp/\"$HOSTNAME\"_inventory_users.txt\n cat /tmp/ANSIBLENODE_sudo.txt\ncat /tmp/ANSIBLENODE_inventory.txt\ncat /tmp/ANSIBLENODE_inventory_users.txt\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5885/" ]
350,150
<p>I am trying to run some Perl CGI scripts under IIS. I get the following message :</p> <pre> <code> CGI Error The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are: perl: warning: Setting locale failed. perl: warning: Please check that your locale settings: LC_ALL = (unset), LANG = (unset) are supported and installed on your system. perl: warning: Falling back to the standard locale ("C"). </code> </pre> <p>I found out that the problem occurs only when I "use" an internal library of ours but it's really a big one (using many other stuff) so I would prefer to know where to look. When I run the same script from the command line, the script runs just fine. I tried to set "LANG" to "C", then "LC_ALL" to "C" but it had no effect.</p> <p>Any pointers welcome!</p>
[ { "answer_id": 350165, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 0, "selected": false, "text": "use CGI::CARP qw(fatalsToBrowser) fatalsToBrowser" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35273/" ]
350,181
<p>What is the best was to evaluate an expression like the following: <br /> (A And B) Or (A And C) Or (Not B And C)<br /> or<br /> (A &amp;&amp; B) || (A &amp;&amp; C) || (!B &amp;&amp; C)<br /></p> <p>At runtime, I was planning on converting the above expressions to the following:<br /> (True And False) Or (True And False) Or (Not False And True)<br /> or<br /> (True &amp;&amp; False) || (True &amp;&amp; False) || (! False &amp;&amp; True)<br /></p> <p>Conditions: 1) The logical expression is not known until runtime. 2) The number variable and their values are not known until runtime. 3) Variable values are never null.</p> <p>I know I could create a simple assemble with a class and a method that I generate at runtime based on the inputs, but is there a better way. I have done this before. Use a string builder to write the code, then call the compiler. After that, you load the assembly and call the method. </p> <p>Suggestions?</p> <p>Thanks.</p>
[ { "answer_id": 350211, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "And And AndAlso Or OrElse" }, { "answer_id": 350784, "author": "hughdbrown", "author_id": 10293, "author_profile": "https://Stackoverflow.com/users/10293", "pm_score": 2, "selected": false, "text": "program: exprList ;\n\nexprList: expr { Append($1); }\n | expr OR exprList { Append(OR); }\n | expr AND exprList { Append(AND); }\n | NOT exprList { Append(NOT); }\n | ( exprList ) { /* Do nothing */ }\n ;\n\nexpr: var { Append($1); }\n | TRUE { Append(True); }\n | FALSE { Append(False); }\n ;\n for each item in list\n if item is symbol or truth value, push onto RPN stack\n else if item is AND, push (pop() AND pop())\n else if item is OR, push (pop() OR pop())\n else if item is NOT, push (NOT pop())\n\nresult = pop()\n" }, { "answer_id": 36846482, "author": "Nibbels", "author_id": 4083450, "author_profile": "https://Stackoverflow.com/users/4083450", "pm_score": 0, "selected": false, "text": "Dim BoolTermParseObjekt As New BoolTermParse\nMsgBox(BoolTermParseObjekt.parseTerm(\"1 und (((0 oder 1 und (0 oder 4))) oder 2)\").ToString)\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25843/" ]
350,202
<p>The following VBA code works great in Excel 2003, but results in a <em>Stack Overflow Error</em> in Excel 2007. The code is required to either unlock or lock certain cells based on a drop-down menu selection. I need to be able to run the code in both Excel 2003 and 2007. Please help.</p> <pre><code>Private Sub Worksheet_Change(ByVal Target As Range) If [E28] = "NO" Then ActiveSheet.Unprotect ("PASSWORD") [K47:K53].Locked = False [K47:K53].Interior.ColorIndex = 16 [K47:K53].ClearContents ActiveSheet.Protect ("PASSWORD") Else ActiveSheet.Unprotect ("PASSWORD") [K47:K53].Interior.ColorIndex = 0 'Next line is optional, remove preceding apostrophe if protection should stay on. ActiveSheet.Protect ("PASSWORD") End If End Sub </code></pre>
[ { "answer_id": 350246, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 2, "selected": false, "text": "Private m_bInChange As Boolean\n\nPrivate Sub Worksheet_Change(ByVal Target As Range)\nIf m_bInChange Then Exit Sub\nOn Error GoTo ErrHandler\n m_bInChange = True\n If [E28] = \"NO\" Then\n ActiveSheet.Unprotect (\"PASSWORD\")\n [K47:K53].Locked = False\n [K47:K53].Interior.ColorIndex = 16\n [K47:K53].ClearContents\n ActiveSheet.Protect (\"PASSWORD\")\n Else\n ActiveSheet.Unprotect (\"PASSWORD\")\n [K47:K53].Interior.ColorIndex = 0\n 'Next line is optional, remove preceding apostrophe if protection should stay on.\n ActiveSheet.Protect (\"PASSWORD\")\n End If\n\n m_bInChange = False\n Exit Sub\nErrHandler:\n m_bInChange = False\n Exit Sub\nEnd Sub\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
350,207
<p>I have an ASP.NET page that uses a menu based on <code>asp:LinkButton</code> control in a Master page. When a user selects a menu item, an <code>onclick</code> handler calls a method in my C# code. The method it calls just does a <code>Server.Transfer()</code> to a new page. From what I have read, this is not supposed to change the URL displayed in the browser.</p> <p>The problem is it that the URL changes in the browser as the user navigates the menu to different pages.</p> <p>Here is an item in the menu:</p> <pre><code>&lt;asp:LinkButton id="foo" runat="server" onclick="changeToHelp"&gt;&lt;span&gt;Help&lt;/span&gt; &lt;/asp:LinkButton&gt; </code></pre> <p>In my C# code, I handle the event with a method like:</p> <pre><code>protected void changeToHelp(object sender, EventArgs e) { Server.Transfer("Help.aspx"); } </code></pre> <p>Any ideas how I can navigate through the menu without the browser's URL bar changing?</p>
[ { "answer_id": 350216, "author": "JoshBerke", "author_id": 26160, "author_profile": "https://Stackoverflow.com/users/26160", "pm_score": 0, "selected": false, "text": "Server.Execute(\"Help.aspx\") Server.Execute(\"Help.aspx\",true);\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16148/" ]
350,214
<p>I have a ListBox whose ItemSource is an ObjectDataProvider that is an instance of an ObservableCollection. The ObservableCollection is a collection of ObservableCollections. The ItemTemplate of the ListBox is a DataTemplate that creates a ListBox for each item of the listbox. To illustrate this better I'm trying to recreate a card game in WPF. Basically, from a hand of cards you can create books. After you have a valid book, you can elect to make it a book which will go into the ObservableCollection of Books. The problem that I'm having is that each item of the ListBox is a ListBox that has an ItemSource that is a Book, that is an ObservableCollection of Cards. I don't think I'm having a problem with the source or the template of the outer ListBox, but I'm having a hard time understanding how I'm going to set the source of the ListBox items to the collection of cards for each book. Essentially, my question may be confusing and a difficult concept to grasp, but essentially I'm trying to figure out how to use a ListBox in a template that will be the template of another ListBox. If anyone has any idea of how to approach this, I would greatly appreciate hearing it.</p>
[ { "answer_id": 351392, "author": "Donnelle", "author_id": 28074, "author_profile": "https://Stackoverflow.com/users/28074", "pm_score": 3, "selected": true, "text": " public class Card\n{\n\n private string _name;\n\n public Card(string name)\n {\n _name = name;\n }\n\n\n public string Name\n {\n get { return _name; }\n set { _name = value; }\n }\n}\n public class Book\n{\n private readonly ObservableCollection<Card> _cards;\n\n public Book(ObservableCollection<Card> cards)\n {\n _cards = cards;\n }\n\n\n public ObservableCollection<Card> Cards\n {\n get { return _cards; }\n }\n}\n <ListBox\n ItemsSource=\"{Binding ElementName=Window, Path=Books}\"\n ItemTemplate=\"{StaticResource MainListTemplate}\" />\n <Window.Resources>\n <ResourceDictionary>\n\n <DataTemplate\n x:Key=\"InsideListTemplate\">\n <TextBlock\n Text=\"{Binding Name}\" />\n\n </DataTemplate>\n\n <DataTemplate\n x:Key=\"MainListTemplate\">\n <ListBox\n ItemsSource=\"{Binding Cards}\"\n ItemTemplate=\"{StaticResource InsideListTemplate}\" />\n\n </DataTemplate>\n\n\n\n </ResourceDictionary>\n</Window.Resources>\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42858/" ]
350,227
<p>I've encountered a very strange bug in VBA and wondered if anyone could shed some light?</p> <p>I'm calling a worksheet function like this: </p> <pre><code>Dim lMyRow As Long lMyRow = WorksheetFunction.Match(vItemID, rngMyRange.Columns(1), 0) </code></pre> <p>This is intended to get the row of the item I pass in. Under certain circumstances (although I can't pin down exactly when), odd things happen to the call to the Match function.</p> <p>If I execute that line in the immediate window, I get the following:</p> <pre><code>lMyRow = WorksheetFunction.Match(vItemID, rngMyRange.Columns(1), 0) ?lMyRow 10 </code></pre> <p>i.e. the lookup works, and lMyRow gets a value assigned to it. If I let that statement execute in the actual code, I lMyRow gets a value of 0.</p> <p>This seems very odd! I don't understand how executing something in the immediate window can succeed in assigning a value, where the same call, at the same point in program execution can give a value of 0 when it runs normally in code!</p> <p>The only thing I can think of is that it's some odd casting thing, but I get the same behaviour taking if the variable to which I'm assigning is an int, a double, or even a string.</p> <p>I don't even know where to begin with this - help!!</p>
[ { "answer_id": 350351, "author": "Dirk Vollmar", "author_id": 40347, "author_profile": "https://Stackoverflow.com/users/40347", "pm_score": 0, "selected": false, "text": "Sub test()\n\nDim vItemID As Variant\nDim lMyRow As Long\nDim rngMyRange As Range\n\n Set rngMyRange = ActiveWorkbook.Sheets(1).Range(\"A1:Z256\")\n\n vItemID = 8\n lMyRow = WorksheetFunction.Match(vItemID, rngMyRange.Columns(1), 0)\n\n Debug.Print lMyRow\n\nEnd Sub\n" }, { "answer_id": 353034, "author": "Jon Artus", "author_id": 4019, "author_profile": "https://Stackoverflow.com/users/4019", "pm_score": 0, "selected": false, "text": "Function makeTheLookup(vItemID As Variant, rngMyRange as Range)\n\nDim lMyRow As Long\nlMyRow = WorksheetFunction.Match(vItemID, rngMyRange.Columns(1), 0)\n\nEnd Function\n" }, { "answer_id": 359294, "author": "Devdatta Tengshe", "author_id": 895, "author_profile": "https://Stackoverflow.com/users/895", "pm_score": 0, "selected": false, "text": "Debug.print" }, { "answer_id": 379640, "author": "Dick Kusleika", "author_id": 4280, "author_profile": "https://Stackoverflow.com/users/4280", "pm_score": 2, "selected": false, "text": "makeTheLookup = lMyRow" }, { "answer_id": 389570, "author": "CABecker", "author_id": 32790, "author_profile": "https://Stackoverflow.com/users/32790", "pm_score": 1, "selected": false, "text": "Function makeTheLookup(vItemID As Variant, rngMyRange as Range)as Long\n makeTheLookUp = WorksheetFunction.Match(vItemID, rngMyRange.Columns(1), 0)\nEnd Function\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4019/" ]
350,240
<p>I am doing some float manipulation and end up with the following numbers:</p> <pre><code>-0.5 -0.4 -0.3000000000000000004 -0.2000000000000000004 -0.1000000000000000003 1.10E-16 0.1 0.2 0.30000000000000000004 0.4 0.5 </code></pre> <p>The algorithm is the following:</p> <pre><code>var inc:Number = nextMultiple(min, stepSize); trace(String(inc)); private function nextMultiple(x:Number, y:Number) { return Math.ceil(x/y)*y; } </code></pre> <p>I understand the fact the float cannot always be represented accurately in a byte. e.g 1/3. I also know my stepsize <strong>being 0.1</strong>. If I have the stepsize how could I get a proper output?</p> <p>The strange thing is that its the first time I've encountered this type of problem. Maybe I dont play with float enough.</p>
[ { "answer_id": 350258, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 1, "selected": false, "text": "float value = 1.0F;\n\nfor (int i = 0; i < 20; i++)\n{\n value -= 0.1F;\n Console.WriteLine(Math.Round(value, 1).ToString() + \" : \" + value.ToString());\n}\n" }, { "answer_id": 350261, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 4, "selected": true, "text": "printf (\"float: %.1f\\n\", number);\n" }, { "answer_id": 350985, "author": "coulix", "author_id": 32032, "author_profile": "https://Stackoverflow.com/users/32032", "pm_score": 0, "selected": false, "text": "var digitsNbr:Number = Math.abs(Math.ceil(((Math.log(stepSize) / Math.log(10))) + 1)); \ntickTxt.text = String(inc.toPrecision(digitsNbr));\n" }, { "answer_id": 403282, "author": "Niko Nyman", "author_id": 36817, "author_profile": "https://Stackoverflow.com/users/36817", "pm_score": 0, "selected": false, "text": "var inc:Number = nextMultiple(min, stepSize);\ntrace(String(inc));\n\nprivate function nextMultiple(x:Number, y:Number) {\n return Math.ceil(x/y)*(y*10)/10;\n}\n y" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32032/" ]
350,250
<p>I need a RegEx pattern for extracting all the properties of an image tag.</p> <p>As we all know, there are lots of malformed HTML out there, so the pattern has to cover those possibilities.</p> <p>I was looking at this solution <a href="https://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php" title="How to Extract img src title and alt">https://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php</a> but it didn't quite get it all:</p> <p>I come up something like:</p> <pre><code>(alt|title|src|height|width)\s*=\s*["'][\W\w]+?["'] </code></pre> <p>Is there any possibilities I'll be missing or a more efficient simple pattern?</p> <p>EDIT: <br>Sorry, I will be more specific, I'm doing this using .NET so it's on the server side. <br>I've already a list of img tags, now I just need to parse the properties.</p>
[ { "answer_id": 350274, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "element.attributes //\\b\\w+=\"[^\"]+\"//" }, { "answer_id": 1994371, "author": "Tor Valamo", "author_id": 228936, "author_profile": "https://Stackoverflow.com/users/228936", "pm_score": 0, "selected": false, "text": "/<img(\\s+([a-z]{3,})=([\"']([^\"']*)[\"']|[\\S]))+\\s*/?>/i\n 0 -> image tag\n1 -> attribute\n2 -> attribute name\n3 -> attribute value (with enclosing quotes if exists)\n4 -> attribute value (without enclosing quotes if it has them, otherwise empty, use 3)\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41385/" ]
350,255
<p>Heres my link:</p> <p><a href="http://tinyurl.com/6j727e" rel="noreferrer">http://tinyurl.com/6j727e</a></p> <p>If you click on the link in test.php, it opens in a modal box which is using the jquery 'facebox' script.</p> <p>I'm trying to act upon a click event in this box, and if you view source of test.php you'll see where I'm trying to loacte the link within the modal box.</p> <pre><code> $('#facebox .hero-link').click(alert('click!')); </code></pre> <p>However, it doesn't detect a click and oddly enough the click event runs when the page loads.</p> <p>The close button DOES however have a click event built in that closes the box, and I suspect my home-grown click event is being prevented somehow, but I can't figure it out.</p> <p>Can anyone help? Typically its the very last part of a project and its holding me up, as is always the way ;)</p>
[ { "answer_id": 350289, "author": "Ryan McGeary", "author_id": 8985, "author_profile": "https://Stackoverflow.com/users/8985", "pm_score": 4, "selected": true, "text": "#click alert #facebox .hero-link $(document).bind('reveal.facebox', function() {\n $('#facebox .hero-link').click(function() { alert('click!'); });\n});\n $('#facebox .hero-link').click(function() { alert('click!'); });\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ]
350,264
<p>I have an Excel spreadsheet containing a list of strings. Each string is made up of several words, but the number of words in each string is different.</p> <p>Using built in Excel functions (no VBA), is there a way to isolate the last word in each string?</p> <p>Examples:</p> <pre> Are you classified as human? -> human? Negative, I am a meat popsicle -> popsicle Aziz! Light! -> Light!</pre>
[ { "answer_id": 350296, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "=RIGHT(A1,LEN(A1)-FIND(\"`*`\",SUBSTITUTE(A1,\" \",\"`*`\",LEN(A1)-LEN(SUBSTITUTE(A1,\" \",\"\"))))) \n" }, { "answer_id": 350339, "author": "Jon", "author_id": 25111, "author_profile": "https://Stackoverflow.com/users/25111", "pm_score": 4, "selected": false, "text": "=IF(COUNTIF(A1,\"* *\"),RIGHT(A1,LEN(A1)-LOOKUP(LEN(A1),FIND(\" \",A1,ROW(INDEX($A:$A,1,1):INDEX($A:$A,LEN(A1),1))))),A1)\n" }, { "answer_id": 350390, "author": "BradC", "author_id": 21398, "author_profile": "https://Stackoverflow.com/users/21398", "pm_score": 9, "selected": true, "text": "=RIGHT(A1,LEN(A1)-FIND(\"|\",SUBSTITUTE(A1,\" \",\"|\",\n LEN(A1)-LEN(SUBSTITUTE(A1,\" \",\"\")))))\n LEN(A1)-LEN(SUBSTITUTE(A1,\" \",\"\")) SUBSTITUTE(A1,\" \",\"|\", ... ) | FIND(\"|\", ... ) | Right(A1,LEN(A1) - ... )) | =IF(ISERROR(FIND(\" \",A1)),A1, ... )\n =IF(ISERROR(FIND(\" \",A1)),A1, RIGHT(A1,LEN(A1) - FIND(\"|\",\n SUBSTITUTE(A1,\" \",\"|\",LEN(A1)-LEN(SUBSTITUTE(A1,\" \",\"\"))))))\n =IF(COUNTIF(A1,\"* *\") =IF(ISERROR(FIND(\" \",B2)),B2, RIGHT(B2,LEN(B2) - FIND(\"|\",\n SUBSTITUTE(B2,\" \",\"|\",LEN(TRIM(B2))-LEN(SUBSTITUTE(B2,\" \",\"\"))))))\n" }, { "answer_id": 1313566, "author": "Marcelo", "author_id": 154591, "author_profile": "https://Stackoverflow.com/users/154591", "pm_score": 0, "selected": false, "text": "\\ =SE(ÉERRO(PROCURAR(\"\\\",A1)),A1,DIREITA(A1,NÚM.CARACT(A1)-PROCURAR(\"|\", SUBSTITUIR(A1,\"\\\",\"|\",NÚM.CARACT(A1)-NÚM.CARACT(SUBSTITUIR(A1,\"\\\",\"\"))))))\n" }, { "answer_id": 4029212, "author": "gabrielu", "author_id": 488256, "author_profile": "https://Stackoverflow.com/users/488256", "pm_score": 2, "selected": false, "text": "{=RIGHT(A1,LEN(A1)-MAX(IF(MID(A1,ROW(1:999),1)=\" \",ROW(1:999),0)))}\n {=RIGHT(TRIM(A1),LEN(TRIM(A1))-MAX(IF(MID(TRIM(A1),ROW($1:$999),1)=\" \",ROW($1:$999),0)))}\n" }, { "answer_id": 4759635, "author": "Ralf", "author_id": 584535, "author_profile": "https://Stackoverflow.com/users/584535", "pm_score": 1, "selected": false, "text": "\"My little cat\" (1)\n \"tac elttil yM\" (2)\n =LEFT(A1;FIND(\" \";A1)-1) \"My\" \"tac\" \"cat\" ReverseString \"My little cat\" =ReverseString(LEFT(ReverseString(A1);IF(ISERROR(FIND(\" \";A1));\n LEN(A1);(FIND(\" \";ReverseString(A1))-1))))\n \"cat\" IF TRIM CLEAN \"tac \" LEFT \" cat\" -1 FIND LEFT FIND RIGHT LEFT FIND ReverseString" }, { "answer_id": 5992776, "author": "Mark Main", "author_id": 752479, "author_profile": "https://Stackoverflow.com/users/752479", "pm_score": 2, "selected": false, "text": "=RIGHT(TRIM(A1),LEN(TRIM(A1))-FIND(CHAR(7),SUBSTITUTE(\" \"&TRIM(A1),\" \",CHAR(7),\nLEN(TRIM(A1))-LEN(SUBSTITUTE(\" \"&TRIM(A1),\" \",\"\"))+1))+1)\n" }, { "answer_id": 9526808, "author": "Jerry Beaucaire", "author_id": 1196002, "author_profile": "https://Stackoverflow.com/users/1196002", "pm_score": 7, "selected": false, "text": "=TRIM(RIGHT(SUBSTITUTE(A1, \" \", REPT(\" \", 100)), 100))\n =TRIM(LEFT(SUBSTITUTE(A1, \" \", REPT(\" \", 100)), 100))\n" }, { "answer_id": 16868040, "author": "Joe Finkle", "author_id": 2325563, "author_profile": "https://Stackoverflow.com/users/2325563", "pm_score": 5, "selected": false, "text": "=TRIM(RIGHT(SUBSTITUTE(TRIM(A1), \" \", REPT(\" \", LEN(TRIM(A1)))), LEN(TRIM(A1))))\n" }, { "answer_id": 17827640, "author": "Andrew B", "author_id": 2613482, "author_profile": "https://Stackoverflow.com/users/2613482", "pm_score": 2, "selected": false, "text": "=TRIM(LEFT(SUBSTITUTE(TRIM(A1), \" \", REPT(\" \", LEN(TRIM(A1)))), LEN(SUBSTITUTE(TRIM(A1), \" \", REPT(\" \", LEN(TRIM(A1)))))-LEN(TRIM(A1))))\n" }, { "answer_id": 38145561, "author": "J.B.", "author_id": 6339516, "author_profile": "https://Stackoverflow.com/users/6339516", "pm_score": 1, "selected": false, "text": "=LEFT(A1,FIND(IF(\n ISERROR(\n FIND(\"_\",A1)\n ),A1,RIGHT(A1,\n LEN(A1)-FIND(\"~\",\n SUBSTITUTE(A1,\"_\",\"~\",\n LEN(A1)-LEN(SUBSTITUTE(A1,\"_\",\"\"))\n )\n )\n )\n),A1,1)-2)\n" }, { "answer_id": 38347850, "author": "Karthick Gunasekaran", "author_id": 2231100, "author_profile": "https://Stackoverflow.com/users/2231100", "pm_score": 0, "selected": false, "text": "=IF(ISERROR(TRIM(MID(TRIM(D14),SEARCH(\"|\",SUBSTITUTE(TRIM(D14),\" \",\"|\",LEN(TRIM(D14))-LEN(SUBSTITUTE(TRIM(D14),\" \",\"\")))),LEN(TRIM(D14))))),TRIM(D14),TRIM(MID(TRIM(D14),SEARCH(\"|\",SUBSTITUTE(TRIM(D14),\" \",\"|\",LEN(TRIM(D14))-LEN(SUBSTITUTE(TRIM(D14),\" \",\"\")))),LEN(TRIM(D14)))))\n" }, { "answer_id": 67720600, "author": "Alexander Don'valderath", "author_id": 9766970, "author_profile": "https://Stackoverflow.com/users/9766970", "pm_score": 0, "selected": false, "text": "=MID(C3,2+LEN(C3)-SEARCH(\" \",CONCAT(MID(C3,SEQUENCE(LEN(C3),,LEN(C3),-1),1))),LEN(A1)) CONCAT(MID(C3,SEQUENCE(LEN(C3),,LEN(C3),-1),1)) SEARCH(\" \",... =MID(C3,2+LEN(C3)-SEARCH..." }, { "answer_id": 73882771, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 1, "selected": false, "text": "=TEXTAFTER(A1,\" \", -1)\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33686/" ]
350,278
<p>I have problem with starting processes in impersonated context in ASP.NET 2.0.</p> <p>I am starting new Process in my web service code. IIS 5.1, .NET 2.0</p> <pre><code>[WebMethod] public string HelloWorld() { string path = @"C:\KB\GetWindowUser.exe"; ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.WorkingDirectory = Path.GetDirectoryName(path); startInfo.FileName = path; startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; startInfo.ErrorDialog = false; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; Process docCreateProcess = Process.Start(startInfo); string errors = docCreateProcess.StandardError.ReadToEnd(); string output = docCreateProcess.StandardOutput.ReadToEnd(); } </code></pre> <p>The "C:\KB\GetWindowUser.exe" is console application containing following code:</p> <pre><code>static void Main(string[] args) { Console.WriteLine("Windows: " + WindowsIdentity.GetCurrent().Name); } </code></pre> <p>When I invoke web service without impersonation, everything works fine.</p> <p>When I turn on impersonation, following error is written in "errors" variable in web service code:</p> <p>Unhandled Exception: System.Security.SecurityException: Access is denied.\r\n\r\n at System.Security.Principal.WindowsIdentity.GetCurrentInternal(TokenAccessLevels desiredAccess, Boolean threadOnly)\r\n at System.Security.Principal.WindowsIdentity.GetCurrent()\r\n at ObfuscatedMdc.Program.Main(String[] args)\r\nThe Zone of the assembly that failed was:\r\nMyComputer</p> <p>Impersonated user is local administrator and has access to C:\KB\GetWindowUser.exe executable.</p> <p>When I specify window user explicitly in ProcesStartInfo properties Domain, User and Password, I got following message: <a href="http://img201.imageshack.us/img201/5870/pstartah8.jpg">http://img201.imageshack.us/img201/5870/pstartah8.jpg</a></p> <p>Is it possible to start process with different credentials than ASPNET from asp.net (IIS 5.1) ?</p>
[ { "answer_id": 850913, "author": "Jeow Li Huan", "author_id": 263003, "author_profile": "https://Stackoverflow.com/users/263003", "pm_score": 1, "selected": false, "text": "using (Impersonator person = new Impersonator(\"domainName\", \"userName\",\n\"password\")\n{\n // do something requiring special permissions\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43178/" ]
350,292
<p>Given the following classes and controller action method:</p> <pre><code>public School { public Int32 ID { get; set; } publig String Name { get; set; } public Address Address { get; set; } } public class Address { public string Street1 { get; set; } public string City { get; set; } public String ZipCode { get; set; } public String State { get; set; } public String Country { get; set; } } [Authorize(Roles = "SchoolEditor")] [AcceptVerbs(HttpVerbs.Post)] public SchoolResponse Edit(Int32 id, FormCollection form) { School school = GetSchoolFromRepository(id); UpdateModel(school, form); return new SchoolResponse() { School = school }; } </code></pre> <p>And the following form:</p> <pre><code>&lt;form method="post"&gt; School: &lt;%= Html.TextBox("Name") %&gt;&lt;br /&gt; Street: &lt;%= Html.TextBox("Address.Street") %&gt;&lt;br /&gt; City: &lt;%= Html.TextBox("Address.City") %&gt;&lt;br /&gt; Zip Code: &lt;%= Html.TextBox("Address.ZipCode") %&gt;&lt;br /&gt; Sate: &lt;select id="Address.State"&gt;&lt;/select&gt;&lt;br /&gt; Country: &lt;select id="Address.Country"&gt;&lt;/select&gt;&lt;br /&gt; &lt;/form&gt; </code></pre> <p>I am able to update both the School instance and the Address member of the school. This is quite nice! Thank you ASP.NET MVC team!</p> <p>However, how do I use jQuery to select the drop down list so that I can pre-fill it? I realize that I could do this server side but there will be other dynamic elements on the page that affect the list.</p> <p>The following is what I have so far, and it does not work as the selectors don't seem to match the IDs:</p> <pre><code>$(function() { $.getJSON("/Location/GetCountryList", null, function(data) { $("#Address.Country").fillSelect(data); }); $("#Address.Country").change(function() { $.getJSON("/Location/GetRegionsForCountry", { country: $(this).val() }, function(data) { $("#Address.State").fillSelect(data); }); }); }); </code></pre>
[ { "answer_id": 350300, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 9, "selected": true, "text": "$(function() {\n $.getJSON(\"/Location/GetCountryList\", null, function(data) {\n $(\"#Address\\\\.Country\").fillSelect(data);\n });\n $(\"#Address\\\\.Country\").change(function() {\n $.getJSON(\"/Location/GetRegionsForCountry\", { country: $(this).val() }, function(data) {\n $(\"#Address\\\\.State\").fillSelect(data);\n });\n });\n});\n" }, { "answer_id": 350533, "author": "gius", "author_id": 19712, "author_profile": "https://Stackoverflow.com/users/19712", "pm_score": 0, "selected": false, "text": "public static string TextBoxFixed(this HtmlHelper html, string name, string value)\n{\n return html.TextBox(name, value, GetIdAttributeObject(name));\n}\n\npublic static string TextBoxFixed(this HtmlHelper html, string name, string value, object htmlAttributes)\n{\n return html.TextBox(name, value, GetIdAttributeObject(name, htmlAttributes));\n}\n\nprivate static IDictionary<string, object> GetIdAttributeObject(string name)\n{\n Dictionary<string, object> list = new Dictionary<string, object>(1);\n list[\"id\"] = name.Replace('.', '_');\n return list;\n}\n\nprivate static IDictionary<string, object> GetIdAttributeObject(string name, object baseObject)\n{\n Dictionary<string, object> list = new Dictionary<string, object>();\n list.LoadFrom(baseObject);\n list[\"id\"] = name.Replace('.', '_');\n return list;\n}\n" }, { "answer_id": 493384, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 3, "selected": false, "text": "<%= Html.TextBox(\"Person.FirstName\") %>\n <input type=\"text\" name=\"Person.FirstName\" id=\"Person_FirstName\" />\n" }, { "answer_id": 667399, "author": "Elliot Nelson", "author_id": 80630, "author_profile": "https://Stackoverflow.com/users/80630", "pm_score": 5, "selected": false, "text": "$('[id=foo bar]').show();\n $('div[id=foo bar]').show();\n" }, { "answer_id": 19137330, "author": "Daniel", "author_id": 1723944, "author_profile": "https://Stackoverflow.com/users/1723944", "pm_score": 2, "selected": false, "text": "var variable=\"namewith.andother\"; \nvar jqueryObj = $(document.getElementById(variable));\n" }, { "answer_id": 23340000, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "function escapeSelector(s){\n return s.replace( /(:|\\.|\\[|\\])/g, \"\\\\$1\" );\n}\n e.find('option[value='+escapeSelector(val)+']')\n" }, { "answer_id": 28321594, "author": "Jon Surrell", "author_id": 1432801, "author_profile": "https://Stackoverflow.com/users/1432801", "pm_score": 3, "selected": false, "text": "!\"#$%&'()*+,./:;<=>?@[\\]^`{|}~ \\\\ id=\"foo.bar\" $(\"#foo\\\\.bar\") . \\\\ $(\"#Address\\\\.Country\")\n . . $('#Address.Country') <div id=\"Address\" class=\"Country\"> \\\\. <div id=\"Address.Country\"> !\"#$%&'()*+,./:;<=>?@[\\]^`{|}~ \\\\ \\\\ \\ \\ \"#Address\\.Country\" \\ $() \"#Address.Country\" \\ . // Javascript, the following \\ is not special.\n// | \n// |\n// v \n$(\"#Address\\\\.Country\");\n// ^ \n// |\n// |\n// jQuery, the following . is not special.\n" }, { "answer_id": 30288286, "author": "Gabriel Molina", "author_id": 4909162, "author_profile": "https://Stackoverflow.com/users/4909162", "pm_score": 1, "selected": false, "text": "//funcion to replace special chars in ID of HTML tag\n\nfunction jq(myid){\n\n\n//return \"#\" + myid.replace( /(:|\\.|\\[|\\]|,)/g, \"\\\\$1\" );\nreturn myid.replace( /(:|\\.|\\[|\\]|,)/g, \"\\\\$1\" );\n\n\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32588/" ]
350,298
<p>I have found the before_dispatch and after_dispatch in dispatcher.rb but I need to access something earlier. Like around when Rails.public_path is defined.</p>
[ { "answer_id": 445124, "author": "eelco", "author_id": 8293, "author_profile": "https://Stackoverflow.com/users/8293", "pm_score": 1, "selected": false, "text": "config/boot.rb config/preinitializer.rb config/initializers/" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
350,308
<p>I'm making a webpage with dynamic content that enters the view with AJAX polling. The page JS occasionally downloads updated information and renders it on the page while the user is reading other information. This sort of thing is costly to bandwidth and processing time. I would like to have the polling pause when the page is not being viewed.</p> <p>I've noticed most of the webpages I have open spend the majority of their time minimized or in a nonviewed tab. I'd like to be able to pause the scripts until the page is actually being viewed.</p> <p>I have no idea how to do it, and it seems to be trying to break out of the sandbox of the html DOM and reach into the user's system. It may be impossible, if the JS engine has no knowledge of its rendering environment. I've never even seen a different site do this (not that the user is intended to see it...)</p> <p>So it makes for an interesting question for discussion, I think. How would you write a web app that is CPU heavy to pause when not being used? Giving the user a pause button is not reliable, I'd like it to be automatic.</p>
[ { "answer_id": 350343, "author": "Pim Jager", "author_id": 35197, "author_profile": "https://Stackoverflow.com/users/35197", "pm_score": 3, "selected": true, "text": " var inactiveTimer;\n var active = true;\n function setTimer(){\n inactiveTimer = setTimeOut(\"stopAjaxUpdateFunction()\", 120000); //120 seconds\n }\n setTimer();\n document.onmouseover = function() { clearTimeout ( inactiveTimer ); \n setTimer(); \n resumeAjaxUpdate();\n }; //clear the timer and reset it.\n function stopAjaxUpdateFunction(){\n //Turn off AJAX update\n active = false; \n }\n function resumeAjaxUpdate(){\n if(active == false){\n //Turn on AJAX update\n active = true;\n }else{\n //do nothing since we are still active and the AJAX update is still on.\n } \n }\n" }, { "answer_id": 350395, "author": "Patrick McElhaney", "author_id": 437, "author_profile": "https://Stackoverflow.com/users/437", "pm_score": 2, "selected": false, "text": "window.onblur = function () { /* stop */ };\nwindow.onfocus = function () { /* start */ };\n" }, { "answer_id": 1844169, "author": "Andy E", "author_id": 94197, "author_profile": "https://Stackoverflow.com/users/94197", "pm_score": 1, "selected": false, "text": "var idleTimer, userIsIdle, pollingTimer;\ndocument.onkeydown = document.onmousemove = resetTimer;\n\nwindow.onload = function () {\n pollingTimer = window.setTimeout(runPollingFunction, 30000);\n resetTimer();\n\n /* IE's onblur/onfocus is buggy */ \n if (window.navigator.appName == \"Microsoft Internet Explorer\")\n document.onfocusin = resetTimer,\n document.onfocusout = setIdle;\n else\n window.onfocus = resetTimer,\n window.onblur = setIdle;\n}\nfunction resetTimer() {\n if (userIsIdle)\n setBack();\n\n window.clearTimeout(idleTimer);\n idleTimer = window.setTimeout(setIdle, 120000); // 2 minutes of no activity \n}\nfunction setIdle() {\n userIsIdle = true;\n window.clearTimeout(pollingTimer); // Clear the timer that initiates polling\n window.clearTimeout(setIdle);\n}\nfunction setBack() {\n userIsIdle = false;\n runPollingFunction(); // call the polling function to instantly update page\n pollingTimer = window.setTimeout(runPollingFunction, 300000);\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36093/" ]
350,314
<p>I have some XML in an XmlDocument, and I want to display it on an ASP.NET page. (The XML should be in a control; the page will have other content.) Right now, we're using the Xml control for that. Trouble is, the XML displays with no indentation. Ugly.</p> <p>It appears that I'm supposed to create an XSLT for it, but that seems kind of boring. I'd rather just throw it into a control and have it automagically parse the XML and indent correctly. Is there an easy way to do that?</p>
[ { "answer_id": 350324, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 2, "selected": false, "text": "< iframe runat=\"server\" id=\"myXMLFrame\" src=\"~/MyXmlFile.xml\" /></pre>\n myXMLFrame.src = Page.ResolveClientUrl(\"~/MyXmlFile.xml\")\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5486/" ]
350,318
<p>I have a single large table which I would like to optimize. I'm using MS-SQL 2005 server. I'll try to describe how it is used and if anyone has any suggestions I would appreciate it very much.</p> <p>The table is about 400GB, has 100 million rows and 1 million rows are inserted each day. The table has 8 columns, 1 data col and 7 columns used for lookups/ordering. </p> <pre><code> k1 k2 k3 k4 k5 k6 k7 d1 </code></pre> <p>where</p> <pre><code> k1: varchar(3), primary key - clustered index, 10 possible values k2: bigint, primary key - clustered index, total rows/10 possible values k3: int, 10 possible values k4: money, 100 possible values k5: bool k6: bool k7: DateTime </code></pre> <p>Only one select query is run which looks like this:</p> <pre><code> SELECT TOP(g) d1 FROM table WITH(NOLOCK) WHERE k1 = a AND k3 = c AND k4 = d AND k5 = e AND k6 = f ORDER BY k7 </code></pre> <p>where g = circa 1 million This query us ran about 10 times per day (often while inserts are happening) and takes about 5-30 minutes.</p> <p>So I currently only have a clustered index on the two primary key columns. My question is: what indexes should I add to improve this query's performance?</p> <p>Would separate indexes on every column be a good choice? I think a single index would take up about 5-8GB. The DB server has 8GB RAM total.</p> <p>Please do not say that the best thing is to experiment. This is akin to 'I don't know, work it out your self' :)</p> <p>Any tips much appreciated!</p> <p><hr> EDIT by doofledorfer--</p> <p>You've caused an outbreak of premature optimization here, if not outright suggestions that "the best thing is to experiment". You need to clarify a number of issues if you want useful help.</p> <p>-- doofledorfer <hr> EDIT: Comments on posts to date are now posted below along with query plan - Mr. Flibble</p> <hr> <blockquote> <p>You are probably I/O bound</p> </blockquote> <p>Yes, it is not CPU bound. Disk access is high. All available RAM seems to be used. Whether it is used wisely or not remains to be seen.</p> <blockquote> <p>You say you can't split the data because all the data is used: IMPOSSIBLE</p> </blockquote> <p>I mean that all data is used at some point - not that all data is used by each user in each query. I can certainly split the data but, so far, I don't understand why partitioning the table is any better than using a clustered index.</p> <blockquote> <p>Why did you choose these types VARCHAR probably should have been INT as it can only be a few values. The rest are sensible enough, Money represents a money value in real life and bigint is an ID, and the bools are onny, offy type things :)</p> <p>By any chance we could get have a look the insert statement, or TSQL or the bulkinsert </p> </blockquote> <p>TSQL. Its basically INSERT INTO table VALUES (k1,k2,k3,k4,k5,k6,d1). The only thing that is in any way interesting is that many duplicate inserts are attempted and the k1 &amp; k2 PK constraint is used to prevent duplicate data entering the database. I believed at design time (and now) that this was as quick a way as any to finter out duplicate data. </p> <blockquote> <p>Can you tell how often your insert happens Every 10 minutes or so inserts run (ADO.NET) maybe 10K at a time and take a few minutes. I estimate currently a full day's inserts take 40% of the time in the day. </p> <p>Does the DateTime field contains the date of insert No. There is actually another DateTime column which does but it is not retrieved in any SELECT query so I didn't mention it for the sake of simplicity.</p> <p>How did you came to this More one man day thinking. </p> <p>if you're interested only in the last data, deleting/archiving the useless data could make sense (start from scratch every morning)</p> </blockquote> <p>I am not interested in recent data only. A query may select some of the very first data that was inserted into the table all the way up to data inserted minutes ago. But as the data is filtered this does not mean that all the data in the DB is requested in that query.</p> <blockquote> <p>if there is only one "inserter" and only one "reader", you may want to switch to a specialised type (hashmap/list/deque/stack) or something more elaborated, in a programming language.</p> </blockquote> <p>I will probably stick with MSSQL for the moment. It's not broke yet, just a little slow.</p> <p>liggett78, do you suggest a clustered index on columns k1,k4,k5,k6,k3 or a non-clustered index on those columns?</p> <hr> <p>My main question right now is should I extend the current clustered index to contain k4 also (this is the col with next most possible values) or should I just add a non-clustered index to k4.</p> <p>Would adding all k1-k6 to a clustered index be an option? Then have a separate non-clustered index on the DateTime column for the ORDER BY? Am I correct in thinking that this would not cause any major increase in DB size but will only affect insert times. Can anyone guesstimate the effect this will have on inserts?</p> <p>I think that if adding indexes to all the columns will double the DB size then it is not viable without large (ie. hardware) changes. </p> <hr> <p>The following plan was run with an index (non clustered) on the DATE column.</p> <p>EDIT: Not sure if you can see the XML below so here is a link to it: <a href="http://conormccarthy.com/box/queryplan.sqlplan.txt" rel="nofollow noreferrer">http://conormccarthy.com/box/queryplan.sqlplan.txt</a></p> <pre><code>&lt;?xml version="1.0" encoding="utf-16"?&gt; &lt;ShowPlanXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Version="1.0" Build="9.00.1399.06" xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan"&gt; &lt;BatchSequence&gt; &lt;Batch&gt; &lt;Statements&gt; &lt;StmtSimple StatementCompId="1" StatementEstRows="11111" StatementId="1" StatementOptmLevel="FULL" StatementSubTreeCost="625.754" StatementText="SELECT TOP(11111) d1 FROM hands WITH (NOLOCK) &amp;#xD;&amp;#xA; WHERE k4 = '10' &amp;#xD;&amp;#xA; AND k6 = 1 &amp;#xD;&amp;#xA; AND k5 = 1 &amp;#xD;&amp;#xA; AND k1 = 'IPN' &amp;#xD;&amp;#xA; AND k3 BETWEEN 2 AND 10 &amp;#xD;&amp;#xA; ORDER BY k7 DESC&amp;#xD;&amp;#xA;&amp;#xD;&amp;#xA;" StatementType="SELECT"&gt; &lt;StatementSetOptions ANSI_NULLS="false" ANSI_PADDING="false" ANSI_WARNINGS="false" ARITHABORT="true" CONCAT_NULL_YIELDS_NULL="false" NUMERIC_ROUNDABORT="false" QUOTED_IDENTIFIER="false" /&gt; &lt;QueryPlan DegreeOfParallelism="1" CachedPlanSize="36"&gt; &lt;MissingIndexes&gt; &lt;MissingIndexGroup Impact="81.7837"&gt; &lt;MissingIndex Database="[MYDB]" Schema="[dbo]" Table="[Hands]"&gt; &lt;ColumnGroup Usage="EQUALITY"&gt; &lt;Column Name="[k1]" ColumnId="1" /&gt; &lt;Column Name="[k4]" ColumnId="7" /&gt; &lt;Column Name="[k5]" ColumnId="9" /&gt; &lt;Column Name="[k6]" ColumnId="10" /&gt; &lt;/ColumnGroup&gt; &lt;ColumnGroup Usage="INEQUALITY"&gt; &lt;Column Name="[k3]" ColumnId="6" /&gt; &lt;/ColumnGroup&gt; &lt;ColumnGroup Usage="INCLUDE"&gt; &lt;Column Name="[d1]" ColumnId="3" /&gt; &lt;Column Name="[k7]" ColumnId="4" /&gt; &lt;/ColumnGroup&gt; &lt;/MissingIndex&gt; &lt;/MissingIndexGroup&gt; &lt;/MissingIndexes&gt; &lt;RelOp AvgRowSize="75" EstimateCPU="0.0011111" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="11111" LogicalOp="Top" NodeId="0" Parallel="false" PhysicalOp="Top" EstimatedTotalSubtreeCost="625.754"&gt; &lt;OutputList&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="d1" /&gt; &lt;/OutputList&gt; &lt;RunTimeInformation&gt; &lt;RunTimeCountersPerThread Thread="0" ActualRows="11111" ActualEndOfScans="1" ActualExecutions="1" /&gt; &lt;/RunTimeInformation&gt; &lt;Top RowCount="false" IsPercent="false" WithTies="false"&gt; &lt;TopExpression&gt; &lt;ScalarOperator ScalarString="(11111)"&gt; &lt;Const ConstValue="(11111)" /&gt; &lt;/ScalarOperator&gt; &lt;/TopExpression&gt; &lt;RelOp AvgRowSize="83" EstimateCPU="135.557" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="11111" LogicalOp="Filter" NodeId="1" Parallel="false" PhysicalOp="Filter" EstimatedTotalSubtreeCost="625.753"&gt; &lt;OutputList&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="d1" /&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k7" /&gt; &lt;/OutputList&gt; &lt;RunTimeInformation&gt; &lt;RunTimeCountersPerThread Thread="0" ActualRows="11111" ActualEndOfScans="0" ActualExecutions="1" /&gt; &lt;/RunTimeInformation&gt; &lt;Filter StartupExpression="false"&gt; &lt;RelOp AvgRowSize="96" EstimateCPU="318.331" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="195691" LogicalOp="Inner Join" NodeId="2" Parallel="false" PhysicalOp="Nested Loops" EstimatedTotalSubtreeCost="625.404"&gt; &lt;OutputList&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="d1" /&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k7" /&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k3" /&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k4" /&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k5" /&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k6" /&gt; &lt;/OutputList&gt; &lt;RunTimeInformation&gt; &lt;RunTimeCountersPerThread Thread="0" ActualRows="341958" ActualEndOfScans="0" ActualExecutions="1" /&gt; &lt;/RunTimeInformation&gt; &lt;NestedLoops Optimized="false" WithOrderedPrefetch="true"&gt; &lt;OuterReferences&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k1" /&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="HandId" /&gt; &lt;ColumnReference Column="Expr1003" /&gt; &lt;/OuterReferences&gt; &lt;RelOp AvgRowSize="32" EstimateCPU="330.366" EstimateIO="790.88" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="195691" LogicalOp="Index Scan" NodeId="4" Parallel="false" PhysicalOp="Index Scan" EstimatedTotalSubtreeCost="2.88444"&gt; &lt;OutputList&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k1" /&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="HandId" /&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k7" /&gt; &lt;/OutputList&gt; &lt;RunTimeInformation&gt; &lt;RunTimeCountersPerThread Thread="0" ActualRows="341958" ActualEndOfScans="0" ActualExecutions="1" /&gt; &lt;/RunTimeInformation&gt; &lt;IndexScan Ordered="true" ScanDirection="BACKWARD" ForcedIndex="false" NoExpandHint="false"&gt; &lt;DefinedValues&gt; &lt;DefinedValue&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k1" /&gt; &lt;/DefinedValue&gt; &lt;DefinedValue&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="HandId" /&gt; &lt;/DefinedValue&gt; &lt;DefinedValue&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k7" /&gt; &lt;/DefinedValue&gt; &lt;/DefinedValues&gt; &lt;Object Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Index="[ix_dateplayed]" /&gt; &lt;Predicate&gt; &lt;ScalarOperator ScalarString="[MYDB].[dbo].[Hands].[k1]=N'IPN'"&gt; &lt;Compare CompareOp="EQ"&gt; &lt;ScalarOperator&gt; &lt;Identifier&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k1" /&gt; &lt;/Identifier&gt; &lt;/ScalarOperator&gt; &lt;ScalarOperator&gt; &lt;Const ConstValue="N'IPN'" /&gt; &lt;/ScalarOperator&gt; &lt;/Compare&gt; &lt;/ScalarOperator&gt; &lt;/Predicate&gt; &lt;/IndexScan&gt; &lt;/RelOp&gt; &lt;RelOp AvgRowSize="88" EstimateCPU="0.0001581" EstimateIO="0.003125" EstimateRebinds="195691" EstimateRewinds="0" EstimateRows="1" LogicalOp="Clustered Index Seek" NodeId="6" Parallel="false" PhysicalOp="Clustered Index Seek" EstimatedTotalSubtreeCost="621.331"&gt; &lt;OutputList&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="d1" /&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k3" /&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k4" /&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k5" /&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k6" /&gt; &lt;/OutputList&gt; &lt;RunTimeInformation&gt; &lt;RunTimeCountersPerThread Thread="0" ActualRows="341958" ActualEndOfScans="0" ActualExecutions="341958" /&gt; &lt;/RunTimeInformation&gt; &lt;IndexScan Lookup="true" Ordered="true" ScanDirection="FORWARD" ForcedIndex="false" NoExpandHint="false"&gt; &lt;DefinedValues&gt; &lt;DefinedValue&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="d1" /&gt; &lt;/DefinedValue&gt; &lt;DefinedValue&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k3" /&gt; &lt;/DefinedValue&gt; &lt;DefinedValue&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k4" /&gt; &lt;/DefinedValue&gt; &lt;DefinedValue&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k5" /&gt; &lt;/DefinedValue&gt; &lt;DefinedValue&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k6" /&gt; &lt;/DefinedValue&gt; &lt;/DefinedValues&gt; &lt;Object Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Index="[PK_Hands]" TableReferenceId="-1" /&gt; &lt;SeekPredicates&gt; &lt;SeekPredicate&gt; &lt;Prefix ScanType="EQ"&gt; &lt;RangeColumns&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k1" /&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="HandId" /&gt; &lt;/RangeColumns&gt; &lt;RangeExpressions&gt; &lt;ScalarOperator ScalarString="[MYDB].[dbo].[Hands].[k1]"&gt; &lt;Identifier&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k1" /&gt; &lt;/Identifier&gt; &lt;/ScalarOperator&gt; &lt;ScalarOperator ScalarString="[MYDB].[dbo].[Hands].[HandId]"&gt; &lt;Identifier&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="HandId" /&gt; &lt;/Identifier&gt; &lt;/ScalarOperator&gt; &lt;/RangeExpressions&gt; &lt;/Prefix&gt; &lt;/SeekPredicate&gt; &lt;/SeekPredicates&gt; &lt;/IndexScan&gt; &lt;/RelOp&gt; &lt;/NestedLoops&gt; &lt;/RelOp&gt; &lt;Predicate&gt; &lt;ScalarOperator ScalarString="[MYDB].[dbo].[Hands].[k4]=($10.0000) AND [MYDB].[dbo].[Hands].[k6]=(1) AND [MYDB].[dbo].[Hands].[k5]=(1) AND [MYDB].[dbo].[Hands].[k3]&amp;gt;=(2) AND [MYDB].[dbo].[Hands].[k3]&amp;lt;=(10)"&gt; &lt;Logical Operation="AND"&gt; &lt;ScalarOperator&gt; &lt;Compare CompareOp="EQ"&gt; &lt;ScalarOperator&gt; &lt;Identifier&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k4" /&gt; &lt;/Identifier&gt; &lt;/ScalarOperator&gt; &lt;ScalarOperator&gt; &lt;Const ConstValue="($10.0000)" /&gt; &lt;/ScalarOperator&gt; &lt;/Compare&gt; &lt;/ScalarOperator&gt; &lt;ScalarOperator&gt; &lt;Compare CompareOp="EQ"&gt; &lt;ScalarOperator&gt; &lt;Identifier&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k6" /&gt; &lt;/Identifier&gt; &lt;/ScalarOperator&gt; &lt;ScalarOperator&gt; &lt;Const ConstValue="(1)" /&gt; &lt;/ScalarOperator&gt; &lt;/Compare&gt; &lt;/ScalarOperator&gt; &lt;ScalarOperator&gt; &lt;Compare CompareOp="EQ"&gt; &lt;ScalarOperator&gt; &lt;Identifier&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k5" /&gt; &lt;/Identifier&gt; &lt;/ScalarOperator&gt; &lt;ScalarOperator&gt; &lt;Const ConstValue="(1)" /&gt; &lt;/ScalarOperator&gt; &lt;/Compare&gt; &lt;/ScalarOperator&gt; &lt;ScalarOperator&gt; &lt;Compare CompareOp="GE"&gt; &lt;ScalarOperator&gt; &lt;Identifier&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k3" /&gt; &lt;/Identifier&gt; &lt;/ScalarOperator&gt; &lt;ScalarOperator&gt; &lt;Const ConstValue="(2)" /&gt; &lt;/ScalarOperator&gt; &lt;/Compare&gt; &lt;/ScalarOperator&gt; &lt;ScalarOperator&gt; &lt;Compare CompareOp="LE"&gt; &lt;ScalarOperator&gt; &lt;Identifier&gt; &lt;ColumnReference Database="[MYDB]" Schema="[dbo]" Table="[Hands]" Column="k3" /&gt; &lt;/Identifier&gt; &lt;/ScalarOperator&gt; &lt;ScalarOperator&gt; &lt;Const ConstValue="(10)" /&gt; &lt;/ScalarOperator&gt; &lt;/Compare&gt; &lt;/ScalarOperator&gt; &lt;/Logical&gt; &lt;/ScalarOperator&gt; &lt;/Predicate&gt; &lt;/Filter&gt; &lt;/RelOp&gt; &lt;/Top&gt; &lt;/RelOp&gt; &lt;/QueryPlan&gt; &lt;/StmtSimple&gt; &lt;/Statements&gt; &lt;/Batch&gt; &lt;/BatchSequence&gt; &lt;/ShowPlanXML&gt; </code></pre>
[ { "answer_id": 350358, "author": "nicodemus13", "author_id": 26463, "author_profile": "https://Stackoverflow.com/users/26463", "pm_score": 2, "selected": false, "text": "SELECT TOP(g) d1 \nFROM table WITH(NOLOCK) \nWHERE k1 = a WHERE k2 = b WHERE k3 = c WHERE k4 = d WHERE k5 = e WHERE k6 = f \nORDER BY k7\n SELECT TOP(g) d1 \nFROM table WITH(NOLOCK) \nWHERE k1 = a AND k2 = b AND k3 = c AND k4 = d AND k5 = e AND k6 = f \nORDER BY k7\n SELECT TOP(g) d1 \nFROM (SELECT * \n FROM table k1=a AND k2=a WITH(NOLOCK)) \nWHERE AND k3 = c AND k4 = d AND k5 = e AND k6 = f \nORDER BY k7\n" }, { "answer_id": 350361, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 0, "selected": false, "text": "where" }, { "answer_id": 1022097, "author": "Jeff Meatball Yang", "author_id": 111934, "author_profile": "https://Stackoverflow.com/users/111934", "pm_score": 1, "selected": false, "text": "create clustered index IX_Clustered on Table(k1 ASC, k2 ASC)\n create table SurrogateKey(\n newPK int -- /*primary key*/\n, k1, k3, k4, k5, k6\n)\n\nconstraint: newPK is primary key, clustered\nconstraint: k1, k3, k4, k5, k6 is unique\n create clustered index IX_Clustered on Table(newPK ASC)\n declare @pk int\nselect @pk = newPK \nfrom SurrogateKey\nwhere\n k1 = @k1\n and k3 = @k3\n and k4 = @k4\n and k5 = @k5\n and k6 = @k6\n\nselect top(g1) d1, k2, k7\nfrom Table with(read uncommitted)\nwhere newPK = @pk\norder by k7\n" }, { "answer_id": 1022225, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "alter table MyTable\n add constraint PK_MyTable\n primary key nonclustered (k1, k2)\ncreate clustered index IX_MyTable\n on MyTable(k4, k1, k3, k5, k6, k7)\n --decreasing order of cardinality of the filter columns\n (k1, k3, k4, k5, k6) (k7 asc) (k1, k3, k4, k5, k6) (k7 asc)" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34632/" ]
350,323
<p>I have a utility (grep) that gives me a list of filenames and a line numbers. After I have determined that devenv is the correct program to open a file, I would like to ensure that it is opened at the indicated line number. In emacs, this would be:</p> <pre><code>emacs +140 filename.c </code></pre> <p>I have found nothing like this for Visual Studio (devenv). The closest I have found is:</p> <pre><code>devenv /Command "Edit.Goto 140" filename.c </code></pre> <p>However, this makes a separate instance of devenv for each such file. I would rather have something that uses an existing instance.</p> <p>These variations re-use an existing devenv, but don't go to the indicated line:</p> <pre><code>devenv /Command "Edit.Goto 140" /Edit filename.c devenv /Command /Edit filename.c "Edit.Goto 140" </code></pre> <p>I thought that using multiple "/Command" arguments might do it, but I probably don't have the right one because I either get errors or no response at all (other than opening an empty devenv).</p> <p>I could write a special macro for devenv, but I would like this utility to be used by others that don't have that macro. And I'm not clear on how to invoke that macro with the "/Command" option.</p> <p>Any ideas?</p> <hr> <p>Well, it doesn't appear that there is a way to do this as I wanted. Since it looks like I'll need to have dedicated code to start up Visual Studio, I've decided to use EnvDTE as shown below. Hopefully this will help somebody else.</p> <pre class="lang-cpp prettyprint-override"><code>#include "stdafx.h" //----------------------------------------------------------------------- // This code is blatently stolen from http://benbuck.com/archives/13 // // This is from the blog of somebody called "BenBuck" for which there // seems to be no information. //----------------------------------------------------------------------- // import EnvDTE #pragma warning(disable : 4278) #pragma warning(disable : 4146) #import "libid:80cc9f66-e7d8-4ddd-85b6-d9e6cd0e93e2" version("8.0") lcid("0") raw_interfaces_only named_guids #pragma warning(default : 4146) #pragma warning(default : 4278) bool visual_studio_open_file(char const *filename, unsigned int line) { HRESULT result; CLSID clsid; result = ::CLSIDFromProgID(L"VisualStudio.DTE", &amp;clsid); if (FAILED(result)) return false; CComPtr&lt;IUnknown&gt; punk; result = ::GetActiveObject(clsid, NULL, &amp;punk); if (FAILED(result)) return false; CComPtr&lt;EnvDTE::_DTE&gt; DTE; DTE = punk; CComPtr&lt;EnvDTE::ItemOperations&gt; item_ops; result = DTE-&gt;get_ItemOperations(&amp;item_ops); if (FAILED(result)) return false; CComBSTR bstrFileName(filename); CComBSTR bstrKind(EnvDTE::vsViewKindTextView); CComPtr&lt;EnvDTE::Window&gt; window; result = item_ops-&gt;OpenFile(bstrFileName, bstrKind, &amp;window); if (FAILED(result)) return false; CComPtr&lt;EnvDTE::Document&gt; doc; result = DTE-&gt;get_ActiveDocument(&amp;doc); if (FAILED(result)) return false; CComPtr&lt;IDispatch&gt; selection_dispatch; result = doc-&gt;get_Selection(&amp;selection_dispatch); if (FAILED(result)) return false; CComPtr&lt;EnvDTE::TextSelection&gt; selection; result = selection_dispatch-&gt;QueryInterface(&amp;selection); if (FAILED(result)) return false; result = selection-&gt;GotoLine(line, TRUE); if (FAILED(result)) return false; return true; } </code></pre>
[ { "answer_id": 350401, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 1, "selected": true, "text": "devenv /command \"Macros.MyMacros.Module1.OpenFavoriteFiles\"\n" }, { "answer_id": 3678070, "author": "Fouré Olivier", "author_id": 443569, "author_profile": "https://Stackoverflow.com/users/443569", "pm_score": 5, "selected": false, "text": "devenv /edit FILE_PATH /command \"edit.goto FILE_LINE\"\n" }, { "answer_id": 10605854, "author": "Dinis Cruz", "author_id": 262379, "author_profile": "https://Stackoverflow.com/users/262379", "pm_score": 1, "selected": false, "text": "var visualStudio = new API_VisualStudio_2010();\n\nvar vsDTE = visualStudio.VsAddIn.VS_Dte;\n//var document = (Document)vsDTE.ActiveDocument;\n//var window = (Window)document.Windows.first(); \nvar textSelection = (TextSelection)vsDTE.ActiveDocument.Selection;\nvar selectedLine = 1;\n20.loop(100,()=>{\n textSelection.GotoLine(selectedLine++);\n textSelection.SelectLine();\n });\nreturn textSelection;\n" }, { "answer_id": 10724025, "author": "reder", "author_id": 1028483, "author_profile": "https://Stackoverflow.com/users/1028483", "pm_score": 5, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace openStudioFileLine\n{\n class Program \n {\n [STAThread]\n static void Main(string[] args) \n {\n try \n {\n String filename = args[0];\n int fileline;\n int.TryParse(args[1], out fileline);\n EnvDTE80.DTE2 dte2;\n dte2 = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject(\"VisualStudio.DTE\");\n dte2.MainWindow.Activate();\n EnvDTE.Window w = dte2.ItemOperations.OpenFile(filename, EnvDTE.Constants.vsViewKindTextView);\n ((EnvDTE.TextSelection)dte2.ActiveDocument.Selection).GotoLine(fileline, true);\n }\n catch (Exception e) \n { \n Console.Write(e.Message); \n }\n }\n }\n}\n openStudioFileLine path_to_file numberOfLine" }, { "answer_id": 17488898, "author": "diimdeep", "author_id": 199154, "author_profile": "https://Stackoverflow.com/users/199154", "pm_score": 4, "selected": false, "text": "usage: <version> <file path> <line number> \n\nVisual Studio version value \nVisualStudio 2002 2 \nVisualStudio 2003 3 \nVisualStudio 2005 5 \nVisualStudio 2008 8 \nVisualStudio 2010 10 \nVisualStudio 2012 12 \nVisualStudio 2013 13 \n VisualStudioFileOpenTool.exe 12 %path% %line%\n" }, { "answer_id": 21989101, "author": "Tahir Hassan", "author_id": 288393, "author_profile": "https://Stackoverflow.com/users/288393", "pm_score": 0, "selected": false, "text": "[ContractException: Precondition failed: session != null]\n System.Diagnostics.Contracts.__ContractsRuntime.TriggerFailure(ContractFailureKind kind, String msg, String userMessage, String conditionTxt, Exception inner) in C:\\_svn\\IntegratedAdaptationsSystem\\Source\\IntegratedAdaptationsSystem\\IAS_UI\\Controllers\\CustomErrorsPageController.cs:0\n System.Diagnostics.Contracts.__ContractsRuntime.ReportFailure(ContractFailureKind kind, String msg, String conditionTxt, Exception inner) in C:\\_svn\\IntegratedAdaptationsSystem\\Source\\IntegratedAdaptationsSystem\\IAS_UI\\Controllers\\CustomErrorsPageController.cs:0\n System.Diagnostics.Contracts.__ContractsRuntime.Requires(Boolean condition, String msg, String conditionTxt) in C:\\_svn\\IntegratedAdaptationsSystem\\Source\\IntegratedAdaptationsSystem\\IAS_UI\\Controllers\\CustomErrorsPageController.cs:0\n IAS_UI.Web.IAS_Session..ctor(HttpSessionStateBase session) in C:\\_svn\\IntegratedAdaptationsSystem\\Source\\IntegratedAdaptationsSystem\\IAS_UI\\Web\\IAS_Session.cs:15\n IAS_UI.Controllers.ServiceUserController..ctor() in C:\\_svn\\IntegratedAdaptationsSystem\\Source\\IntegratedAdaptationsSystem\\IAS_UI\\Controllers\\ServiceUserController.cs:41\n ServiceUserController.cs:41 Alt + v $!v::\nif (NOT ProcessExists(\"devenv.exe\"))\n{\n MsgBox, % \"Visual Studio is not loaded\"\n}\nelse\n{\n IfWinExist, Microsoft Visual Studio\n {\n ToolTip, Opening Visual Studio...\n c := GetClip()\n\n if (NOT c) {\n MsgBox, % \"No text selected\"\n }\n else \n {\n WinActivate ; now activate visual studio\n Sleep, 50\n ; for now assume that there is only one instance of visual studio - handling of multiple instances comes in later\n\n arr := StringSplitF(c, \":\")\n\n if (arr.MaxIndex() <> 2) {\n MsgBox, % \"Text: '\" . c . \"' is invalid.\"\n }\n else {\n fileName := arr[1]\n lineNumber := arr[2]\n\n ; give focus to the \"Find\" box\n SendInput, ^d \n\n ; delete the contents of the \"Find\" box\n SendInput, {Home}\n SendInput, +{End}\n SendInput, {Delete}\n\n ; input *** >of FILENAME *** into the \"Find\" box\n SendInput, >of{Space}\n SendInput, % fileName\n\n ; select the first entry in the drop down list\n SendInput, {Down}\n SendInput, {Enter}\n\n ; lineNumber := 12 remove later\n\n ; open the go to line dialog\n SendInput, ^g\n Sleep, 20\n\n ; send the file number and press enter\n SendInput, % lineNumber\n SendInput {Enter}\n }\n } \n ToolTip\n }\n}\nreturn\n GetClip()\n{\n ClipSaved := ClipboardAll\n Clipboard=\n Sleep, 30\n Send ^c\n ClipWait, 2\n Sleep, 30\n Gc := Clipboard\n Clipboard := ClipSaved\n ClipSaved=\n\n return Gc\n}\n\nProcessExists(procName)\n{\n Process, Exist, %procName%\n\n return (ErrorLevel != 0)\n}\n\nStringSplitF(str, delimeters)\n{\n Arr := Object()\n\n Loop, parse, str, %delimeters%,\n {\n Arr.Insert(A_LoopField)\n }\n\n return Arr\n}\n" }, { "answer_id": 27070497, "author": "Wade Hatler", "author_id": 647492, "author_profile": "https://Stackoverflow.com/users/647492", "pm_score": 2, "selected": false, "text": "; http://msdn.microsoft.com/en-us/library/envdte.textselection.aspx\n; http://msdn.microsoft.com/en-us/library/envdte.textselection.movetodisplaycolumn.aspx\nVST_Goto(Filename, Row:=1, Col:=1) {\n DTE := ComObjActive(\"VisualStudio.DTE.12.0\")\n DTE.ExecuteCommand(\"File.OpenFile\", Filename)\n DTE.ActiveDocument.Selection.MoveToDisplayColumn(Row, Col)\n}\n VST_Goto(\"C:\\Palabra\\.NET\\Addin\\EscDoc\\EscDoc.cs\", 328, 40)\n" }, { "answer_id": 33244420, "author": "Evgeny Panasyuk", "author_id": 1762344, "author_profile": "https://Stackoverflow.com/users/1762344", "pm_score": 2, "selected": false, "text": "import sys\nimport win32com.client\n\nfilename = sys.argv[1]\nline = int(sys.argv[2])\ncolumn = int(sys.argv[3])\n\ndte = win32com.client.GetActiveObject(\"VisualStudio.DTE\")\n\ndte.MainWindow.Activate\ndte.ItemOperations.OpenFile(filename)\ndte.ActiveDocument.Selection.MoveToLineAndOffset(line, column+1)\n" }, { "answer_id": 35070139, "author": "Richard Mills", "author_id": 5853806, "author_profile": "https://Stackoverflow.com/users/5853806", "pm_score": 1, "selected": false, "text": "wingrep syntax new instance \"C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\devenv.exe\" $F /command \"edit.goto $L\"\n studio version number" }, { "answer_id": 39696080, "author": "Evgeny Panasyuk", "author_id": 1762344, "author_profile": "https://Stackoverflow.com/users/1762344", "pm_score": 2, "selected": false, "text": "open-in-msvs.vbs full-path-to-file line column\n" }, { "answer_id": 54869165, "author": "OnceUponATimeInTheWest", "author_id": 1734863, "author_profile": "https://Stackoverflow.com/users/1734863", "pm_score": 2, "selected": false, "text": "using System.Reflection;\nusing System.Runtime.InteropServices;\n\nprivate static void OpenFileAtLine(string file, int line) {\n object vs = Marshal.GetActiveObject(\"VisualStudio.DTE\");\n object ops = vs.GetType().InvokeMember(\"ItemOperations\", BindingFlags.GetProperty, null, vs, null);\n object window = ops.GetType().InvokeMember(\"OpenFile\", BindingFlags.InvokeMethod, null, ops, new object[] { file });\n object selection = window.GetType().InvokeMember(\"Selection\", BindingFlags.GetProperty, null, window, null);\n selection.GetType().InvokeMember(\"GotoLine\", BindingFlags.InvokeMethod, null, selection, new object[] { line, true });\n}\n" }, { "answer_id": 58111604, "author": "Mungo64", "author_id": 4827625, "author_profile": "https://Stackoverflow.com/users/4827625", "pm_score": 2, "selected": false, "text": "using EnvDTE; \n\nprivate static void OpenFileAtLine(string file, int line)\n{\n DTE dte = (DTE) Marshal.GetActiveObject(\"VisualStudio.DTE.15.0\");\n dte.MainWindow.Visible = true;\n dte.ExecuteCommand(\"File.OpenFile\", file);\n dte.ExecuteCommand(\"Edit.GoTo\", line.ToString());\n}\n" }, { "answer_id": 59276417, "author": "Joe", "author_id": 6865887, "author_profile": "https://Stackoverflow.com/users/6865887", "pm_score": 1, "selected": false, "text": "private static void OpenFileAtLine(string file, int line)\n{\n //The number needs to be rolled to the next version each time a new version of visual studio is used... \n EnvDTE.DTE dte = null;\n\n\n for (int i = 25; i > 8; i--) {\n try\n {\n dte = (EnvDTE.DTE)Marshal.GetActiveObject(\"VisualStudio.DTE.\" + i.ToString() + \".0\");\n }\n catch (Exception ex)\n {\n //don't care... just keep bashing head against wall until success\n }\n }\n\n //the following line works fine for visual studio 2019:\n //EnvDTE.DTE dte = (EnvDTE.DTE)Marshal.GetActiveObject(\"VisualStudio.DTE.16.0\");\n dte.MainWindow.Visible = true;\n dte.ExecuteCommand(\"File.OpenFile\", file);\n dte.ExecuteCommand(\"Edit.GoTo\", line.ToString());\n}\n" }, { "answer_id": 73950667, "author": "Robert Husák", "author_id": 2105235, "author_profile": "https://Stackoverflow.com/users/2105235", "pm_score": 0, "selected": false, "text": "using System.Runtime.InteropServices;\n\nprivate static void OpenFileAtLine(string file, int line) {\n dynamic vs = Marshal.GetActiveObject(\"VisualStudio.DTE\");\n dynamic window = vs.ItemOperations.OpenFile(path);\n window.Selection.GotoLine(line, true);\n}\n dynamic" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10574/" ]
350,345
<p>Is there a way run Emacs from a USB drive? I am a Windows user and I would like to be able use it on any PC without an Emacs install.</p>
[ { "answer_id": 350369, "author": "ShreevatsaR", "author_id": 4958, "author_profile": "https://Stackoverflow.com/users/4958", "pm_score": 6, "selected": true, "text": " (info \"(emacs) Windows HOME\")\n" }, { "answer_id": 6692788, "author": "sayth", "author_id": 461887, "author_profile": "https://Stackoverflow.com/users/461887", "pm_score": 2, "selected": false, "text": "(defvar %~dp0 (substring data-directory 0 3)) (defvar usb-home-dir (concat %~dp0 \"home/\"))\n(setenv \"HOME\" usb-home-dir)\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/350345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]