qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
182,044
<p>Can anyone give me an example of what the Artifact paths setting defined for a build configuration could look like if I want to create two artifacts dist and source where I am using the sln 2008 build runner and building my projects using the default bin/Release?</p> <pre> **/Source/Code/MyProject/bin/Release/*.* => dist **/*.* => source </pre> <p>I get two artifact roots dist and source but under dist I get the whole directory structure (Source/Code/MyProject/bin/Release) which I don't want and under source I get the whole thing along with obj and bin/Release which I do not want.</p> <p>Can you give some advice on how to do this correctly?</p> <p>Do I need to change the target location for all the projects I am building to be able to get this thing to work?</p>
[ { "answer_id": 190573, "author": "Scott Cowan", "author_id": 253, "author_profile": "https://Stackoverflow.com/users/253", "pm_score": 5, "selected": false, "text": "Source\\Code\\MyProject\\bin\\Release\\* => dist\nSource\\**\\* => source\n Source\\Code\\MyProject\\bin\\Release\\**\\* => dist\n" }, { "answer_id": 1922877, "author": "user233173", "author_id": 233173, "author_profile": "https://Stackoverflow.com/users/233173", "pm_score": 0, "selected": false, "text": "file_name|directory_name|Ant-like wildcard [ => target_directory ]\n Source\\Code\\MyProject\\bin\\Release|**\\* => dist (| not \\)\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15771/" ]
182,053
<p>How do I setup a Python environment on windows computer so I can start writing and running Python scripts, is there an install bundle? Also which database should i use?</p> <hr> <p>I should of mentioned that I am using this for web based applications. Does it require apache? or does it use another http server? What is the standard setup for Python running web apps?</p>
[ { "answer_id": 182195, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 2, "selected": false, "text": "import CGIHTTPServer\nimport BaseHTTPServer\n\nclass Handler(CGIHTTPServer.CGIHTTPRequestHandler):\n cgi_directories = [\"/cgi\"]\n\nPORT = 9999\n\nhttpd = BaseHTTPServer.HTTPServer((\"\", PORT), Handler)\nprint \"serving at port\", PORT\nhttpd.serve_forever()\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
182,060
<p>I have webservice which is passed an array of ints. I'd like to do the select statement as follows but keep getting errors. Do I need to change the array to a string?</p> <pre><code>[WebMethod] public MiniEvent[] getAdminEvents(int buildingID, DateTime startDate) { command.CommandText = @"SELECT id, startDateTime, endDateTime From tb_bookings WHERE buildingID IN (@buildingIDs) AND startDateTime &lt;= @fromDate"; SqlParameter buildID = new SqlParameter("@buildingIDs", buildingIDs); } </code></pre>
[ { "answer_id": 182092, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 5, "selected": false, "text": "WHERE buildingID IN (@buildingID1, @buildingID2, @buildingID3...)\n WHERE buildingID IN (@buildingID)\n\ncommand.CommandText = command.CommandText.Replace(\n \"@buildingID\", \n string.Join(buildingIDs.Select(b => b.ToString()), \",\")\n);\n WHERE buildingID IN (1,2,3,4)\n" }, { "answer_id": 183068, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 3, "selected": false, "text": "private string SQLArrayToInString(Array a)\n{\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < a.GetUpperBound(0); i++)\n sb.AppendFormat(\"{0},\", a.GetValue(i));\n string retVal = sb.ToString();\n return retVal.Substring(0, retVal.Length - 1);\n}\n command.CommandText = @\"SELECT id,\n startDateTime, endDateTime From\n tb_bookings WHERE buildingID IN\n (\" + SQLArrayToInString(buildingIDs) + \") AND startDateTime <=\n @fromDate\";\n" }, { "answer_id": 205875, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 3, "selected": false, "text": "CREATE function IntegerCommaSplit(@ListofIds nvarchar(1000))\nreturns @rtn table (IntegerValue int)\nAS\nbegin\nWhile (Charindex(',',@ListofIds)>0)\nBegin\n Insert Into @Rtn \n Select ltrim(rtrim(Substring(@ListofIds,1,Charindex(',',@ListofIds)-1)))\n Set @ListofIds = Substring(@ListofIds,Charindex(',',@ListofIds)+len(','),len(@ListofIds))\nend\nInsert Into @Rtn \n Select ltrim(rtrim(@ListofIds))\nreturn \nend\n create procedure GetAdminEvents \n @buildingids nvarchar(1000),\n @startdate datetime\nas\nSELECT id,startDateTime, endDateTime From\n tb_bookings t INNER JOIN \ndbo.IntegerCommaSplit(@buildingids) i\non i.IntegerValue = t.id\n WHERE startDateTime <= @fromDate\n [WebMethod]\n public MiniEvent[] getAdminEvents(int[] buildingIDs, DateTime startDate)\n command.CommandText = @\"exec GetAdminEvents\";\n SqlParameter buildID= new SqlParameter(\"@buildingIDs\", buildingIDs);\n" }, { "answer_id": 15191562, "author": "Nishant", "author_id": 2089165, "author_profile": "https://Stackoverflow.com/users/2089165", "pm_score": 2, "selected": false, "text": "Declare @XMLList xml\nSET @XMLList=cast('<i>'+replace(@buildingIDs,',','</i><i>')+'</i>' as xml)\nSELECT x.i.value('.','varchar(5)') from @XMLList.nodes('i') x(i))\n" }, { "answer_id": 31456449, "author": "Igo Soares", "author_id": 5123926, "author_profile": "https://Stackoverflow.com/users/5123926", "pm_score": 0, "selected": false, "text": "IF EXISTS(\n SELECT *\n FROM sysobjects\n WHERE name = 'FN_RETORNA_ID_FROM_VARCHAR_TO_TABLE_INT')\nBEGIN\n DROP FUNCTION FN_RETORNA_ID_FROM_VARCHAR_TO_TABLE_INT\nEND\nGO\n\nCREATE FUNCTION [dbo].FN_RETORNA_ID_FROM_VARCHAR_TO_TABLE_INT (@IDList VARCHAR(8000))\nRETURNS\n @IDListTable TABLE (ID INT)\nAS\nBEGIN\n\n DECLARE\n --@IDList VARCHAR(100),\n @LastCommaPosition INT,\n @NextCommaPosition INT,\n @EndOfStringPosition INT,\n @StartOfStringPosition INT,\n @LengthOfString INT,\n @IDString VARCHAR(100),\n @IDValue INT\n\n --SET @IDList = '11,12,113'\n\n SET @LastCommaPosition = 0\n SET @NextCommaPosition = -1\n\n IF LTRIM(RTRIM(@IDList)) <> ''\n BEGIN\n\n WHILE(@NextCommaPosition <> 0)\n BEGIN\n\n SET @NextCommaPosition = CHARINDEX(',',@IDList,@LastCommaPosition + 1)\n\n IF @NextCommaPosition = 0\n SET @EndOfStringPosition = LEN(@IDList)\n ELSE\n SET @EndOfStringPosition = @NextCommaPosition - 1\n\n SET @StartOfStringPosition = @LastCommaPosition + 1\n SET @LengthOfString = (@EndOfStringPosition + 1) - @StartOfStringPosition\n\n SET @IDString = SUBSTRING(@IDList,@StartOfStringPosition,@LengthOfString) \n\n IF @IDString <> ''\n INSERT @IDListTable VALUES(@IDString)\n\n SET @LastCommaPosition = @NextCommaPosition\n\n END --WHILE(@NextCommaPosition <> 0)\n\n END --IF LTRIM(RTRIM(@IDList)) <> ''\n\n RETURN\n\nErrorBlock:\n\n RETURN\n\nEND --FUNCTION\n command.CommandText = @\"SELECT id,\n startDateTime, endDateTime From\n tb_bookings WHERE buildingID IN\n (SELECT ID FROM FN_RETORNA_ID_FROM_VARCHAR_TO_TABLE_INT(@buildingIDs))) AND startDateTime <=\n @fromDate\";\n\ncommand.Parameters.Add(new SqlParameter(){\n DbType = DbType.String,\n ParameterName = \"@buildingIDs\",\n Value = \"1,2,3,4,5\" //Enter the parameters here separated with commas\n });\n" }, { "answer_id": 39169627, "author": "Gonçalo Dinis", "author_id": 5758761, "author_profile": "https://Stackoverflow.com/users/5758761", "pm_score": 1, "selected": false, "text": " command = new SqlCommand(\"SELECT x FROM y WHERE x.id IN (@actions)\", conn); \n command.Parameters.AddWithValue(\"@actions\", act);\n command.CommandText = command.CommandText.Replace(\"@actions\", act);\n" }, { "answer_id": 40803195, "author": "Nyerguds", "author_id": 395685, "author_profile": "https://Stackoverflow.com/users/395685", "pm_score": 0, "selected": false, "text": "[WebMethod]\npublic MiniEvent[] getAdminEvents(Int32[] buildingIDs, DateTime startDate)\n{\n // Gets a list with numbers from 0 to the max index in buildingIDs,\n // then transforms it into a list of strings using those numbers.\n String idParamString = String.Join(\", \", (Enumerable.Range(0, buildingIDs.Length).Select(i => \"@item\" + i)).ToArray());\n command.CommandText = @\"SELECT id,\n startDateTime, endDateTime From\n tb_bookings WHERE buildingID IN\n (\" + idParamString + @\") AND startDateTime <=\n @fromDate\";\n // Reproduce the same parameters in idParamString \n for (Int32 i = 0; i < buildingIDs.Length; i++)\n command.Parameters.Add(new SqlParameter (\"@item\" + i, buildingIDs[i]));\n command.Parameters.Add(new SqlParameter(\"@fromDate\", startDate);\n // the rest of your code...\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17510/" ]
182,066
<p>If I have two tables... Category and Pet. </p> <p>Is there a way in LINQ to SQL to make the result of the joined query map to a another strongly typed class (such as: PetWithCategoryName) so that I can strongly pass it to a MVC View?</p> <p>I currently have Category and Pet classes... should I make another one?</p> <p>Maybe I missing something here. Can any of you enlighten me?</p> <pre><code>from p in petTable join c in categoryTable on p.CategoryId equals c.Id where (c.Id == categoryId.Value) select new { p.Id, p.Name, p.Description, p.Price, CategoryName = c.Name } &lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;Database Name="PetShop" xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007"&gt; &lt;Table Name="Category" Member="PetShop.Models.Category"&gt; &lt;Type Name="PetShop.Models.Category"&gt; &lt;Column Name="Id" Member="Id" IsDbGenerated="true" IsPrimaryKey="true" /&gt; &lt;Column Name="Name" Member="Name" /&gt; &lt;Column Name="Description" Member="Description" /&gt; &lt;/Type&gt; &lt;/Table&gt; &lt;Table Name="Pet" Member="PetShop.Models.Pet"&gt; &lt;Type Name="PetShop.Models.Pet"&gt; &lt;Column Name="Id" Member="Id" IsDbGenerated="true" IsPrimaryKey="true" /&gt; &lt;Column Name="Name" Member="Name" /&gt; &lt;Column Name="Description" Member="Description" /&gt; &lt;Column Name="ImageUrl" Member="ImageUrl" /&gt; &lt;Column Name="Price" Member="Price" /&gt; &lt;Column Name="CategoryId" Member="CategoryId" /&gt; &lt;Association Name="FK_Pet_Category" Member="Category" ThisKey="CategoryId" OtherKey="Id" IsForeignKey="true" /&gt; &lt;/Type&gt; &lt;/Table&gt; &lt;/Database&gt; </code></pre>
[ { "answer_id": 182359, "author": "Giovanni Galbo", "author_id": 4050, "author_profile": "https://Stackoverflow.com/users/4050", "pm_score": 3, "selected": true, "text": "var loadOption = new DataLoadOptions(); \nloadOption.LoadWith<Pets>(p => p.Category);\ndb.LoadOptions = loadOption; \n\nvar pets = from p in PetStoreContext.Pets\n select p;\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4481/" ]
182,070
<p>The situation is like this : Main project A. and a class library B. <strong>A references B</strong></p> <p>Project B has the classes that will be serialized. The classes are used in A. Now, the problem appears when from Project A I try to serialize the objects from B. An exception is thrown that says a class from A cannot be serialized. This is the strange part since in the classes in B I cant have a reference to those in A. (a circular dependency would be created).</p> <p>How can I track down the problem ? because the exception method doesn't say where the Problem appeared ?</p> <p><strong>Edit :</strong> Ok, I found the problem with the help of <strong>Kent Boogaart's</strong> small app :D . I have a PropertyChanged listener in a class in project A that is not marked Serializable - and I don't want to mark it so. ( it would serialize that class to right ?)</p> <p>I've solved the problem with the event by following this link : <a href="http://www.lhotka.net/weblog/CommentView,guid,776f44e8-aaec-4845-b649-e0d840e6de2c.aspx#commentstart" rel="nofollow noreferrer">.NET 2.0 solution to serialization of objects that raise events</a>. There still is a problem , but it's probably something similar.</p> <p><strong>PS:</strong> Great tool from <strong>Kent Boogaart</strong></p>
[ { "answer_id": 182107, "author": "Tsvetomir Tsonev", "author_id": 25449, "author_profile": "https://Stackoverflow.com/users/25449", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Runtime.Serialization;\nusing System.Security.Permissions;\n\n[Serializable]\npublic class Test : ISerializable\n{\n private Test(SerializationInfo info, StreamingContext context)\n {\n PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(Test));\n\n foreach (SerializationEntry entry in info)\n {\n PropertyDescriptor property = properties.Find(entry.Name, false);\n property.SetValue(this, entry.Value);\n }\n }\n\n [SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)]\n void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)\n {\n PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(Test));\n\n foreach (PropertyDescriptor property in properties)\n {\n info.AddValue(property.Name, property.GetValue(this));\n }\n }\n}\n" }, { "answer_id": 182217, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 0, "selected": false, "text": "TB b = new TB();\nb.P = new TA();\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5246/" ]
182,077
<p>Simplified, I have an application where data is intended to flow over the internet between two servers. Ideally, I'd like to test at what point the software ceases to function. At what lowerbound limit (bandwidth, latency, dropped packets) do things stop working to test the reliability of the software.</p> <p>What I thought I would do was the following:</p> <ol> <li>Setup up 3 machines (VMware instances) </li> <li>Install the 2 applications on two of the servers.</li> <li>Setup up the 3rd server to sit between the two machines by doing some sort of magic with Routing and Remote Access on Windows 2003</li> <li>Install either <a href="http://bandwidthcontroller.com/trafficShaperXp.html" rel="noreferrer">Traffic Shaper XP</a> or <a href="http://netlimiter.com/" rel="noreferrer">NetLimiter</a> to limit the bandwidth</li> <li>Run something like <a href="http://www.tmurgent.com/download%5CTMnetsim32_02040000.zip" rel="noreferrer">TMnetSim Network Simulator</a> to simulate a bad connection.</li> </ol> <p>Does this sound like a good idea or are there easier/better ways of doing this? I'm not that comfortable on Linux and my team mates are even less so.</p>
[ { "answer_id": 4140375, "author": "MarcH", "author_id": 317623, "author_profile": "https://Stackoverflow.com/users/317623", "pm_score": 2, "selected": false, "text": "tc qdisc add dev eth0 root netem delay 50ms\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9539/" ]
182,082
<p>I cureently have a set up like below </p> <pre><code>Public ClassA property _classB as ClassB End Class Public ClassB property _someProperty as someProperty End Class </code></pre> <p>what I want to do is to databind object A to a gridview with one of the columns being databound to ClassB._someProperty. When I try to databind it as Classb._someProperty I get a "Field or Property not found on Selected Datasource" error</p> <p>I have tried to use the objectContainerDataSource and also directly binding to the gridview with no success. </p> <p>Has anyone come across this in the past?</p>
[ { "answer_id": 182113, "author": "Neil Hewitt", "author_id": 22178, "author_profile": "https://Stackoverflow.com/users/22178", "pm_score": 2, "selected": false, "text": "IList<ClassA> listOfClassAObjects = GetMyListOfClassAObjectsFromSomewhere();\nvar projection = from ClassA a in listOfClassAObjects\n select new { SomeProperty = a.SomeProperty, \n SomeOtherProperty = a.SomeOtherProperty,\n SomePropertyFromB = a.ClassB.SomeProperty };\ndatagrid.DataSource = projection;\ndatagrid.DataBind();\n SomePropertyFromB var data = GetMyListOfClassAObjectsFromSomewhere().ProjectionForDataGrid();\ndatagrid.DataSource = data;\ndatagrid.DataBind();\n" }, { "answer_id": 182929, "author": "Dean", "author_id": 11802, "author_profile": "https://Stackoverflow.com/users/11802", "pm_score": 1, "selected": true, "text": "<asp:TemplateField HeaderText=\"_someProperty\">\n<ItemTemplate> \n <%#Eval(\"classB._someProperty\")%>\n\n</ItemTemplate>\n</asp:TemplateField>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11802/" ]
182,086
<p>given a matrix of distances between points is there an algorithm for determining a set of n-dimensional points that has these distances? (or at least minimises the error) </p> <p>sort of like a n-dimensional version of the turnpike problem.</p> <p>The best I can come up with is using multidimensional scaling.</p>
[ { "answer_id": 500226, "author": "jheriko", "author_id": 17604, "author_profile": "https://Stackoverflow.com/users/17604", "pm_score": 2, "selected": false, "text": "#include <conio.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#define DAMPING_FACTOR 0.99f\n\nclass point\n{\npublic:\n float x;\n float y;\npublic:\n point() : x(0), y(0) {}\n};\n\n// symmetric matrix with distances\nfloat matrix[5][5] = {\n { 0.0f, 4.5f, 1.5f, 2.0f, 4.0f },\n { 4.5f, 0.0f, 4.0f, 3.0f, 3.5f },\n { 1.5f, 4.0f, 0.0f, 1.0f, 5.0f },\n { 2.0f, 3.0f, 1.0f, 0.0f, 4.5f },\n { 4.0f, 3.5f, 5.0f, 4.5f, 0.0f }\n };\nint main(int argc, char** argv)\n{\n point p[5];\n for(unsigned int i = 0; i < 5; ++i)\n {\n p[i].x = (float)(rand()%100)*0.1f;\n p[i].y = (float)(rand()%100)*0.1f;\n }\n\n // do 1000 iterations\n float dx = 0.0f, dy = 0.0f, d = 0.0f;\n float xmoves[5], ymoves[5];\n\n for(unsigned int c = 0; c < 1000; ++c)\n {\n for(unsigned int i = 0; i < 5; ++i) xmoves[i] = ymoves[i] = 0.0f;\n // iterate across each point x each point to work out the results of all of the constraints in the matrix\n // collect moves together which are slightly less than enough (DAMPING_FACTOR) to correct half the distance between each pair of points\n for(unsigned int i = 0; i < 5; ++i)\n for(unsigned int j = 0; j < 5; ++j)\n {\n if(i==j) continue;\n dx = p[i].x - p[j].x;\n dy = p[i].y - p[j].y;\n d = sqrt(dx*dx + dy*dy);\n dx /= d;\n dy /= d;\n d = (d - matrix[i][j])*DAMPING_FACTOR*0.5f*0.2f;\n\n xmoves[i] -= d*dx;\n ymoves[i] -= d*dy;\n\n xmoves[j] += d*dx;\n ymoves[j] += d*dy;\n }\n\n // apply all at once\n for(unsigned int i = 0; i < 5; ++i)\n {\n p[i].x += xmoves[i];\n p[i].y += ymoves[i];\n }\n }\n\n // output results\n printf(\"Result:\\r\\n\");\n for(unsigned int i = 0; i < 5; ++i)\n {\n for(unsigned int j = 0; j < 5; ++j)\n {\n dx = p[i].x - p[j].x;\n dy = p[i].y - p[j].y;\n printf(\"%f \", sqrt(dx*dx + dy*dy));\n }\n printf(\"\\r\\n\");\n }\n\n printf(\"\\r\\nDesired:\\r\\n\");\n for(unsigned int i = 0; i < 5; ++i)\n {\n for(unsigned int j = 0; j < 5; ++j)\n {\n printf(\"%f \", matrix[i][j]);\n }\n printf(\"\\r\\n\");\n }\n\n printf(\"Absolute difference:\\r\\n\");\n for(unsigned int i = 0; i < 5; ++i)\n {\n for(unsigned int j = 0; j < 5; ++j)\n {\n dx = p[i].x - p[j].x;\n dy = p[i].y - p[j].y;\n printf(\"%f \", abs(sqrt(dx*dx + dy*dy) - matrix[i][j]));\n }\n printf(\"\\r\\n\");\n }\n\n printf(\"Press any key to continue...\");\n\n while(!_kbhit());\n\n return 0;\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26094/" ]
182,088
<p>I am writing a Time Sheeting web application that involves users entering their tasks for the week. I would like not to have the page refresh so I am exploring ways to add/delete/edit tasks using JavaScript on the client browser. </p> <p>Currently I am using ASP.NET-MVC, Ajax, JQuery and LiveValidation and I am make steady (if slow) progress.</p> <p>I am interested to see if this is a solved problem and the pros and cons of various approaches.</p> <p>For example my current approach to adding a new task (Category/Activity/Hours) involves basic validation using LiveValidation with a web service call to check the Category/Activity. If all the fields validate I create a new table row to show the task and the hide it. Next I call the web service again to add the task to the DB and on success I show the new row and enable it for deletion/editing</p>
[ { "answer_id": 182549, "author": "Ben Crouse", "author_id": 6705, "author_profile": "https://Stackoverflow.com/users/6705", "pm_score": 2, "selected": true, "text": "EditorGridPanel" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18349/" ]
182,130
<p>I want to record user states and then be able to report historically based on the record of changes we've kept. I'm trying to do this in SQL (using PostgreSQL) and I have a proposed structure for recording user changes like the following.</p> <pre><code>CREATE TABLE users ( userid SERIAL NOT NULL PRIMARY KEY, name VARCHAR(40), status CHAR NOT NULL ); CREATE TABLE status_log ( logid SERIAL, userid INTEGER NOT NULL REFERENCES users(userid), status CHAR NOT NULL, logcreated TIMESTAMP ); </code></pre> <p>That's my proposed table structure, based on the data.</p> <p>For the status field 'a' represents an active user and 's' represents a suspended user,</p> <pre><code>INSERT INTO status_log (userid, status, logcreated) VALUES (1, 's', '2008-01-01'); INSERT INTO status_log (userid, status, logcreated) VALUES (1, 'a', '2008-02-01'); </code></pre> <p>So this user was suspended on 1st Jan and active again on 1st of February.</p> <p>If I wanted to get a suspended list of customers on 15th January 2008, then userid 1 should show up. If I get a suspended list of customers on 15th February 2008, then userid 1 should not show up.</p> <p>1) Is this the best way to structure this data for this kind of query?</p> <p>2) How do I query the data in either this structure or in your proposed modified structure so that I can simply have a date (say 15th January) and find a list of customers that had an active status on that date in SQL only? Is this a job for SQL?</p>
[ { "answer_id": 182255, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 3, "selected": true, "text": "select l1.userid\nfrom status_log l1\nwhere l1.status='s'\nand l1.logcreated = (select max(l2.logcreated)\n from status_log l2\n where l2.userid = l1.userid\n and l2.logcreated <= date '2008-02-15'\n );\n select userid\nfrom status_log\nwhere status='s'\nand logcreated <= date '2008-02-15'\nand logsuperseded >= date '2008-02-15';\n userid from to status\nFRED 2008-01-01 2008-01-31 s\nFRED 2008-02-01 2008-02-07 c\nFRED 2008-02-08 a\n select userid\nfrom status_log\nwhere status='s'\nand logcreated <= date '2008-02-15'\nand (logsuperseded is null or logsuperseded >= date '2008-02-15');\n" }, { "answer_id": 184747, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 1, "selected": false, "text": "select userid\nfrom\n(\nselect logid, \n userid, \n status, \n logcreated,\n max(logcreated) over (partition by userid) max_logcreated_by_user\nfrom status_log\nwhere logcreated <= date '2008-02-15'\n)\nwhere logcreated = max_logcreated_by_user\n and status = 'a'\n/\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1087/" ]
182,133
<p>I've never been so good at design because there are so many different possibilities and they all have pros and cons and I'm never sure which to go with. Anyway, here's my problem, I have a need for many different loosly related classes to have validation. However, some of these classes will need extra information to do the validation. I want to have a method <code>validate</code> that can be used to validate a Object and I want to determine if an Object is validatable with an interface, say <code>Validatable</code>. The following are the two basic solutions I can have.</p> <pre><code>interface Validatable { public void validate() throws ValidateException; } interface Object1Validatable { public void validate(Object1Converse converse) throws ValidateException; } class Object1 implements Object1Validatable { ... public void validate() throws ValidateException { throw new UnsupportedOperationException(); } } class Object2 implements Validatable { ... public void validate() throws ValidateException { ... } } </code></pre> <p>This is the first solution whereby I have a general global interface that something that's validatable implements and I could use <code>validate()</code> to validate, but Object1 doesn't support this so it's kind of defunc, but Object2 does support it and so may many other classes.</p> <p>Alternatively I could have the following which would leave me without a top level interface.</p> <pre><code>interface Object1Validatable { public void validate(Object1Converse converse) throws ValidateException; } class Object1 implements Object1Validatable { ... public void validate(Object1Converse converse) throws ValidateException { ... } } interface Object2Validatable { public void validate() throws ValidateException; } class Object2 implements Object2Validatable { ... public void validate() throws ValidateException { ... } } </code></pre> <p>I think the main problem I have is that I'm kind of stuck on the idea of having a top level interface so that I can at least say X or Y Object is validatable.</p>
[ { "answer_id": 182156, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 2, "selected": false, "text": "interface Validatable {\n void validate(Validator v);\n}\n\nclass Object1 implements Validatable{\n void validate(Validator v){\n v.foo\n v.bar\n }\n}\nclass Object1Converse implements Validator{\n //....\n}\nclass Object2 implements Validatable{\n void validate(Validator v){\n //do whatever you need and ingore validator ? \n }\n}\n" }, { "answer_id": 182161, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "public class MyClass {\n //Properties and methods here\n}\n\npublic class MyClassValidator : IValidator<MyClass> {\n IList<IValidatorError> IValidator.Validate(MyClass obj) {\n //Perform some checks here\n }\n}\n\n//...\n\npublic void RegisterValidators() {\n Validators.Add<MyClassValidator>();\n}\n\n//...\n\npublic void PerformSomeLogic() {\n var myobj = new MyClass { };\n //Set some properties, call some methods, etc.\n var v = Validators.Get<MyClass>();\n if(v.GetErrors(myobj).Count() > 0)\n throw new Exception();\n SaveToDatabase(myobj);\n}\n" }, { "answer_id": 182190, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 0, "selected": false, "text": "interface Validateable\n{\n}\n\ninterface EmptyValidateable inherits Validateable //Or is it implements?\n{\n void validate() throws ValidateException;\n}\n\ninterface Objectvalidateable inherits Validateable\n{\n void validate(Object validateObj);\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6414/" ]
182,160
<p>I'm new to Spring Security. How do I add an event listener which will be called as a user logs in successfully? Also I need to get some kind of unique session ID in this listener which should be available further on. I need this ID to synchronize with another server.</p>
[ { "answer_id": 182203, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "public void onApplicationEvent(ApplicationEvent appEvent)\n{\n if (appEvent instanceof AuthenticationSuccessEvent)\n {\n AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent;\n UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();\n\n // ....\n }\n}\n" }, { "answer_id": 5957272, "author": "Wanderson Santos", "author_id": 128857, "author_profile": "https://Stackoverflow.com/users/128857", "pm_score": 3, "selected": false, "text": "grails.plugins.springsecurity.useSecurityEventListener = true\n\ngrails.plugins.springsecurity.onAuthenticationSuccessEvent = { e, appCtx ->\n\n def session = SecurityRequestHolder.request.getSession(false)\n session.myVar = true\n\n}\n" }, { "answer_id": 14043376, "author": "user1857829", "author_id": 1857829, "author_profile": "https://Stackoverflow.com/users/1857829", "pm_score": 5, "selected": false, "text": "public class AuthenticationListener implements ApplicationListener<AuthenticationSuccessEvent> {\n\n @Override\n public void onApplicationEvent(final AuthenticationSuccessEvent event) {\n\n // ...\n\n }\n\n}\n" }, { "answer_id": 18127973, "author": "John29", "author_id": 2324685, "author_profile": "https://Stackoverflow.com/users/2324685", "pm_score": 6, "selected": false, "text": "@Component\npublic class LoginListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {\n\n @Override\n public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event)\n {\n UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();\n // ...\n }\n}\n" }, { "answer_id": 54063699, "author": "Sujit", "author_id": 10637296, "author_profile": "https://Stackoverflow.com/users/10637296", "pm_score": 3, "selected": false, "text": "@EventListener @EventListener\npublic void doSomething(InteractiveAuthenticationSuccessEvent event) { // any spring event\n // your code \n\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/578/" ]
182,177
<p>Which Template-Engine and Ajax-Framework/-Toolkit is able to load template information from JAR-Files?</p>
[ { "answer_id": 182203, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "public void onApplicationEvent(ApplicationEvent appEvent)\n{\n if (appEvent instanceof AuthenticationSuccessEvent)\n {\n AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent;\n UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();\n\n // ....\n }\n}\n" }, { "answer_id": 5957272, "author": "Wanderson Santos", "author_id": 128857, "author_profile": "https://Stackoverflow.com/users/128857", "pm_score": 3, "selected": false, "text": "grails.plugins.springsecurity.useSecurityEventListener = true\n\ngrails.plugins.springsecurity.onAuthenticationSuccessEvent = { e, appCtx ->\n\n def session = SecurityRequestHolder.request.getSession(false)\n session.myVar = true\n\n}\n" }, { "answer_id": 14043376, "author": "user1857829", "author_id": 1857829, "author_profile": "https://Stackoverflow.com/users/1857829", "pm_score": 5, "selected": false, "text": "public class AuthenticationListener implements ApplicationListener<AuthenticationSuccessEvent> {\n\n @Override\n public void onApplicationEvent(final AuthenticationSuccessEvent event) {\n\n // ...\n\n }\n\n}\n" }, { "answer_id": 18127973, "author": "John29", "author_id": 2324685, "author_profile": "https://Stackoverflow.com/users/2324685", "pm_score": 6, "selected": false, "text": "@Component\npublic class LoginListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {\n\n @Override\n public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event)\n {\n UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();\n // ...\n }\n}\n" }, { "answer_id": 54063699, "author": "Sujit", "author_id": 10637296, "author_profile": "https://Stackoverflow.com/users/10637296", "pm_score": 3, "selected": false, "text": "@EventListener @EventListener\npublic void doSomething(InteractiveAuthenticationSuccessEvent event) { // any spring event\n // your code \n\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
182,181
<p>I'm trying to call the SQL statement below but get the following error:</p> <blockquote> <p>System.Data.SqlClient.SqlException: Conversion failed when converting the varchar value '+@buildingIDs+' to data type int.</p> </blockquote> <pre><code>@"SELECT id, startDateTime, endDateTime FROM tb_bookings WHERE buildingID IN ('+@buildingIDs+') AND startDateTime &lt;= @fromDate"; </code></pre> <p><code>buildingID</code> is an <code>int</code> type column in the db. Will I need to pass the IDs as an array of ints?</p>
[ { "answer_id": 182219, "author": "Bravax", "author_id": 13911, "author_profile": "https://Stackoverflow.com/users/13911", "pm_score": -1, "selected": false, "text": "\nbuildingsIDs = \"1, 5, 6\";\n@\"SELECT id, startDateTime, endDateTime From tb_bookings WHERE buildingID IN (\" + buildingIDs + \") AND startDateTime <= @fromDate\";\n" }, { "answer_id": 182276, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 3, "selected": true, "text": "int[] buildingIDs = new int[] { 1, 2, 3 };\n\n/***/ @\"SELECT id, startDateTime, endDateTime From tb_bookings WHERE buildingID IN (\" +\n string.Join(\", \", buildingIDs.Select(id => id.ToString()).ToArray())\n + \") AND startDateTime <= @fromDate\"; \n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17510/" ]
182,192
<p>ModRewrite can easily handle stripping the www off the front of my domain.<br> In .htaccess:</p> <pre><code>RewriteEngine On RewriteCond %{HTTPS} on RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^(.*)$ https://%1/$1 [R=301,L] RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L] </code></pre> <p>But with SSL, the certificate check comes before the .htaccess rewrite, causing certificate error.<br> I would rather not buy an SSL certificate for the www only to redirect it.<br> Can you offer me a smarter solution? (btw EV Certificates are not available as wildcards)</p>
[ { "answer_id": 182205, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "mydomain.com www.mydomain.com" }, { "answer_id": 193601, "author": "Jolyon", "author_id": 11740, "author_profile": "https://Stackoverflow.com/users/11740", "pm_score": 1, "selected": false, "text": "RewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteCond %{HTTP_HOST} ^www\\.(.+)$ [NC]\nRewriteRule ^(.*)$ http://%1/$1 [R=301,L]\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11740/" ]
182,197
<p>I have a log file being written by another process which I want to watch for changes. Each time a change occurs I'd like to read the new data in to do some processing on it.</p> <p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p> <p>If anyone's done anything like this I'd be really grateful to hear how...</p> <p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p> <p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
[ { "answer_id": 182235, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": -1, "selected": false, "text": " try:\n f = open(filePath)\n except IOError:\n print \"No such file: %s\" % filePath\n raw_input(\"Press Enter to close window\")\n try:\n lines = f.readlines()\n while True:\n line = f.readline()\n try:\n if not line:\n time.sleep(1)\n else:\n functionThatAnalisesTheLine(line)\n except Exception, e:\n # handle the exception somehow (for example, log the trace) and raise the same exception again\n raw_input(\"Press Enter to close window\")\n raise e\n finally:\n f.close()\n functionThatAnalisesTheLine" }, { "answer_id": 182242, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 3, "selected": false, "text": "import time\n\nwhile 1:\n where = file.tell()\n line = file.readline()\n if not line:\n time.sleep(1)\n file.seek(where)\n else:\n print line, # already has newline\n" }, { "answer_id": 182259, "author": "Deestan", "author_id": 6848, "author_profile": "https://Stackoverflow.com/users/6848", "pm_score": 7, "selected": false, "text": "os.stat(filename).st_mtime\n import os\n\nclass Monkey(object):\n def __init__(self):\n self._cached_stamp = 0\n self.filename = '/path/to/file'\n\n def ook(self):\n stamp = os.stat(self.filename).st_mtime\n if stamp != self._cached_stamp:\n self._cached_stamp = stamp\n # File has changed, so do something...\n" }, { "answer_id": 182297, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 2, "selected": false, "text": "System.IO.FileSystemWatcher\n" }, { "answer_id": 182441, "author": "seuvitor", "author_id": 23477, "author_profile": "https://Stackoverflow.com/users/23477", "pm_score": 3, "selected": false, "text": "f = open('file.log')\n line = f.readline()\nif line:\n // Do what you want with the line\n readline" }, { "answer_id": 182953, "author": "Jon Cage", "author_id": 15369, "author_profile": "https://Stackoverflow.com/users/15369", "pm_score": 4, "selected": false, "text": "import os\n\nimport win32file\nimport win32con\n\npath_to_watch = \".\" # look at the current directory\nfile_to_watch = \"test.txt\" # look for changes to a file called test.txt\n\ndef ProcessNewData( newData ):\n print \"Text added: %s\"%newData\n\n# Set up the bits we'll need for output\nACTIONS = {\n 1 : \"Created\",\n 2 : \"Deleted\",\n 3 : \"Updated\",\n 4 : \"Renamed from something\",\n 5 : \"Renamed to something\"\n}\nFILE_LIST_DIRECTORY = 0x0001\nhDir = win32file.CreateFile (\n path_to_watch,\n FILE_LIST_DIRECTORY,\n win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,\n None,\n win32con.OPEN_EXISTING,\n win32con.FILE_FLAG_BACKUP_SEMANTICS,\n None\n)\n\n# Open the file we're interested in\na = open(file_to_watch, \"r\")\n\n# Throw away any exising log data\na.read()\n\n# Wait for new data and call ProcessNewData for each new chunk that's written\nwhile 1:\n # Wait for a change to occur\n results = win32file.ReadDirectoryChangesW (\n hDir,\n 1024,\n False,\n win32con.FILE_NOTIFY_CHANGE_LAST_WRITE,\n None,\n None\n )\n\n # For each change, check to see if it's updating the file we're interested in\n for action, file in results:\n full_filename = os.path.join (path_to_watch, file)\n #print file, ACTIONS.get (action, \"Unknown\")\n if file == file_to_watch:\n newText = a.read()\n if newText != \"\":\n ProcessNewData( newText )\n" }, { "answer_id": 473471, "author": "Maxime", "author_id": 58332, "author_profile": "https://Stackoverflow.com/users/58332", "pm_score": 5, "selected": false, "text": "import time\nimport fcntl\nimport os\nimport signal\n\nFNAME = \"/HOME/TOTO/FILETOWATCH\"\n\ndef handler(signum, frame):\n print \"File %s modified\" % (FNAME,)\n\nsignal.signal(signal.SIGIO, handler)\nfd = os.open(FNAME, os.O_RDONLY)\nfcntl.fcntl(fd, fcntl.F_SETSIG, 0)\nfcntl.fcntl(fd, fcntl.F_NOTIFY,\n fcntl.DN_MODIFY | fcntl.DN_CREATE | fcntl.DN_MULTISHOT)\n\nwhile True:\n time.sleep(10000)\n" }, { "answer_id": 1867970, "author": "AlaXul", "author_id": 227261, "author_profile": "https://Stackoverflow.com/users/227261", "pm_score": 3, "selected": false, "text": "# Check file for new data.\n\nimport time\n\nf = open(r'c:\\temp\\test.txt', 'r')\n\nwhile True:\n\n line = f.readline()\n if not line:\n time.sleep(1)\n print 'Nothing New'\n else:\n print 'Call Function: ', line\n" }, { "answer_id": 5339877, "author": "hipersayan_x", "author_id": 664435, "author_profile": "https://Stackoverflow.com/users/664435", "pm_score": 6, "selected": false, "text": "from PyQt4 import QtCore\n\n@QtCore.pyqtSlot(str)\ndef directory_changed(path):\n print('Directory Changed!!!')\n\n@QtCore.pyqtSlot(str)\ndef file_changed(path):\n print('File Changed!!!')\n\nfs_watcher = QtCore.QFileSystemWatcher(['/path/to/files_1', '/path/to/files_2', '/path/to/files_3'])\n\nfs_watcher.connect(fs_watcher, QtCore.SIGNAL('directoryChanged(QString)'), directory_changed)\nfs_watcher.connect(fs_watcher, QtCore.SIGNAL('fileChanged(QString)'), file_changed)\n" }, { "answer_id": 15071134, "author": "ronedg", "author_id": 1453618, "author_profile": "https://Stackoverflow.com/users/1453618", "pm_score": 3, "selected": false, "text": "#!/usr/bin/env python\n\nimport os, sys, time\n\ndef files_to_timestamp(path):\n files = [os.path.join(path, f) for f in os.listdir(path)]\n return dict ([(f, os.path.getmtime(f)) for f in files])\n\nif __name__ == \"__main__\":\n\n path_to_watch = sys.argv[1]\n print('Watching {}..'.format(path_to_watch))\n\n before = files_to_timestamp(path_to_watch)\n\n while 1:\n time.sleep (2)\n after = files_to_timestamp(path_to_watch)\n\n added = [f for f in after.keys() if not f in before.keys()]\n removed = [f for f in before.keys() if not f in after.keys()]\n modified = []\n\n for f in before.keys():\n if not f in removed:\n if os.path.getmtime(f) != before.get(f):\n modified.append(f)\n\n if added: print('Added: {}'.format(', '.join(added)))\n if removed: print('Removed: {}'.format(', '.join(removed)))\n if modified: print('Modified: {}'.format(', '.join(modified)))\n\n before = after\n" }, { "answer_id": 18947445, "author": "imp", "author_id": 2622785, "author_profile": "https://Stackoverflow.com/users/2622785", "pm_score": 2, "selected": false, "text": "ACTIONS = {\n 1 : \"Created\",\n 2 : \"Deleted\",\n 3 : \"Updated\",\n 4 : \"Renamed from something\",\n 5 : \"Renamed to something\"\n}\nFILE_LIST_DIRECTORY = 0x0001\n\nclass myThread (threading.Thread):\n def __init__(self, threadID, fileName, directory, origin):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.fileName = fileName\n self.daemon = True\n self.dir = directory\n self.originalFile = origin\n def run(self):\n startMonitor(self.fileName, self.dir, self.originalFile)\n\ndef startMonitor(fileMonitoring,dirPath,originalFile):\n hDir = win32file.CreateFile (\n dirPath,\n FILE_LIST_DIRECTORY,\n win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,\n None,\n win32con.OPEN_EXISTING,\n win32con.FILE_FLAG_BACKUP_SEMANTICS,\n None\n )\n # Wait for new data and call ProcessNewData for each new chunk that's\n # written\n while 1:\n # Wait for a change to occur\n results = win32file.ReadDirectoryChangesW (\n hDir,\n 1024,\n False,\n win32con.FILE_NOTIFY_CHANGE_LAST_WRITE,\n None,\n None\n )\n # For each change, check to see if it's updating the file we're\n # interested in\n for action, file_M in results:\n full_filename = os.path.join (dirPath, file_M)\n #print file, ACTIONS.get (action, \"Unknown\")\n if len(full_filename) == len(fileMonitoring) and action == 3:\n #copy to main file\n ...\n" }, { "answer_id": 23181354, "author": "bas080", "author_id": 989394, "author_profile": "https://Stackoverflow.com/users/989394", "pm_score": 2, "selected": false, "text": "file_size_stored = os.stat('neuron.py').st_size\n\n while True:\n try:\n file_size_current = os.stat('neuron.py').st_size\n if file_size_stored != file_size_current:\n restart_program()\n except: \n pass\n def restart_program(): #restart application\n python = sys.executable\n os.execl(python, python, * sys.argv)\n" }, { "answer_id": 24410417, "author": "redestructa", "author_id": 1926824, "author_profile": "https://Stackoverflow.com/users/1926824", "pm_score": 3, "selected": false, "text": "watchmedo shell-command \\\n--patterns=\"*.sql\" \\\n--recursive \\\n--command='~/Desktop/load_files_into_mysql_database.sh' \\\n.\n" }, { "answer_id": 39606320, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "from PyQt5.QtCore import QFileSystemWatcher, QSettings, QThread\nfrom ui_main_window import Ui_MainWindow # Qt Creator gen'd \n\nclass MainWindow(QMainWindow, Ui_MainWindow):\n def __init__(self, parent=None):\n QMainWindow.__init__(self, parent)\n Ui_MainWindow.__init__(self)\n self._fileWatcher = QFileSystemWatcher()\n self._fileWatcher.fileChanged.connect(self.fileChanged)\n\n def fileChanged(self, filepath):\n QThread.msleep(300) # Reqd on some machines, give chance for write to complete\n # ^^ About to test this, may need more sophisticated solution\n with open(filepath) as file:\n lastLine = list(file)[-1]\n destPath = self._filemap[filepath]['dest file']\n with open(destPath, 'a') as out_file: # a= append\n out_file.writelines([lastLine])\n" }, { "answer_id": 48532931, "author": "george", "author_id": 1773599, "author_profile": "https://Stackoverflow.com/users/1773599", "pm_score": 0, "selected": false, "text": "from pygtail import Pygtail\nimport sys\n\nwhile True:\n for line in Pygtail(\"some.log\"):\n sys.stdout.write(line)\n" }, { "answer_id": 49007649, "author": "4Oh4", "author_id": 5859283, "author_profile": "https://Stackoverflow.com/users/5859283", "pm_score": 4, "selected": false, "text": "import os\nimport sys \nimport time\n\nclass Watcher(object):\n running = True\n refresh_delay_secs = 1\n\n # Constructor\n def __init__(self, watch_file, call_func_on_change=None, *args, **kwargs):\n self._cached_stamp = 0\n self.filename = watch_file\n self.call_func_on_change = call_func_on_change\n self.args = args\n self.kwargs = kwargs\n\n # Look for changes\n def look(self):\n stamp = os.stat(self.filename).st_mtime\n if stamp != self._cached_stamp:\n self._cached_stamp = stamp\n # File has changed, so do something...\n print('File changed')\n if self.call_func_on_change is not None:\n self.call_func_on_change(*self.args, **self.kwargs)\n\n # Keep watching in a loop \n def watch(self):\n while self.running: \n try: \n # Look for changes\n time.sleep(self.refresh_delay_secs) \n self.look() \n except KeyboardInterrupt: \n print('\\nDone') \n break \n except FileNotFoundError:\n # Action on file not found\n pass\n except: \n print('Unhandled error: %s' % sys.exc_info()[0])\n\n# Call this function each time a change happens\ndef custom_action(text):\n print(text)\n\nwatch_file = 'my_file.txt'\n\n# watcher = Watcher(watch_file) # simple\nwatcher = Watcher(watch_file, custom_action, text='yes, changed') # also call custom action function\nwatcher.watch() # start the watch going\n" }, { "answer_id": 53375904, "author": "Rafal Enden", "author_id": 3042543, "author_profile": "https://Stackoverflow.com/users/3042543", "pm_score": 0, "selected": false, "text": "repyt ./app.py\n" }, { "answer_id": 56788212, "author": "mexekanez", "author_id": 795622, "author_profile": "https://Stackoverflow.com/users/795622", "pm_score": 0, "selected": false, "text": "import os\nimport sys\nimport time\n\nclass Watcher(object):\n running = True\n refresh_delay_secs = 1\n\n # Constructor\n def __init__(self, watch_files, call_func_on_change=None, *args, **kwargs):\n self._cached_stamp = 0\n self._cached_stamp_files = {}\n self.filenames = watch_files\n self.call_func_on_change = call_func_on_change\n self.args = args\n self.kwargs = kwargs\n\n # Look for changes\n def look(self):\n for file in self.filenames:\n stamp = os.stat(file).st_mtime\n if not file in self._cached_stamp_files:\n self._cached_stamp_files[file] = 0\n if stamp != self._cached_stamp_files[file]:\n self._cached_stamp_files[file] = stamp\n # File has changed, so do something...\n file_to_read = open(file, 'r')\n value = file_to_read.read()\n print(\"value from file\", value)\n file_to_read.seek(0)\n if self.call_func_on_change is not None:\n self.call_func_on_change(*self.args, **self.kwargs)\n\n # Keep watching in a loop\n def watch(self):\n while self.running:\n try:\n # Look for changes\n time.sleep(self.refresh_delay_secs)\n self.look()\n except KeyboardInterrupt:\n print('\\nDone')\n break\n except FileNotFoundError:\n # Action on file not found\n pass\n except Exception as e:\n print(e)\n print('Unhandled error: %s' % sys.exc_info()[0])\n\n# Call this function each time a change happens\ndef custom_action(text):\n print(text)\n # pass\n\nwatch_files = ['/Users/mexekanez/my_file.txt', '/Users/mexekanez/my_file1.txt']\n\n# watcher = Watcher(watch_file) # simple\n\n\n\nif __name__ == \"__main__\":\n watcher = Watcher(watch_files, custom_action, text='yes, changed') # also call custom action function\n watcher.watch() # start the watch going\n" }, { "answer_id": 63453878, "author": "John Henckel", "author_id": 1812732, "author_profile": "https://Stackoverflow.com/users/1812732", "pm_score": -1, "selected": false, "text": "@echo off\n:top\nxcopy /m /y %1 %2 | find /v \"File(s) copied\"\ntimeout /T 1 > nul\ngoto :top\n" }, { "answer_id": 64124075, "author": "Magnus", "author_id": 8620332, "author_profile": "https://Stackoverflow.com/users/8620332", "pm_score": 2, "selected": false, "text": "src src/app.py nodemon -w 'src/**' -e py,html --exec python src/app.py\n -e py,html" }, { "answer_id": 67755619, "author": "Rafael Beirigo", "author_id": 3684790, "author_profile": "https://Stackoverflow.com/users/3684790", "pm_score": 0, "selected": false, "text": "import inotify.adapters\nfrom datetime import datetime\n\n\nLOG_FILE='/var/log/mysql/server_audit.log'\n\n\ndef main():\n start_time = datetime.now()\n while True:\n i = inotify.adapters.Inotify()\n i.add_watch(LOG_FILE)\n for event in i.event_gen(yield_nones=False):\n break\n del i\n\n with open(LOG_FILE, 'r') as f:\n for line in f:\n entry = line.split(',')\n entry_time = datetime.strptime(entry[0],\n '%Y%m%d %H:%M:%S')\n if entry_time > start_time:\n start_time = entry_time\n print(entry)\n\n\nif __name__ == '__main__':\n main()\n" }, { "answer_id": 71053159, "author": "Ketan", "author_id": 15346361, "author_profile": "https://Stackoverflow.com/users/15346361", "pm_score": 0, "selected": false, "text": " while True:\n # Capturing the two instances models.py after certain interval of time\n print(\"Looking for changes in \" + app_name.capitalize() + \" models.py\\nPress 'CTRL + C' to stop the program\")\n with open(app_name.capitalize() + '/filename', 'r+') as app_models_file:\n filename_content = app_models_file.read()\n time.sleep(5)\n with open(app_name.capitalize() + '/filename', 'r+') as app_models_file_1:\n filename_content_1 = app_models_file_1.read()\n # Comparing models.py after certain interval of time\n if filename_content == filename_content_1:\n pass\n else:\n print(\"You made a change in \" + app_name.capitalize() + \" filename.\\n\")\n cmd = str(input(\"Do something with the file?(y/n):\"))\n if cmd == 'y':\n # Do Something\n elif cmd == 'n':\n # pass or do something\n else:\n print(\"Invalid input\")\n" }, { "answer_id": 72113544, "author": "Boštjan Mejak", "author_id": 7771315, "author_profile": "https://Stackoverflow.com/users/7771315", "pm_score": 1, "selected": false, "text": "filecmp cmp() from filecmp import cmp cmp() cmp() import filecmp\nfilecmp.cmp(path_to_file_1, path_to_file_2, shallow=True)\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15369/" ]
182,229
<p>I'd like to run a script to populate my database. I'd like to access it through the Django database API.</p> <p>The only problem is that I don't know what I would need to import to gain access to this.</p> <p>How can this be achieved?</p>
[ { "answer_id": 182345, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 5, "selected": true, "text": "import os\nos.environ[\"DJANGO_SETTINGS_MODULE\"] = \"mysite.settings\"\n\nfrom mysite.polls.models import Poll, Choice\n" }, { "answer_id": 182790, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "shell manage.py $ cd mysite/\n$ ./manage.py shell\nPython 2.5.2 (r252:60911, Jun 10 2008, 10:35:34) \n[GCC 4.0.1 (Apple Inc. build 5465)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> from myapp.models import *\n>>>\n manage.py" }, { "answer_id": 184898, "author": "Sam Corder", "author_id": 2351, "author_profile": "https://Stackoverflow.com/users/2351", "pm_score": 3, "selected": false, "text": "import string\nimport sys\ntry:\n import settings # Assumed to be in the same directory.\n #settings.DISABLE_TRANSACTION_MANAGEMENT = True\nexcept ImportError:\n sys.stderr.write(\"Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\\nYou'll have to run django-admin.py, passing it your settings module.\\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\\n\" % __file__)\nsys.exit(1)\n\n#Setup the django environment with the settings module.\nimport django\nimport django.core.management\ndjango.core.management.setup_environ(settings)\n\nfrom django.db import transaction\n transaction.enter_transaction_management()\ntry:\n #Do some stuff\n transaction.commit()\nfinally:\n transaction.rollback()\n pass\ntransaction.leave_transaction_management()\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15616/" ]
182,243
<p>I am trying to recreate a Perl script in C# but have a problem creating a checksum value that a target system needs.</p> <p>In Perl this checksum is calculated using the <code>unpack</code> function:</p> <pre><code>while (&lt;PACKAGE&gt;) { $checksum += unpack("%32C*", $_); } $checksum %= 32767; close(PACKAGE); </code></pre> <p>where <code>PACKAGE</code> is the .tar file input stream</p> <p>I need to replicate this in C# but can't find a means of replicating that <code>unpack</code> function.</p> <p>All help appreciated!</p> <p>(I know there are much better checksum calculations available but can't change target system so can't change calculation) </p>
[ { "answer_id": 182266, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "int sum = 0;\nfor (byte b : buffer) {\n sum += (int) b & 255;\n}\nreturn sum % 32767;\n" }, { "answer_id": 185057, "author": "piCookie", "author_id": 8763, "author_profile": "https://Stackoverflow.com/users/8763", "pm_score": 0, "selected": false, "text": "print unpack(\"%32C*\", 'A');\n65\nprint unpack(\"%32C*\", 'AA');\n130\n" }, { "answer_id": 28964314, "author": "Guillermo Veneranda", "author_id": 4653939, "author_profile": "https://Stackoverflow.com/users/4653939", "pm_score": 0, "selected": false, "text": "int fileCheckSum(const char *fileName)\n{\n FILE *fp;\n long fileSize;\n char *fileBuffer;\n size_t result;\n int sum = 0;\n long index;\n\n fp = fopen(fileName, \"rb\");\n if (fp == NULL)\n {\n fputs (\"File error\",stderr); \n exit (1);\n }\n\n fseek(fp, 0L, SEEK_END);\n fileSize = ftell(fp);\n fseek(fp, 0L, SEEK_SET);\n\n fileBuffer = (char*) malloc (sizeof(char) * fileSize); \n if (fileBuffer == NULL)\n {\n fputs (\"Memory error\",stderr);\n exit (2);\n }\n\n result = fread(fileBuffer, 1, fileSize, fp); \n if (result != fileSize)\n {\n fputs (\"Reading error\", stderr);\n if (fileBuffer != NULL)\n free(fileBuffer);\n\n exit (3);\n }\n\n for (index = 0; index < fileSize; index++)\n {\n sum += fileBuffer[index] & 255;\n }\n\n fclose(fp);\n if (fileBuffer != NULL)\n free(fileBuffer);\n\n return sum % 32767; \n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
182,253
<p>I love Python because it comes batteries included, and I use built-in functions, a lot, to do the dirty job for me.</p> <p>I have always been using happily the os.path module to deal with file path but recently I ended up with unexpected results on Python 2.5 under Ubuntu linux, while dealing with string that represent windows file paths :</p> <pre><code>filepath = r"c:\ttemp\FILEPA~1.EXE" print os.path.basename(filepath) 'c:\\ttemp\\FILEPA~1.EXE'] print os.path.splitdrive(filepath) ('', 'c:\ttemp\\FILEPA~1.EXE') </code></pre> <p>WTF ?</p> <p>It ends up the same way with filepath = u"c:\ttemp\FILEPA~1.EXE" and filepath = "c:\ttemp\FILEPA~1.EXE".</p> <p>Do you have a clue ? Ubuntu use UTF8 but I don't feel like it has something to do with it. Maybe my Python install is messed up but I did not perform any particular tweak on it that I can remember.</p>
[ { "answer_id": 182282, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 2, "selected": false, "text": "os.path import re\n(drive, tail) = re.compile('([a-zA-Z]\\:){0,1}(.*)').match(filepath).groups() \n drive : c: u: None tail" }, { "answer_id": 182417, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 6, "selected": true, "text": ">>> import ntpath\n>>> filepath = r\"c:\\ttemp\\FILEPA~1.EXE\"\n>>> print ntpath.basename(filepath)\nFILEPA~1.EXE\n>>> print ntpath.splitdrive(filepath)\n('c:', '\\\\ttemp\\\\FILEPA~1.EXE')\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9951/" ]
182,262
<p>Using Oracle, if a column value can be 'YES' or 'NO' is it possible to constrain a table so that only one row can have a 'YES' value?</p> <p>I would rather redesign the table structure but this is not possible.</p> <p>[UDPATE] Sadly, null values are not allowed in this table.</p>
[ { "answer_id": 182427, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 5, "selected": true, "text": "create unique index only_one_yes on mytable\n(case when col='YES' then 'YES' end);\n" }, { "answer_id": 182490, "author": "Nick Pierpoint", "author_id": 4003, "author_profile": "https://Stackoverflow.com/users/4003", "pm_score": 2, "selected": false, "text": "create table mytest (\n yesorno varchar2(3 char)\n);\n\ncreate unique index uk_mytest_yesorno on mytest(yesorno);\n\nalter table mytest add constraint ck_mytest_yesorno check (yesorno is null or yesorno = 'YES');\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26108/" ]
182,273
<p>How can I modify a SharePoint site so that versioning is turned on by default in Document Libraries?</p>
[ { "answer_id": 185433, "author": "Bryan Friedman", "author_id": 16985, "author_profile": "https://Stackoverflow.com/users/16985", "pm_score": 3, "selected": false, "text": "public class SetVersioning : SPItemEventReceiver\n{\n public override void ItemAdding(SPItemEventProperties properties)\n {\n SPWeb CurrentWeb = properties.OpenWeb();\n foreach (SPDocumentLibrary doclib in CurrentWeb.GetListsOfType(SPBaseType.DocumentLibrary))\n {\n doclib.EnableVersioning = true;\n doclib.MajorVersionLimit = 8;\n //doclib.EnableMinorVersions = true;\n doclib.Update();\n }\n //now get rid of the receiver\n SPEventReceiverDefinitionCollection receivers = CurrentWeb.EventReceivers;\n foreach (SPEventReceiverDefinition definition in receivers)\n {\n if (definition.Name.Equals(EVENT_RECEIVER_NAME))\n {\n definition.Delete();\n break;\n }\n }\n\n base.ItemAdding(properties);\n }\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23427/" ]
182,278
<p>I would like to be able to write a Java class in one package which can access non-public methods of a class in another package without having to make it a subclass of the other class. Is this possible?</p>
[ { "answer_id": 316838, "author": "Matthew Murdoch", "author_id": 4023, "author_profile": "https://Stackoverflow.com/users/4023", "pm_score": 7, "selected": true, "text": "package api;\n\npublic final class Exposed {\n static {\n // Declare classes in the implementation package as 'friends'\n Accessor.setInstance(new AccessorImpl());\n }\n\n // Only accessible by 'friend' classes.\n Exposed() {\n\n }\n\n // Only accessible by 'friend' classes.\n void sayHello() {\n System.out.println(\"Hello\");\n }\n\n static final class AccessorImpl extends Accessor {\n protected Exposed createExposed() {\n return new Exposed();\n }\n\n protected void sayHello(Exposed exposed) {\n exposed.sayHello();\n }\n }\n}\n package impl;\n\npublic abstract class Accessor {\n\n private static Accessor instance;\n\n static Accessor getInstance() {\n Accessor a = instance;\n if (a != null) {\n return a;\n }\n\n return createInstance();\n }\n\n private static Accessor createInstance() {\n try {\n Class.forName(Exposed.class.getName(), true, \n Exposed.class.getClassLoader());\n } catch (ClassNotFoundException e) {\n throw new IllegalStateException(e);\n }\n\n return instance;\n }\n\n public static void setInstance(Accessor accessor) {\n if (instance != null) {\n throw new IllegalStateException(\n \"Accessor instance already set\");\n }\n\n instance = accessor;\n }\n\n protected abstract Exposed createExposed();\n\n protected abstract void sayHello(Exposed exposed);\n}\n package impl;\n\npublic final class FriendlyAccessExample {\n public static void main(String[] args) {\n Accessor accessor = Accessor.getInstance();\n Exposed exposed = accessor.createExposed();\n accessor.sayHello(exposed);\n }\n}\n" }, { "answer_id": 1533414, "author": "eirikma", "author_id": 82991, "author_profile": "https://Stackoverflow.com/users/82991", "pm_score": 2, "selected": false, "text": "package application;\n\nimport application.entity.Entity;\nimport application.service.Service;\nimport junit.framework.TestCase;\n\npublic class EntityFriendTest extends TestCase {\n public void testFriendsAreOkay() {\n Entity entity = new Entity();\n Service service = new Service();\n assertNull(\"entity should not be processed yet\", entity.getPublicData());\n service.processEntity(entity);\n assertNotNull(\"entity should be processed now\", entity.getPublicData());\n }\n}\n package application.service;\n\nimport application.entity.Entity;\n\npublic class Service {\n\n public void processEntity(Entity entity) {\n String value = entity.getFriend().getEntityPackagePrivateData();\n entity.setPublicData(value);\n }\n\n /**\n * Class that Entity explicitly can expose private aspects to subclasses of.\n * Public, so the class itself is visible in Entity's package.\n */\n public static abstract class EntityFriend {\n /**\n * Access method: private not visible (a.k.a 'friendly') outside enclosing class.\n */\n private String getEntityPackagePrivateData() {\n return getEntityPackagePrivateDataImpl();\n }\n\n /** contribute access to private member by implementing this */\n protected abstract String getEntityPackagePrivateDataImpl();\n }\n}\n package application.entity;\n\nimport application.service.Service;\n\npublic class Entity {\n\n private String publicData;\n private String packagePrivateData = \"secret\"; \n\n public String getPublicData() {\n return publicData;\n }\n\n public void setPublicData(String publicData) {\n this.publicData = publicData;\n }\n\n String getPackagePrivateData() {\n return packagePrivateData;\n }\n\n /** provide access to proteced method for Service'e helper class */\n public Service.EntityFriend getFriend() {\n return new Service.EntityFriend() {\n protected String getEntityPackagePrivateDataImpl() {\n return getPackagePrivateData();\n }\n };\n }\n}\n" }, { "answer_id": 18634125, "author": "Salomon BRYS", "author_id": 1269640, "author_profile": "https://Stackoverflow.com/users/1269640", "pm_score": 9, "selected": false, "text": "Romeo Juliet Romeo cuddle Juliet Juliet Romeo cuddle Juliet Romeo friend package capulet;\n\nimport montague.Romeo;\n\npublic class Juliet {\n\n public static void cuddle(Romeo.Love love) {\n Objects.requireNonNull(love);\n System.out.println(\"O Romeo, Romeo, wherefore art thou Romeo?\");\n }\n\n}\n Juliet.cuddle public Romeo.Love Romeo.Love Romeo NullPointerException null package montague;\n\nimport capulet.Juliet;\n\npublic class Romeo {\n public static final class Love { private Love() {} }\n private static final Love love = new Love();\n\n public static void cuddleJuliet() {\n Juliet.cuddle(love);\n }\n}\n Romeo.Love private Romeo Romeo.Love Romeo cuddle Juliet Romeo.Love Juliet cuddle NullPointerException" }, { "answer_id": 22948824, "author": "jpfx1342", "author_id": 1709144, "author_profile": "https://Stackoverflow.com/users/1709144", "pm_score": 0, "selected": false, "text": "class Foo {\n private String locked;\n\n /* Anyone can get locked. */\n public String getLocked() { return locked; }\n\n /* This is the accessor. Anyone with a reference to this has special access. */\n public class FooAccessor {\n private FooAccessor (){};\n public void setLocked(String locked) { Foo.this.locked = locked; }\n }\n private FooAccessor accessor;\n\n /** You get an accessor by calling this method. This method can only\n * be called once, so calling is like claiming ownership of the accessor. */\n public FooAccessor getAccessor() {\n if (accessor != null)\n throw new IllegalStateException(\"Cannot return accessor more than once!\");\n return accessor = new FooAccessor();\n }\n}\n getAccessor() Foo bar = new Foo(); //This object is safe to share.\nFooAccessor barAccessor = bar.getAccessor(); //This one is not.\n class Foo {\n private String secret;\n private String locked;\n\n /* Anyone can get locked. */\n public String getLocked() { return locked; }\n\n /* Normal accessor. Can write to locked, but not read secret. */\n public class FooAccessor {\n private FooAccessor (){};\n public void setLocked(String locked) { Foo.this.locked = locked; }\n }\n private FooAccessor accessor;\n\n public FooAccessor getAccessor() {\n if (accessor != null)\n throw new IllegalStateException(\"Cannot return accessor more than once!\");\n return accessor = new FooAccessor();\n }\n\n /* Super accessor. Allows access to secret. */\n public class FooSuperAccessor {\n private FooSuperAccessor (){};\n public String getSecret() { return Foo.this.secret; }\n }\n private FooSuperAccessor superAccessor;\n\n public FooSuperAccessor getAccessor() {\n if (superAccessor != null)\n throw new IllegalStateException(\"Cannot return accessor more than once!\");\n return superAccessor = new FooSuperAccessor();\n }\n}\n class Foo {\n private String secret;\n private String locked;\n\n public String getLocked() { return locked; }\n\n public class FooAccessor {\n private FooAccessor (){};\n public void setLocked(String locked) { Foo.this.locked = locked; }\n }\n public class FooSuperAccessor {\n private FooSuperAccessor (){};\n public String getSecret() { return Foo.this.secret; }\n }\n public class FooReference {\n public final Foo foo;\n public final FooAccessor accessor;\n public final FooSuperAccessor superAccessor;\n\n private FooReference() {\n this.foo = Foo.this;\n this.accessor = new FooAccessor();\n this.superAccessor = new FooSuperAccessor();\n }\n }\n\n private FooReference reference;\n\n /* Beware, anyone with this object has *all* the accessors! */\n public FooReference getReference() {\n if (reference != null)\n throw new IllegalStateException(\"Cannot return reference more than once!\");\n return reference = new FooReference();\n }\n}\n getReference" }, { "answer_id": 31983744, "author": "intrepidis", "author_id": 847235, "author_profile": "https://Stackoverflow.com/users/847235", "pm_score": 2, "selected": false, "text": "Friend Friend public class Owner {\n private final String member = \"value\";\n\n public String getMember(final Friend friend) {\n // Make sure only a friend is accepted.\n friend.is(Other.class);\n return member;\n }\n}\n public class Other {\n private final Friend friend = new Friend(this);\n\n public void test() {\n String s = new Owner().getMember(friend);\n System.out.println(s);\n }\n}\n Friend public final class Friend {\n private final Class as;\n\n public Friend(final Object is) {\n as = is.getClass();\n }\n\n public void is(final Class c) {\n if (c == as)\n return;\n throw new ClassCastException(String.format(\"%s is not an expected friend.\", as.getName()));\n }\n\n public void is(final Class... classes) {\n for (final Class c : classes)\n if (c == as)\n return;\n is((Class)null);\n }\n}\n public class Abuser {\n public void doBadThings() {\n Friend badFriend = new Friend(new Other());\n String s = new Owner().getMember(badFriend);\n System.out.println(s);\n }\n}\n Other Abuser Other2 public class Other2 {\n private final Friend friend = new Friend();\n\n public final class Friend {\n private Friend() {}\n public void check() {}\n }\n\n public void test() {\n String s = new Owner2().getMember(friend);\n System.out.println(s);\n }\n}\n Owner2 public class Owner2 {\n private final String member = \"value\";\n\n public String getMember(final Other2.Friend friend) {\n friend.check();\n return member;\n }\n}\n Other2.Friend" }, { "answer_id": 38703299, "author": "Chris", "author_id": 6360153, "author_profile": "https://Stackoverflow.com/users/6360153", "pm_score": 1, "selected": false, "text": "public class ProtectedContainer {\n protected String iwantAccess;\n\n protected ProtectedContainer() {\n super();\n iwantAccess = \"Default string\";\n }\n\n protected ProtectedContainer(ProtectedContainer other) {\n super();\n this.iwantAccess = other.iwantAccess;\n }\n\n public int calcSquare(int x) {\n iwantAccess = \"calculated square\";\n return x * x;\n }\n}\n public class MyApp {\n\n private static class ProtectedAccessor extends ProtectedContainer {\n\n protected ProtectedAccessor() {\n super();\n }\n\n protected PrivateAccessor(ProtectedContainer prot) {\n super(prot);\n }\n\n public String exposeProtected() {\n return iwantAccess;\n }\n }\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ]
182,281
<p>I have a template in word (.docx) format and want to replace some placeholders in this template with my own data, do you know where I can find the right classes for this project? It would be nice for me to know the namespace. Are there any newer classes for handling word documents in the docx format (xml) than the com classes? Thank you for all your answers, I hope someone can help me with my problem.</p> <p>greets </p> <p>Sebastian</p>
[ { "answer_id": 190411, "author": "Sebastian Müller", "author_id": 23681, "author_profile": "https://Stackoverflow.com/users/23681", "pm_score": 0, "selected": false, "text": " NameTable nt = new NameTable();\n XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);\n nsManager.AddNamespace(\"w\", wordmlNamespace);\n\n XmlDocument xDoc = new XmlDocument();\n xDoc.Load(doc.MainDocumentPart.GetStream());\n\n XmlNodeList nodeList = xDoc.SelectNodes(@\"./w:document/w:body//w:sdt\", nsManager);\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23681/" ]
182,287
<p>Why can't I pass the table name to a prepared PDO statement?</p> <pre><code>$stmt = $dbh-&gt;prepare('SELECT * FROM :table WHERE 1'); if ($stmt-&gt;execute(array(':table' =&gt; 'users'))) { var_dump($stmt-&gt;fetchAll()); } </code></pre> <p>Is there another safe way to insert a table name into a SQL query? With safe, I mean that I don't want to do</p> <pre><code>$sql = "SELECT * FROM $table WHERE 1" </code></pre>
[ { "answer_id": 182312, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 3, "selected": false, "text": "$table $table" }, { "answer_id": 182353, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 9, "selected": true, "text": "switch() function buildQuery( $get_var ) \n{\n switch($get_var)\n {\n case 1:\n $tbl = 'users';\n break;\n }\n\n $sql = \"SELECT * FROM $tbl\";\n}\n" }, { "answer_id": 15990488, "author": "IMSoP", "author_id": 157957, "author_profile": "https://Stackoverflow.com/users/157957", "pm_score": 7, "selected": false, "text": "SELECT name FROM my_table WHERE id = :value :value SELECT name FROM :table WHERE id = :value" }, { "answer_id": 16305689, "author": "Don", "author_id": 207069, "author_profile": "https://Stackoverflow.com/users/207069", "pm_score": 4, "selected": false, "text": "function getTableInfo($inTableName, $inColumnName) {\n ....\n}\n $allowed_tables_array = array('tblTheTable');\n$allowed_columns_array['tblTheTable'] = array('the_col_to_check');\n if(in_array($inTableName, $allowed_tables_array) && in_array($inColumnName,$allowed_columns_array[$inTableName]))\n{\n $sql = \"SELECT $inColumnName AS columnInfo\n FROM $inTableName\";\n $stmt = $pdo->prepare($sql); \n $stmt->execute();\n $result = $stmt->fetchAll(PDO::FETCH_ASSOC);\n}\n" }, { "answer_id": 23353392, "author": "Phil LaNasa", "author_id": 2374900, "author_profile": "https://Stackoverflow.com/users/2374900", "pm_score": 1, "selected": false, "text": "$value = preg_replace('/[^a-zA-Z_]*/', '', $value);\n" }, { "answer_id": 25748686, "author": "man", "author_id": 1881655, "author_profile": "https://Stackoverflow.com/users/1881655", "pm_score": 0, "selected": false, "text": "class myPdo{\n private $user = 'dbuser';\n private $pass = 'dbpass';\n private $host = 'dbhost';\n private $db = 'dbname';\n private $pdo;\n private $dbInfo;\n public function __construct($type){\n $this->pdo = new PDO('mysql:host='.$this->host.';dbname='.$this->db.';charset=utf8',$this->user,$this->pass);\n if(isset($type)){\n //when class is called upon, it stores column names and column types from the table of you choice in $this->dbInfo;\n $stmt = \"select distinct column_name,column_type from information_schema.columns where table_name='sometable';\";\n $stmt = $this->pdo->prepare($stmt);//not really necessary since this stmt doesn't contain any dynamic values;\n $stmt->execute();\n $this->dbInfo = $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n }\n public function pdo_param($col){\n $param_type = PDO::PARAM_STR;\n foreach($this->dbInfo as $k => $arr){\n if($arr['column_name'] == $col){\n if(strstr($arr['column_type'],'int')){\n $param_type = PDO::PARAM_INT;\n break;\n }\n }\n }//for testing purposes i only used INT and VARCHAR column types. Adjust to your needs...\n return $param_type;\n }\n public function columnIsAllowed($col){\n $colisAllowed = false;\n foreach($this->dbInfo as $k => $arr){\n if($arr['column_name'] === $col){\n $colisAllowed = true;\n break;\n }\n }\n return $colisAllowed;\n }\n public function q($data){\n //$data is received by post as a JSON object and looks like this\n //{\"data\":{\"column_a\":\"value\",\"column_b\":\"value\",\"column_c\":\"value\"},\"get\":\"column_x\"}\n $data = json_decode($data,TRUE);\n $continue = true;\n foreach($data['data'] as $column_name => $value){\n if(!$this->columnIsAllowed($column_name)){\n $continue = false;\n //means that someone possibly messed with the post and tried to get data from a column that does not exist in the current table, or the column name is a sql injection string and so on...\n break;\n }\n }\n //since $data['get'] is also a column, check if its allowed as well\n if(isset($data['get']) && !$this->columnIsAllowed($data['get'])){\n $continue = false;\n }\n if(!$continue){\n exit('possible injection attempt');\n }\n //continue with the rest of the func, as you normally would\n $stmt = \"SELECT DISTINCT \".$data['get'].\" from sometable WHERE \";\n foreach($data['data'] as $k => $v){\n $stmt .= $k.' LIKE :'.$k.'_val AND ';\n }\n $stmt = substr($stmt,0,-5).\" order by \".$data['get'];\n //$stmt should look like this\n //SELECT DISTINCT column_x from sometable WHERE column_a LIKE :column_a_val AND column_b LIKE :column_b_val AND column_c LIKE :column_c_val order by column_x\n $stmt = $this->pdo->prepare($stmt);\n //obviously now i have to bindValue()\n foreach($data['data'] as $k => $v){\n $stmt->bindValue(':'.$k.'_val','%'.$v.'%',$this->pdo_param($k));\n //setting PDO::PARAM... type based on column_type from $this->dbInfo\n }\n $stmt->execute();\n return $stmt->fetchAll(PDO::FETCH_ASSOC);//or whatever\n }\n}\n$pdo = new myPdo('anything');//anything so that isset() evaluates to TRUE.\nvar_dump($pdo->q($some_json_object_as_described_above));\n" }, { "answer_id": 53210496, "author": "Funk Forty Niner", "author_id": 1415724, "author_profile": "https://Stackoverflow.com/users/1415724", "pm_score": 2, "selected": false, "text": "CREATE DATABASE IF NOT EXISTS :database\n" }, { "answer_id": 69846926, "author": "totalnoob", "author_id": 9588276, "author_profile": "https://Stackoverflow.com/users/9588276", "pm_score": -1, "selected": false, "text": "$unsanitized_table_name = \"users' OR '1'='1\"; //SQL Injection attempt\n$sanitized_table_name = sanitize_input($unsanitized_table_name);\n\n$stmt = $dbh->prepare(\"SELECT * FROM {$unsanitized_table_name} WHERE 1\"); //<--- REALLY bad idea\n$stmt = $dbh->prepare(\"SELECT * FROM {$sanitized_table_name} WHERE 1\"); //<--- Not ideal but hey, at least you're safe.\n\n//PDO Cant sanitize everything so we limp along with mysqli instead\nfunction sanitize_input($string)\n{\n $mysqli = new mysqli(\"localhost\",\"UsahName\",\"Passerrrd\");\n $string = $mysqli->real_escape_string($string);\n\n return $string;\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
182,306
<p>My application runs under CF 2.0 locally and i would like to know how to connect and send something to print in the embedded printer of a http://www.milliontech.com/home/content/view/195/95/'>Bluebird BIP-1300 device.</p> <p>Ideally i would like an example in C#.</p> <p>Thank you in advance.</p>
[ { "answer_id": 4518794, "author": "Musa", "author_id": 552371, "author_profile": "https://Stackoverflow.com/users/552371", "pm_score": 2, "selected": false, "text": "using Bluebird.BIP.Printer;\n...\nthis.prn1 = new Bluebird.BIP.Printer.Printer();\nif (!this.prn1.Open(0))\n {\n MessageBox.Show(\"Can not open Printer\", \"Printer problem\");\n }\nthis.prn1.PrintText(\"sdfgidfui\", 0);\nthis.prn1.PrintBitmap(@\"\\My Documents\\sample.bmp\", 0);\n\nif (this.prn1.WaitUntilPrintEnd() == 1)\n{\nMessageBox.Show(\"No paper in Printer\", \"Printer problem\");\n }\n }\nthis.prn1.Close();\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17443/" ]
182,316
<p>I've often heard criticism of the lack of thread safety in the Swing libraries. Yet, I am not sure as to what I would be doing in my own code with could cause issues:</p> <p>In what situations does the fact Swing is not thread safe come into play ?</p> <p>What should I actively avoid doing ?</p>
[ { "answer_id": 182652, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 3, "selected": false, "text": "class MyApp {\n public static void main(String[] args) {\n java.awt.EventQueue.invokeLater(new Runnable() { public void run() {\n runEDT();\n }});\n }\n private static void runEDT() {\n assert java.awt.EventQueue.isDispatchThread();\n ...\n" }, { "answer_id": 185012, "author": "Paul Brinkley", "author_id": 18160, "author_profile": "https://Stackoverflow.com/users/18160", "pm_score": 4, "selected": false, "text": "java.awt.Component repaint() revalidate() invalidate() start() setVisible(true) show() pack() setVisible(true) init() start() invokeLater() someTextField.getText() invokeLater()" }, { "answer_id": 185541, "author": "Tim Williscroft", "author_id": 2789, "author_profile": "https://Stackoverflow.com/users/2789", "pm_score": 1, "selected": false, "text": "doAction(){\nnew Thread(){\n public void run(){\n //kick off thread to do actionImpl().\n actionImpl();\n MyAction.this.interrupt();\n }.start(); // use a worker pool if you care about garbage.\ntry {\nsleep(300);\nGo to a busy cursor\nsleep(600);\nShow a busy dialog(Name) // name comes in handy here\n} catch( interrupted exception){\n show normal cursor\n}\n" }, { "answer_id": 1940539, "author": "Pool", "author_id": 2352432, "author_profile": "https://Stackoverflow.com/users/2352432", "pm_score": 2, "selected": false, "text": "public final static void checkOnEventDispatchThread() {\n if (!SwingUtilities.isEventDispatchThread()) {\n throw new RuntimeException(\"This method can only be run on the EDT\");\n }\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4857/" ]
182,323
<p>I'm trying to serialize objects from a database that have been retrieved with Hibernate, and I'm only interested in the objects' actual data in its entirety (cycles included).</p> <p>Now I've been working with <a href="http://xstream.codehaus.org/" rel="nofollow noreferrer">XStream</a>, which seems powerful. The problem with XStream is that it looks all too blindly on the information. It recognizes Hibernate's PersistentCollections as they are, with all the Hibernate metadata included. I don't want to serialize those.</p> <p>So, is there a reasonable way to extract the original Collection from within a PersistentCollection, and also initialize all referring data the objects might be pointing to. Or can you recommend me to a better approach?</p> <p>(The results from <a href="http://simple.sourceforge.net/" rel="nofollow noreferrer">Simple</a> seem perfect, but it can't cope with such basic util classes as Calendar. It also accepts only one annotated object at a time)</p>
[ { "answer_id": 182955, "author": "Miguel Ping", "author_id": 22992, "author_profile": "https://Stackoverflow.com/users/22992", "pm_score": 1, "selected": false, "text": "MapperIF mapper = DozerBeanMapperSingletonWrapper.getInstance();\nPersonEJB serializablePerson = mapper.map(myPersonInstance, PersonEJB.class);\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2238/" ]
182,334
<p>I work at a company that, for some reason, insists that all our development documentation should be in MS Word format. Which, being a binary format, means we cannot:</p> <ul> <li>Diff versions of a document against each other (so peer reviewing them is a pain - because of the domain we work in, peer reviews for all changes are essential)</li> <li>Grep a folder-full of documents for keywords</li> </ul> <p>What do you use to write documentation in and why?</p> <p>Please also give me ammo to change this situation with...</p>
[ { "answer_id": 182352, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": ".docx" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11347/" ]
182,365
<p>Is there a way to figure out versions of modules that were loaded into the process' address space when the process crashed from a crash dump that was generated by the process calling the MiniDumpWriteDump function? In other words, is any version information stored inside a dmp file?</p> <p>Thanks.</p>
[ { "answer_id": 55760110, "author": "Bootuz", "author_id": 5865129, "author_profile": "https://Stackoverflow.com/users/5865129", "pm_score": 0, "selected": false, "text": "lm v <name_of_module> // shows information about specified module\n lm v" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26114/" ]
182,372
<p>What is the easiest way to check if events have been logged in the eventlog during a period of time?</p> <p>I want to perform a series of automated test steps and then check if any errors were logged to the Application Event Log, ignoring a few sources that I'm not interested in. I can use System.Diagnostics.EventLog and then look at the Entries collection, but it doesn't seem very useable for this scenario. For instance Entries.Count can get smaller over time if the event log is removing old entries. I'd prefer some way to either query the log or monitor it for changes during a period of time. e.g. </p> <pre><code>DateTime start = DateTime.Now; // do some stuff... foreach(EventLogEntry entry in CleverSolution.EventLogEntriesSince(start, "Application")) { // Now I can do stuff with entry, or ignore if its Source is one // that I don't care about. // ... } </code></pre>
[ { "answer_id": 182716, "author": "Rory", "author_id": 8479, "author_profile": "https://Stackoverflow.com/users/8479", "pm_score": 0, "selected": false, "text": "/// <summary>\n/// Steps through each of the entries in the specified event log and returns any that were written \n/// after the given point in time. \n/// </summary>\n/// <param name=\"logName\">The event log to inspect, eg \"Application\"</param>\n/// <param name=\"writtenSince\">The point in time to return entries from</param>\n/// <param name=\"type\">The type of entry to return, or null for all entry types</param>\n/// <returns>A list of all entries of interest, which may be empty if there were none in the event log.</returns>\npublic List<EventLogEntry> GetEventLogEntriesSince(string logName, DateTime writtenSince, EventLogEntryType type)\n{\n List<EventLogEntry> results = new List<EventLogEntry>();\n EventLog eventLog = new System.Diagnostics.EventLog(logName);\n foreach (EventLogEntry entry in eventLog.Entries)\n {\n if (entry.TimeWritten > writtenSince && (type==null || entry.EntryType == type))\n results.Add(entry);\n }\n return results;\n}\n private DateTime whenLastEventLogEntryWritten;\n EventLog eventLog = new EventLog(\"Application\");\nwhenLastEventLogEntryWritten = eventLog.Entries.Count > 0 ? \n eventLog.Entries[eventLog.Entries.Count - 1] : DateTime.Now;\n Assert.IsEmpty(GetEventLogEntriesSince(\"Application\",\n whenLastEventLogEntryWritten, \n EventLogEntryType.Error), \n \"Application Event Log errors occurred during test execution.\");\n" }, { "answer_id": 183768, "author": "Tim Farley", "author_id": 4425, "author_profile": "https://Stackoverflow.com/users/4425", "pm_score": 2, "selected": false, "text": "GetEventLogEntriesSince()" }, { "answer_id": 183794, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 0, "selected": false, "text": "$d=Get-Date\n$recent=[System.Management.ManagementDateTimeConverter]::ToDMTFDateTime($d.AddDays(-7))\n\nget-wmiobject -computer HOSTNAME -class Win32_NTLogEvent `\n -filter \"logfile = 'Application' and (sourcename = 'SOURCENAME' or sourcename like 'OTHERSOURCENAME%') and (type = 'error' or type = 'warning') AND (TimeGenerated >='$recent')\" | \nsort-object @{ expression = {$_.TimeWritten} } -descending |\nselect SourceName, Message | \nformat-table @{Expression = { $_.SourceName};Width = 20;Label=\"SourceName\"}, Message\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8479/" ]
182,373
<p>I am currently creating a custom control that needs to handle animation in a C# project. It is basically a listbox that contains a fixed number of elements that are subject to move. An element (another user control with a background image and a couple of generated labels) can move upwards, downwards or be taken out of the list. </p> <p>I would like to create animated movement as the elements get moved around within the container custom control but it seems to me that moving controls around using lines such as</p> <pre><code>myCustomControl.left -= m_iSpeed;</code></pre> <p>triggered within a timer event is flickery and has a terrible rendering, even with double buffering turned on.</p> <p>So here's the question : <strong>What is the best way to achieve a flicker-free animated C# control?</strong> Should I just not create custom controls and handle all of the drawing within a panel's background image that I generate? Is there a super animation method that I have not discovered? :)</p> <p>Thanks!</p>
[ { "answer_id": 182474, "author": "Mark Heath", "author_id": 7532, "author_profile": "https://Stackoverflow.com/users/7532", "pm_score": 3, "selected": true, "text": "this.SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | \n ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor,\n true);\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25152/" ]
182,379
<p>I've got a column in a database table (SQL Server 2005) that contains data like this:</p> <pre><code>TQ7394 SZ910284 T r1534 su8472 </code></pre> <p>I would like to update this column so that the first two characters are uppercase. I would also like to remove any spaces between the first two characters. So <code>T q1234</code> would become <code>TQ1234</code>.</p> <p><strong>The solution should be able to cope with multiple spaces between the first two characters.</strong></p> <p>Is this possible in T-SQL? How about in ANSI-92? I'm always interested in seeing how this is done in other db's too, so feel free to post answers for PostgreSQL, MySQL, et al.</p>
[ { "answer_id": 182438, "author": "Learning", "author_id": 18275, "author_profile": "https://Stackoverflow.com/users/18275", "pm_score": 0, "selected": false, "text": "update Table set Column = case when len(rtrim(substring (Column , 1 , 2))) < 2 \n then UPPER(substring (Column , 1 , 1) + substring (Column , 3 , 1)) + substring(Column , 4, len(Column)\n else UPPER(substring (Column , 1 , 2)) + substring(Column , 3, len(Column) end\n" }, { "answer_id": 182442, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "// uses a fixed column length - 20-odd in this case\nUPDATE FOO\nSET bar = RTRIM(SUBSTRING(bar, 1, 2)) + SUBSTRING(bar, 3, 20)\n\nUPDATE FOO\nSET bar = UPPER(SUBSTRING(bar, 1, 2)) + SUBSTRING(bar, 3, 20)\n" }, { "answer_id": 182469, "author": "huo73", "author_id": 15657, "author_profile": "https://Stackoverflow.com/users/15657", "pm_score": 2, "selected": false, "text": "UPDATE YourTable \nSET YourColumn = UPPER(\n SUBSTRING(\n REPLACE(YourColumn, ' ', ''), 1, 2\n )\n ) \n + \n SUBSTRING(YourColumn, 3, LEN(YourColumn))\n" }, { "answer_id": 182481, "author": "leoinfo", "author_id": 6948, "author_profile": "https://Stackoverflow.com/users/6948", "pm_score": 3, "selected": true, "text": "/* TEST TABLE */\nDECLARE @T AS TABLE(code Varchar(20))\nINSERT INTO @T SELECT 'ab1234x1' UNION SELECT ' ab1234x2' \n UNION SELECT ' ab1234x3' UNION SELECT 'a b1234x4' \n UNION SELECT 'a b1234x5' UNION SELECT 'a b1234x6' \n UNION SELECT 'ab 1234x7' UNION SELECT 'ab 1234x8' \n\nSELECT * FROM @T\n/* INPUT\n code\n --------------------\n ab1234x3\n ab1234x2\n a b1234x6\n a b1234x5\n a b1234x4\n ab 1234x8\n ab 1234x7\n ab1234x1\n*/\n\n/* START PROCESSING SECTION */\nDECLARE @s Varchar(20)\nDECLARE @firstChar INT\nDECLARE @secondChar INT\n\nUPDATE @T SET\n @firstChar = PATINDEX('%[^ ]%',code)\n ,@secondChar = @firstChar + PATINDEX('%[^ ]%', STUFF(code,1, @firstChar,'' ) )\n ,@s = STUFF(\n code,\n 1,\n @secondChar,\n REPLACE(LEFT(code,\n @secondChar\n ),' ','')\n ) \n ,@s = STUFF(\n @s, \n 1,\n 2,\n UPPER(LEFT(@s,2))\n )\n ,code = @s\n/* END PROCESSING SECTION */\n\nSELECT * FROM @T\n/* OUTPUT\n code\n --------------------\n AB1234x3\n AB1234x2\n AB1234x6\n AB1234x5\n AB1234x4\n AB 1234x8\n AB 1234x7\n AB1234x1\n*/\n" }, { "answer_id": 182517, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "UPPER UPDATE tbl\nSET col = REPLACE(UPPER(col), ' ', '')\n" }, { "answer_id": 182608, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 1, "selected": false, "text": "UPPER(REPLACE(YourColumn, ' ', '')) \n ALTER TABLE YourTable ADD\n CONSTRAINT YourColumn__char_pos_1_uppercase_letter\n CHECK (ASCII(SUBSTRING(YourColumn, 1, 1)) BETWEEN ASCII('A') AND ASCII('Z'));\n\n ALTER TABLE YourTable ADD\n CONSTRAINT YourColumn__char_pos_2_uppercase_letter\n CHECK (ASCII(SUBSTRING(YourColumn, 2, 1)) BETWEEN ASCII('A') AND ASCII('Z'));\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1944/" ]
182,393
<p>In a few large projects i have been working on lately it seems to become increasingly important to choose one or the other (XML or Annotation). As projects grow, consistency is very important for maintainability. </p> <p>My questions are: what are the advantages of XML-based configuration over Annotation-based configuration and what are the advantages of Annotation-based configuration over XML-based configuration?</p>
[ { "answer_id": 182686, "author": "Huibert Gill", "author_id": 1254442, "author_profile": "https://Stackoverflow.com/users/1254442", "pm_score": 4, "selected": false, "text": "@Autowire @Element @Webservice" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24390/" ]
182,408
<p>Is there a manual for cross-compiling a C++ application from Linux to Windows?</p> <p>Just that. I would like some information (links, reference, examples...) to guide me to do that.</p> <p>I don't even know if it's possible. </p> <p>My objective is to compile a program in Linux and get a .exe file that I can run under Windows.</p>
[ { "answer_id": 182456, "author": "richq", "author_id": 4596, "author_profile": "https://Stackoverflow.com/users/4596", "pm_score": 7, "selected": true, "text": "sudo apt-get install mingw32 \ncat > main.c <<EOF\nint main()\n{\n printf(\"Hello, World!\");\n}\nEOF\ni586-mingw32msvc-cc main.c -o hello.exe\n apt-get yum hello.exe CC=i586-mingw32msvc-cc CC=i586-mingw32msvc-cc ./configure && make\n /usr/cross/i586-mingw32msvc/{include,lib}" }, { "answer_id": 182470, "author": "Anders Hansson", "author_id": 20364, "author_profile": "https://Stackoverflow.com/users/20364", "pm_score": 3, "selected": false, "text": "cygwin.dll" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366094/" ]
182,410
<p>I have a JavaScript array that, among others, contains a URL. If I try to simply put the URL in the page (the array is in a project involving the Yahoo! Maps API) it shows the URL as it should be.</p> <p>But if I try to do a redirect or simply do an 'alert' on the link array element I get: </p> <blockquote> <p>function(){return JSON.encode(this);}</p> </blockquote> <p>As far as I see it this is because the browser does an JSON.encode when it renders the page, thus the link is displayed OK. I have tried several methods to make it redirect (that's what I want to do with the link) correctly (including the usage of 'eval') but with no luck.</p> <p>After following some suggestions I've run <code>eval('(' + jsonObject + ')')</code> but it still returns the same output.</p> <p>So how's this done ? </p>
[ { "answer_id": 183346, "author": "Joel Anair", "author_id": 7441, "author_profile": "https://Stackoverflow.com/users/7441", "pm_score": 3, "selected": false, "text": "function(){return JSON.encode(this);}\n" }, { "answer_id": 183362, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 2, "selected": false, "text": "eval('(' + jsonObject + ')')\n" }, { "answer_id": 189613, "author": "Leonel Martins", "author_id": 26673, "author_profile": "https://Stackoverflow.com/users/26673", "pm_score": 1, "selected": false, "text": "var url = myArray[i]();\n" }, { "answer_id": 5308754, "author": "Floccinaucinihilipilification.", "author_id": 609705, "author_profile": "https://Stackoverflow.com/users/609705", "pm_score": 3, "selected": false, "text": "echo json_encode($iniData);\n <script type=\"text/javascript\">\n $(document).ready(function(){\n $.ajax({\n type: \"GET\",\n url: \"ajaxCalls.php\",\n data: \"dataType=ini\",\n success: function(msg)\n {\n var x = eval('(' + msg + ')');\n $('#allowed').html(x.allowed); // these are the fields which you can now easily access..\n $('#completed').html(x.completed);\n $('#running').html(x.running);\n $('#expired').html(x.expired);\n $('#balance').html(x.balance);\n }\n });\n });\n</script>\n" }, { "answer_id": 6541474, "author": "matija kancijan", "author_id": 655430, "author_profile": "https://Stackoverflow.com/users/655430", "pm_score": 5, "selected": false, "text": "var obj = jQuery.parseJSON('{\"name\":\"John\"}');\nalert( obj.name === \"John\" );\n" }, { "answer_id": 15613878, "author": "pirogtm", "author_id": 2098782, "author_profile": "https://Stackoverflow.com/users/2098782", "pm_score": -1, "selected": false, "text": "eval( 'var from_json_object = ' + my_json_str + ';' );\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20603/" ]
182,436
<p>Are there any tools available for validating a database schema against a set of design rules, naming conventions, etc.</p> <p>I'm not talking about comparing one database to another (as covered by <a href="https://stackoverflow.com/questions/165401/how-to-comparevalidate-sql-schema">this question</a>).</p> <p>I want to be able to say "What in this database doesn't meet this set of rules". </p> <p>Some examples of the type of rules I'm talking about would be like:<br> - Primary key fields should be the first in the table.<br> - Foreign keys should have an index on that field.<br> - Field names ending 'xxx' should be of a certain type.<br> - Fields with a constraint limiting it it certain values it should have a default.</p> <p>I've written a bunch of scripts to do this in the past and was wondering if there was something generic available.</p> <p>Ideally I'd like something for SQL Server, but if you're aware of something for other databases it may be useful to know about them too.</p>
[ { "answer_id": 183346, "author": "Joel Anair", "author_id": 7441, "author_profile": "https://Stackoverflow.com/users/7441", "pm_score": 3, "selected": false, "text": "function(){return JSON.encode(this);}\n" }, { "answer_id": 183362, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 2, "selected": false, "text": "eval('(' + jsonObject + ')')\n" }, { "answer_id": 189613, "author": "Leonel Martins", "author_id": 26673, "author_profile": "https://Stackoverflow.com/users/26673", "pm_score": 1, "selected": false, "text": "var url = myArray[i]();\n" }, { "answer_id": 5308754, "author": "Floccinaucinihilipilification.", "author_id": 609705, "author_profile": "https://Stackoverflow.com/users/609705", "pm_score": 3, "selected": false, "text": "echo json_encode($iniData);\n <script type=\"text/javascript\">\n $(document).ready(function(){\n $.ajax({\n type: \"GET\",\n url: \"ajaxCalls.php\",\n data: \"dataType=ini\",\n success: function(msg)\n {\n var x = eval('(' + msg + ')');\n $('#allowed').html(x.allowed); // these are the fields which you can now easily access..\n $('#completed').html(x.completed);\n $('#running').html(x.running);\n $('#expired').html(x.expired);\n $('#balance').html(x.balance);\n }\n });\n });\n</script>\n" }, { "answer_id": 6541474, "author": "matija kancijan", "author_id": 655430, "author_profile": "https://Stackoverflow.com/users/655430", "pm_score": 5, "selected": false, "text": "var obj = jQuery.parseJSON('{\"name\":\"John\"}');\nalert( obj.name === \"John\" );\n" }, { "answer_id": 15613878, "author": "pirogtm", "author_id": 2098782, "author_profile": "https://Stackoverflow.com/users/2098782", "pm_score": -1, "selected": false, "text": "eval( 'var from_json_object = ' + my_json_str + ';' );\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1755/" ]
182,440
<p>This question is a follow-up from <a href="https://stackoverflow.com/questions/161822/how-to-indicate-that-a-method-was-unsuccessful">How to indicate that a method was unsuccessful</a>. The xxx() Tryxxx() pattern is something that can be very useful in many libraries. I am wondering what is the best way to offer both implementations without duplicating my code.</p> <p>What is best:</p> <pre><code>public int DoSomething(string a) { // might throw an exception } public bool TrySomething(string a, out result) { try { result = DoSomething(a) return true; } catch (Exception) { return false; } </code></pre> <p>or</p> <pre><code>public int DoSomething(string a) { int result; if (TrySomething(a, out result)) { return result; } else { throw Exception(); // which exception? } } public bool TrySomething(string a, out result) { //... } </code></pre> <p>I'd instinctively assume that the first example is more correct (you know exactly which exception happened), but couldn't the try/catch be too expensive? Is there a way to catch the exception in the second example?</p>
[ { "answer_id": 182483, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 2, "selected": false, "text": "public bool TrySomething(string a, out result, bool throwException)\n{\n try\n {\n // Whatever\n }\n catch\n {\n if(throwException)\n {\n throw;\n }\n else\n {\n return false;\n }\n }\n\n}\n\npublic bool TrySomething(string a, out result)\n{\n return TrySomething(a, out result, false);\n}\n public int DoSomething(string a)\n{\n int result;\n\n // This will throw the execption or \n // change to false to not, or don't use the overloaded one.\n TrySomething(a, out result, true) \n\n return result; \n}\n" }, { "answer_id": 182494, "author": "Ben Crouse", "author_id": 6705, "author_profile": "https://Stackoverflow.com/users/6705", "pm_score": 2, "selected": false, "text": "public bool TrySomething(string a, out result)\n{\n try\n {\n result = DoSomething(a)\n return true;\n }\n catch (Exception)\n {\n return false;\n }\n}\n int.TryParse(string s, out int result)" }, { "answer_id": 182507, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "public object DoSomething(object input){\n return DoSomethingInternal(input, true);\n}\n\npublic bool TryDoSomething(object input, out object result){\n result = DoSomethingInternal(input, false);\n return result != null;\n}\n\nprivate object DoSomethingInternal(object input, bool throwOnError){\n /* do your work here; only throw if you cannot proceed and throwOnError is true */\n}\n" }, { "answer_id": 182515, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "public int DoSomething(string input)\n{\n int ret;\n Exception exception = DoSomethingImpl(input, out ret);\n if (exception != null)\n {\n // Note that you'll lose stack trace accuracy here\n throw exception;\n }\n return ret;\n}\n\npublic bool TrySomething(string input, out int ret)\n{\n Exception exception = DoSomethingImpl(input, out ret);\n return exception == null;\n}\n\nprivate Exception DoSomethingImpl(string input, out int ret)\n{\n ret = 0;\n if (input != \"bad\")\n {\n ret = 5;\n return null;\n }\n else\n {\n return new ArgumentException(\"Some details\");\n }\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5789/" ]
182,446
<p>Internet Explorer (from versions 4 to 7, at least) limits the number of files uploaded using a single 'input type="file"' form field to one. What is the best approach to take if I want to upload more than one file in a single HTTP POST request?</p>
[ { "answer_id": 182457, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 4, "selected": true, "text": "input" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ]
182,452
<p>I use <a href="http://xfire.codehaus.org/" rel="nofollow noreferrer">XFire</a> to create a webservice wrapper around my application. XFire provides the webservice interface and WSDL at runtime (or creates them at compile time, don't know exactly).</p> <p>Many of our customers don't know webservices very well and additionally they simply don't read any external documentation like Javadoc. I know that it's possible to add documentation (for parameters and methods) directly to the WSDL file. </p> <p>I thought about Annotations or Aegis XML files but I don't know how... Do you know a way?</p> <p>Edit: I just found this <a href="http://jira.codehaus.org/browse/XFIRE-507" rel="nofollow noreferrer">JIRA issue</a> but the last activity was 2006. Any ideas? </p>
[ { "answer_id": 189577, "author": "Chris Vest", "author_id": 13251, "author_profile": "https://Stackoverflow.com/users/13251", "pm_score": 3, "selected": true, "text": "java2wsdl" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17473/" ]
182,455
<p>How do I remove a trailing comma from a string in ColdFusion?</p>
[ { "answer_id": 182464, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 3, "selected": false, "text": "<cfset myStr = \"hello, goodbye,\">\n<cfset myStr = trim(myStr)>\n\n<cfif right(myStr, 1) is \",\">\n <cfset myStr = left(myStr, len(myStr)-1)>\n</cfif>\n" }, { "answer_id": 182466, "author": "Patrick McElhaney", "author_id": 437, "author_profile": "https://Stackoverflow.com/users/437", "pm_score": 6, "selected": true, "text": "REReplace(list, \",$\", \"\")\n REReplace(list, \",+$\", \"\")\n" }, { "answer_id": 182511, "author": "Jason", "author_id": 3242, "author_profile": "https://Stackoverflow.com/users/3242", "pm_score": 2, "selected": false, "text": "<cfset myString = \"This is the string, with training commas,,,\">\n<cfset onlyTheLastTrailingComma = reReplace(myString, \",$\", \"\", \"all\")>\n<cfset allTrailingCommas = reReplace(myString, \",+$\", \"\", \"all\")>\n<cfoutput>#onlyTheLastTrailingComma#<br />#allTrailingCommas#</cfoutput>\n" }, { "answer_id": 197995, "author": "Phydiux", "author_id": 27465, "author_profile": "https://Stackoverflow.com/users/27465", "pm_score": 2, "selected": false, "text": "\n<cfset someVariable = arrayToList(listToArray(someVariable, \",\"), \",\")>\n" }, { "answer_id": 217758, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": false, "text": "<cfset CleanList = ListChangeDelims(DirtyList, \",\", \",\")>\n ListChangeDelims()" }, { "answer_id": 2291045, "author": "richard", "author_id": 276352, "author_profile": "https://Stackoverflow.com/users/276352", "pm_score": 1, "selected": false, "text": "<cfset theFunnyList = \",!@2ed32,a,b,c,d,%442,d,a\">\n <cfset theList = rereplace(theFunnyList, \"[^A-Za-z0-9]+\", \",\", \"all\")>\n<cfset theList = trim(theList)>\n<cfif left(theList, 1) is \",\" and right(theList, 1) is \",\">\n <cfset theList = right(theList, len(theList)-1)>\n <cfset theList = left(theList, len(theList)-1)>\n<cfelseif right(theList, 1) is \",\">\n <cfset theList = left(theList, len(theList)-1)>\n<cfelseif left(theList, 1) is \",\">\n <cfset theList = right(theList, len(theList)-1)>\n</cfif>\n <cfoutput> #ListSort(\"#theList#\", \"text\", \"ASC\", \",;\")# </cfoutput>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26121/" ]
182,475
<p>AFAIK, Currency type in Delphi Win32 depends on the processor floating point precision. Because of this I'm having rounding problems when comparing two Currency values, returning different results depending on the machine.</p> <p>For now I'm using the SameValue function passing a Epsilon parameter = 0.009, because I only need 2 decimal digits precision.</p> <p>Is there any better way to avoid this problem?</p>
[ { "answer_id": 182509, "author": "Matt Lacey", "author_id": 1755, "author_profile": "https://Stackoverflow.com/users/1755", "pm_score": -1, "selected": false, "text": "\"Been there. Done That. Written the unit tests.\"" }, { "answer_id": 182822, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 5, "selected": true, "text": "{$APPTYPE CONSOLE}\n\nuses Math;\n\nvar\n x: Currency;\n y: Currency;\nbegin\n SetRoundMode(rmTruncate);\n x := 1;\n x := x / 6;\n SetRoundMode(rmNearest);\n y := 1;\n y := y / 6;\n Writeln(x = y); // false\n Writeln(x - y); // 0.0001; i.e. 0.1666 vs 0.1667\nend.\n" }, { "answer_id": 830280, "author": "mjn", "author_id": 80901, "author_profile": "https://Stackoverflow.com/users/80901", "pm_score": 0, "selected": false, "text": "TIBDataBase.Create(nil);\n Expected: <12.34> - Found: <12.34>\n" }, { "answer_id": 8061486, "author": "Arnaud Bouchez", "author_id": 458259, "author_profile": "https://Stackoverflow.com/users/458259", "pm_score": 2, "selected": false, "text": "currency Int64 function CompCurrency(var A,B: currency): Int64;\nvar A64: Int64 absolute A;\n B64: Int64 absolute B;\nbegin\n result := A64-B64;\nend;\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089/" ]
182,492
<p>I would like TortoiseSVN (1.5.3) to ignore certain folders, their contents and certain other files wherever they might appear in my directory hierarchy but I cannot get the global ignore string right.</p> <p>Whatever I do, it either adds to much or ignores too much</p> <p>What is the correct 'Global ignore pattern' to ignore....</p> <pre><code>Folders : bin obj release compile Files : *.bak *.user *.suo </code></pre> <p>Update: To help clarify... yes I am using this on windows. </p>
[ { "answer_id": 182508, "author": "PersistenceOfVision", "author_id": 6721, "author_profile": "https://Stackoverflow.com/users/6721", "pm_score": 7, "selected": true, "text": "bin obj CVS .cvsignore *.user *.suo Debug Release *.pdb test.* Thumbs.db\n bin obj release compile *.bak *.user *.suo bin obj release compile *.bak *.user *.suo\n" }, { "answer_id": 32848430, "author": "Andreas Reiff", "author_id": 586754, "author_profile": "https://Stackoverflow.com/users/586754", "pm_score": 3, "selected": false, "text": "global-ignores = *.suo *.user *.userosscache *.sln.docstates *.userprefs debug release Debug Release bin x64 x86 obj Obj *_i.c *_p.c *_i.h *.ilk *.meta *.obj *.pch *.pdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *.log *.psess *.vsp *.vspx *.sap Thumbs.db _UpgradeReport_Files *.dbmdl\n %APPDATA%/Subversion/config\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11356/" ]
182,497
<p>Please give me the direction of the best guidance on the Entity Framework.</p>
[ { "answer_id": 182508, "author": "PersistenceOfVision", "author_id": 6721, "author_profile": "https://Stackoverflow.com/users/6721", "pm_score": 7, "selected": true, "text": "bin obj CVS .cvsignore *.user *.suo Debug Release *.pdb test.* Thumbs.db\n bin obj release compile *.bak *.user *.suo bin obj release compile *.bak *.user *.suo\n" }, { "answer_id": 32848430, "author": "Andreas Reiff", "author_id": 586754, "author_profile": "https://Stackoverflow.com/users/586754", "pm_score": 3, "selected": false, "text": "global-ignores = *.suo *.user *.userosscache *.sln.docstates *.userprefs debug release Debug Release bin x64 x86 obj Obj *_i.c *_p.c *_i.h *.ilk *.meta *.obj *.pch *.pdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *.log *.psess *.vsp *.vspx *.sap Thumbs.db _UpgradeReport_Files *.dbmdl\n %APPDATA%/Subversion/config\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11135/" ]
182,510
<p>I have to produce an RSS/Atom feed in various applications, and I want to know a good library or class which is able to produce both, and which already handles all common problems.</p> <p>For example, the one I used for years does not put the right format for date, so my feed is not well-handled by several aggregators.</p> <p><strong>Update:</strong> Why I am looking for a library? Because the one I used for years, which I had hacked a few times, has a little problem. Maybe a specification is not being correctly followed.</p> <p><a href="https://stackoverflow.com/questions/182615/why-my-rss-feed-duplicate-some-entries">Why does my RSS feed duplicate some entries?</a></p>
[ { "answer_id": 3802163, "author": "Alex Sosic", "author_id": 459263, "author_profile": "https://Stackoverflow.com/users/459263", "pm_score": 2, "selected": false, "text": "$nodeText .= (in_array($tagName, $this->CDATAEncoding))? $tagContent : htmlentities($tagContent, ENT_COMPAT, 'UTF-8');\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8404/" ]
182,519
<p>Ok I give up, I've been trying to write a regexp in ant to replace the version number from something that I have in a properties file. I have the following:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;feature id="some.feature.id" label="Some test feature" version="1.0.0" provider-name="Provider"&gt; &lt;plugin id="test.plugin" download-size="0" install-size="0" version="0.0.0" unpack="false"/&gt; ..... many plugins later.... &lt;/feature&gt; </code></pre> <p>What I want to achieve is substitute the version number of the feature tag only, without changing the version of the xml or the version of the miriad of plugins in the file.</p> <p>The problem I have is that I either match too much or too little. Definitively matching "version" is not enough, because everything would be changed</p> <p>Is there any easy way to match then only the version inside the tag, taking into consideration that the '0.0.0' could be any number?</p>
[ { "answer_id": 182537, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 0, "selected": false, "text": "s/<feature(.*?)version=\".*?\"/<feature$1version=\"1.2.3.4\"/s\n" }, { "answer_id": 182570, "author": "Tomas Sedovic", "author_id": 2239, "author_profile": "https://Stackoverflow.com/users/2239", "pm_score": 0, "selected": false, "text": "<feature[^<>]+version\\s*=\\s*\"(\\d+\\.\\d+\\.\\d+)\"[^<>]*>\n" }, { "answer_id": 182577, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "(?<=<feature[^>]{*,1000}version=\")[^\"]*(?=\")\n **" }, { "answer_id": 182601, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 3, "selected": true, "text": "replaceregexp <replaceregexp file=\"whatever\"\n match=\"(<feature\\b[^<>]+?version=\\\")[^\\\"]+\"\n replace=\"\\1${feature.version}\" />\n <feature>" }, { "answer_id": 182629, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 0, "selected": false, "text": ":s/\\(label=\".+\"\\_.\\s*version=\"\\).+\"/\\1NEWVERSIONNUMBER\"/\n" }, { "answer_id": 182954, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 1, "selected": false, "text": "irb(main):001:0* require \"rexml/document\";include REXML;file = File.new(\"a.xml\"); doc = Document.new(file);puts doc; doc.elements.each(\"/feature\") {|e| e.attributes[\"version\"]=\"1.2.3\" }; puts doc\n\n<?xml version='1.0' encoding='UTF-8'?>\n<feature id='some.feature.id' version='1.0.0' provider-name='Provider' label='Some test feature'>\n <plugin unpack='false' id='test.plugin' download-size='0' version='0.0.0' install-size='0'/>\n</feature>\n\n\n<?xml version='1.0' encoding='UTF-8'?>\n<feature id='some.feature.id' version='1.2.3' provider-name='Provider' label='Some test feature'>\n <plugin unpack='false' id='test.plugin' download-size='0' version='0.0.0' install-size='0'/>\n</feature>\n" }, { "answer_id": 183252, "author": "Adam Crume", "author_id": 25498, "author_profile": "https://Stackoverflow.com/users/25498", "pm_score": 1, "selected": false, "text": "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n <xsl:template match=\"@*|*\">\n <xsl:copy>\n <xsl:apply-templates select=\"node()|@*|*\"/>\n </xsl:copy>\n </xsl:template>\n\n\n <xsl:template match=\"/feature/@version\">\n <xsl:attribute name=\"version\">\n <xsl:text>1.0.1</xsl:text>\n </xsl:attribute>\n </xsl:template>\n</xsl:stylesheet>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309/" ]
182,528
<p>Leaving aside the question of whether you should serve single or multiple stylesheets, assuming you're sending just one, what do you think of this as a basic structure?</p> <p>/* Structure */</p> <p>Any template layout stuff should be put into here, so header, footer, body etc.</p> <p>/* Structure End */</p> <p>/* Common Components*/</p> <p>Repeated elements, such as signup forms, lists, etc.</p> <p>/* Common Components End*/</p> <p>/* Specific Page 1 */</p> <p>Some pages might have specific styles, that would go here.</p> <p>/* Specific Page 1 End */</p> <p>/* Specific Page 2 */</p> <p>As above</p> <p>/* Specific Page 2 End */</p> <p>/* Specific Page etc */</p> <p>And so on.</p> <p>/* Specific Page etc End */</p>
[ { "answer_id": 183327, "author": "Matt", "author_id": 17020, "author_profile": "https://Stackoverflow.com/users/17020", "pm_score": 4, "selected": true, "text": ".float-right { float: right; }\n.float-left { float: left; }\n.float-center { margin-left: auto; margin-right: auto; }\n.clear { clear: both }\n.clear-block { display: block }\n.text-left { text-align: left }\n.text-right { text-align: right }\n.text-center { text-align: center }\n.text-justify { text-align: justify }\n.bold { font-weight: bold }\n.italic { font-style: italic }\n.underline { border-bottom: 1px solid }\n.nopadding { padding: 0 }\n.nobullet { list-style: none; list-style-image: none }\n .class {\n width: 200px;\n height: 200px;\n border: 1px solid #000000;\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2977/" ]
182,529
<p>I have have some code which adds new cells to a table and fills them with text boxes. </p> <p>The way I've coded it so far works fine:</p> <pre><code> TableCell tCell1 = new TableCell(); TableCell tCell2 = new TableCell(); TableCell tCell3 = new TableCell(); TableCell tCell4 = new TableCell(); TableCell tCell5 = new TableCell(); TableCell tCell6 = new TableCell(); TableCell tCell7 = new TableCell(); TextBox txt1 = new TextBox(); TextBox txt2 = new TextBox(); TextBox txt3 = new TextBox(); TextBox txt4 = new TextBox(); TextBox txt5 = new TextBox(); TextBox txt6 = new TextBox(); TextBox txt7 = new TextBox(); tCell1.Controls.Add(txt1); tCell2.Controls.Add(txt2); tCell3.Controls.Add(txt3); tCell4.Controls.Add(txt4); tCell5.Controls.Add(txt5); tCell6.Controls.Add(txt6); tCell7.Controls.Add(txt7); tRow.Cells.Add(tCell1); tRow.Cells.Add(tCell2); tRow.Cells.Add(tCell3); tRow.Cells.Add(tCell4); tRow.Cells.Add(tCell5); tRow.Cells.Add(tCell6); tRow.Cells.Add(tCell7); </code></pre> <p>As you can see there's basically 4 instructions getting repeated 7 times. I'm sure there has to be a way to accomplish this with just 4 lines of code within a FOR loop and having all the names dynamically assigned but I just can't seem to find anything that would point me in the direction of how to do it.</p> <p>Something like the following is what I'm after:</p> <pre><code> for (int i = 0; i &lt; 6; i++) { TableCell tCell[i] = new TableCell(); TextBox txt[i] = new TextBox(); tCell[i].Controls.Add(txt[i]); tRow.Cells.Add(tCell[i]); } </code></pre> <p>Any help would be much appreciated.</p>
[ { "answer_id": 182551, "author": "Lars Mæhlum", "author_id": 960, "author_profile": "https://Stackoverflow.com/users/960", "pm_score": 0, "selected": false, "text": "for (int i = 0; i < 6; i++)\n{\n TableCell tCell = new TableCell();\n TextBox txt = new TextBox();\n tCell.Controls.Add(txt);\n tRow.Cells.Add(tCell);\n}\n tRow.Cells[4].Controls[0] As TextBox" }, { "answer_id": 182557, "author": "Eugene Katz", "author_id": 1533, "author_profile": "https://Stackoverflow.com/users/1533", "pm_score": 3, "selected": true, "text": " for (int i = 0; i < 7; i++)\n {\n\n TableCell tCell = new TableCell();\n TextBox txt = new TextBox();\n tCell.Controls.Add(txt);\n tRow.Cells.Add(tCell);\n\n }\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26126/" ]
182,542
<p>What do you use to validate an email address on a ASP.NET form. I want to make sure that it contains no XSS exploits.</p> <p>This is ASP.NET 1.1</p>
[ { "answer_id": 182580, "author": "Martin Brown", "author_id": 20553, "author_profile": "https://Stackoverflow.com/users/20553", "pm_score": 3, "selected": false, "text": "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\n" }, { "answer_id": 182582, "author": "WebDude", "author_id": 15360, "author_profile": "https://Stackoverflow.com/users/15360", "pm_score": 8, "selected": true, "text": "<asp:RegularExpressionValidator ID=\"regexEmailValid\" runat=\"server\" ValidationExpression=\"\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\" ControlToValidate=\"tbEmail\" ErrorMessage=\"Invalid Email Format\"></asp:RegularExpressionValidator>\n" }, { "answer_id": 271946, "author": "John_", "author_id": 26081, "author_profile": "https://Stackoverflow.com/users/26081", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Web.UI.WebControls;\nusing System.Text.RegularExpressions;\nusing System.Web.UI;\n\nnamespace CompanyName.Library.Web.Controls\n{\n [ToolboxData(\"<{0}:EmailValidator runat=server></{0}:EmailValidator>\")]\n public class EmailValidator : BaseValidator\n {\n\n protected override bool EvaluateIsValid()\n {\n string val = this.GetControlValidationValue(this.ControlToValidate);\n string pattern = @\"^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\\.([a-z][a-z|0-9]*(\\.[a-z][a-z|0-9]*)?)$\";\n Match match = Regex.Match(val.Trim(), pattern, RegexOptions.IgnoreCase);\n\n if (match.Success)\n return true;\n else\n return false;\n }\n\n }\n}\n" }, { "answer_id": 43138457, "author": "VDWWD", "author_id": 5836671, "author_profile": "https://Stackoverflow.com/users/5836671", "pm_score": 3, "selected": false, "text": "public bool IsValidEmailAddress(string email)\n{\n try\n {\n var emailChecked = new System.Net.Mail.MailAddress(email);\n return true;\n }\n catch\n {\n return false;\n }\n}\n EmailAddressAttribute System.ComponentModel.DataAnnotations public bool IsValidEmailAddress(string email)\n{\n if (!string.IsNullOrEmpty(email) && new EmailAddressAttribute().IsValid(email))\n return true;\n else\n return false;\n}\n IsNullOrEmpty null" }, { "answer_id": 51764513, "author": "Naveen", "author_id": 5718260, "author_profile": "https://Stackoverflow.com/users/5718260", "pm_score": 1, "selected": false, "text": "public static bool IsValidEmail(this string email)\n{\n const string pattern = @\"^(?!\\.)(\"\"([^\"\"\\r\\\\]|\\\\[\"\"\\r\\\\])*\"\"|\" + @\"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\\.)\\.)*)(?<!\\.)\" + @\"@[a-z0-9][\\w\\.-]*[a-z0-9]\\.[a-z][a-z\\.]*[a-z]$\"; \n var regex = new Regex(pattern, RegexOptions.IgnoreCase); \n return regex.IsMatch(email);\n}\n" }, { "answer_id": 66397618, "author": "Code", "author_id": 9787173, "author_profile": "https://Stackoverflow.com/users/9787173", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Globalization;\nusing System.Text.RegularExpressions;\n\n/// <summary>\n/// Summary description for RegexUtilities\n/// </summary>\npublic class RegexUtilities\n{\n bool InValid = false;\n\n public bool IsValidEmail(string strIn)\n {\n InValid = false;\n if (String.IsNullOrEmpty(strIn))\n return false;\n\n // Use IdnMapping class to convert Unicode domain names.\n strIn = Regex.Replace(strIn, @\"(@)(.+)$\", this.DomainMapper);\n if (InValid)\n return false;\n\n // Return true if strIn is in valid e-mail format. \n return Regex.IsMatch(strIn, @\"^(?(\"\")(\"\"[^\"\"]+?\"\"@)|(([0-9a-z]((\\.(?!\\.))|[-!#\\$%&'\\*\\+/=\\?\\^`\\{\\}\\|~\\w])*)(?<=[0-9a-z])@))\" + @\"(?(\\[)(\\[(\\d{1,3}\\.){3}\\d{1,3}\\])|(([0-9a-z][-\\w]*[0-9a-z]*\\.)+[a-z0-9]{2,17}))$\",\n RegexOptions.IgnoreCase);\n }\n\n private string DomainMapper(Match match)\n {\n // IdnMapping class with default property values.\n IdnMapping idn = new IdnMapping();\n\n string domainName = match.Groups[2].Value;\n try\n {\n domainName = idn.GetAscii(domainName);\n }\n catch (ArgumentException)\n {\n InValid = true;\n }\n return match.Groups[1].Value + domainName;\n }\n\n}\n\n\n\n\n\nRegexUtilities EmailRegex = new RegexUtilities();\n\n if (txtEmail.Value != \"\")\n {\n string[] SplitClients_Email = txtEmail.Value.Split(',');\n string Send_Email, Hold_Email;\n Send_Email = Hold_Email = \"\";\n \n int CountEmail;/**Region For Count Total Email**/\n CountEmail = 0;/**First Time Email Counts Zero**/\n bool EmaiValid = false;\n Hold_Email = SplitClients_Email[0].ToString().Trim().TrimEnd().TrimStart().ToString();\n if (SplitClients_Email[0].ToString() != \"\")\n {\n if (EmailRegex.IsValidEmail(Hold_Email))\n {\n Send_Email = Hold_Email;\n CountEmail = 1;\n EmaiValid = true;\n }\n else\n {\n EmaiValid = false;\n }\n }\n \n if (EmaiValid == false)\n {\n divStatusMsg.Style.Add(\"display\", \"\");\n divStatusMsg.Attributes.Add(\"class\", \"alert alert-danger alert-dismissable\");\n divStatusMsg.InnerText = \"ERROR !!...Please Enter A Valid Email ID.\";\n txtEmail.Focus();\n txtEmail.Value = null;\n ScriptManager.RegisterStartupScript(Page, this.GetType(), \"SmoothScroll\", \"SmoothScroll();\", true);\n divStatusMsg.Visible = true;\n ClientScript.RegisterStartupScript(this.GetType(), \"alert\", \"HideLabel();\", true);\n return false;\n }\n }\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
182,544
<p>SQL to find duplicate entries (within a group)</p> <p>I have a small problem and I'm not sure what would be the best way to fix it, as I only have limited access to the database (Oracle) itself. In our Table "EVENT" we have about 160k entries, each EVENT has a GROUPID and a normal entry has exactly 5 rows with the same GROUPID. Due to a bug we currently get a couple of duplicate entries (duplicate, so 10 rows instead of 5, just a different EVENTID. This may change, so it's just &lt;> 5). We need to filter all the entries of these groups.</p> <p>Due to limited access to the database we can not use a temporary table, nor can we add an index to the GROUPID column to make it faster.</p> <p>We can get the GROUPIDs with this query, but we would need a second query to get the needed data</p> <pre><code>select A."GROUPID" from "EVENT" A group by A."GROUPID" having count(A."GROUPID") &lt;&gt; 5 </code></pre> <p>One solution would be a subselect:</p> <pre><code>select * from "EVENT" A where A."GROUPID" IN ( select B."GROUPID" from "EVENT" B group by B."GROUPID" having count(B."GROUPID") &lt;&gt; 5 ) </code></pre> <p>Without an index on GROUPID and 160k entries, this takes much too long. Tried thinking about a join that can handle this, but can't find a good solution so far.</p> <p>Anybody can find a good solution for this maybe?</p> <p>Small edit: We don't have 100% duplicates here, as each entry still has a unique ID and the GROUPID is not unique either (that's why we need to use "group by") - or maybe I just miss an easy solution for it :)</p> <p>Small example about the data (I don't want to delete it, just find it)</p> <p><code> EVENTID | GROUPID | TYPEID<br> 123456&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;12<br> 123457&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;145<br> 123458&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2612<br> 123459&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;41<br> 123460&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;238<br> <br> 234567&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;12<br> 234568&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;145<br> 234569&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2612<br> 234570&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;41<br> 234571&nbsp;&nbsp;&nbsp;&nbsp;123&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;238<br> </code><br> It has some more columns, like timestamp etc, but as you can see already, everything is identical, besides the EVENTID.</p> <p>We will run it more often for testing, to find the bug and check if it happens again.</p>
[ { "answer_id": 182669, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": false, "text": "SQL> create table my_objects as \n 2 select object_name, ceil(rownum/5) groupid, rpad('x',500,'x') filler\n 3 from all_objects;\n\nTable created.\n\nSQL> select count(*) from my_objects;\n\n COUNT(*)\n----------\n 83782\n\nSQL> select * from my_objects where groupid in (\n 2 select groupid from my_objects\n 3 group by groupid\n 4 having count(*) <> 5\n 5 );\n\nOBJECT_NAME GROUPID FILLER\n------------------------------ ---------- --------------------------------\nXYZ 16757 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nYYYY 16757 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\nElapsed: 00:00:01.67\n -------------------------------------------------------------------------\n| Id | Operation | Name | Rows | Bytes | Cost (%CPU)|\n-------------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 389 | 112K| 14029 (2)|\n|* 1 | HASH JOIN | | 389 | 112K| 14029 (2)|\n| 2 | VIEW | VW_NSO_1 | 94424 | 1198K| 6570 (2)|\n|* 3 | FILTER | | | | |\n| 4 | HASH GROUP BY | | 1 | 1198K| 6570 (2)|\n| 5 | TABLE ACCESS FULL| MY_OBJECTS | 94424 | 1198K| 6504 (1)|\n| 6 | TABLE ACCESS FULL | MY_OBJECTS | 94424 | 25M| 6506 (1)|\n-------------------------------------------------------------------------\n" }, { "answer_id": 182694, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 4, "selected": true, "text": "select\n a.*\nfrom\n event as a\ninner join\n (select groupid\n from event\n group by groupid\n having count(*) <> 5) as b\n on a.groupid = b.groupid\n" }, { "answer_id": 182713, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 0, "selected": false, "text": "select * \nfrom group g\nwhere (select count(*) from event e where g.groupid = e.groupid) <> 5\n" }, { "answer_id": 182734, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 0, "selected": false, "text": "SELECT * FROM (\nSELECT eventid, groupid, typeid, COUNT(groupid) OVER (PARTITION BY groupid) group_count\n FROM event\n)\n WHERE group_count <> 5\n" }, { "answer_id": 182747, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 3, "selected": false, "text": "select eventid,\n groupid,\n typeid\nfrom (\n Select eventid,\n groupid,\n typeid,\n count(*) over (partition by group_id) count_by_group_id\n from EVENT\n )\nwhere count_by_group_id <> 5\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3134/" ]
182,553
<p>Is there a way to automatically apply a theme/template/style to all controls of the targettype, so I don't have to specify Template=..., Style=... on all controls?</p>
[ { "answer_id": 9305281, "author": "Prathibha", "author_id": 672094, "author_profile": "https://Stackoverflow.com/users/672094", "pm_score": 1, "selected": false, "text": "//App.xaml\n\n<Application x:Uid=\"Application_1\" x:Class=\"SampleApp.Home.App\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n StartupUri=\"MainWindow.xaml\"\n Startup=\"Application_Startup\">\n\n//App.xaml.cs\n\nprivate void Application_Startup(object sender, StartupEventArgs e)\n {\n StyleManager.ApplicationTheme = new MetroTheme(); //Set your theme here \n } \n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26049/" ]
182,569
<p>Sybase db tables do not have a concept of self updating row numbers. However , for one of the modules , I require the presence of rownumber corresponding to each row in the database such that max(Column) would always tell me the number of rows in the table.</p> <p>I thought I'll introduce an int column and keep updating this column to keep track of the row number. However I'm having problems in updating this column in case of deletes. What sql should I use in delete trigger to update this column? </p>
[ { "answer_id": 182744, "author": "AdamH", "author_id": 21081, "author_profile": "https://Stackoverflow.com/users/21081", "pm_score": 2, "selected": false, "text": "select * from table where column = (select max(column) from table).\n" }, { "answer_id": 183510, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "create table test\n ( \n col1 int,\n col2 varchar(3)\n )\n\n insert into test values (100, \"abc\")\n insert into test values (111, \"def\")\n insert into test values (222, \"ghi\")\n insert into test values (300, \"jkl\")\n insert into test values (400, \"mno\")\n\nselect rank = identity(10), col1 into #t1 from Test\nselect * from #t1\n\ndelete from test where col2=\"ghi\"\n\nselect rank = identity(10), col1 into #t2 from Test\nselect * from #t2\n\ndrop table test\ndrop table #t1\ndrop table #t2\n" }, { "answer_id": 187083, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 1, "selected": true, "text": "CREATE TRIGGER tigger ON myTable FOR DELETE\nAS \nupdate myTable \nset id = id - (select count(*) from deleted d where d.id < t.id) \nfrom myTable t\n CREATE TABLE rowCounter \n(id int, -- foreign key to main table\n rownum int) \n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18275/" ]
182,571
<p>We are developing a considerably big application using Ruby on Rails framework (CRM system) and are considering to rewrite it to use ExtJS so that Rails would just do the data handling, while ExtJS would do all the browser heavylifting in a desktop-like manner. </p> <p>Anyone has some experience and hints about what would be the best approach? Is ExtJS mature enough to be used in relatively big (and complex) applications? And what about the Rails part - what would be the best approach here?</p> <p>EDIT:</p> <p>Just to make it clear. I would prefer to do it in such a way that all the javascript client side application code is loaded at once (at the start up of the application, optimally as one compressed js file) and then just use ajax to send data to and from Rails app. Also, it would be nice to have ERB available for dynamic generation of the Ext apliccation elements.</p>
[ { "answer_id": 182593, "author": "Ben Crouse", "author_id": 6705, "author_profile": "https://Stackoverflow.com/users/6705", "pm_score": 1, "selected": false, "text": "to_json scaffold ActiveRecord ActionView" }, { "answer_id": 195484, "author": "Dave Nolan", "author_id": 9474, "author_profile": "https://Stackoverflow.com/users/9474", "pm_score": 2, "selected": false, "text": "Ext.data.Store Ext.data.Record Ext.grid.EditorPanel Ext.form.BasicForm ActiveRecord::Base ApplicationController Ext.grid.EditorPanel Ext.form.BasicForm" }, { "answer_id": 274964, "author": "Jonathan Soeder", "author_id": 453185, "author_profile": "https://Stackoverflow.com/users/453185", "pm_score": 6, "selected": true, "text": "include_root_in_json" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26123/" ]
182,573
<p>PowerShell v1.0 is obviously a console based administrative shell. It doesn't really require a GUI interface. If one is required, like the Exchange 2007 management GUI, it is built on top of PowerShell. You can create your own GUI using Windows Forms in a PowerShell script. My question is, "What sort of PowerShell scripts or management tasks do you think would be best served with the addition of even a simple graphical interface? What have you created winforms to accomplish?"</p>
[ { "answer_id": 185822, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 1, "selected": false, "text": "PS D:\\> $dir = & \"C:\\python25\\python.exe\" \"C:\\python25\\selectdir.pyw\"; cd $dir;\n# Directory selection dialog opens here, user selects the directory to goto.\nPS D:\\NewDirectory>\n import Tkinter\nimport tkFileDialog\n\nroot = Tkinter.Tk()\nroot.withdraw()\ndirname = tkFileDialog.askdirectory(parent=root)\n\nprint dirname\n" }, { "answer_id": 216936, "author": "Emperor XLII", "author_id": 2495, "author_profile": "https://Stackoverflow.com/users/2495", "pm_score": 2, "selected": false, "text": "OpenFileDialog [void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' )\n\nfunction Select-File( [string]$initialDirectory=$pwd, [switch]$multiselect ) {\n $dialog = New-Object Windows.Forms.OpenFileDialog\n $dialog.ShowHelp = $true # http://tinyurl.com/6cnmrr\n $dialog.InitialDirectory = $initialDirectory\n $dialog.Multiselect = $multiselect\n\n if( $dialog.ShowDialog( ) -eq 'OK' ) { $dialog.FileNames }\n $dialog.Dispose( )\n}\n Select-Directory FolderBrowserDialog FolderBrowserDialog function Select-Directory( ) {\n $app = New-Object -COM Shell.Application\n $directory = $app.BrowseForFolder( 0, \"Select Directory\", 0 )\n $path = $directory.Self.Path\n if( $path ) { return $path }\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25508/" ]
182,587
<p>Is there a best practice when it comes to setting client side "onclick" events when using ASP.Net controls? Simply adding the onclick attribute results in a Visual Studio warning that onclick is not a valid attribute of that control. Adding it during the Page_Load event through codebehind works, but is less clear than I'd like.</p> <p>Are these the only two choices? Is there a right way to do this that I'm missing?</p> <p>Thanks! Eric Sipple</p>
[ { "answer_id": 182642, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "WebControl.Attributes[\"onclick\"] click" }, { "answer_id": 182649, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "** <html>\n <head>\n <script type=\"text/javascript\" src=\"jquery.js\"></script>\n <script type=\"text/javascript\">\n $(document).ready(function(){\n $(\"controlId\").bind(\"click\", function(e) { /* do your best here! */ });\n });\n </script>\n </head>\n <!-- etc -->\n </html>\n" }, { "answer_id": 182688, "author": "Alex Gyoshev", "author_id": 25427, "author_profile": "https://Stackoverflow.com/users/25427", "pm_score": 2, "selected": false, "text": "document.getElementById('myLovelyButtonId').attachEvent('onclick',doSomething)\n document.getElementById('myLovelyButtonId').addEventListener('click',doSomething,false)\n $('#myLovelyButtonId').click(\n function doSomething () {\n alert('my lovely code here');\n });\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111/" ]
182,592
<p>I have a webapp that segfaults when the database in restarted and it tries to use the old connections. Running it under <code>gdb --args apache -X</code> leads to the following output:</p> <pre><code>Program received signal SIGSEGV, Segmentation fault. [Switching to Thread -1212868928 (LWP 16098)] 0xb7471c20 in mysql_send_query () from /usr/lib/libmysqlclient.so.15 </code></pre> <p>I've checked that the drivers and database are all up to date (<a href="http://search.cpan.org/dist/DBD-mysql/" rel="nofollow noreferrer" title="DBD::mysql">DBD::mysql</a> 4.0008, MySQL 5.0.32-Debian_7etch6-log).</p> <p>Annoyingly I can't reproduce this with a trivial script:</p> <pre><code>use DBI; use Test::More tests =&gt; 2; my $dbh = DBI-&gt;connect( "dbi:mysql:test", 'root' ); sub test_db { my ($number) = $dbh-&gt;selectrow_array("select 1 "); return $number; } is test_db, 1, "connected to db"; warn "restart db now"; getc; is test_db, 1, "connected to db"; </code></pre> <p>Which gives the following:</p> <pre><code>ok 1 - connected to db restart db now at dbd-mysql-test.pl line 23. DBD::mysql::db selectrow_array failed: MySQL server has gone away at dbd-mysql-test.pl line 17. not ok 2 - connected to db # Failed test 'connected to db' # at dbd-mysql-test.pl line 26. # got: undef # expected: '1' </code></pre> <p>This behaves correctly, telling me why the request failed.</p> <p>What stumps me is that it is segfaulting, which it shouldn't do. As it only appears to happen when the whole app is running (which uses <a href="http://search.cpan.org/dist/DBIx-Class" rel="nofollow noreferrer" title="DBIx::Class">DBIx::Class</a>) it is hard to reduce it to a test case.</p> <p>Where should I start to look to debug this? Has anyone else seen this?</p> <p><strong>UPDATE</strong>: further prodding showed that it being under mod_perl was a red herring. Having reduced it to a simple test script I've now posted to the <a href="http://www.mail-archive.com/dbi-users@perl.org/msg31416.html" rel="nofollow noreferrer">DBI mailing list</a>. Thanks for your answers.</p>
[ { "answer_id": 186228, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 2, "selected": false, "text": "gbd /usr/bin/httpd core\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5349/" ]
182,600
<p>If you had to iterate through a loop 7 times, would you use:</p> <pre><code>for (int i = 0; i &lt; 7; i++) </code></pre> <p>or:</p> <pre><code>for (int i = 0; i &lt;= 6; i++) </code></pre> <p>There are two considerations:</p> <ul> <li>performance</li> <li>readability </li> </ul> <p>For performance I'm assuming Java or C#. Does it matter if "less than" or "less than or equal to" is used? If you have insight for a different language, please indicate which.</p> <p>For readability I'm assuming 0-based arrays.</p> <p><strong>UPD:</strong> My mention of 0-based arrays may have confused things. I'm not talking about iterating through array elements. Just a general loop. </p> <p>There is a good point below about using a constant to which would explain what this magic number is. So if I had "<code>int NUMBER_OF_THINGS = 7</code>" then "<code>i &lt;= NUMBER_OF_THINGS - 1</code>" would look weird, wouldn't it. </p>
[ { "answer_id": 182613, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "for (int i: myArray) {\n ...\n}\n" }, { "answer_id": 182616, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "0..6 (0,1,2,3,4,5,6)" }, { "answer_id": 182617, "author": "Dominic Rodger", "author_id": 20972, "author_profile": "https://Stackoverflow.com/users/20972", "pm_score": 3, "selected": false, "text": "for (int i = 0; i < 7; i++)\n" }, { "answer_id": 182620, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": true, "text": "for (int i=0; i < count; i++) // For 0-based APIs\n\nfor (int i=1; i <= count; i++) // For 1-based APIs\n" }, { "answer_id": 182624, "author": "erlando", "author_id": 4192, "author_profile": "https://Stackoverflow.com/users/4192", "pm_score": 4, "selected": false, "text": "for ( int i = 0; i < array.size(); i++ )\n for ( int i = 0; i <= array.size() -1; i++ )\n" }, { "answer_id": 182647, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 2, "selected": false, "text": "for (int i = 0; i < this->GetCount(); i++)\n{\n // Do something\n}\n const int count = this->GetCount();\nfor (int i = 0; i < count; ++i)\n{\n // Do something\n}\n" }, { "answer_id": 182661, "author": "Henry B", "author_id": 6414, "author_profile": "https://Stackoverflow.com/users/6414", "pm_score": 0, "selected": false, "text": "< count <= count <=" }, { "answer_id": 182684, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 2, "selected": false, "text": "foreach (string item in myarray)\n{\n System.Console.WriteLine(item);\n}\n" }, { "answer_id": 182754, "author": "Martin Brown", "author_id": 20553, "author_profile": "https://Stackoverflow.com/users/20553", "pm_score": 6, "selected": false, "text": "for (int i = 6; i > -1; i--)\n const int NUMBER_OF_CARS = 7;\nfor (int i = 0; i < NUMBER_OF_CARS; i++)\n mov esi, 0\nloopStartLabel:\n ; Do some stuff\n inc esi\n ; Note cmp command on next line\n cmp esi, 10\n jle exitLoopLabel\n jmp loopStartLabel\nexitLoopLabel:\n mov esi, 10\nloopStartLabel:\n ; Do some stuff\n dec esi\n ; Note no cmp command on next line\n jns exitLoopLabel\n jmp loopStartLabel\nexitLoopLabel:\n for (int i = 10; i >= 0; i--) \n for (int i = 10; i >= 0; i--)\n for (int i = 10; i > -1; i--)\nfor (int i = 0; i <= 10; i++)\n" }, { "answer_id": 182782, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 1, "selected": false, "text": "for ( int count = 7 ; count > 0 ; -- count )\n" }, { "answer_id": 182881, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 1, "selected": false, "text": "!=" }, { "answer_id": 182972, "author": "Carra", "author_id": 21679, "author_profile": "https://Stackoverflow.com/users/21679", "pm_score": 2, "selected": false, "text": "int numberOfDays = 7;\nfor (int day = 0; day < numberOfDays ; day++){\n\n}\n for (int day = 0; day <= numberOfDays - 1; day++){\n\n}\n for(int day = 0; day < dayArray.Length; i++){\n\n}\n foreach (int day in days){// day : days in Java\n\n}\n" }, { "answer_id": 183184, "author": "Krakkos", "author_id": 15533, "author_profile": "https://Stackoverflow.com/users/15533", "pm_score": 1, "selected": false, "text": "for ( int i = 0; i < array.size(); i++ )\n" }, { "answer_id": 183216, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "!=" }, { "answer_id": 183373, "author": "Ryan Rodemoyer", "author_id": 1444511, "author_profile": "https://Stackoverflow.com/users/1444511", "pm_score": 0, "selected": false, "text": "for (int i = 0; i < 7; i++)\n" }, { "answer_id": 183539, "author": "Jeff Mc", "author_id": 25521, "author_profile": "https://Stackoverflow.com/users/25521", "pm_score": 3, "selected": false, "text": "int len = somearray.Length;\nfor(i = 0; i < len; i++)\n{\n somearray[i].something();\n}\n for(i = 0; i < somearray.Length; i++)\n{\n somearray[i].something();\n}\n" }, { "answer_id": 183726, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 1, "selected": false, "text": "0 n-1 <= <" }, { "answer_id": 184201, "author": "Ryan Delucchi", "author_id": 9931, "author_profile": "https://Stackoverflow.com/users/9931", "pm_score": 2, "selected": false, "text": "index < count" }, { "answer_id": 241310, "author": "cciotti", "author_id": 16834, "author_profile": "https://Stackoverflow.com/users/16834", "pm_score": 0, "selected": false, "text": "< <=" }, { "answer_id": 263686, "author": "Mike Dunlavey", "author_id": 23771, "author_profile": "https://Stackoverflow.com/users/23771", "pm_score": 0, "selected": false, "text": "for (i = 7; --i >= 0; ) ...\n" }, { "answer_id": 2041240, "author": "Pavel Radzivilovsky", "author_id": 73656, "author_profile": "https://Stackoverflow.com/users/73656", "pm_score": 1, "selected": false, "text": "i < strlen(s) i BOOST_FOREACH(i, IntegerInterval(0,7))" }, { "answer_id": 3765406, "author": "Nick Westgate", "author_id": 313445, "author_profile": "https://Stackoverflow.com/users/313445", "pm_score": 1, "selected": false, "text": "for (int i = 0; i <= array.Length - 1; ++i) for (int i = 1; i <= 7; ++i)" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1533/" ]
182,602
<p>I have a BulletedList in asp.net that is set to DisplayMode="LinkButton". I would like to trigger the first "bullet" from a javascript, can this be done? And if so, how?</p>
[ { "answer_id": 183374, "author": "Alex Gyoshev", "author_id": 25427, "author_profile": "https://Stackoverflow.com/users/25427", "pm_score": 3, "selected": true, "text": "<asp:BulletedList runat=\"server\" ID=\"MyLovelyBulletedList\" DisplayMode=\"LinkButton\">\n <asp:ListItem Text=\"My Lovely Text 1\" />\n <asp:ListItem Text=\"My Lovely Text 2\" />\n</asp:BulletedList>\n var links = document.getElementById('<%= MyLovelyBulletedList.ClientID %>').getElementsByTagName('a');\n\nvar targetLink = links[0];\n\nif (targetLink.fireEvent)\n{\n // IE\n targetLink.fireEvent(\"onclick\");\n}\nelse if (targetLink.dispatchEvent)\n{\n // W3C\n var evt = document.createEvent(\"MouseEvents\");\n\n evt.initMouseEvent(\"click\", true, true, window,\n 0, 0, 0, 0, 0, false, false, false, false, 0, null);\n\n targetLink.dispatchEvent(evt);\n}\n" }, { "answer_id": 185751, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "$('#<%= MyLovelyBulletedList.ClientID %>')\n .contents()\n .find('a:first')\n .trigger('click');\n" }, { "answer_id": 515836, "author": "Cros", "author_id": 1523, "author_profile": "https://Stackoverflow.com/users/1523", "pm_score": 1, "selected": false, "text": "__doPostBack('MyLovelyBulletedList', '0');\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1523/" ]
182,615
<p>When reading my RSS feed with the Thunderbird feed reader, some entries are duplicated. <a href="https://en.wikipedia.org/wiki/Google_Reader" rel="nofollow noreferrer">Google Reader</a> does not have the same problem.</p> <p>Here is the faulty feed: <a href="http://plcoder.net/rss.php?rss=Blog" rel="nofollow noreferrer">http://plcoder.net/rss.php?rss=Blog</a></p> <p>There is a problem, but where?</p> <p>I added a <a href="https://en.wikipedia.org/wiki/Globally_unique_identifier" rel="nofollow noreferrer">GUID</a>, but the problem remains. Other feeds do not duplicate like mine, so I will do rework on this module and replace this old good code.</p> <p>Conclusion: I completely reworked the RSS generator code, and it's OK. I think I was using a very old version of <a href="https://en.wikipedia.org/wiki/Resource_Description_Framework" rel="nofollow noreferrer">RDF</a>.</p>
[ { "answer_id": 182646, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 4, "selected": true, "text": "<guid> <item rdf:about=\"http://plcoder.net/?doc=2134&amp;amp;titre=mon-pc-se-la-pete\">\n <link>http://plcoder.net/?doc=2134&amp;amp;titre=mon-pc-se-la-pete</link>\n <guid>http://plcoder.net/?doc=2134&amp;amp;titre=mon-pc-se-la-pete</guid>\n ...\n</item>\n" }, { "answer_id": 182768, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 1, "selected": false, "text": "Item A\nItem B\nItem C\n Item D\nItem A\nItem B\n Item A\nItem B\nItem C\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8404/" ]
182,622
<p>I have an application that seems to throw exceptions only after the program has been closed. And it is very inconsistent. (We all know how fun inconsistent bugs are...)</p> <p>My guess is there is an error during the clean up process. But these memory read/write errors seem to indicate something wrong in my "unsafe" code usage (pointers?).</p> <p>What I am interested in is what is the best method to debug these situations?<br> How do you debug a program that has already closed?<br> I am looking for a starting point to break down a larger problem.</p> <p>These errors seem to present themselves in several ways (some run time, some debug):</p> <pre> 1: .NET-BroadcastEventWindow.2.0.0.0.378734a.0: Application.exe - Application Error<BR> The instruction at "0x03b4eddb" referenced memory at "0x00000004". The memory could not be "written". 2: Application.vshost.exe - Application Error<br> The instruction at "0x0450eddb" referenced memory at "0x00000004". The memory could not be "written". 3: Application.vshost.exe - Application Error<br> The instruction at "0x7c911669" referenced memory at "0x00000000". The memory could not be "read". 4: Application.vshost.exe - Application Error<br> The instruction at "0x7c910ed4" referenced memory at "0xfffffff8". The memory could not be "read". </pre>
[ { "answer_id": 184285, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 1, "selected": false, "text": "IDisposable Dispose() using" }, { "answer_id": 315312, "author": "jyoung", "author_id": 14841, "author_profile": "https://Stackoverflow.com/users/14841", "pm_score": 0, "selected": false, "text": " //set as many statics as you can to null;\n GC.Collect();\n GC.WaitForPendingFinalizers();\n} //exit main\n" }, { "answer_id": 2835201, "author": "Mark Paint", "author_id": 341356, "author_profile": "https://Stackoverflow.com/users/341356", "pm_score": 0, "selected": false, "text": "GC.Collect(); \nGC.WaitForPendingFinalizers(); \n" }, { "answer_id": 3438858, "author": "Miroslav Zadravec", "author_id": 8239, "author_profile": "https://Stackoverflow.com/users/8239", "pm_score": 3, "selected": false, "text": "<DllImport(\"kernel32.dll\", EntryPoint:=\"GetModuleHandle\", _\n SetLastError:=True, CharSet:=CharSet.Auto, _\n CallingConvention:=CallingConvention.StdCall)> _\nPublic Overloads Shared Function GetModuleHandle(ByVal sLibName As String) As IntPtr\nEnd Function\n\n<DllImport(\"kernel32.dll\", EntryPoint:=\"FreeLibrary\", _\n SetLastError:=True, CallingConvention:=CallingConvention.StdCall)> _\nPublic Overloads Shared Function FreeLibrary(ByVal hMod As IntPtr) As Integer\nEnd Function\n Dim hOwcHandle As IntPtr = GetModuleHandle(\"AcroPDF.dll\")\nIf Not hOwcHandle.Equals(IntPtr.Zero) Then\n FreeLibrary(hOwcHandle)\n Debug.WriteLine(\"AcroPDF.dll freed\")\nEnd If\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6721/" ]
182,630
<h2>Syntax</h2> <ul> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2218129#2218129">Shorthand for the ready-event</a> by roosteronacid</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2218135#2218135">Line breaks and chainability</a> by roosteronacid</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/389474#389474">Nesting filters</a> by Nathan Long</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/552831#552831">Cache a collection and execute commands on the same line</a> by roosteronacid</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1519474#1519474">Contains selector</a> by roosteronacid</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2750689#2750689">Defining properties at element creation</a> by roosteronacid</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/3967325#3967325">Access jQuery functions as you would an array</a> by roosteronacid</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/182666#182666">The noConflict function - Freeing up the $ variable</a> by Oli</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/382853#382853">Isolate the $ variable in noConflict mode</a> by nickf</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2218120#2218120">No-conflict mode</a> by roosteronacid</li> </ul> <h2>Data Storage</h2> <ul> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/382834#382834">The data function - bind data to elements</a> by TenebrousX</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/5410587#5410587">HTML5 data attributes support, on steroids!</a> by roosteronacid</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/504776#504776">The jQuery metadata plug-in</a> by Filip Dupanović</li> </ul> <h2>Optimization</h2> <ul> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1019899#1019899">Optimize performance of complex selectors</a> by roosteronacid</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/504732#504732">The context parameter</a> by lupefiasco</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/389793#389793">Save and reuse searches</a> by Nathan Long</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/382922#382922">Creating an HTML Element and keeping a reference, Checking if an element exists, Writing your own selectors</a> by Andreas Grech</li> </ul> <h2>Miscellaneous</h2> <ul> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/389906#389906">Check the index of an element in a collection</a> by redsquare</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/892617#892617">Live event handlers</a> by TM</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/696385#696385">Replace anonymous functions with named functions</a> by ken</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/191139#191139">Microsoft AJAX framework and jQuery bridge</a> by Slace</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/922865#922865">jQuery tutorials</a> by egyamado</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/998547#998547">Remove elements from a collection and preserve chainability</a> by roosteronacid</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/191061#191061">Declare $this at the beginning of anonymous functions</a> by Ben</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1771311#1771311">FireBug lite, Hotbox plug-in, tell when an image has been loaded and Google CDN</a> by Colour Blend</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/182715#182715">Judicious use of third-party jQuery scripts</a> by harriyott</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1584927#1584927">The each function</a> by Jan Zich</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1235178#1235178">Form Extensions plug-in</a> by Chris S</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2750689#2750689">Asynchronous each function</a> by OneNerd</li> <li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/4962433#4962433">The jQuery template plug-in: implementing complex logic using render-functions</a> by roosteronacid</li> </ul>
[ { "answer_id": 182666, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 6, "selected": false, "text": "$(document).ready(fn) $(document).ready(...) $(...) jQuery.noConflict(); var $j = jQuery.noConflict();\n\n$j(\"#myDiv\").hide();\n $x(...)" }, { "answer_id": 191061, "author": "Ben Crouse", "author_id": 6705, "author_profile": "https://Stackoverflow.com/users/6705", "pm_score": 4, "selected": false, "text": "$this $('a').each(function() {\n var $this = $(this);\n\n // Other code\n});\n" }, { "answer_id": 191139, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 4, "selected": false, "text": "Sys.UI.Control.prototype.j = function Sys$UI$Control$j(){\n return $('#' + this.get_id());\n}\n $get('#myControl').j().hide();\n" }, { "answer_id": 382834, "author": "clawr", "author_id": 46201, "author_profile": "https://Stackoverflow.com/users/46201", "pm_score": 7, "selected": false, "text": "data()" }, { "answer_id": 382853, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": false, "text": "var $ = someOtherFunction(); // from a different library\n\njQuery(function($) {\n if ($ instanceOf jQuery) {\n alert(\"$ is the jQuery object!\");\n }\n});\n (function($) {\n $('...').etc() // whatever jQuery code you want\n})(jQuery);\n" }, { "answer_id": 382922, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 8, "selected": false, "text": "var newDiv = $(\"<div />\");\n\nnewDiv.attr(\"id\", \"myNewDiv\").appendTo(\"body\");\n\n/* Now whenever I want to append the new div I created, \n I can just reference it from the \"newDiv\" variable */\n if ($(\"#someDiv\").length)\n{\n // It exists...\n}\n $.extend($.expr[\":\"], {\n over100pixels: function (e)\n {\n return $(e).height() > 100;\n }\n});\n\n$(\".box:over100pixels\").click(function ()\n{\n alert(\"The element you clicked is over 100 pixels height\");\n});\n" }, { "answer_id": 389474, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 7, "selected": false, "text": ".filter(\":not(:has(.selected))\")\n" }, { "answer_id": 389793, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 4, "selected": false, "text": "// Bad: searching the DOM multiple times for the same elements\n$('div.foo').each...\n$('div.foo').each...\n\n// Better: saving that search for re-use\nvar $foos = $('div.foo');\n$foos.each...\n$foos.each...\n organic lowfat .organic var $allFoods, $matchingFoods;\n$allFoods = $('div.food');\n // Whenever a checkbox in the form is clicked (to check or uncheck)...\n$someForm.find('input:checkbox').click(function(){\n\n // Start out assuming all foods should be showing\n // (in case a checkbox was just unchecked)\n var $matchingFoods = $allFoods;\n\n // Go through all the checked boxes and keep only the foods with\n // a matching class \n this.closest('form').find(\"input:checked\").each(function() { \n $matchingFoods = $matchingFoods.filter(\".\" + $(this).attr(\"name\")); \n });\n\n // Hide any foods that don't match the criteria\n $allFoods.not($matchingFoods).hide();\n});\n" }, { "answer_id": 389906, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 5, "selected": false, "text": "var index = e.g $('#ul>li').index( liDomObject );\n $(\"ul > li\").click(function () {\n var index = $(this).prevAll().length;\n});\n" }, { "answer_id": 504732, "author": "mshafrir", "author_id": 5675, "author_profile": "https://Stackoverflow.com/users/5675", "pm_score": 5, "selected": false, "text": "$(\"input:radio\", document.forms[0]);\n" }, { "answer_id": 504776, "author": "Filip Dupanović", "author_id": 44041, "author_profile": "https://Stackoverflow.com/users/44041", "pm_score": 6, "selected": false, "text": "<input \n name=\"email\" \n validation=\"required\" \n validate=\"email\" \n minLength=\"7\" \n maxLength=\"30\"/> \n <input \n name=\"email\" \n class=\"validation {validate: email, minLength: 2, maxLength: 50}\" />\n\n<script>\n jQuery('*[class=validation]').each(function () {\n var metadata = $(this).metadata();\n // etc.\n });\n</script>\n" }, { "answer_id": 552831, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 4, "selected": false, "text": "var jQueryCollection = $(\"\");\n\njQueryCollection.command().command();\n var jQueryCollection = $(\"\").command().command();\n var cache = $(\"#container div.usehovereffect\").mouseover(function ()\n{\n cache.removeClass(\"hover\").filter(this).addClass(\"hover\");\n});\n" }, { "answer_id": 696385, "author": "ken", "author_id": 84473, "author_profile": "https://Stackoverflow.com/users/84473", "pm_score": 6, "selected": false, "text": "$('div').toggle(\n function(){\n // do something\n },\n function(){\n // do something else\n }\n);\n function onState(){\n // do something\n}\n\nfunction offState(){\n // do something else\n}\n\n$('div').toggle( offState, onState );\n" }, { "answer_id": 892617, "author": "TM.", "author_id": 12983, "author_profile": "https://Stackoverflow.com/users/12983", "pm_score": 6, "selected": false, "text": "$('button.someClass').live('click', someFunction);\n $('button.someClass').die('click', someFunction);\n live() die() live() delegate() undelegate() live() $('button.someClass').live('click', someFunction); delegate() $(document).delegate('button.someClass', 'click', someFunction);" }, { "answer_id": 922865, "author": "egyamado", "author_id": 66493, "author_profile": "https://Stackoverflow.com/users/66493", "pm_score": 4, "selected": false, "text": "<script language=\"javascript\" type=\"text/javascript\">\n $(function() {\n $('a').click(function() {\n var originalSize = $('p').css('font-size'); // get the font size \n var number = parseFloat(originalSize, 10); // that method will chop off any integer from the specified variable \"originalSize\"\n var unitOfMeasure = originalSize.slice(-2);// store the unit of measure, Pixle or Inch\n\n $('p').css('font-size', number / 1.2 + unitOfMeasure);\n if(this.id == 'larger'){$('p').css('font-size', number * 1.2 + unitOfMeasure);}// figure out which element is triggered\n }); \n });\n</script>\n <style type=\"text/css\" >\nbody{ margin-left:300px;text-align:center; width:700px; background-color:#666666;}\n.box {width:500px; text-align:justify; padding:5px; font-family:verdana; font-size:11px; color:#0033FF; background-color:#FFFFCC;}\n</style>\n <div class=\"box\">\n <a href=\"#\" id=\"larger\">Larger</a> | \n <a href=\"#\" id=\"Smaller\">Smaller</a>\n <p>\n In today’s video tutorial, I’ll show you how to resize text every time an associated anchor tag is clicked. We’ll be examining the “slice”, “parseFloat”, and “CSS” Javascript/jQuery methods. \n </p>\n</div>\n" }, { "answer_id": 998547, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 3, "selected": false, "text": "<ul>\n <li>One</li>\n <li>Two</li>\n <li>Three</li>\n <li>Four</li>\n <li>Five</li>\n</ul>\n $(\"li\").filter(function()\n{\n var text = $(this).text();\n\n // return true: keep current element in the collection\n if (text === \"One\" || text === \"Two\") return true;\n\n // return false: remove current element from the collection\n return false;\n}).each(function ()\n{\n // this will alert: \"One\" and \"Two\" \n alert($(this).text());\n});\n filter()" }, { "answer_id": 1019899, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 4, "selected": false, "text": "var subset = $(\"\");\n\n$(\"input[value^='']\", subset);\n" }, { "answer_id": 1235178, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 1, "selected": false, "text": "// elementExists is also added\nif ($(\"#someid\").elementExists())\n alert(\"found it\");\n\n// Select box related\n$(\"#mydropdown\").isDropDownList();\n\n// Can be any of the items from a list of radio boxes - it will use the name\n$(\"#randomradioboxitem\").isRadioBox(\"myvalue\");\n$(\"#radioboxitem\").isSelected(\"myvalue\");\n\n// The value of the item selected. For multiple selects it's the first value\n$(\"#radioboxitem\").selectedValue();\n\n// Various, others include password, hidden. Buttons also\n$(\"#mytextbox\").isTextBox();\n$(\"#mycheck\").isCheckBox();\n$(\"#multi-select\").isSelected(\"one\", \"two\", \"three\");\n\n// Returns the 'type' property or 'select-one' 'select-multiple'\nvar fieldType = $(\"#someid\").formElementType();\n" }, { "answer_id": 1519474, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 3, "selected": false, "text": "// hide all elements which contains the text \"abc\"\n$(\"p\").each(function ()\n{\n var that = $(this);\n\n if (that.text().indexOf(\"abc\") > -1) that.hide();\n}); \n $(\"p.value:contains('abc')\").hide();\n" }, { "answer_id": 1584927, "author": "Jan Zich", "author_id": 15716, "author_profile": "https://Stackoverflow.com/users/15716", "pm_score": 4, "selected": false, "text": "var functions = [];\nvar someArray = [1, 2, 3];\nfor (var i = 0; i < someArray.length; i++) {\n functions.push(function() { alert(someArray[i]) });\n}\n functions undefined i i someArrary[3] undefined var functions = [];\nvar someArray = [1, 2, 3];\n$.each(someArray, function(item) {\n functions.push(function() { alert(item) });\n});\n" }, { "answer_id": 1771311, "author": "Orson", "author_id": 207756, "author_profile": "https://Stackoverflow.com/users/207756", "pm_score": 3, "selected": false, "text": "<script type='text/javascript' src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>\n <script src=\"http://www.google.com/jsapi\"></script> \n<script type=\"text/javascript\"> \n\n // Load jQuery \n google.load(\"jquery\", \"1.2.6\"); \n\n google.setOnLoadCallback(function() { \n // Your code goes here. \n }); \n\n</script>\n <script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js\" type=\"text/javascript\"></script>\n $('#myImage').attr('src', 'image.jpg').load(function() { \n alert('Image Loaded'); \n});\n console.time('create list');\n\nfor (i = 0; i < 1000; i++) {\n var myList = $('.myList');\n myList.append('This is list item ' + i);\n}\n\nconsole.timeEnd('create list');\n" }, { "answer_id": 2217596, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 6, "selected": false, "text": "var e = $(\"<a />\", { href: \"#\", class: \"a-class another-class\", title: \"...\" });\n $(\"<a />\", {\n ...\n css: {\n color: \"#FF0000\",\n display: \"block\"\n }\n});\n" }, { "answer_id": 2218120, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 0, "selected": false, "text": "jQuery.noConflict();\n $ $ jQuery $(\"div p\") jQuery(\"div p\")" }, { "answer_id": 2218129, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 5, "selected": false, "text": "$(document).ready(function ()\n{\n // ...\n});\n $(function ()\n{\n // ...\n});\n" }, { "answer_id": 2218135, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 3, "selected": false, "text": "$(\"a\").hide().addClass().fadeIn().hide();\n $(\"a\")\n.hide()\n.addClass()\n.fadeIn()\n.hide();\n" }, { "answer_id": 2218334, "author": "Vivin Paliath", "author_id": 263004, "author_profile": "https://Stackoverflow.com/users/263004", "pm_score": 3, "selected": false, "text": "var oldButton = jQuery(\"#Submit\");\nvar newButton = oldButton.clone();\n\nnewButton.attr(\"type\", \"button\");\nnewButton.attr(\"id\", \"newSubmit\");\nnewButton.insertBefore(oldButton);\noldButton.remove();\nnewButton.attr(\"id\", \"Submit\");\n" }, { "answer_id": 2750689, "author": "OneNerd", "author_id": 76682, "author_profile": "https://Stackoverflow.com/users/76682", "pm_score": 4, "selected": false, "text": "jQuery.forEach = function (in_array, in_pause_ms, in_callback)\n{\n if (!in_array.length) return; // make sure array was sent\n\n var i = 0; // starting index\n\n bgEach(); // call the function\n\n function bgEach()\n {\n if (in_callback.call(in_array[i], i, in_array[i]) !== false)\n {\n i++; // move to next item\n\n if (i < in_array.length) setTimeout(bgEach, in_pause_ms);\n }\n }\n\n return in_array; // returns array\n};\n\n\njQuery.fn.forEach = function (in_callback, in_optional_pause_ms)\n{\n if (!in_optional_pause_ms) in_optional_pause_ms = 10; // default\n\n return jQuery.forEach(this, in_optional_pause_ms, in_callback); // run it\n};\n $('your_selector').forEach( function() {} );\n $('your_selector').forEach( function() {}, 1000 );\n $('your_selector').forEach( function() {}, 500 );\n// next lines of code will run before above code is complete\n" }, { "answer_id": 2777444, "author": "Kenneth J", "author_id": 195456, "author_profile": "https://Stackoverflow.com/users/195456", "pm_score": 3, "selected": false, "text": "$(\"#someElement\").hover(function(){\n $(\"div.desc\", this).stop(true,true).fadeIn();\n},function(){\n $(\"div.desc\", this).fadeOut();\n});\n" }, { "answer_id": 3189444, "author": "Rixius", "author_id": 212307, "author_profile": "https://Stackoverflow.com/users/212307", "pm_score": 3, "selected": false, "text": ".append() $(\"<ul>\").append((function ()\n{\n var data = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\"],\n output = $(\"<div>\"),\n x = -1,\n y = data.length;\n\n while (++x < y) output.append(\"<li>\" + info[x] + \"</li>\");\n\n return output.children();\n}()));\n" }, { "answer_id": 3189764, "author": "adam", "author_id": 73894, "author_profile": "https://Stackoverflow.com/users/73894", "pm_score": 0, "selected": false, "text": "'0_row' $(this).attr('name', $(this).attr('name').replace(/^\\d+/, function(n){ return ++n; }));\n '1_row'" }, { "answer_id": 3967325, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 4, "selected": false, "text": "function changeState(b)\n{\n $(\"selector\")[b ? \"addClass\" : \"removeClass\"](\"name of the class\");\n}\n function changeState(b)\n{\n if (b)\n {\n $(\"selector\").addClass(\"name of the class\");\n }\n else\n {\n $(\"selector\").removeClass(\"name of the class\");\n }\n}\n $('selector').toggleClass('name_of_the_class', true/false);\n" }, { "answer_id": 4348522, "author": "Ralph Holzmann", "author_id": 346724, "author_profile": "https://Stackoverflow.com/users/346724", "pm_score": 3, "selected": false, "text": "$('.class:first')\n $('.class').eq(0)\n" }, { "answer_id": 5059173, "author": "adardesign", "author_id": 56449, "author_profile": "https://Stackoverflow.com/users/56449", "pm_score": 2, "selected": false, "text": " $.extend($.expr[':'], {\n \"aboveFold\": function(a, i, m) {\n var container = m[3],\n var fold;\n if (typeof container === \"undefined\") {\n fold = $(window).height() + $(window).scrollTop();\n } else {\n if ($(container).length == 0 || $(container).offset().top == null) return false;\n fold = $(container).offset().top + $(container).height();\n }\n return fold >= $(a).offset().top;\n } \n});\n $(\"p:aboveFold\").css({color:\"red\"});\n" }, { "answer_id": 5409115, "author": "Shahin", "author_id": 369161, "author_profile": "https://Stackoverflow.com/users/369161", "pm_score": 1, "selected": false, "text": "$(function(){\n var iFrameDOM = $(\"iframe#someID\").contents();\n //Now you can use <strong>find()</strong> to access any element in the iframe:\n\n iFrameDOM.find(\".message\").slideUp();\n //Slides up all elements classed 'message' in the iframe\n});\n" }, { "answer_id": 5410587, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 3, "selected": false, "text": "<p data-xyz = '{\"str\": \"hi there\", \"int\": 2, \"obj\": { \"arr\": [1, 2, 3] } }' />\n var data = $(\"p\").data(\"xyz\");\n\ndata.str // \"hi there\"\ntypeof data.str // \"string\"\n\ndata.int + 2 // 4\ntypeof data.int // \"number\"\n\ndata.obj.arr.join(\" + \") + \" = 6\" // \"1 + 2 + 3 = 6\"\ntypeof data.obj.arr // \"object\" ... Gobbles! Errrghh!\n" }, { "answer_id": 5724897, "author": "btt", "author_id": 193479, "author_profile": "https://Stackoverflow.com/users/193479", "pm_score": 1, "selected": false, "text": "$(\"[id$='txtFirstName']\");\n $(\".container [id$='txtFirstName']\");\n" }, { "answer_id": 6769692, "author": "ngn", "author_id": 23109, "author_profile": "https://Stackoverflow.com/users/23109", "pm_score": 0, "selected": false, "text": "$('selector').bind('change now', function () { // bind to two events: 'change' and 'now'\n // update other portions of the UI\n}).trigger('now'); // 'now' is a custom event\n function update() {\n // update other portions of the UI\n}\n$('selector').change(update);\nupdate();\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20946/" ]
182,635
<p>I am trying to find all matches in a string that begins with <code>| |</code>. </p> <p>I have tried: <code>if ($line =~ m/^\\\|\s\\\|/)</code> which didn't work. </p> <p>Any ideas?</p>
[ { "answer_id": 182650, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 5, "selected": false, "text": "print \"YES!\" if ($line =~ m/^\\|\\s\\|/);\n" }, { "answer_id": 182676, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": -1, "selected": false, "text": "m/^\\|\\s*\\|/ \n" }, { "answer_id": 183271, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "my @lines = <DATA>;\n\nfor (@lines) {\n print if /^\\| \\|/;\n}\n\n__DATA__ \n| | Good - space \n|| Bad - no space \n| | Bad - tab \n | | Bad - beginning space \n Bad - no bars \n" }, { "answer_id": 183297, "author": "Kyle", "author_id": 2237619, "author_profile": "https://Stackoverflow.com/users/2237619", "pm_score": 2, "selected": false, "text": "my $search_for = '| |';\nmy $search_in = whatever();\nif ( substr( $search_in, 0, length $search_for ) eq $search_for ) {\n print \"found '$search_for' at start of string.\\n\";\n}\n my $search_for = '| |';\nmy $search_in = whatever();\nif ( 0 == index( $search_in, $search_for ) ) {\n print \"found '$search_for' at start of string.\\n\";\n}\n" }, { "answer_id": 727016, "author": "Mathieu Longtin", "author_id": 54320, "author_profile": "https://Stackoverflow.com/users/54320", "pm_score": 0, "selected": false, "text": "m/\\|\\s\\|/\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
182,636
<p>I'm creating a generic class and in one of the methods I need to know the Class of the generic type currently in use. The reason is that one of the method's I call expects this as an argument.</p> <p>Example:</p> <pre><code>public class MyGenericClass&lt;T&gt; { public void doSomething() { // Snip... // Call to a 3rd party lib T bean = (T)someObject.create(T.class); // Snip... } } </code></pre> <p>Clearly the example above doesn't work and results in the following error: Illegal class literal for the type parameter T.</p> <p>My question is: does someone know a good alternative or workaround for this?</p>
[ { "answer_id": 182672, "author": "Nicolas", "author_id": 1730, "author_profile": "https://Stackoverflow.com/users/1730", "pm_score": 7, "selected": true, "text": "public class MyGenericClass<T> {\n\n private final Class<T> clazz;\n\n public static <U> MyGenericClass<U> createMyGeneric(Class<U> clazz) {\n return new MyGenericClass<U>(clazz);\n }\n\n protected MyGenericClass(Class<T> clazz) {\n this.clazz = clazz;\n }\n\n public void doSomething() {\n T instance = clazz.newInstance();\n }\n}\n" }, { "answer_id": 4699117, "author": "Christoph", "author_id": 576648, "author_profile": "https://Stackoverflow.com/users/576648", "pm_score": 5, "selected": false, "text": "import java.lang.reflect.ParameterizedType;\n\npublic abstract class A<B> {\n public Class<B> g() throws Exception {\n ParameterizedType superclass =\n (ParameterizedType) getClass().getGenericSuperclass();\n\n return (Class<B>) superclass.getActualTypeArguments()[0];\n }\n}\n A new A<String>() {}.g() // this will work\n\nclass B extends A<String> {}\nnew B().g() // this will work\n\nclass C<T> extends A<T> {}\nnew C<String>().g() // this will NOT work\n" }, { "answer_id": 4927744, "author": "Steven Collins", "author_id": 602136, "author_profile": "https://Stackoverflow.com/users/602136", "pm_score": 2, "selected": false, "text": "g() A private Class<?> extractClassFromType(Type t) throws ClassCastException {\n if (t instanceof Class<?>) {\n return (Class<?>)t;\n }\n return (Class<?>)((ParameterizedType)t).getRawType();\n}\n\npublic Class<B> g() throws ClassCastException {\n Class<?> superClass = getClass(); // initial value\n Type superType;\n do {\n superType = superClass.getGenericSuperclass();\n superClass = extractClassFromType(superType);\n } while (! (superClass.equals(A.class)));\n\n Type actualArg = ((ParameterizedType)superType).getActualTypeArguments()[0];\n return (Class<B>)extractClassFromType(actualArg);\n}\n public class Foo<U,T extends Collection<?>> extends A<T> {}\n\n(new Foo<String,List<Object>>() {}).g();\n ClassCastException Class ParameterizedType TypeVariable T T" }, { "answer_id": 8061600, "author": "Jet Geng", "author_id": 1004479, "author_profile": "https://Stackoverflow.com/users/1004479", "pm_score": 2, "selected": false, "text": "public Class<?> getGenericClass(){\n Class<?> result =null;\n Type type =this.getClass().getGenericSuperclass();\n\n if(type instanceofParameterizedType){\n ParameterizedType pt =(ParameterizedType) type;\n Type[] fieldArgTypes = pt.getActualTypeArguments();\n result =(Class<?>) fieldArgTypes[0];\n }\n return result;\n }\n" }, { "answer_id": 25253110, "author": "intrepidis", "author_id": 847235, "author_profile": "https://Stackoverflow.com/users/847235", "pm_score": 0, "selected": false, "text": "private abstract class ClassGetter<T> {\n public final Class<T> get() {\n final ParameterizedType superclass = (ParameterizedType)\n getClass().getGenericSuperclass();\n return (Class<T>)superclass.getActualTypeArguments()[0];\n }\n}\n public static <T> Class<T> getGenericClass() {\n return new ClassGetter<T>() {}.get();\n}\n public static final <T> T instantiate() {\n final Class<T> clazz = getGenericClass();\n try {\n return clazz.getConstructor((Class[])null).newInstance(null);\n } catch (Exception e) {\n return null;\n }\n}\n T var = instantiate();\n" }, { "answer_id": 50577180, "author": "Abul Kasim M", "author_id": 9822428, "author_profile": "https://Stackoverflow.com/users/9822428", "pm_score": -1, "selected": false, "text": "EntityManagerFactory entitymanagerfactory;\nEntityManager entitymanager;\n\npublic DatabaseAccessUtil() {\n entitymanagerfactory=Persistence.createEntityManagerFactory(\"bookmyshow\");\n entitymanager=entitymanagerfactory.createEntityManager();\n}\n\npublic void save (T t) {\n entitymanager.getTransaction().begin();\n entitymanager.persist(t);\n entitymanager.getTransaction().commit();\n}\n\npublic void update(T t) {\n entitymanager.getTransaction().begin();\n entitymanager.persist(t);\n entitymanager.getTransaction().commit();\n}\n\npublic void delete(T t) {\n entitymanager.getTransaction().begin();\n entitymanager.remove(t);\n entitymanager.getTransaction().commit();\n}\n\npublic Object retrieve(Query query) {\n return query.getSingleResult();\n}\n//call the method - retrieve(object,requiredclass.class)\npublic Object retrieve(Object primaryKey,class clazz) throws Exception {\n\n return entitymanager.find(clazz,primaryKey); \n\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26066/" ]
182,641
<p>I have fname and lname in my database, and a name could be stored as JOHN DOE or john DOE or JoHN dOE, but ultimately I want to display it as John Doe</p> <p>fname being John and lname being Doe</p>
[ { "answer_id": 182663, "author": "Dave Rutledge", "author_id": 2486915, "author_profile": "https://Stackoverflow.com/users/2486915", "pm_score": 4, "selected": false, "text": "text-transform:capitalize;\n .name { text-transform:capitalize;}\n" }, { "answer_id": 182674, "author": "Jacco", "author_id": 22674, "author_profile": "https://Stackoverflow.com/users/22674", "pm_score": 5, "selected": true, "text": "string ucfirst ( string $str ); string ucwords ( string $str ); string strtolower ( string $str );" }, { "answer_id": 182677, "author": "Rimas Kudelis", "author_id": 25804, "author_profile": "https://Stackoverflow.com/users/25804", "pm_score": 2, "selected": false, "text": "$bar = 'HELLO WORLD!';\n$bar = ucfirst($bar); // HELLO WORLD!\n$bar = ucfirst(strtolower($bar)); // Hello world!\n" }, { "answer_id": 182726, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 1, "selected": false, "text": "SELECT --step 2: combine broken parts into a final name\n NAME_PARTS.FNAME_INITIAL + NAME_PARTS.REST_OF_FNAME AS FNAME\n ,NAME_PARTS.LNAME_INITIAL + NAME_PARTS.REST_OF_LNAME AS LNAME\nFROM\n ( --step 1: break name into 1st letter and \"everything else\"\n SELECT\n UPPER(SUBSTRING(TEST.FNAME,1,1)) AS FNAME_INITIAL\n ,UPPER(SUBSTRING(TEST.LNAME,1,1)) AS LNAME_INITIAL\n ,LOWER(SUBSTRING(TEST.FNAME,2,LEN(TEST.FNAME))) AS REST_OF_FNAME\n ,LOWER(SUBSTRING(TEST.LNAME,2,LEN(TEST.LNAME))) AS REST_OF_LNAME\n FROM\n ( --step 0: generate some test data\n SELECT 'john' AS FNAME, 'doe' as LNAME\n UNION SELECT 'SUZY', 'SMITH'\n UNION SELECT 'bIlLy', 'BOb'\n UNION SELECT 'RoNALD', 'McDonald'\n UNION SELECT 'Edward', NULL\n UNION SELECT NULL, 'Jones'\n ) TEST\n ) NAME_PARTS\n SELECT --step 2: combine broken parts into a final name\n NAME_PARTS.FNAME_INITIAL || NAME_PARTS.REST_OF_FNAME AS FNAME\n ,NAME_PARTS.LNAME_INITIAL || NAME_PARTS.REST_OF_LNAME AS LNAME\nFROM\n ( --step 1: break name into 1st letter and \"everything else\"\n SELECT\n UPPER(SUBSTR(TEST.FNAME,1,1)) AS FNAME_INITIAL\n ,UPPER(SUBSTR(TEST.LNAME,1,1)) AS LNAME_INITIAL\n ,LOWER(SUBSTR(TEST.FNAME,2,LENGTH(TEST.FNAME))) AS REST_OF_FNAME\n ,LOWER(SUBSTR(TEST.LNAME,2,LENGTH(TEST.LNAME))) AS REST_OF_LNAME\n FROM\n ( --step 0: generate some test data\n SELECT 'john' AS FNAME, 'doe' as LNAME FROM DUAL\n UNION SELECT 'SUZY', 'SMITH' FROM DUAL\n UNION SELECT 'bIlLy', 'BOb' FROM DUAL\n UNION SELECT 'RoNALD', 'McDonald' FROM DUAL\n UNION SELECT 'Edward', NULL FROM DUAL\n UNION SELECT NULL, 'Jones' FROM DUAL\n ) TEST\n ) NAME_PARTS\n" }, { "answer_id": 182870, "author": "conny", "author_id": 23023, "author_profile": "https://Stackoverflow.com/users/23023", "pm_score": 1, "selected": false, "text": "function ucname($f, $l)\n{\n return ucwords(strtolower($f.\" \".$l));\n}\necho ucname($fname, $lname);\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
182,691
<p>I really don't like the VS2008 Start Page. I don't need the RSS reader, Getting started or Headlines. The only thing useful is "Recent Projects"</p> <p><strong>Is there a way to customize it or replace with a better one?</strong><br> It will be nice that the page contains Favorites Projects and Recent projects.</p> <p>P.S. I know that I can disabled it or replace it with other web page, just looking for a good productivity tip.</p>
[ { "answer_id": 187178, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 0, "selected": false, "text": "http://localhost:12345" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2385/" ]
182,702
<p>Using JDK1.5 how does one send a binary attachemnt (such as a PDF file) easily using the JavaMail API?</p>
[ { "answer_id": 182817, "author": "cynicalman", "author_id": 410, "author_profile": "https://Stackoverflow.com/users/410", "pm_score": 2, "selected": false, "text": "MimeMultipart messageContent = new MimeMultipart();\n\nBodyPart bodyPart = new MimeBodyPart();\nDataSource source = new FileDataSource(yourFile);\nbodyPart.setDataHandler(new DataHandler(source));\nbodyPart.setFileName(\"MyFile.ext\");\nbodyPart.setDisposition(Part.ATTACHMENT);\n\n// Then add to your message:\nmessageContent.addBodyPart(bodyPart);\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
182,711
<p>Exception Thrown: "System.ComponentModel.ReflectPropertyDescriptor is not marked as Serializable"</p> <p>Does this mean I missed marking something as serializable myself, or is this something beyond my control?</p>
[ { "answer_id": 182759, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "NonSerializedAttribute BinaryFormatter XmlIgnoreAttribute XmlSerializer PropertyDescriptor ISerializable IXmlSerializable INotifyPropertyChanged [field: NonSerialized]\npublic event EventHandler BarChanged;\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13244/" ]
182,721
<p>We use Spring + Hibernate for a Webapp.</p> <p>This Webapp will be deployed on two unrelated production sites. These two production sites will use the Webapp to generate and use Person data in parallel.</p> <p>What I need to do, is to make sure that the Persons generated on these two unrelated production sites all have distinct PKs, so that we can merge the Person data from these two sites at any time.</p> <p>A further constraint imposed to me is that these PKs fit in a <code>Long</code>, so I can't use UUIDs.</p> <p>What I'm trying to do is to change the current hibernate mapping, that has sequence <code>S_PERSON</code> as generator:</p> <pre><code>&lt;hibernate-mapping default-cascade="save-update" auto-import="false"&gt; &lt;class name="com.some.domain.Person" abstract="true"&gt; &lt;id name="id"&gt; &lt;column name="PERSON_ID"/&gt; &lt;generator class="sequence"&gt; &lt;param name="sequence"&gt;S_PERSON&lt;/param&gt; &lt;/generator&gt; &lt;/id&gt; ... &lt;/hibernate-mapping&gt; </code></pre> <p>into something configurable, so that <code>PERSON_ID</code> have its PKs generated from different sequences (maybe <code>S_PERSON_1</code> and <code>S_PERSON_2</code>) depending on the deployment site's Spring configuration files.</p> <p>Of course,</p> <pre><code> &lt;generator class="sequence"&gt; &lt;param name="sequence"&gt;${sequenceName}&lt;/param&gt; &lt;/generator&gt; </code></pre> <p>doesn't work, so I have to figure out something else... I guess my generator should point to a configurable bean that in turn points to a sequence or another, but I can't figure how to do that...</p> <p>Any ideas or workaround?</p> <p>Thanks!</p>
[ { "answer_id": 184018, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "insert VALUES('Sys1' || to_char(sequence.nextval), val1, val2, val3);\ninsert VALUES('Sys2' || to_char(sequence.nextval), val1, val2, val3);\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2797/" ]
182,739
<p>I'm using the wxGlade designer to generate the GUI for a small application. It generates a class, inherited from wxFrame, which is the main application window. In order to facilitate the maintenance, I'd like to avoid writing additional code in this generated class.</p> <p>But all the widgets created with the wxGlade are actually created in the auto-generated method do_layout() and it is not possible to access them outside the scope of that generated method in the generated class.</p> <p>Is there a way to get pointer of certain widget outside that generated class - by name, by type, by enumerating the children or something like that?</p>
[ { "answer_id": 182815, "author": "m_pGladiator", "author_id": 446104, "author_profile": "https://Stackoverflow.com/users/446104", "pm_score": 1, "selected": false, "text": "wxWindowList & children = myframe->GetChildren();\nfor ( wxWindowList::Node *node = children.GetFirst(); node; node = node->GetNext() )\n{\n wxWindow *current = (wxWindow *)node->GetData();\n\n // .. do something with current\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446104/" ]
182,742
<p>Specifically MSSQL 2005.</p>
[ { "answer_id": 182769, "author": "sebagomez", "author_id": 23893, "author_profile": "https://Stackoverflow.com/users/23893", "pm_score": 2, "selected": false, "text": "DATEADD (DAY, -1, DATEADD (MONTH, DATEDIFF (MONTH, 0, CURRENT_TIMESTAMP) + 1, 0)\n" }, { "answer_id": 182776, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 5, "selected": true, "text": "select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );\n DATEADD(datepart, number, date) \nDATEDIFF(datepart, startdate, enddate)\n select datediff(m, 0, getdate() ); \n1327\n select dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 );\n2010-09-01 00:00:00.000\n select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );\n2010-08-31 23:59:59.000\n dateadd(day, -day(getdate()), dateadd(month, 1, getdate()))\n" }, { "answer_id": 182950, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "DECLARE\n @Now datetime,\n @Today datetime,\n @ThisMonth datetime,\n @NextMonth datetime,\n @LastDayThisMonth datetime\n\nSET @Now = getdate()\nSET @Today = DateAdd(dd, DateDiff(dd, 0, @Now), 0)\nSET @ThisMonth = DateAdd(mm, DateDiff(mm, 0, @Now), 0)\nSET @NextMonth = DateAdd(mm, 1, @ThisMonth)\nSET @LastDayThisMonth = DateAdd(dd, -1, @NextMonth)\n WHERE @ThisMonth <= someDate and someDate < @NextMonth\n" }, { "answer_id": 183022, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 2, "selected": false, "text": "SELECT DATEADD(M, DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP), '1990-01-31T00:00:00.000')\n SELECT '1990-01-01T00:00:00.000', '1990-01-31T00:00:00.000'\n SELECT DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP)\n @calc SELECT DATEADD(M, @calc, '1990-01-31T00:00:00.000')\n @calc" }, { "answer_id": 183591, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 0, "selected": false, "text": "select add_months(trunc(sysdate,'MM'),1) ...\n select last_day(sysdate)+1 ...\n" }, { "answer_id": 1453783, "author": "van", "author_id": 99594, "author_profile": "https://Stackoverflow.com/users/99594", "pm_score": 0, "selected": false, "text": "DATEADD(dd, -1, DATEADD(mm, +1, DATEADD(dd, 1 - DATEPART(dd, @myDate), @myDate)))\n" }, { "answer_id": 6610577, "author": "Taherul", "author_id": 833497, "author_profile": "https://Stackoverflow.com/users/833497", "pm_score": 2, "selected": false, "text": "SELECT DATEADD(MM, DATEDIFF(MM,0,GETDATE())+1,0)\n" }, { "answer_id": 33475656, "author": "Ragul", "author_id": 5010874, "author_profile": "https://Stackoverflow.com/users/5010874", "pm_score": 1, "selected": false, "text": "EOMONTH() CREATE FUNCTION dbo.endofmonth(@date DATETIME= NULL)\nRETURNS DATETIME\nBEGIN\nRETURN DATEADD(DD, -1, DATEADD(MM, +1, DATEADD(DD, 1 - DATEPART(DD, ISNULL(@date,GETDATE())), ISNULL(@date,GETDATE()))))\nEND\n SELECT dbo.endofmonth(DEFAULT) --Current month-end date\nSELECT dbo.endofmonth('02/25/2012') --User-defined month-end date\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7577/" ]
182,749
<p>This is a question for anyone who has the pleasure to work in both Java and C#.</p> <p>Do you find that you have to make a mental context switch of some kind when you move from one to the other?</p> <p>I'm working in both at the moment and because the syntax and libraries are so similar and yet subtly different I'm finding it frustrating when i move from one to the other.</p> <p>This is more so than I've experienced moving between any other programming languages.</p> <p>Does anyone have any tips for making your brain work differently for languages that are so similar?</p>
[ { "answer_id": 182767, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "foreach (X x in y) for (X x : y)" }, { "answer_id": 183911, "author": "Jon Schneider", "author_id": 12484, "author_profile": "https://Stackoverflow.com/users/12484", "pm_score": 2, "selected": false, "text": "string == // C# string value comparison example\nstring string1 = GetStringValue1();\nstring string2 = GetStringValue2();\n\n// Check to see whether the string values are equal\nif (string1 == string2) \n{\n // Do something...\n}\n == equals() // Java string value comparison example\nString string1 = getStringValue1();\nString string2 = getStringValue2();\n\n// Check to see whether the string values are equal\nif (string1.equals(string2)) \n{\n // Do something...\n}\n == !=" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
182,750
<p>Suppose some Windows service uses code that wants mapped network drives and no UNC paths. How can I make the drive mapping available to the service's session when the service is started? Logging in as the service user and creating a persistent mapping will not establish the mapping in the context of the actual service.</p>
[ { "answer_id": 182794, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 4, "selected": false, "text": "var p = System.Diagnostics.Process.Start(\"net.exe\", \"use K: \\\\\\\\Server\\\\path\");\nvar isCompleted = p.WaitForExit(5000);\n" }, { "answer_id": 4763324, "author": "ForcePush", "author_id": 585004, "author_profile": "https://Stackoverflow.com/users/585004", "pm_score": 8, "selected": false, "text": "psexec -i -s cmd.exe nt authority\\system whoami -i net use z: \\\\servername\\sharedfolder /persistent:yes net use z: /delete" }, { "answer_id": 7867064, "author": "larry", "author_id": 1009646, "author_profile": "https://Stackoverflow.com/users/1009646", "pm_score": 6, "selected": false, "text": "net use z: \\servername\\sharedfolder /persistent:yes\n" }, { "answer_id": 21286732, "author": "lk7777", "author_id": 2513868, "author_profile": "https://Stackoverflow.com/users/2513868", "pm_score": 3, "selected": false, "text": "net use \\\\\\server\\share ... net use Z: \\\\\\..." }, { "answer_id": 34895821, "author": "Val", "author_id": 681830, "author_profile": "https://Stackoverflow.com/users/681830", "pm_score": 2, "selected": false, "text": "echo %time% >> c:\\mount_nfs_log.txt\nnet use Z: \\\\{your ip}\\{netdisk folder}\\ >> C:\\mount_nfs_log.txt 2>&1\n" }, { "answer_id": 37605101, "author": "philu", "author_id": 647612, "author_profile": "https://Stackoverflow.com/users/647612", "pm_score": 5, "selected": false, "text": "mklink /D C:\\myLink \\\\127.0.0.1\\c$\n" }, { "answer_id": 37665216, "author": "CanadaDave", "author_id": 6431942, "author_profile": "https://Stackoverflow.com/users/6431942", "pm_score": 0, "selected": false, "text": " \\\\servername\\share \n \\\\123.456.789.012\\share \n" }, { "answer_id": 48469421, "author": "jeff", "author_id": 9274391, "author_profile": "https://Stackoverflow.com/users/9274391", "pm_score": -1, "selected": false, "text": "net use Q: \\\\share.domain.com\\share \nforfiles /p Q:\\myfolder /s /m *.txt /d -0 /c \"cmd /c del @path\"\nnet use Q: /delete\n" }, { "answer_id": 70120282, "author": "lengxuehx", "author_id": 2272451, "author_profile": "https://Stackoverflow.com/users/2272451", "pm_score": 2, "selected": false, "text": "$User = \"usernmae\"\n$PWord = ConvertTo-SecureString -String \"password\" -AsPlainText -Force\n$creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord\nNew-SmbGlobalMapping -RemotePath \\\\192.168.88.11\\shares -Credential $creds -LocalPath S:\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23424/" ]
182,865
<p>I'm using Test/Unit with a standard <strong>rails 2.1</strong> project. I would like to be able to test Partial Views in isolation from any particular controller / action.</p> <p>It seemed as though <a href="http://zentest.rubyforge.org/" rel="noreferrer">ZenTest's Test::Rails::ViewTestCase</a> would help, but I couldn't get it working, similarly with view_test <a href="http://www.continuousthinking.com/tags/view_test" rel="noreferrer">http://www.continuousthinking.com/tags/view_test</a> </p> <p>Most of the stuff Google turns up seems quite out of date, so I'm guessing doesn't really work with Rails 2.1</p> <p>Any help with this much appreciated.</p> <p>Thanks, Roland</p>
[ { "answer_id": 189607, "author": "Sam Stokes", "author_id": 20131, "author_profile": "https://Stackoverflow.com/users/20131", "pm_score": 3, "selected": false, "text": "describe \"/posts/_form\" do\n before do\n render :partial => \"posts/form\"\n end\n it \"says hello\" do\n response.should match(/hello/i)\n end\n it \"renders a form\" do\n response.should have_tag(\"form\")\n end\nend\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15965/" ]
182,872
<p>What is the easiest way to test (using reflection), whether given method (i.e. java.lang.Method instance) has a return type, which can be safely casted to List&lt;String&gt;?</p> <p>Consider this snippet:</p> <pre><code>public static class StringList extends ArrayList&lt;String&gt; {} public List&lt;String&gt; method1(); public ArrayList&lt;String&gt; method2(); public StringList method3(); </code></pre> <p>All methods 1, 2, 3 fulfill the requirement. It's quite easy to test it for the method1 (via getGenericReturnType(), which returns instance of ParameterizedType), but for methods2 and 3, it's not so obvious. I imagine, that by traversing all getGenericSuperclass() and getGenericInterfaces(), we can get quite close, but I don't see, how to match the TypeVariable in List&lt;E&gt; (which occurs somewhere in the superclass interfaces) with the actual type parameter (i.e. where this E is matched to String).</p> <p>Or maybe is there a completely different (easier) way, which I overlook?</p> <p><strong>EDIT:</strong> For those looking into it, here is method4, which also fulfills the requirement and which shows some more cases, which have to be investigated:</p> <pre><code>public interface Parametrized&lt;T extends StringList&gt; { T method4(); } </code></pre>
[ { "answer_id": 183232, "author": "Jasper", "author_id": 18702, "author_profile": "https://Stackoverflow.com/users/18702", "pm_score": 3, "selected": false, "text": "public class Main {\n/**\n * @param args the command line arguments\n */\npublic static void main(String[] args) {\n try{\n Method m = Main.class.getDeclaredMethod(\"method1\", new Class[]{});\n instanceOf(m, List.class, String.class);\n m = Main.class.getDeclaredMethod(\"method2\", new Class[]{});\n instanceOf(m, List.class, String.class);\n m = Main.class.getDeclaredMethod(\"method3\", new Class[]{});\n instanceOf(m, List.class, String.class);\n m = Main.class.getDeclaredMethod(\"method4\", new Class[]{});\n instanceOf(m, StringList.class);\n }catch(Exception e){\n System.err.println(e.toString());\n }\n}\n\npublic static boolean instanceOf (\n Method m, \n Class<?> returnedBaseClass, \n Class<?> ... genericParameters) {\n System.out.println(\"Testing method: \" + m.getDeclaringClass().getName()+\".\"+ m.getName());\n boolean instanceOf = false;\n instanceOf = returnedBaseClass.isAssignableFrom(m.getReturnType());\n System.out.println(\"\\tReturn type test succesfull: \" + instanceOf + \" (expected '\"+returnedBaseClass.getName()+\"' found '\"+m.getReturnType().getName()+\"')\");\n System.out.print(\"\\tNumber of generic parameters matches: \");\n Type t = m.getGenericReturnType();\n if(t instanceof ParameterizedType){\n ParameterizedType pt = (ParameterizedType)t;\n Type[] actualGenericParameters = pt.getActualTypeArguments();\n instanceOf = instanceOf\n && actualGenericParameters.length == genericParameters.length;\n System.out.println(\"\" + instanceOf + \" (expected \"+ genericParameters.length +\", found \" + actualGenericParameters.length+\")\");\n for (int i = 0; instanceOf && i < genericParameters.length; i++) {\n if (actualGenericParameters[i] instanceof Class) {\n instanceOf = instanceOf\n && genericParameters[i].isAssignableFrom(\n (Class) actualGenericParameters[i]);\n System.out.println(\"\\tGeneric parameter no. \" + (i+1) + \" matches: \" + instanceOf + \" (expected '\"+genericParameters[i].getName()+\"' found '\"+((Class) actualGenericParameters[i]).getName()+\"')\");\n } else {\n instanceOf = false;\n System.out.println(\"\\tFailure generic parameter is not a class\");\n }\n }\n } else {\n System.out.println(\"\" + true + \" 0 parameters\");\n }\n return instanceOf;\n}\npublic List<String> method1() {\n return null;\n}\npublic ArrayList<String> method2() {\n return new ArrayList<String>();\n}\npublic StringList method3() {\n return null;\n}\npublic <T extends StringList> T method4() {\n return null;\n}\n" }, { "answer_id": 189511, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 0, "selected": false, "text": "//For string list\nParameterizedType type = (ParameterizedType)StringList.class.getGenericSuperclass();\nSystem.out.println( type.getActualTypeArguments()[0] );\n\n//for a descendant of string list\nClass clazz = (Class)StringListChild.class.getGenericSuperclass();\nParameterizedType type = (ParameterizedType)clazz.getGenericSuperclass();\nSystem.out.println( type.getActualTypeArguments()[0] );\n" }, { "answer_id": 405594, "author": "Wouter Coekaerts", "author_id": 3432, "author_profile": "https://Stackoverflow.com/users/3432", "pm_score": 3, "selected": true, "text": "GenericTypeReflector.isSuperType TypeToken List<String> GenericTypeReflector.getExactReturnType" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7135/" ]
182,876
<p>Often, I found OutOfMemoryException on IBM Websphere Application Server. I think this exception occur because my application retrieve Huge data from database. So, I limit all query don't retreive data more than 1000 records and set JVM of WAS follow</p> <pre><code>+ Verbose garbage collection + Maximum Heap size = 1024 (RAM on my server is 16 GB and now I already change to 8192) + Debug arguments = -Djava.compiler=NONE -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=7777 + Generic JVM arguments = -Dsun.rmi.dgc.server.gcInterval=60000 -Dsun.rmi.dgc.client.gcInterval=60000 -Xdisableexplicitgc -Dws.log=E:\WebApp\log -Dws.log.level=debug (ws.log and ws.log.level are my properties) </code></pre> <p>And I found <strong>heapdump</strong>, <strong>javacore</strong> and <strong>snap</strong> files in profiles folder I think them can tell me about cause of problem but I don't know how to read/use heapdump, javacore and snap files.</p> <p>Please tell me how to prevent/avoid/fix OutOfMemoryException. Thanks</p>
[ { "answer_id": 189591, "author": "Chris Vest", "author_id": 13251, "author_profile": "https://Stackoverflow.com/users/13251", "pm_score": 0, "selected": false, "text": "permgen heapspace" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24550/" ]
182,891
<p>Does anyone have an XSLT that will take the app.config and render it into a non-techie palatable format?</p> <p>The purpose being mainly informational, but with the nice side-effect of validating the XML (if it's been made invalid, it won't render)</p>
[ { "answer_id": 203485, "author": "Don Vince", "author_id": 6023, "author_profile": "https://Stackoverflow.com/users/6023", "pm_score": 3, "selected": true, "text": "<?xml-stylesheet type=\"text/xsl\" href=\"display-config.xslt\"?>\n <?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n\n <xsl:template match=\"/\">\n <html>\n <body>\n <h2>Settings</h2> \n <xsl:apply-templates /> \n </body>\n </html>\n </xsl:template> \n\n\n <xsl:template match=\"connectionStrings\">\n <h3>Connection Strings</h3>\n <table border=\"1\">\n <tr bgcolor=\"#abcdef\">\n <th align=\"left\">Name</th>\n <th align=\"left\">Connection String</th>\n </tr>\n <xsl:for-each select=\"add\">\n <tr>\n <td><xsl:value-of select=\"@name\"/></td>\n <td><xsl:value-of select=\"@connectionString\"/></td>\n </tr>\n </xsl:for-each>\n </table>\n </xsl:template>\n\n\n <xsl:template match=\"appSettings\">\n <h3>Settings</h3>\n <table border=\"1\">\n <tr bgcolor=\"#abcdef\">\n <th align=\"left\">Key</th>\n <th align=\"left\">Value</th>\n </tr>\n <xsl:for-each select=\"add\">\n <tr>\n <td><xsl:value-of select=\"@key\"/></td>\n <td><xsl:value-of select=\"@value\"/></td>\n </tr>\n </xsl:for-each>\n </table>\n </xsl:template>\n</xsl:stylesheet>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6023/" ]
182,901
<p>I have a friend who is need of a web page. He does interior construction, and would like to have a gallery of his work. I'll probably go for a php host, and was thinking about the best way to implement the image gallery for him. I came up with:</p> <ul> <li>Use flickr to host the images. They can be tagged, added to sets, and I can use both the tag and set information to display "categories" for the gallery, as well as browsing. Flickr also has multi-upload tools so that a 20 photo job won't be a PITA to upload.</li> <li>How to best get at the api? Is there a good PHP library for flickr integration? Should I roll my own?</li> <li>API key - is this considered a commercial project? The web page is for his business, and he will be paying me to create the site...</li> <li>Is flickr the wrong tool for the job? It seems like a pretty good solution in my head, but is there something I'm missing? I haven't used their APIs at all.</li> </ul> <p>Thanks for any input!</p>
[ { "answer_id": 245668, "author": "Jim Nelson", "author_id": 32168, "author_profile": "https://Stackoverflow.com/users/32168", "pm_score": 1, "selected": false, "text": "function newFlickr()\n{\n\n static $flickr = NULL;\n\n\n if($flickr != NULL)\n {\n return $flickr;\n }\n\n $flickr = new phpFlickr(api-key, secret);\n $flickr->setToken(token);\n $flickr->enableCache(\"db\", \"mysql://acct:pass@localhost/flickrcache\");\n\n return $flickr;\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ]
182,910
<p>I need to determine the highest .NET framework version installed on a desktop machine from C\C++ code. Looks like I can iterate the folders under <code>%systemroot%\Microsoft.NET\Framework</code>, but that seems kind of error prone. Is there a better way? Perhaps a registry key I can inspect? Thanks.</p>
[ { "answer_id": 182935, "author": "chills42", "author_id": 23855, "author_profile": "https://Stackoverflow.com/users/23855", "pm_score": 4, "selected": true, "text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP" }, { "answer_id": 182975, "author": "Luc Touraille", "author_id": 20984, "author_profile": "https://Stackoverflow.com/users/20984", "pm_score": 3, "selected": false, "text": "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\NET Framework Setup\\NDP\\\n" }, { "answer_id": 182980, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 0, "selected": false, "text": "c:\\Program Files>clrver\nVersions installed on the machine:\nv2.0.50727\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24898/" ]
182,928
<p>we have a template project we often copy. so we can costumize the copy and still have a common template.<br></p> <p>To optimize the "copy &amp; initial changes"-process, i though that i can write a little script, that does the following:</p> <ul> <li>copy the project-template (in svn) to another directory in the svn</li> <li>check-out the project and do some changes (change names in some files)</li> <li>check-in the customized project</li> </ul> <p>The question is: what's the best way to do this? any experience in this? which type of script (normal batch or java)? any example code?</p> <p>thanks for your answers</p>
[ { "answer_id": 183056, "author": "Jason Miesionczek", "author_id": 18811, "author_profile": "https://Stackoverflow.com/users/18811", "pm_score": 1, "selected": true, "text": "#!/bin/bash\n\n\nsearchterm=\"<ProjectName>\"\nreplaceterm=\"New Project\"\nsrcsvnrepo=\"file:///svnrepoaddress\"\ndestsvnrepo=\"file:///data/newrepo\"\ndumpfile=\"/home/<user>/repo.dump\"\ntmpfolder=\"/home/<user>/tmp_repo\"\n\nsvnadmin dump $srcsvnrepo > $dumpfile\nsvnadmin create --fs-type fsfs $destsvnrepo\nsvnadmin load $destsvnrepo < $dumpfile\nsvn co $destsvnrepo $tmpfolder\n\nfor file in $(grep -l -R $searchterm $tmpfolder)\n do\n sed -e \"s/$searchterm/$replaceterm/ig\" $file > /tmp/tempfile.tmp\n mv /tmp/tempfile.tmp $file\n echo \"Modified: \" $file\n done\n\nsvn ci $tmpfolder --message \"Initial Check-In\"\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25730/" ]
182,945
<p>I've committed changes in numerous files to a SVN repository from Eclipse.</p> <p>I then go to website directory on the linux box where I want to update these changes from the repository to the directory there.</p> <p>I want to say "svn update project100" which will update the directories under "project100" with all my added and changed files, etc.</p> <p>HOWEVER, I don't want to necessarily update changes that I didn't make. So I thought I could say "svn status project100" but when I do this I get a totally different list of changes that will be made, none of mine are in the list, which is odd.</p> <p>Hence to be sure that only my changes are updated to the web directory, I am forced to navigate to every directory where I know there is a change that I made and explicitly update only those files, e.g. "svn update newfile1.php" etc. which is tedious.</p> <p>Can anyone shed any light on the standard working procedure here, namely how do I get an accurate list of all the changes that are about to be made before I execute the "svn update" command? I thought it was the "status" command.</p>
[ { "answer_id": 182960, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 6, "selected": false, "text": "svn merge --dry-run -r BASE:HEAD .\n" }, { "answer_id": 182966, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 8, "selected": true, "text": "svn status --show-updates\n svn status -u\n" }, { "answer_id": 4997135, "author": "Jeff", "author_id": 616827, "author_profile": "https://Stackoverflow.com/users/616827", "pm_score": 4, "selected": false, "text": "svn help svn diff -r BASE:HEAD .\n" }, { "answer_id": 7157966, "author": "Kenzo", "author_id": 1952147, "author_profile": "https://Stackoverflow.com/users/1952147", "pm_score": 4, "selected": false, "text": "svn st -u\n" }, { "answer_id": 13292998, "author": "TianCaiBenBen", "author_id": 1521200, "author_profile": "https://Stackoverflow.com/users/1521200", "pm_score": 6, "selected": false, "text": "$ svn st -u\n $ svn st -u | grep -E '^M {7}\\*'\n $ svn diff -r revisionNumber:HEAD --summarize\n $ svn diff -r revisionNumber:anotherRevisionNumber --summarize\n $ svn merge --dry-run -r BASE:HEAD .\n $ svn diff -r BASE:HEAD ./pathToYour/file\n $ svn diff -r BASE:HEAD .\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
182,957
<p>im trying to locate the position of the minimum value in a vector, using STL find algorithm (and the min_element algorithm), but instead of returning the postion, its just giving me the value. E.g, if the minimum value is it, is position will be returned as 8 etc. What am I doing wrong here?</p> <pre><code>int value = *min_element(v2.begin(), v2.end()); cout &lt;&lt; "min value at position " &lt;&lt; *find(v2.begin(), v2.end(), value); </code></pre>
[ { "answer_id": 182973, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": true, "text": "min_element find distance - cout << \"min value at \" << min_element(v2.begin(), v2.end()) - v2.begin();\n" }, { "answer_id": 183036, "author": "Luc Touraille", "author_id": 20984, "author_profile": "https://Stackoverflow.com/users/20984", "pm_score": 4, "selected": false, "text": "cout << \"min value at position \" << *find(v2.begin(), v2.end(), value);\n cout << \"min value at \" << min_element(v2.begin(), v2.end()) - v2.begin();\n cout << \"min value at \" << distance(v2.begin(), min_element(v2.begin(), v2.end()));\n" }, { "answer_id": 186054, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 3, "selected": false, "text": "std::vector<> std::distance using namespace std;\nvector<int>::const_iterator it = min_element(v2.begin(), v2.end());\ncout << \"min value at position \" << distance(v2.begin(), it) << \" is \" << *it;\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8768/" ]
182,976
<p>I have parsed XML using both of the following two methods...</p> <ul> <li>Parsing the XmlDocument using the object model and XPath queries.</li> <li>XSL/T</li> </ul> <p>But I have never used...</p> <ul> <li>The Linq Xml object model that was new to .Net 3.5</li> </ul> <p>Can anyone tell me the comparative efficiency between the three alternatives?</p> <p>I realise that the particular usage would be a factor, but I just want a rough idea. For example, is the Linq option massively slower than the others?</p>
[ { "answer_id": 184466, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 6, "selected": true, "text": "XmlReader XmlReader" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3362/" ]
182,984
<p>Files:</p> <p>Website\Controls\map.ascx</p> <p>Website\App_Code\map.cs</p> <p>I'd like to create a strongly typed instance of map.ascx in map.cs</p> <p>Normally, in an aspx, you would add a &lt;%Register... tag to be able to instantiate in codebehind. Is this possible in an app_code class? I'm using .NET 3.5/Visual Studio 2008</p> <p>Thanks!</p>
[ { "answer_id": 182992, "author": "Ryan Duffield", "author_id": 2696, "author_profile": "https://Stackoverflow.com/users/2696", "pm_score": 3, "selected": true, "text": "Map map = (Map)LoadControl(\"~/Controls/map.ascx\");\n" }, { "answer_id": 183117, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "public partial class controls_Map : UserControl\n{\n protected void Page_Load( object sender, EventArgs e )\n {\n ...code here....\n }\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11831/" ]
182,988
<p>I have valid <code>HBITMAP</code> handle of <code>ARGB</code> type. How to draw it using <em>GDI+</em>?</p> <p>I've tried method:</p> <pre><code>graphics.DrawImage(Bitmap::FromHBITMAP(m_hBitmap, NULL), 0, 0); </code></pre> <p>But it doesn't use alpha channel.</p>
[ { "answer_id": 183512, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "BITMAP bmpInfo; \n::GetObject(m_hBitmap, sizeof(BITMAP), &bmpInfo); \nint cxBitmap = bmpInfo.bmWidth; \nint cyBitmap = bmpInfo.bmHeight; \nvoid* bits = bmpInfo.bmBits; \n Gdiplus::Graphics graphics(dcMemory); \nGdiplus::Bitmap bitmap(cxBitmap, cyBitmap, cxBitmap*4, PixelFormat32bppARGB, (BYTE*)bits); \ngraphics.DrawImage(&bitmap, 0, 0); \n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/182988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
183,004
<p>I'm trying to highlight just one specific row in a table using jQuery. The row will have an 'active' status. I have seen plenty of examples online which show how to do zebra striping for alternate row styling. Does anyone know of a jQuery expression which will get a element based on the value of a element in a specific column? </p>
[ { "answer_id": 183028, "author": "gamue", "author_id": 25730, "author_profile": "https://Stackoverflow.com/users/25730", "pm_score": 1, "selected": false, "text": "$(\"td\").contains(\"test\");\n $(\"div:contains('John')\");\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ]
183,009
<p>A friend of mine has embedded a google earth plugin into a C# user control. All works fine but when you close the window we recieve and "Unspecified Error" with the option to continue running the scripts or not. From our tracking it down it appears this is being cause by a script that google is dropping onto the page. Any ideas?</p>
[ { "answer_id": 183111, "author": "Adam Lerman", "author_id": 673, "author_profile": "https://Stackoverflow.com/users/673", "pm_score": 0, "selected": false, "text": "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n<html>\n<head>\n <script src=\"http://www.google.com/jsapi?key=ABQIAAAAzghEPRV_D0MDzTELJ4nkXBT2AlVLQD8Rz4_aVbiXesLoyhRIMBRo399nnxv9aY-fqnkVGgTgR-pTsg\">\n </script>\n <script>\n google.load(\"earth\", \"1\");\n var ge = null;\n var placemark;\n function init(){\n google.earth.createInstance(\"map3d\", initCallback, failureCallback);\n }\n\n function initCallback(object){\n ge = object;\n ge.getWindow().setVisibility(true);\n ge.getNavigationControl().setVisibility(ge.VISIBILITY_SHOW);\n ge.getLayerRoot().enableLayerById(ge.LAYER_TERRAIN, false);\n\n placemark = ge.createPlacemark('');\n placemark.setName(\"Current Position\");\n // Create style map for placemark\n var normal = ge.createIcon('');\n normal.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png');\n var iconNormal = ge.createStyle('');\n iconNormal.getIconStyle().setIcon(normal);\n var highlight = ge.createIcon('');\n highlight.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png');\n var iconHighlight = ge.createStyle('');\n iconHighlight.getIconStyle().setIcon(highlight);\n var styleMap = ge.createStyleMap('');\n styleMap.setNormalStyle(iconNormal);\n styleMap.setHighlightStyle(iconHighlight);\n placemark.setStyleSelector(styleMap);\n\n var options = ge.getOptions();\n\n options.setStatusBarVisibility(true);\n options.setScaleLegendVisibility(true);\n }\n\n function failureCallback(object){\n // Gracefully handle failure.\n alert(\"Error\");\n }\n\n function changeViewAngle(angle){\n var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_ABSOLUTE);\n lookAt.setTilt(angle);\n ge.getView().setAbstractView(lookAt);\n }\n\n function ShowMarker(){\n ge.getFeatures().appendChild(placemark);\n }\n\n function MoveMarker(lon, lat){\n // Create point\n var la = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);\n var point = ge.createPoint('');\n point.setLatitude(lat);\n point.setLongitude(lon);\n placemark.setGeometry(point);\n }\n\n function HideMarker(){\n ge.getFeatures().removeChild(placemark);\n }\n\n function SetPosition(lon, lat, heading){\n var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);\n lookAt.setLatitude(lat);\n lookAt.setLongitude(lon);\n lookAt.setHeading(heading);\n ge.getView().setAbstractView(lookAt);\n }\n\n function SetAltitude(alt){\n var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);\n lookAt.set(lookAt.getLatitude(), lookAt.getLongitude(), 0, ge.ALTITUDE_RELATIVE_TO_GROUND, 0, lookAt.getTilt(), alt);\n ge.getView().setAbstractView(lookAt);\n }\n\n function ResizeMap(w, h){\n var map = document.getElementById('map3d_container');\n map.style.height = h;\n map.style.width = w;\n }\n\n function AddKML(kml){\n var parseKML = ge.parseKml(kml);\n ge.getFeatures().appendChild(parseKML);\n return ge.getFeatures().getLastChild().getName();\n }\n\n function RemoveKML(kmlName){\n if (ge.getFeatures().hasChildNodes()) {\n var nodes = ge.getFeatures().getChildNodes();\n for (var i = 0; i < nodes.getLength(); i++) {\n var child = nodes.item(i);\n if (child.getName() == kmlName) {\n ge.getFeatures().removeChild(child);\n }\n }\n }\n }\n\n function OptionsChanged(nav, status, scale, grid, map, terrain, road, border, building){\n var options = ge.getOptions();\n var form = document.options;\n\n if (nav) {\n ge.getNavigationControl().setVisibility(ge.VISIBILITY_SHOW);\n }\n else {\n ge.getNavigationControl().setVisibility(ge.VISIBILITY_HIDE);\n }\n\n options.setStatusBarVisibility(status);\n options.setScaleLegendVisibility(scale);\n options.setGridVisibility(grid);\n options.setOverviewMapVisibility(map);\n ge.getLayerRoot().enableLayerById(ge.LAYER_TERRAIN, terrain);\n ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, road);\n ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, border);\n ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, building);\n }\n\n\n\n </script>\n</head>\n<body onload='init()'>\n <center>\n <div id='map3d_container' style='border: 1px solid silver; height: 510px; width: 767px;'>\n <DIV id=map3d style=\"HEIGHT: 100%\">\n </DIV>\n </div>\n </center>\n</body>\n</html>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/673/" ]
183,013
<p>I want to compare the current value of an in-memory Hibernate entity with the value in the database:</p> <pre><code>HibernateSession sess = HibernateSessionFactory.getSession(); MyEntity newEntity = (MyEntity)sess.load(MyEntity.class, id); newEntity.setProperty("new value"); MyEntity oldEntity = (MyEntity)sess.load(MyEntity.class, id); // CODEBLOCK#1 evaluate differences between newEntity and oldEntity sess.update(newEntity); </code></pre> <p>In <strong>CODEBLOCK#1</strong> I get that <code>newEntity.getProperty()="new value"</code> AND <code>oldEntity.getProperty()="new value"</code> (while I expected <code>oldEntity.getProperty()="old value"</code>, of course). In fact the two objects are exactly the same in memory.</p> <p>I messed around with <code>HibernateSessionFactory.getSession().evict(newEntity)</code> and attempted to set <code>oldEntity=null</code> to get rid of it (I need it only for the comparison):</p> <pre><code>HibernateSession sess = HibernateSessionFactory.getSession(); MyEntity newEntity = (MyEntity)sess.load(MyEntity.class, id); newEntity.setProperty("new value"); HibernateSessionFactory.getSession().evict(newEntity); MyEntity oldEntity = (MyEntity)sess.load(MyEntity.class, id); // CODEBLOCK#1 evaluate differences between newEntity and oldEntity oldEntity = null; sess.update(newEntity); </code></pre> <p>and now the two entities are distinct, but of course I get the dreaded <code>org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session</code>.</p> <p>Any idea?</p> <p><strong>EDIT:</strong> I tried the double session strategy; I modified my <code>HibernateSessionFactory</code> to implement a map of session and then...</p> <pre><code>Session session1 = HibernateSessionFactory.getSession(SessionKeys.DEFAULT); Session session2 = HibernateSessionFactory.getSession(SessionKeys.ALTERNATE); Entity newEntity = (Entity)entity; newEntity.setNote("edited note"); Entity oldEntity = (Entity)session1.load(Entity.class, id); System.out.println("NEW:" + newEntity.getNote()); System.out.println("OLD: " + oldEntity.getNote()); // HANGS HERE!!! HibernateSessionFactory.closeSession(SessionKeys.ALTERNATE); </code></pre> <p>My unit test hangs while attempting to print the oldEntity note... :-(</p>
[ { "answer_id": 186561, "author": "Cowan", "author_id": 17041, "author_profile": "https://Stackoverflow.com/users/17041", "pm_score": 4, "selected": true, "text": "HibernateSession sess = ...;\nMyEntity oldEntity = (MyEntity) sess.load(...);\nsess.evict(oldEntity); // old is now not in the session's persistence context\nMyEntity newEntity = (MyEntity) sess.load(...); // new is the only one in the context now\nnewEntity.setProperty(\"new value\");\n// Evaluate differences\nsess.update(newEntity); // saving the one that's in the context anyway = fine\n HibernateSession sess = ...;\nMyEntity newEntity = (MyEntity) sess.load(...);\nnewEntity.setProperty(\"new value\");\nsess.evict(newEntity); // otherwise load() will return the same object again from the context\nMyEntity oldEntity = (MyEntity) sess.load(...); // fresh copy into the context\nsess.merge(newEntity); // replaces old in the context with this one\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4690/" ]
183,016
<p>I'm making a report in Access 2003 that contains a sub report of related records. Within the sub report, I want the top two records only. When I add "TOP 2" to the sub report's query, it seems to select the top two records before it filters on the link fields. How do I get the top two records of only those records that apply to the corresponding link field? Thanks.</p>
[ { "answer_id": 183544, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 2, "selected": true, "text": "SELECT o1.order_number, o1.order_date,\n (SELECT COUNT(*) FROM orders AS o2\n WHERE o2.order_date <= o1.order_date) AS RowNum\n FROM\n orders AS o1\n ORDER BY o1.order_date \n" }, { "answer_id": 258114, "author": "Yarik", "author_id": 31415, "author_profile": "https://Stackoverflow.com/users/31415", "pm_score": 2, "selected": false, "text": "select\n Order.ID,\n Order.Customer_ID,\n Order.PlacementDate\nfrom\n Order\nwhere\n Order.ID in \n (\n select top 2\n RecentOrder.ID\n from\n Order as RecentOrder\n where\n RecentOrder.Customer_ID = Order.Customer_ID\n order by\n RecentOrder.PlacementDate Desc\n )\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7899/" ]
183,017
<p>When i deploy a rails application in production mode, it appends a date-time string as a query param to the end of all the static asset urls. This is to prevent browsers using old-out of date cahed copies of the assets after I redeploy the application. </p> <p>Is there a way to make rails use the old time stamps for the assets that have not changed (and <strong>only</strong> the ones that have not changed) since the last deployment. I want to do this to prevent users having to redownload those assets that have not changed.</p>
[ { "answer_id": 192536, "author": "Daniel Beardsley", "author_id": 13216, "author_profile": "https://Stackoverflow.com/users/13216", "pm_score": 4, "selected": false, "text": "set :normalize_asset_timestamps, false\n #Etags should be based on the file parameters only (default includes INode)\nFileETag MTime Size \n\n#Rewrite stuff\nRewriteEngine On \n\n#This sets the environment variable (is_versioned) when the URL query string\n#looks like ?874353948543 or any string of digits\nRewriteCond %{QUERY_STRING} ^[0-9]+$\nRewriteRule ^(.*)$ $1 [env=is_versioned:true] \n\n<Directory /deployed-rails-app/public/ >\n Options -Indexes FollowSymLinks -MultiViews\n AllowOverride None\n Order allow,deny\n allow from all \n\n #For files, force the browser to rely on cache-control directives and \n #Rails asset timestamps by removing Etags and Last-Modified dates \n\n #For all assets that aren't stamped by rails, cache them for ~ 3 hours\n Header set \"Cache-Control\" \"max-age=10000\"\n Header unset Etag\n Header unset \"Last-Modified\" \n\n #For all assets that ARE stamped by rails, cache them for 30 days\n Header set \"Cache-Control\" \"max-age=2592000\" env=is_versioned\n\n</Directory>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ]
183,018
<p>Looking into System.Data.DbType there is no SqlVariant type there. SqlDataReader, for example, provides the GetString method for reading into string variable. What is the appropriate way to retrieve data from the database field of type sql_variant, presumably into object? </p> <p>The aim is to read data stored as <a href="http://msdn.microsoft.com/en-us/library/ms173829.aspx" rel="nofollow noreferrer">sql_variant type</a> in database. Not to assign the value into variable of object type. I mentioned object type variable because I thing the sql_variant, if possible, would go into such type.</p>
[ { "answer_id": 183027, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 2, "selected": false, "text": "object result = null;\nresult = reader[\"columnNameGoesHere\"];\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23730/" ]
183,032
<p>Is it possible to send a list of IDs to a stored procedure from c#?</p> <pre><code>UPDATE Germs SET Mutated = ~Mutated WHERE (GermID IN (ids)) </code></pre>
[ { "answer_id": 183073, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 2, "selected": false, "text": "CREATE TABLE #ids (id int)\nINSERT INTO #ids VALUES ('123') -- your C# code would generate all of the inserts\n\n-- From within your stored procedure...\nUPDATE g\nSET Mutated = ~Mutated\nFROM Germs g\nJOIN #ids i ON g.GermID = i.id\n" }, { "answer_id": 183095, "author": "Kevin Dark", "author_id": 26151, "author_profile": "https://Stackoverflow.com/users/26151", "pm_score": 2, "selected": false, "text": "set ANSI_NULLS ON\nset QUOTED_IDENTIFIER ON\ngo\n\nCREATE FUNCTION [dbo].[Split_String] \n( \n @MyString varchar(5000)\n)\nRETURNS @Results TABLE\n(\n Value varchar(1000)\n) \nAS\n BEGIN\n DECLARE @Pos int\n DECLARE @StrLen int\n DECLARE @MyLen int\n DECLARE @MyVal varchar\n SET @pos = 1\n SET @MyLen = 1\n WHILE @MyString <> ''\n BEGIN\n SET @MyLen = charindex(',',@MyString) \n IF @MyLen = 0 SET @MyLen = Len(@MyString)\n INSERT @Results SELECT replace(substring(@MyString, @pos, @MyLen),',','')\n SET @MyString = SUBSTRING(@MyString,@MyLen+1,len(@MyString))\n END\n RETURN \n END\n SELECT * FROM [youDataBase].[dbo].[Split_String] (<@MyString, varchar(5000),>)\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
183,033
<p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p> <ul> <li><p><strong>Firstly</strong>: Given an established C# project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li> <li><p><strong>Secondly</strong>: When writing a program from scratch in C#, what are some good ways to greatly improve performance?</p></li> </ul> <p><strong>Please stay away from general optimization techniques unless they are <em>C# specific</em>.</strong></p> <p>This has previously been asked for <a href="https://stackoverflow.com/questions/172720/speeding-up-python">Python</a>, <a href="https://stackoverflow.com/questions/177122/speeding-up-perl">Perl</a>, and <a href="https://stackoverflow.com/questions/179745/speeding-up-java">Java</a>.</p>
[ { "answer_id": 183046, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "object SuspendLayout ResumeLayout" }, { "answer_id": 296121, "author": "Lurker Indeed", "author_id": 16951, "author_profile": "https://Stackoverflow.com/users/16951", "pm_score": -1, "selected": false, "text": "protected override System.Windows.Forms.CreateParams CreateParams { \n get { \n CreateParams cp = base.CreateParams; \n cp.ExStyle = cp.ExStyle | 0x2000000; \n return cp; \n } \n} \n" }, { "answer_id": 522347, "author": "GWLlosa", "author_id": 18071, "author_profile": "https://Stackoverflow.com/users/18071", "pm_score": 0, "selected": false, "text": "private Item _myResult;\npublic Item Result\n{\n get\n {\n if (_myResult == null)\n {\n _myResult = Database.DoQueryForResult();\n }\n return _myResult;\n }\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ]
183,035
<p>I have a strange bug with WPF Interop and an Excel Addin. I'm using .Net 3.5 SP1.</p> <p>I'm using Add-in Express to create a Custom Task Pane for Excel 2003. Within that taskpane I'm using ElementHost to host a WPF UserControl. The UserControl simply contains a Grid with a TextBox and ComboBox. My problem is that whilst everything displays properly, the ComboBox won't stay dropped-down unless I hold the mouse down over the down-arrow.</p> <p>I don't believe this is necessarily related to Add-in Express because I've had a similar problem when I tried displaying a WPF window modelessly in Excel.</p> <p>A second problem is that the ComboBox seems reluctant to give up focus. If I click it, the text area goes grey to indicate that it has focus, but I can't move focus anywhere else in the window. The only way to wrest focus away is to move the mousewheel.</p> <p>Anybody else had a similar problem, and managed to fix it?</p>
[ { "answer_id": 697518, "author": "Samuel Jack", "author_id": 1727, "author_profile": "https://Stackoverflow.com/users/1727", "pm_score": 3, "selected": true, "text": "private const uint WS_CHILD = 0x40000000;\nprivate const uint WS_CLIPCHILDREN = 0x02000000;\nprivate const uint WS_CLIPSIBLINGS = 0x04000000;\n\nprivate CreateParams _CreateParams = new CreateParams();\nprotected override CreateParams CreateParams\n{\n get\n {\n _CreateParams = base.CreateParams;\n if (!DesignMode)\n _CreateParams.Style = (int)(WS_CLIPCHILDREN | WS_CLIPSIBLINGS); //| WS_CHILD\n\n return _CreateParams;\n }\n}\n" }, { "answer_id": 5191938, "author": "Pacome", "author_id": 644443, "author_profile": "https://Stackoverflow.com/users/644443", "pm_score": 0, "selected": false, "text": "public WpfContainerUserControl()\n{\n InitializeComponent();\n GpecsBrowserTabUserControl gpecBrowser = elementHost1.Child as GpecsBrowserTabUserControl;\n gpecBrowser.MouseEnter += new System.Windows.Input.MouseEventHandler(gpecBrowser_MouseEnter);\n}\n\nvoid gpecBrowser_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)\n{\n this.Focus();\n} \n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1727/" ]
183,042
<p>Is there a way to define a column (primary key) as a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier" rel="noreferrer">UUID</a> in <a href="http://www.sqlalchemy.org/" rel="noreferrer">SQLAlchemy</a> if using <a href="http://www.postgresql.org/" rel="noreferrer">PostgreSQL</a> (Postgres)?</p>
[ { "answer_id": 188427, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": -1, "selected": false, "text": "import sqlalchemy.types as types\n\nclass UUID(types.TypeEngine):\n def get_col_spec(self):\n return \"uuid\"\n\n def bind_processor(self, dialect):\n def process(value):\n return value\n return process\n\n def result_processor(self, dialect):\n def process(value):\n return value\n return process\n\ntable = Table('foo', meta,\n Column('id', UUID(), primary_key=True),\n)\n" }, { "answer_id": 812363, "author": "Tom Willis", "author_id": 67393, "author_profile": "https://Stackoverflow.com/users/67393", "pm_score": 6, "selected": false, "text": "from sqlalchemy import types\nfrom sqlalchemy.dialects.mysql.base import MSBinary\nfrom sqlalchemy.schema import Column\nimport uuid\n\n\nclass UUID(types.TypeDecorator):\n impl = MSBinary\n def __init__(self):\n self.impl.length = 16\n types.TypeDecorator.__init__(self,length=self.impl.length)\n\n def process_bind_param(self,value,dialect=None):\n if value and isinstance(value,uuid.UUID):\n return value.bytes\n elif value and not isinstance(value,uuid.UUID):\n raise ValueError,'value %s is not a valid uuid.UUID' % value\n else:\n return None\n\n def process_result_value(self,value,dialect=None):\n if value:\n return uuid.UUID(bytes=value)\n else:\n return None\n\n def is_mutable(self):\n return False\n\n\nid_column_name = \"id\"\n\ndef id_column():\n import uuid\n return Column(id_column_name,UUID(),primary_key=True,default=uuid.uuid4)\n\n# Usage\nmy_table = Table('test',\n metadata,\n id_column(),\n Column('parent_id',\n UUID(),\n ForeignKey(table_parent.c.id)))\n" }, { "answer_id": 19935248, "author": "Nemeth", "author_id": 370299, "author_profile": "https://Stackoverflow.com/users/370299", "pm_score": 2, "selected": false, "text": "class UUID(types.TypeDecorator):\n impl = types.LargeBinary\n\n def __init__(self):\n self.impl.length = 16\n types.TypeDecorator.__init__(self, length=self.impl.length)\n\n def process_bind_param(self, value, dialect=None):\n if value and isinstance(value, uuid.UUID):\n return value.bytes\n elif value and isinstance(value, basestring):\n return uuid.UUID(value).bytes\n elif value:\n raise ValueError('value %s is not a valid uuid.UUId' % value)\n else:\n return None\n\n def process_result_value(self, value, dialect=None):\n if value:\n return uuid.UUID(bytes=value)\n else:\n return None\n\n def is_mutable(self):\n return False\n" }, { "answer_id": 30604002, "author": "zwirbeltier", "author_id": 769486, "author_profile": "https://Stackoverflow.com/users/769486", "pm_score": 3, "selected": false, "text": "import uuid\n\nfrom sqlalchemy.types import TypeDecorator, BINARY\nfrom sqlalchemy.dialects.postgresql import UUID as psqlUUID\n\nclass UUID(TypeDecorator):\n \"\"\"Platform-independent GUID type.\n\n Uses Postgresql's UUID type, otherwise uses\n BINARY(16), to store UUID.\n\n \"\"\"\n impl = BINARY\n\n def load_dialect_impl(self, dialect):\n if dialect.name == 'postgresql':\n return dialect.type_descriptor(psqlUUID())\n else:\n return dialect.type_descriptor(BINARY(16))\n\n def process_bind_param(self, value, dialect):\n if value is None:\n return value\n else:\n if not isinstance(value, uuid.UUID):\n if isinstance(value, bytes):\n value = uuid.UUID(bytes=value)\n elif isinstance(value, int):\n value = uuid.UUID(int=value)\n elif isinstance(value, str):\n value = uuid.UUID(value)\n if dialect.name == 'postgresql':\n return str(value)\n else:\n return value.bytes\n\n def process_result_value(self, value, dialect):\n if value is None:\n return value\n if dialect.name == 'postgresql':\n return uuid.UUID(value)\n else:\n return uuid.UUID(bytes=value)\n" }, { "answer_id": 32332765, "author": "Berislav Lopac", "author_id": 122033, "author_profile": "https://Stackoverflow.com/users/122033", "pm_score": 5, "selected": false, "text": "UUIDType SQLAlchemy-Utils" }, { "answer_id": 41434923, "author": "Kushal Ahmed", "author_id": 7367289, "author_profile": "https://Stackoverflow.com/users/7367289", "pm_score": 5, "selected": false, "text": "def generate_uuid():\n return str(uuid.uuid4())\n\nclass MyTable(Base):\n __tablename__ = 'my_table'\n\n uuid = Column(String, name=\"uuid\", primary_key=True, default=generate_uuid)\n" }, { "answer_id": 49398042, "author": "JDiMatteo", "author_id": 1007353, "author_profile": "https://Stackoverflow.com/users/1007353", "pm_score": 8, "selected": false, "text": "from sqlalchemy.dialects.postgresql import UUID\nfrom flask_sqlalchemy import SQLAlchemy\nimport uuid\n\ndb = SQLAlchemy()\n\nclass Foo(db.Model):\n id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)\n callable uuid.uuid4 uuid.uuid4()" }, { "answer_id": 57919049, "author": "Granat", "author_id": 12061926, "author_profile": "https://Stackoverflow.com/users/12061926", "pm_score": 4, "selected": false, "text": "from app.main import db\nfrom sqlalchemy.dialects.postgresql import UUID\n\nclass Foo(db.Model):\n id = db.Column(UUID(as_uuid=True), primary_key=True)\n name = db.Column(db.String, nullable=False)\n" }, { "answer_id": 69000211, "author": "Atul Anand", "author_id": 16687498, "author_profile": "https://Stackoverflow.com/users/16687498", "pm_score": 0, "selected": false, "text": "UUIDType from sqlalchemy_utils import UUIDType\nfrom sqlalchemy import String\n\nclass User(Base):\n id = Column(UUIDType(binary=False), primary_key=True, default=uuid.uuid4)\n name = Column(String)\n" }, { "answer_id": 74367684, "author": "gentiand", "author_id": 11727882, "author_profile": "https://Stackoverflow.com/users/11727882", "pm_score": 1, "selected": false, "text": "from sqlalchemy import Column, text\nfrom sqlalchemy.dialects.postgresql import UUID\n\nColumn(\n \"id\", UUID(as_uuid=True),\n primary_key=True,\n server_default=text(\"gen_random_uuid()\"),\n)\n CREATE EXTENSION IF NOT EXISTS \"pgcrypto\";\n uuid_generate_v4() CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7883/" ]
183,062
<p>How does one go about establishing a CSS 'schema', or hierarchy, of general element styles, nested element styles, and classed element styles. For a rank novice like me, the amount of information in stylesheets I view is completely overwhelming. What process does one follow in creating a well factored stylesheet or sheets, compared to inline style attributes?</p>
[ { "answer_id": 183160, "author": "Andre Bossard", "author_id": 21027, "author_profile": "https://Stackoverflow.com/users/21027", "pm_score": 1, "selected": false, "text": "The human editor perspective: The consumer perspective:" }, { "answer_id": 183205, "author": "Marcus Downing", "author_id": 1000, "author_profile": "https://Stackoverflow.com/users/1000", "pm_score": 2, "selected": false, "text": "class left header_links_object2_left id class id margin padding float clear" }, { "answer_id": 300736, "author": "Ola Tuvesson", "author_id": 6903, "author_profile": "https://Stackoverflow.com/users/6903", "pm_score": 4, "selected": true, "text": " ul.tabs {\n list-style-type: none;\n }\n ul.tabs li {\n float: left;\n }\n ul.tabs li img {\n border: none;\n }\n <style>\ndiv.box {\nfloat: left;\nborder: 1px solid blue;\npadding: 1em;\n}\n\ndiv.wide {\nwidth: 15em; \n}\n\ndiv.narrow {\nwidth: 8em; \n}\n\ndiv#oddOneOut {\nfloat: right;\n}\n</style>\n\n<div class=\"box wide\">a wide box</div>\n<div class=\"box narrow\">a narrow box</div>\n<div class=\"box wide\" id=\"oddOneOut\">an odd box</div>\n" }, { "answer_id": 300770, "author": "One Crayon", "author_id": 38666, "author_profile": "https://Stackoverflow.com/users/38666", "pm_score": 2, "selected": false, "text": "* {margin: 0; padding: 0} .error .left #content #header" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
183,071
<p>My normal IDE is Visual Studio, but I'm currently doing some development in Eclipse for the first time. If you press Ctrl-X with text selected in either program, it cuts the text and puts on the clipboard exactly as you'd expect. If press Ctrl-X with no text selected in Visual Studio, it cuts the current line. In Eclipse it is ignored. Is there a way to get Eclipse to use Studio's behavior?</p>
[ { "answer_id": 183160, "author": "Andre Bossard", "author_id": 21027, "author_profile": "https://Stackoverflow.com/users/21027", "pm_score": 1, "selected": false, "text": "The human editor perspective: The consumer perspective:" }, { "answer_id": 183205, "author": "Marcus Downing", "author_id": 1000, "author_profile": "https://Stackoverflow.com/users/1000", "pm_score": 2, "selected": false, "text": "class left header_links_object2_left id class id margin padding float clear" }, { "answer_id": 300736, "author": "Ola Tuvesson", "author_id": 6903, "author_profile": "https://Stackoverflow.com/users/6903", "pm_score": 4, "selected": true, "text": " ul.tabs {\n list-style-type: none;\n }\n ul.tabs li {\n float: left;\n }\n ul.tabs li img {\n border: none;\n }\n <style>\ndiv.box {\nfloat: left;\nborder: 1px solid blue;\npadding: 1em;\n}\n\ndiv.wide {\nwidth: 15em; \n}\n\ndiv.narrow {\nwidth: 8em; \n}\n\ndiv#oddOneOut {\nfloat: right;\n}\n</style>\n\n<div class=\"box wide\">a wide box</div>\n<div class=\"box narrow\">a narrow box</div>\n<div class=\"box wide\" id=\"oddOneOut\">an odd box</div>\n" }, { "answer_id": 300770, "author": "One Crayon", "author_id": 38666, "author_profile": "https://Stackoverflow.com/users/38666", "pm_score": 2, "selected": false, "text": "* {margin: 0; padding: 0} .error .left #content #header" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9323/" ]
183,078
<p>I have data loaded and various transformations on the data complete, the problem is there is a parent/child relationship managed in the data - best explained by an example</p> <p>each row has (column names are made up)</p> <pre><code>row_key parent_row_key row_name parent_row_name </code></pre> <p>some rows have row_key == parent_row_key (their own parent) some rows relate to another row (row 25 is the parent to row 44 for example).</p> <p>In this case, row 25 is parent to row 44. I need to put row 25's row_name in row 44's parent_row_name. How do I query the data in the pipeline for the value?</p>
[ { "answer_id": 8520780, "author": "deroby", "author_id": 357429, "author_profile": "https://Stackoverflow.com/users/357429", "pm_score": 0, "selected": false, "text": "UPDATE staging_table\n SET parent_row_name = COALESCE(new.row_name, old.row_name, '#N/A#')\n FROM staging_table upd\n LEFT OUTER JOIN staging_table new\n ON new.row_key = upd.parent_row_key\n LEFT OUTER JOIN destination_table old\n ON old.row_key = upd.parent_row_key\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10868/" ]
183,083
<p>I would like to add a BuildListener to my headless build process, which is building an Eclipse product. The docs on how to do this are, shall we say, a bit scanty. I think I need to put my custom jar in a plugin and then use the org.eclipse.ant.core.extraClasspathEntries extension point to make that jar visible to Ant. But everything I have tried results in <pre> [myClass] which was specified to be a build listener is not an instance of org.apache.tools.ant.BuildListener.</pre></p> <p>My class implements the BuildListener interface. Various postings seem to indicate that this means my class is visible-to/loaded-by the Plugin classloader rather than the Ant classloader. But I thought the whole point of the extension point was to make jars visible to Ant...</p> <p>Can anyone shed light on what I'm doing wrong? Additional info: I am trying to run this build from the Eclipse IDE at the moment using the AntRunner application.</p>
[ { "answer_id": 188700, "author": "ILikeCoffee", "author_id": 25270, "author_profile": "https://Stackoverflow.com/users/25270", "pm_score": 2, "selected": true, "text": "ant.jar org.apache.ant ant.jar" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/460599/" ]
183,093
<p>I'm looking for ideas and opinions here, not a "real answer", I guess...</p> <p>Back in the old VB6 days, there was this property called "Tag" in all controls, that was a useful way to store custom information related to a control. Every single control had it, and all was bliss...</p> <p>Now, in .Net (at least for WebForms), it's not there anymore...</p> <p>Does anyone have a good replacement for that?</p> <p>I find this problem very often, where I have different functions that run at different times in the lifecycle, and they do stuff with my controls, and I want to keep them as separate as they are, but one should pass information to the other about specific controls.</p> <p>I can think of a million alternatives (starting with a module-level dictionary, obviously), but none as clean as the good ol' Tag.</p> <p>(NOTE: I know I can subclass ALL the controls and use my version instead. I'd rather not)</p> <p>Any suggestions? How do you solve this normally? Any ideas on why they removed this i the first place?</p> <p>EDIT: I'm looking for something Intra-Request, not Inter-Request. I don't need this information to still be there on a PostBack. This is between the _Load and the _PreRender methods, for example.</p> <p>EDIT2: I DO know my ASp.Net and I do know the difference between the desktop and the web, guys!. I 'm just trying to use the abstraction that .Net gives me to the maximum. I understand the tradeoffs, believe me, and please answer assuming that I do.</p>
[ { "answer_id": 183109, "author": "harriyott", "author_id": 5744, "author_profile": "https://Stackoverflow.com/users/5744", "pm_score": 0, "selected": false, "text": "<div attrName=\"attrValue\">" }, { "answer_id": 183121, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 0, "selected": false, "text": "Attributes MyImgCtrl.Attributes[\"myCustomTagAttribute\"] = \"myVal\";\n" }, { "answer_id": 183262, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 4, "selected": true, "text": "Imports System.Runtime.CompilerServices\n\nPublic Module Extensions\n <Extension()> _\n Public Sub SetTag(ByVal ctl As Control, ByVal tagValue As String)\n If SessionTagDictionary.ContainsKey(TagName(ctl)) Then\n SessionTagDictionary(TagName(ctl)) = tagValue\n Else\n SessionTagDictionary.Add(TagName(ctl), tagValue)\n End If\n End Sub\n\n <Extension()> _\n Public Function GetTag(ByVal ctl As Control) As String\n If SessionTagDictionary.ContainsKey(TagName(ctl)) Then\n Return SessionTagDictionary(TagName(ctl))\n Else\n Return String.Empty\n End If\n End Function\n\n Private Function TagName(ByVal ctl As Control) As String\n Return ctl.Page.ClientID & \".\" & ctl.ClientID\n End Function\n\n Private Function SessionTagDictionary() As Dictionary(Of String, String)\n If HttpContext.Current.Session(\"TagDictionary\") Is Nothing Then\n SessionTagDictionary = New Dictionary(Of String, String)\n HttpContext.Current.Session(\"TagDictionary\") = SessionTagDictionary\n Else\n SessionTagDictionary = DirectCast(HttpContext.Current.Session(\"TagDictionary\"), _ \n Dictionary(Of String, String))\n End If\n End Function\nEnd Module\n Imports WebApplication1.Extensions\n TextBox1.SetTag(\"Test\")\n\nLabel1.Text = TextBox1.GetTag\n <Extension()> _\n Public Sub SetTag(ByVal ctl As Control, ByVal tagValue As String)\n ViewState.Add(ctl.ID & \"_Tag\", tagValue)\n End Sub\n\n<Extension()> _\n Public Function GetTag(ByVal ctl As Control) As String\n Return ViewState(ctl.ID & \"_Tag\")\n End Function\n\nPrivate Function ViewState() As Web.UI.StateBag\n Return HttpContext.Current.Handler.GetType.InvokeMember(\"ViewState\", _\n Reflection.BindingFlags.GetProperty + _\n Reflection.BindingFlags.Instance + _\n Reflection.BindingFlags.NonPublic, _\n Nothing, HttpContext.Current.CurrentHandler, Nothing)\nEnd Function\n Public Class PageEx\n Inherits System.Web.UI.Page\n\n Friend ReadOnly Property ViewStateEx() As Web.UI.StateBag\n Get\n Return MyBase.ViewState\n End Get\n End Property\nEnd Class\n Private Function ViewState() As Web.UI.StateBag\n Return DirectCast(HttpContext.Current.Handler, PageEx).ViewStateEx\nEnd Function\n" }, { "answer_id": 183278, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": -1, "selected": false, "text": "Tag Control Tag Dictionary<Control,TValue> Page Dictionary<Control,string> Dictionary<Control,BusinessObject>" }, { "answer_id": 183722, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "public class TaggedControl<TControl, TTag> : Control \n where TControl : Control, new()\n { public TaggedControl() {this.Control= new TControl();}\n\n public TControl Control {get; private set;}\n public TTag Tag {get; set;} \n\n protected override void CreateChildControls(){Controls.Add(Control);}\n }\n\n var textBox = new TaggedControl<TextBox, string>();\n textBox.Tag = \"Test\";\n label.Text = textBox.Tag;\n" }, { "answer_id": 61001788, "author": "Westley Bennett", "author_id": 7308469, "author_profile": "https://Stackoverflow.com/users/7308469", "pm_score": 1, "selected": false, "text": "using System.Collections.Generic;\nusing System.Web;\nusing System.Web.UI;\n\npublic static class Extensions\n{\n public static void SetTag(this Control ctl, object tagValue)\n {\n if (ctl.SessionTagDictionary().ContainsKey(TagName(ctl)))\n ctl.SessionTagDictionary()[TagName(ctl)] = tagValue;\n else\n ctl.SessionTagDictionary().Add(TagName(ctl), tagValue);\n }\n\n public static object GetTag(this Control ctl)\n {\n if (ctl.SessionTagDictionary().ContainsKey(TagName(ctl)))\n return ctl.SessionTagDictionary()[TagName(ctl)];\n else\n return string.Empty;\n }\n\n private static string TagName(Control ctl)\n {\n return ctl.Page.ClientID + \".\" + ctl.ClientID;\n }\n\n private static Dictionary<string, object> SessionTagDictionary(this Control ctl)\n {\n Dictionary<string, object> SessionTagDictionary;\n if (HttpContext.Current.Session[\"TagDictionary\"] == null)\n {\n SessionTagDictionary = new Dictionary<string, object>();\n HttpContext.Current.Session[\"TagDictionary\"] = SessionTagDictionary;\n }\n else\n SessionTagDictionary = (Dictionary<string, object>)HttpContext.Current.Session[\"TagDictionary\"];\n return SessionTagDictionary;\n }\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ]
183,101
<p>I use the MFC list control in report view with grid lines to display data in a vaguely spreadsheet manner.</p> <p>Sometimes when the user scrolls vertically through the control, extra grid lines are drawn, which looks terrible.</p> <p>This does not happen when the slider or the mousewheel are used to scroll, only when the little down arrow button at the bottom of the scroll control is used.</p> <p>It seems that this occurs when the size of the list control window is not an exact even number of rows, so that a partial row is visible at the bottom.</p> <p>If I adjust the size of the list control so that there is no partial rows visible, the problem is solved. However, it will appear when the program is run on another computer, presumably because the number of pixels occupied by a row changes. </p> <p>I am assuming that it is an interaction between screen resolution, font size and "dialog units".</p> <p>I guess that I need to programmatically force the size of the control when it is created. But what size?</p> <p>I have tried using the ApproximateViewRect() method but I cannot get it to work. Perhaps this method does not know about report view?</p> <p>The other method, I suppose, would be to create my own specialization of CListCtrl and over-ride whatever method is doing the scrolling. This seems likely to be a lot of work.</p> <p>This screenshot shows a closely related problem where the grid lines go missing</p> <p><img src="https://i.stack.imgur.com/K5XzV.jpg" alt="alt text"></p> <p>and here is one with the extra grid lines</p> <p><img src="https://i.stack.imgur.com/6pADr.jpg" alt="alt text"></p> <p>The only difference between these two and between them and one which scrolls perfectly is a few pixels different in the vertical size of the control.</p>
[ { "answer_id": 183926, "author": "Aidan Ryan", "author_id": 1042, "author_profile": "https://Stackoverflow.com/users/1042", "pm_score": 3, "selected": false, "text": "void CMyListCtrl::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)\n{\n __super::OnVScroll(nSBCode, nPos, pScrollBar);\n Invalidate();\n UpdateWindow();\n}\n" }, { "answer_id": 184315, "author": "ravenspoint", "author_id": 16582, "author_profile": "https://Stackoverflow.com/users/16582", "pm_score": -1, "selected": true, "text": "class cSmoothListControl : public CListCtrl\n{\npublic:\n DECLARE_MESSAGE_MAP()\n afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);\n};\n BEGIN_MESSAGE_MAP(cSmoothListControl, CListCtrl)\nON_WM_VSCROLL()\nEND_MESSAGE_MAP()\n\nvoid cSmoothListControl::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)\n{\n // call base class method to do scroll\n CListCtrl::OnVScroll(nSBCode, nPos, pScrollBar);\n\n // force redraw to cover any mess that may be created\n Invalidate();\n UpdateWindow();\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16582/" ]
183,108
<p>I have a C++ template class that gets instantiated with 3 different type parameters. There's a method that the class needs to have for only one of those types and that isn't ever called with the two other types.</p> <p>Will object code for that method be generated thrice (for all types for which the template is instantiated), or is object code generated only once (for the type with which it is actually used)?</p>
[ { "answer_id": 183235, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 6, "selected": true, "text": "constexpr template <class T>\nclass Xyzzy\n{\npublic:\n void CallFoo() { t.foo(); } // Invoke T::foo()\n void CallBar() { t.bar(); } // Invoke T::bar()\n\nprivate:\n T t;\n};\n\nclass FooBar\n{\npublic:\n void foo() { ... }\n void bar() { ... }\n};\n\nclass BarOnly\n{\npublic:\n void bar() { ... }\n};\n\nint main(int argc, const char** argv)\n{\n Xyzzy<FooBar> foobar; // Xyzzy<FooBar> is instantiated\n Xyzzy<BarOnly> baronly; // Xyzzy<BarOnly> is instantiated\n\n foobar.CallFoo(); // Calls FooBar::foo()\n foobar.CallBar(); // Calls FooBar::bar()\n\n baronly.CallBar(); // Calls BarOnly::bar()\n\n return 0;\n}\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18721/" ]