qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
128,241
|
<p>Here's a question that's been haunting me for a year now. The root question is how do I set the size of an element relative to its parent so that it is inset by N pixels from every edge? Setting the width would be nice, but you don't know the width of the parent, and you want the elements to resize with the window. (You don't want to use percents because you need a specific number of pixels.) </p>
<p>Edit
I also need to prevent the content (or lack of content) from stretching or shrinking both elements. First answer I got was to use padding on the parent, which would work great. I want the parent to be exactly 25% wide, and exactly the same height as the browser client area, without the child being able to push it and get a scroll bar.
/Edit</p>
<p>I tried solving this problem using {top:Npx;left:Npx;bottom:Npx;right:Npx;} but it only works in certain browsers.</p>
<p>I could potentially write some javascript with jquery to fix all elements with every page resize, but I'm not real happy with that solution. (What if I want the top offset by 10px but the bottom only 5px? It gets complicated.)</p>
<p>What I'd like to know is either how to solve this in a cross-browser way, or some list of browsers which allow the easy CSS solution. Maybe someone out there has a trick that makes this easy.</p>
|
[
{
"answer_id": 128253,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 0,
"selected": false,
"text": "display:block"
},
{
"answer_id": 128293,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 0,
"selected": false,
"text": "margin"
},
{
"answer_id": 128306,
"author": "Lincoln Johnson",
"author_id": 13419,
"author_profile": "https://Stackoverflow.com/users/13419",
"pm_score": 0,
"selected": false,
"text": ".parent {padding:Npx; display:block;}\n.child {width:100%; display:block;}\n {padding-top:Mpx; padding-bottom:Npx; padding-right:Xpx; padding-left:Ypx;}\n"
},
{
"answer_id": 128315,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 1,
"selected": false,
"text": "position: relative top left top right bottom left #outer {\n width: 10em;\n height: 10em;\n background: red;\n position: relative;\n}\n\n#inner {\n background: white;\n position: absolute;\n top: 1em;\n left: 1em;\n right: 1em;\n bottom: 1em;\n}\n overflow overflow: auto"
},
{
"answer_id": 136808,
"author": "Carl Camera",
"author_id": 12804,
"author_profile": "https://Stackoverflow.com/users/12804",
"pm_score": 2,
"selected": true,
"text": "<style type=\"text/css\">\nhtml { height: 100%; }\nbody { font: normal 11px verdana; height: 100%; }\n#one { background-color:gray; float:left; height:100%; padding:5px; width:25%; }\n#two { height: 100%; background-color:pink;}\n</style>\n</head>\n<body>\n<div id=\"one\">\n<div id=\"two\">\n<p>content ... content ... content</p>\n</div>\n</div>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5114/"
] |
128,259
|
<p>I have a list of data in the following form:</p>
<p><code>[(id\__1_, description, id\_type), (id\__2_, description, id\_type), ... , (id\__n_, description, id\_type))</code></p>
<p>The data are loaded from files that belong to the same group. In each group there could be multiples of the same id, each coming from different files. I don't care about the duplicates, so I thought that a nice way to store all of this would be to throw it into a Set type. But there's a problem.</p>
<p>Sometimes for the same id the descriptions can vary slightly, as follows:</p>
<p>IPI00110753</p>
<ul>
<li>Tubulin alpha-1A chain</li>
<li>Tubulin alpha-1 chain</li>
<li>Alpha-tubulin 1</li>
<li>Alpha-tubulin isotype M-alpha-1</li>
</ul>
<p>(Note that this example is taken from the <a href="http://www.uniprot.org/uniprot/P68369" rel="nofollow noreferrer">uniprot protein database</a>.) </p>
<p>I don't care if the descriptions vary. I cannot throw them away because there is a chance that the protein database I am using will not contain a listing for a certain identifier. If this happens I will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at.</p>
<p>I am currently solving this problem by using a dictionary type. However I don't really like this solution because it uses a lot of memory (I have a lot of these ID's). This is only an intermediary listing of them. There is some additional processing the ID's go through before they are placed in the database so I would like to keep my data-structure smaller.</p>
<p>I have two questions really. First, will I get a smaller memory footprint using the Set type (over the dictionary type) for this, or should I use a sorted list where I check every time I insert into the list to see if the ID exists, or is there a third solution that I haven't thought of? Second, if the Set type is the better answer how do I key it to look at just the first element of the tuple instead of the whole thing? </p>
<p>Thank you for reading my question, <br>
Tim</p>
<p><strong>Update</strong></p>
<p>based on some of the comments I received let me clarify a little. Most of what I do with data-structure is insert into it. I only read it twice, once to annotate it with additional information,* and once to do be inserted into the database. However down the line there may be additional annotation that is done before I insert into the database. Unfortunately I don't know if that will happen at this time. </p>
<p>Right now I am looking into storing this data in a structure that is not based on a hash-table (ie. a dictionary). I would like the new structure to be fairly quick on insertion, but reading it can be linear since I only really do it twice. I am trying to move away from the hash table to save space. Is there a better structure or is a hash-table about as good as it gets?</p>
<p>*The information is a list of Swiss-Prot protein identifiers that I get by querying uniprot.</p>
|
[
{
"answer_id": 128361,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "{ 'id1': [ ('description1a', 'type1'), ('description1b','type1') ], \n 'id2': [ ('description2', 'type2') ],\n...\n}\n { 'id1': ( ('description1a', 'description1b' ), 'type1' ),\n 'id2': ( ('description2',), 'type2' ),\n...\n}\n struct"
},
{
"answer_id": 128393,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 0,
"selected": false,
"text": "{id: (description, id_type)} {(id, id_type): description}"
},
{
"answer_id": 128526,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 0,
"selected": false,
"text": "class ProteinTuple(tuple):\n def __new__(cls, m1, m2, m3):\n return tuple.__new__(cls, (m1, m2, m3))\n\n def __hash__(self):\n return hash(self[0])\n __hash__"
},
{
"answer_id": 128565,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "source1.sort()\nsource2.sort()\nresult= []\nwhile len(source1) > 0 or len(source2) > 0:\n if len(source1) == 0:\n result.append( source2.pop(0) )\n elif len(source2) == 0:\n result.append( source1.pop(0) )\n elif source1[0][0] < source2[0][0]:\n result.append( source1.pop(0) )\n elif source2[0][0] < source1[0][0]:\n result.append( source2.pop(0) )\n else:\n # keys are equal\n result.append( source1.pop(0) )\n # check for source2, to see if the description is different.\n"
},
{
"answer_id": 129396,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "def merge( *sources ):\n keyPos= 0\n for s in sources:\n s.sort()\n while any( [len(s)>0 for s in sources] ):\n topEnum= enumerate([ s[0][keyPos] if len(s) > 0 else None for s in sources ])\n top= [ t for t in topEnum if t[1] is not None ]\n top.sort( key=lambda a:a[1] )\n src, key = top[0]\n #print src, key\n yield sources[ src ].pop(0)\n def unique( sequence ):\n keyPos= 0\n seqIter= iter(sequence)\n curr= seqIter.next()\n for next in seqIter:\n if next[keyPos] == curr[keyPos]:\n # might want to create a sub-list of matches\n continue\n yield curr\n curr= next\n yield curr\n for u in unique( merge( source1, source2, source3, ... ) ):\n print u\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14107/"
] |
128,267
|
<p>I'm trying to define a task that emits (using echo) a message when a target completes execution, regardless of whether that target was successful or not. Specifically, the target executes a task to run some unit tests, and I want to emit a message indicating where the results are available:</p>
<pre><code><target name="mytarget">
<testng outputDir="${results}" ...>
...
</testng>
<echo>Tests complete. Results available in ${results}</echo>
</target>
</code></pre>
<p>Unfortunately, if the tests fail, the task fails and execution aborts. So the message is only output if the tests pass - the opposite of what I want. I know I can put the task before the task, but this will make it easier for users to miss this message. Is what I'm trying to do possible?</p>
<p><strong>Update:</strong> It turns out I'm dumb. I had haltOnFailure="true" in my <testng> task, which explains the behaviour I was seeing. Now the issue is that setting this to false causes the overall ant build to succeed even if tests fail, which is not what I want. The answer below using the task looks like it might be what I want..</p>
|
[
{
"answer_id": 128325,
"author": "bernie",
"author_id": 21141,
"author_profile": "https://Stackoverflow.com/users/21141",
"pm_score": 3,
"selected": false,
"text": "<target name=\"myTarget\">\n <trycatch property=\"foo\" reference=\"bar\">\n <try>\n <testing outputdir=\"${results}\" ...>\n ...\n </testing>\n </try>\n\n <catch>\n <echo>Test failed</echo>\n </catch>\n\n <finally>\n <echo>Tests complete. Results available in ${results}</echo>\n </finally>\n </trycatch>\n</target>\n"
},
{
"answer_id": 128382,
"author": "mithu",
"author_id": 16618,
"author_profile": "https://Stackoverflow.com/users/16618",
"pm_score": 0,
"selected": false,
"text": "<target name=\"junit\" depends=\"junitcompile\">\n <junit printsummary=\"withOutAndErr\" fork=\"yes\" haltonfailure=\"yes\">\n"
},
{
"answer_id": 134563,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 3,
"selected": true,
"text": "failureProperty haltOnFailure <target name=\"mytarget\">\n <testng outputDir=\"${results}\" failureProperty=\"tests.failed\" haltOnFailure=\"false\" ...>\n ...\n </testng>\n <echo>Tests complete. Results available in ${results}</echo>\n</target>\n <target name=\"doSomethingIfTestsWereSuccessful\" unless=\"tests.failed\">\n ...\n</target>\n\n<target name=\"doSomethingIfTestsFailed\" if=\"tests.failed\">\n ...\n <fail message=\"Tests Failed\" />\n</target>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16977/"
] |
128,277
|
<p><strong>UPDATE</strong></p>
<p>I'm basically binding the query to a WinForms <code>DataGridView</code>. I want the column headers to be appropriate and have spaces when needed. For example, I would want a column header to be <code>First Name</code> instead of <code>FirstName</code>.</p>
<hr>
<p>How do you create your own custom column names in LINQ? </p>
<p>For example:</p>
<pre><code>Dim query = From u In db.Users _
Select u.FirstName AS 'First Name'
</code></pre>
|
[
{
"answer_id": 128391,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 5,
"selected": false,
"text": "var query = from u in db.Users\n select new\n {\n FirstName = u.FirstName,\n LastName = u.LastName,\n FullName = u.FirstName + \" \" + u.LastName\n };\n foreach (var u in query)\n{\n // Full name will be available now \n Debug.Print(u.FullName); \n}\n var query = from u in db.Users\n select new\n {\n First = u.FirstName,\n Last = u.LastName\n };\n"
},
{
"answer_id": 128602,
"author": "Steve Owens",
"author_id": 19304,
"author_profile": "https://Stackoverflow.com/users/19304",
"pm_score": -1,
"selected": false,
"text": "Dim query = From u In db.Users _\n Select 'First Name' = u.FirstName\n"
},
{
"answer_id": 128862,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "namespace MyControls \n{\npublic SpacedHeaderTextField : System.Web.UI.WebControls.BoundField\n { public override string HeaderText\n { get \n { string value = base.HeaderText;\n return (value.Length > 0) ? value : DataField.Replace(\" \",\"\");\n }\n set\n { base.HeaderText = value;\n } \n }\n } \n }\n <%@Register TagPrefix=\"my\" Namespace=\"MyControls\" %>\n\n<asp:GridView DataSourceID=\"LinqDataSource1\" runat='server'>\n <Columns>\n <my:SpacedHeaderTextField DataField=\"First_Name\" />\n </Columns>\n</asp:GridView>\n"
},
{
"answer_id": 128907,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 4,
"selected": false,
"text": "<asp:GridView ID=\"GridView1\" runat=\"server\" AutoGenerateColumns=\"false\">\n <Columns>\n <asp:BoundField DataField=\"FirstName\" HeaderText=\"First Name\" />\n </Columns>\n</asp:GridView>\n protected void Page_Load(object sender, EventArgs e)\n{\n // initialize db datacontext\n var query = from u in db.Users\n select u;\n GridView1.DataSource = query;\n GridView1.DataBind();\n}\n"
},
{
"answer_id": 131329,
"author": "KristoferA",
"author_id": 11241,
"author_profile": "https://Stackoverflow.com/users/11241",
"pm_score": 1,
"selected": false,
"text": "//gridview with more formatting options\nnamespace GridViewCF\n{\n [ToolboxData(\"<{0}:GridViewCF runat=server></{0}:GridViewCF>\")]\n public class GridViewCF : GridView\n {\n //public Dictionary<string, UserReportField> _fieldProperties = null;\n\n public GridViewCF()\n {\n }\n\n public List<FieldProperties> FieldProperties\n {\n get\n {\n return (List<FieldProperties>)ViewState[\"FieldProperties\"];\n }\n set\n {\n ViewState[\"FieldProperties\"] = value;\n }\n }\n\n protected override AutoGeneratedField CreateAutoGeneratedColumn(AutoGeneratedFieldProperties fieldProperties)\n {\n AutoGeneratedField field = base.CreateAutoGeneratedColumn(fieldProperties);\n StateBag sb = (StateBag)field.GetType()\n .InvokeMember(\"ViewState\",\n BindingFlags.GetProperty |\n BindingFlags.NonPublic |\n BindingFlags.Instance,\n null, field, new object[] {});\n\n if (FieldProperties != null)\n {\n FieldProperties fps = FieldProperties.Where(fp => fp.Name == fieldProperties.Name).Single();\n if (fps.FormatString != null && fps.FormatString != \"\")\n {\n //formatting\n sb[\"DataFormatString\"] = \"{0:\" + fps.FormatString + \"}\";\n field.HtmlEncode = false;\n }\n\n //header caption\n field.HeaderText = fps.HeaderText;\n\n //alignment\n field.ItemStyle.HorizontalAlign = fps.HorizontalAlign;\n }\n\n return field;\n }\n }\n\n [Serializable()]\n public class FieldProperties\n {\n public FieldProperties()\n { }\n\n public FieldProperties(string name, string formatString, string headerText, HorizontalAlign horizontalAlign)\n {\n Name = name;\n FormatString = formatString;\n HeaderText = headerText;\n HorizontalAlign = horizontalAlign;\n }\n\n public string Name { get; set; }\n public string FormatString { get; set; }\n public string HeaderText { get; set; }\n public HorizontalAlign HorizontalAlign { get; set; }\n }\n}\n"
},
{
"answer_id": 425254,
"author": "cjk",
"author_id": 52201,
"author_profile": "https://Stackoverflow.com/users/52201",
"pm_score": 2,
"selected": false,
"text": "var query = from u in db.Users\n select new\n {\n FirstName = u.FirstName,\n LastName = u.LastName,\n FullName = u.FirstName + \" \" + u.LastName\n };\n"
},
{
"answer_id": 443471,
"author": "Bryan Roth",
"author_id": 299,
"author_profile": "https://Stackoverflow.com/users/299",
"pm_score": 5,
"selected": true,
"text": "LINQ Dim query = From u In Users _\n Select First_Name = u.FirstName\n Paint DataGridView Private Sub DataGridView1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles DataGridView1.Paint\n For Each c As DataGridViewColumn In DataGridView1.Columns\n c.HeaderText = c.HeaderText.Replace(\"_\", \" \")\n Next\nEnd Sub\n"
},
{
"answer_id": 486086,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "datagrid1.ItemDataBound += \n new DataGridItemEventHandler(datagrid1_HeaderItemDataBound);\n private void datagrid1_HeaderItemDataBound(object sender, DataGridItemEventArgs e)\n{\n\n if (e.Item.ItemType == ListItemType.Header)\n {\n foreach(TableCell cell in e.Item.Cells)\n cell.Text = cell.Text.Replace('_', ' ');\n }\n\n}\n"
},
{
"answer_id": 27022004,
"author": "usefulBee",
"author_id": 2093880,
"author_profile": "https://Stackoverflow.com/users/2093880",
"pm_score": 2,
"selected": false,
"text": "SomeDataSource.Select(i => new { NewColumnName = i.OldColumnName, NewColumnTwoName = i.OldColumnTwoName});\n"
},
{
"answer_id": 50485606,
"author": "Muhammad Abrar Anwar",
"author_id": 7532209,
"author_profile": "https://Stackoverflow.com/users/7532209",
"pm_score": 0,
"selected": false,
"text": " system.Name,\n sysentity.Name \n //change this to \n entity = sysentity.Name\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/299/"
] |
128,279
|
<p>I have a <a href="http://en.wikipedia.org/wiki/WiX" rel="nofollow noreferrer">WiX</a> installer and a single custom action (plus undo and rollback) for it which uses a property from the installer. The custom action has to happen after all the files are on the hard disk. It seems that you need 16 entries in the WXS file for this; eight within the root, like so:</p>
<pre><code><CustomAction Id="SetForRollbackDo" Execute="immediate" Property="RollbackDo" Value="[MYPROP]"/>
<CustomAction Id="RollbackDo" Execute="rollback" BinaryKey="MyDLL" DllEntry="UndoThing" Return="ignore"/>
<CustomAction Id="SetForDo" Execute="immediate" Property="Do" Value="[MYPROP]"/>
<CustomAction Id="Do" Execute="deferred" BinaryKey="MyDLL" DllEntry="DoThing" Return="check"/>
<CustomAction Id="SetForRollbackUndo" Execute="immediate" Property="RollbackUndo" Value="[MYPROP]"/>
<CustomAction Id="RollbackUndo" Execute="rollback" BinaryKey="MyDLL" DllEntry="DoThing" Return="ignore"/>
<CustomAction Id="SetForUndo" Execute="immediate" Property="Undo" Value="[MYPROP]"/>
<CustomAction Id="Undo" Execute="deferred" BinaryKey="MyDLL" DllEntry="UndoThing" Return="check"/>
</code></pre>
<p>And eight within the <code>InstallExecuteSequence</code>, like so:</p>
<pre><code><Custom Action="SetForRollbackDo" After="InstallFiles">REMOVE&lt;>"ALL"</Custom>
<Custom Action="RollbackDo" After="SetForRollbackDo">REMOVE&lt;>"ALL"</Custom>
<Custom Action="SetForDo" After="RollbackDo">REMOVE&lt;>"ALL"</Custom>
<Custom Action="Do" After="SetForDo">REMOVE&lt;>"ALL"</Custom>
<Custom Action="SetForRollbackUndo" After="InstallInitialize">REMOVE="ALL"</Custom>
<Custom Action="RollbackUndo" After="SetForRollbackUndo">REMOVE="ALL"</Custom>
<Custom Action="SetForUndo" After="RollbackUndo">REMOVE="ALL"</Custom>
<Custom Action="Undo" After="SetForUndo">REMOVE="ALL"</Custom>
</code></pre>
<p>Is there a better way?</p>
|
[
{
"answer_id": 152961,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 2,
"selected": false,
"text": "CustomAction Custom MsiDoAction MsiDoAction MsiSetProperty IISExtension"
},
{
"answer_id": 6371772,
"author": "Kun-Yao Huang",
"author_id": 698171,
"author_profile": "https://Stackoverflow.com/users/698171",
"pm_score": 3,
"selected": true,
"text": "<CustomTable Id=\"LocalGroupPermissionTable\">\n <Column Id=\"GroupName\" Category=\"Text\" PrimaryKey=\"yes\" Type=\"string\"/>\n <Column Id=\"ACL\" Category=\"Text\" PrimaryKey=\"no\" Type=\"string\"/>\n <Row>\n <Data Column=\"GroupName\">GroupToCreate</Data>\n <Data Column=\"ACL\">SeIncreaseQuotaPrivilege</Data>\n </Row>\n</CustomTable>\n extern \"C\" UINT __stdcall ScheduleLocalGroupCreation(MSIHANDLE hInstall)\n{\n try {\n ScheduleAction(hInstall,L\"SELECT * FROM CreateLocalGroupTable\", L\"CA.LocalGroupCustomAction.deferred\", L\"create\");\n ScheduleAction(hInstall,L\"SELECT * FROM CreateLocalGroupTable\", L\"CA.LocalGroupCustomAction.rollback\", L\"create\");\n }\n catch( CMsiException & ) {\n return ERROR_INSTALL_FAILURE;\n }\n return ERROR_SUCCESS;\n}\n /propname:value void ScheduleAction(MSIHANDLE hInstall,\n const wchar_t *szQueryString,\n const wchar_t *szCustomActionName,\n const wchar_t *szAction)\n{\n CTableView view(hInstall,szQueryString);\n PMSIHANDLE record;\n\n //For each record in the custom action table\n while( view.Fetch(record) ) {\n //get the \"GroupName\" property\n wchar_t recordBuf[2048] = {0};\n DWORD dwBufSize(_countof(recordBuf));\n MsiRecordGetString(record, view.GetPropIdx(L\"GroupName\"), recordBuf, &dwBufSize);\n\n //Format two properties \"GroupName\" and \"Operation\" into\n //the custom action data string.\n CCustomActionDataUtil formatter;\n formatter.addProp(L\"GroupName\", recordBuf);\n formatter.addProp(L\"Operation\", szAction );\n\n //Set the \"CustomActionData\" property\".\n MsiSetProperty(hInstall,szCustomActionName,formatter.GetCustomActionData());\n\n //Add the custom action into installation script. Each\n //MsiDoAction adds a distinct custom action into the\n //script, so if we have multiple entries in the custom\n //action table, the deferred custom action will be called\n //multiple times.\n nRet = MsiDoAction(hInstall,szCustomActionName);\n }\n}\n extern \"C\" UINT __stdcall LocalGroupCustomAction(MSIHANDLE hInstall)\n{\n try {\n //Parse the properties from the \"CustomActionData\" property\n std::map<std::wstring,std::wstring> mapProps;\n {\n wchar_t szBuf[2048]={0};\n DWORD dwBufSize = _countof(szBuf); MsiGetProperty(hInstall,L\"CustomActionData\",szBuf,&dwBufSize);\n CCustomActionDataUtil::ParseCustomActionData(szBuf,mapProps);\n }\n\n //Find the \"GroupName\" and \"Operation\" property\n std::wstring sGroupName;\n bool bCreate = false;\n std::map<std::wstring,std::wstring>::const_iterator it;\n it = mapProps.find(L\"GroupName\");\n if( mapProps.end() != it ) sGroupName = it->second;\n it = mapProps.find(L\"Operation\");\n if( mapProps.end() != it )\n bCreate = wcscmp(it->second.c_str(),L\"create\") == 0 ? true : false ;\n\n //Since we know what opeartion to perform, and we know whether it is\n //running rollback, commit or deferred script by MsiGetMode, the\n //implementation is straight forward\n if( MsiGetMode(hInstall,MSIRUNMODE_SCHEDULED) ) {\n if( bCreate )\n CreateLocalGroup(sGroupName.c_str());\n else\n DeleteLocalGroup(sGroupName.c_str());\n }\n else if( MsiGetMode(hInstall,MSIRUNMODE_ROLLBACK) ) {\n if( bCreate )\n DeleteLocalGroup(sGroupName.c_str());\n else\n CreateLocalGroup(sGroupName.c_str());\n }\n }\n catch( CMsiException & ) {\n return ERROR_INSTALL_FAILURE;\n }\n return ERROR_SUCCESS;\n}\n <CustomAction Id=\"CA.ScheduleLocalGroupCreation\"\n Return=\"check\"\n Execute=\"immediate\"\n BinaryKey=\"CustomActionDLL\"\n DllEntry=\"ScheduleLocalGroupCreation\"\n HideTarget=\"yes\"/>\n<CustomAction Id=\"CA.ScheduleLocalGroupDeletion\"\n Return=\"check\"\n Execute=\"immediate\"\n BinaryKey=\"CustomActionDLL\"\n DllEntry=\"ScheduleLocalGroupDeletion\"\n HideTarget=\"yes\"/>\n<CustomAction Id=\"CA.LocalGroupCustomAction.deferred\"\n Return=\"check\"\n Execute=\"deferred\"\n BinaryKey=\"CustomActionDLL\"\n DllEntry=\"LocalGroupCustomAction\"\n HideTarget=\"yes\"/>\n<CustomAction Id=\"CA.LocalGroupCustomAction.commit\"\n Return=\"check\"\n Execute=\"commit\"\n BinaryKey=\"CustomActionDLL\"\n DllEntry=\"LocalGroupCustomAction\"\n HideTarget=\"yes\"/>\n<CustomAction Id=\"CA.LocalGroupCustomAction.rollback\"\n Return=\"check\"\n Execute=\"rollback\"\n BinaryKey=\"CustomActionDLL\"\n DllEntry=\"LocalGroupCustomAction\"\n HideTarget=\"yes\"/>\n <InstallExecuteSequence>\n <Custom Action=\"CA.ScheduleLocalGroupCreation\" \n After=\"InstallFiles\">\n Not Installed\n </Custom>\n <Custom Action=\"CA.ScheduleLocalGroupDeletion\" \n After=\"InstallFiles\">\n Installed\n </Custom>\n</InstallExecuteSequence>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20686/"
] |
128,287
|
<p>What is currently the best tool for JavaME unit testing? I´ve never really used unit testing before (shame on me!), so learning curve is important. I would appreciate some pros and cons with your answer. :)</p>
|
[
{
"answer_id": 128318,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 0,
"selected": false,
"text": "@Before @After @BeforeClass @AfterClass"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12423/"
] |
128,305
|
<p>How to tag images in the image itself in a web page? </p>
<p>I know <a href="http://www.taggify.net/" rel="nofollow noreferrer">Taggify</a>, but... is there other options?</p>
<p><a href="http://en.blog.orkut.com/2008/06/tag-thats-me.html" rel="nofollow noreferrer">Orkut</a> also does it to tag people faces... How is it done?</p>
<p>Anyone knows any public framework that is able to do it?</p>
<p>See a sample bellow from Taggify:</p>
<p><img src="https://i.stack.imgur.com/gT1zq.jpg" alt="alt text" title="Taggify Sample""></p>
|
[
{
"answer_id": 128518,
"author": "Luke Foust",
"author_id": 646,
"author_profile": "https://Stackoverflow.com/users/646",
"pm_score": 2,
"selected": false,
"text": "public static BitmapMetadata GetMetaData(string path)\n{\n using (Stream s = new System.IO.FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))\n {\n var decoder = BitmapDecoder.Create(s, BitmapCreateOptions.None, BitmapCacheOption.OnDemand);\n var frame = decoder.Frames.FirstOrDefault();\n if (frame != null)\n {\n return frame.Metadata as BitmapMetadata;\n }\n return null;\n }\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] |
128,342
|
<p>For a project of mine I would love to provide auto completion for a specific textarea. Similar to how intellisense/omnicomplete works. For that however I have to find out the absolute cursor position so that I know where the DIV should appear.</p>
<p>Turns out: that's (nearly I hope) impossible to achieve. Does anyone has some neat ideas how to solve that problem?</p>
|
[
{
"answer_id": 163395,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 5,
"selected": false,
"text": "selection.end y x context.measureText selection.end <!DOCTYPE html>\n<html lang=\"en-US\">\n <head>\n <meta charset=\"utf-8\" />\n <title>Tooltip 2</title>\n <script type=\"text/javascript\" src=\"//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js\"></script>\n <script type=\"text/javascript\" src=\"http://enobrev.info/cursor/js/jquery-fieldselection.js\"></script>\n <style type=\"text/css\">\n form {\n float: left;\n margin: 20px;\n }\n\n #textariffic {\n height: 400px;\n width: 300px;\n font-size: 12px;\n font-family: 'Arial';\n line-height: 12px;\n }\n\n #tip {\n width:5px;\n height:30px;\n background-color: #777;\n position: absolute;\n z-index:10000\n }\n\n #mock-text {\n float: left;\n margin: 20px;\n border: 1px inset #ccc;\n }\n\n /* way the hell off screen */\n .scrollbar-measure {\n width: 100px;\n height: 100px;\n overflow: scroll;\n position: absolute;\n top: -9999px;\n }\n\n #randomize {\n float: left;\n display: block;\n }\n </style>\n <script type=\"text/javascript\">\n var oCanvas;\n var oTextArea;\n var $oTextArea;\n var iScrollWidth;\n\n $(function() {\n iScrollWidth = scrollMeasure();\n oCanvas = document.getElementById('mock-text');\n oTextArea = document.getElementById('textariffic');\n $oTextArea = $(oTextArea);\n\n $oTextArea\n .keyup(update)\n .mouseup(update)\n .scroll(update);\n\n $('#randomize').bind('click', randomize);\n\n update();\n });\n\n function randomize() {\n var aFonts = ['Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Impact', 'Times New Roman', 'Verdana', 'Webdings'];\n var iFont = Math.floor(Math.random() * aFonts.length);\n var iWidth = Math.floor(Math.random() * 500) + 300;\n var iHeight = Math.floor(Math.random() * 500) + 300;\n var iFontSize = Math.floor(Math.random() * 18) + 10;\n var iLineHeight = Math.floor(Math.random() * 18) + 10;\n\n var oCSS = {\n 'font-family': aFonts[iFont],\n width: iWidth + 'px',\n height: iHeight + 'px',\n 'font-size': iFontSize + 'px',\n 'line-height': iLineHeight + 'px'\n };\n\n console.log(oCSS);\n\n $oTextArea.css(oCSS);\n\n update();\n return false;\n }\n\n function showTip(x, y) {\n $('#tip').css({\n left: x + 'px',\n top: y + 'px'\n });\n }\n\n // https://stackoverflow.com/a/11124580/14651\n // https://stackoverflow.com/a/3960916/14651\n\n function wordWrap(oContext, text, maxWidth) {\n var aSplit = text.split(' ');\n var aLines = [];\n var sLine = \"\";\n\n // Split words by newlines\n var aWords = [];\n for (var i in aSplit) {\n var aWord = aSplit[i].split('\\n');\n if (aWord.length > 1) {\n for (var j in aWord) {\n aWords.push(aWord[j]);\n aWords.push(\"\\n\");\n }\n\n aWords.pop();\n } else {\n aWords.push(aSplit[i]);\n }\n }\n\n while (aWords.length > 0) {\n var sWord = aWords[0];\n if (sWord == \"\\n\") {\n aLines.push(sLine);\n aWords.shift();\n sLine = \"\";\n } else {\n // Break up work longer than max width\n var iItemWidth = oContext.measureText(sWord).width;\n if (iItemWidth > maxWidth) {\n var sContinuous = '';\n var iWidth = 0;\n while (iWidth <= maxWidth) {\n var sNextLetter = sWord.substring(0, 1);\n var iNextWidth = oContext.measureText(sContinuous + sNextLetter).width;\n if (iNextWidth <= maxWidth) {\n sContinuous += sNextLetter;\n sWord = sWord.substring(1);\n }\n iWidth = iNextWidth;\n }\n aWords.unshift(sContinuous);\n }\n\n // Extra space after word for mozilla and ie\n var sWithSpace = (jQuery.browser.mozilla || jQuery.browser.msie) ? ' ' : '';\n var iNewLineWidth = oContext.measureText(sLine + sWord + sWithSpace).width;\n if (iNewLineWidth <= maxWidth) { // word fits on current line to add it and carry on\n sLine += aWords.shift() + \" \";\n } else {\n aLines.push(sLine);\n sLine = \"\";\n }\n\n if (aWords.length === 0) {\n aLines.push(sLine);\n }\n }\n }\n return aLines;\n }\n\n // http://davidwalsh.name/detect-scrollbar-width\n function scrollMeasure() {\n // Create the measurement node\n var scrollDiv = document.createElement(\"div\");\n scrollDiv.className = \"scrollbar-measure\";\n document.body.appendChild(scrollDiv);\n\n // Get the scrollbar width\n var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;\n\n // Delete the DIV\n document.body.removeChild(scrollDiv);\n\n return scrollbarWidth;\n }\n\n function update() {\n var oPosition = $oTextArea.position();\n var sContent = $oTextArea.val();\n var oSelection = $oTextArea.getSelection();\n\n oCanvas.width = $oTextArea.width();\n oCanvas.height = $oTextArea.height();\n\n var oContext = oCanvas.getContext(\"2d\");\n var sFontSize = $oTextArea.css('font-size');\n var sLineHeight = $oTextArea.css('line-height');\n var fontSize = parseFloat(sFontSize.replace(/[^0-9.]/g, ''));\n var lineHeight = parseFloat(sLineHeight.replace(/[^0-9.]/g, ''));\n var sFont = [$oTextArea.css('font-weight'), sFontSize + '/' + sLineHeight, $oTextArea.css('font-family')].join(' ');\n\n var iSubtractScrollWidth = oTextArea.clientHeight < oTextArea.scrollHeight ? iScrollWidth : 0;\n\n oContext.save();\n oContext.clearRect(0, 0, oCanvas.width, oCanvas.height);\n oContext.font = sFont;\n var aLines = wordWrap(oContext, sContent, oCanvas.width - iSubtractScrollWidth);\n\n var x = 0;\n var y = 0;\n var iGoal = oSelection.end;\n aLines.forEach(function(sLine, i) {\n if (iGoal > 0) {\n oContext.fillText(sLine.substring(0, iGoal), 0, (i + 1) * lineHeight);\n\n x = oContext.measureText(sLine.substring(0, iGoal + 1)).width;\n y = i * lineHeight - oTextArea.scrollTop;\n\n var iLineLength = sLine.length;\n if (iLineLength == 0) {\n iLineLength = 1;\n }\n\n iGoal -= iLineLength;\n } else {\n // after\n }\n });\n oContext.restore();\n\n showTip(oPosition.left + x, oPosition.top + y);\n }\n\n </script>\n </head>\n <body>\n\n <a href=\"#\" id=\"randomize\">Randomize</a>\n\n <form id=\"tipper\">\n <textarea id=\"textariffic\">Aliquam urna. Nullam augue dolor, tincidunt condimentum, malesuada quis, ultrices at, arcu. Aliquam nunc pede, convallis auctor, sodales eget, aliquam eget, ligula. Proin nisi lacus, scelerisque nec, aliquam vel, dictum mattis, eros. Curabitur et neque. Fusce sollicitudin. Quisque at risus. Suspendisse potenti. Mauris nisi. Sed sed enim nec dui viverra congue. Phasellus velit sapien, porttitor vitae, blandit volutpat, interdum vel, enim. Cras sagittis bibendum neque. Proin eu est. Fusce arcu. Aliquam elit nisi, malesuada eget, dignissim sed, ultricies vel, purus. Maecenas accumsan diam id nisi.\n\nPhasellus et nunc. Vivamus sem felis, dignissim non, lacinia id, accumsan quis, ligula. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed scelerisque nulla sit amet mi. Nulla consequat, elit vitae tempus vulputate, sem libero rhoncus leo, vulputate viverra nulla purus nec turpis. Nam turpis sem, tincidunt non, congue lobortis, fermentum a, ipsum. Nulla facilisi. Aenean facilisis. Maecenas a quam eu nibh lacinia ultricies. Morbi malesuada orci quis tellus.\n\nSed eu leo. Donec in turpis. Donec non neque nec ante tincidunt posuere. Pellentesque blandit. Ut vehicula vestibulum risus. Maecenas commodo placerat est. Integer massa nunc, luctus at, accumsan non, pulvinar sed, odio. Pellentesque eget libero iaculis dui iaculis vehicula. Curabitur quis nulla vel felis ullamcorper varius. Sed suscipit pulvinar lectus.</textarea>\n\n </form>\n\n <div id=\"tip\"></div>\n\n <canvas id=\"mock-text\"></canvas>\n </body>\n</html>\n monospace Courier New \"Courier New\" 'Lucida Grand' monospace -webkit-monospace \"Courier New\" <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n <title>Tooltip</title>\n <script type=\"text/javascript\" src=\"js/jquery-1.2.6.js\"></script>\n <script type=\"text/javascript\" src=\"js/jquery-fieldselection.js\"></script>\n <script type=\"text/javascript\" src=\"js/jquery.dimensions.js\"></script>\n <style type=\"text/css\">\n form {\n margin: 20px auto;\n width: 500px;\n }\n\n #textariffic {\n height: 400px;\n font-size: 12px;\n font-family: monospace;\n line-height: 15px;\n }\n\n #tip {\n position: absolute;\n z-index: 2;\n padding: 20px;\n border: 1px solid #000;\n background-color: #FFF;\n }\n </style>\n <script type=\"text/javascript\">\n $(function() {\n $('textarea')\n .keyup(update)\n .mouseup(update)\n .scroll(update);\n });\n\n function showTip(x, y) { \n y = y + $('#tip').height();\n\n $('#tip').css({\n left: x + 'px',\n top: y + 'px'\n });\n }\n\n function update() {\n var oPosition = $(this).position();\n var sContent = $(this).val();\n\n var bGTE = jQuery.browser.mozilla || jQuery.browser.msie;\n\n if ($(this).css('font-family') == 'monospace' // mozilla\n || $(this).css('font-family') == '-webkit-monospace' // Safari\n || $(this).css('font-family') == '\"Courier New\"') { // Opera\n var lineHeight = $(this).css('line-height').replace(/[^0-9]/g, '');\n lineHeight = parseFloat(lineHeight);\n var charsPerLine = this.cols;\n var charWidth = parseFloat($(this).innerWidth() / charsPerLine);\n\n\n var iChar = 0;\n var iLines = 1;\n var sWord = '';\n\n var oSelection = $(this).getSelection();\n var aLetters = sContent.split(\"\");\n var aLines = [];\n\n for (var w in aLetters) {\n if (aLetters[w] == \"\\n\") {\n iChar = 0;\n aLines.push(w);\n sWord = '';\n } else if (aLetters[w] == \" \") { \n var wordLength = parseInt(sWord.length);\n\n\n if ((bGTE && iChar + wordLength >= charsPerLine)\n || (!bGTE && iChar + wordLength > charsPerLine)) {\n iChar = wordLength + 1;\n aLines.push(w - wordLength);\n } else { \n iChar += wordLength + 1; // 1 more char for the space\n }\n\n sWord = '';\n } else if (aLetters[w] == \"\\t\") {\n iChar += 4;\n } else {\n sWord += aLetters[w]; \n }\n }\n\n var iLine = 1;\n for(var i in aLines) {\n if (oSelection.end < aLines[i]) {\n iLine = parseInt(i) - 1;\n break;\n }\n }\n\n if (iLine > -1) {\n var x = parseInt(oSelection.end - aLines[iLine]) * charWidth;\n } else {\n var x = parseInt(oSelection.end) * charWidth;\n }\n var y = (iLine + 1) * lineHeight - this.scrollTop; // below line\n\n showTip(oPosition.left + x, oPosition.top + y);\n }\n }\n\n </script>\n </head>\n <body>\n <form id=\"tipper\">\n <textarea id=\"textariffic\" cols=\"50\">\nAliquam urna. Nullam augue dolor, tincidunt condimentum, malesuada quis, ultrices at, arcu. Aliquam nunc pede, convallis auctor, sodales eget, aliquam eget, ligula. Proin nisi lacus, scelerisque nec, aliquam vel, dictum mattis, eros. Curabitur et neque. Fusce sollicitudin. Quisque at risus. Suspendisse potenti. Mauris nisi. Sed sed enim nec dui viverra congue. Phasellus velit sapien, porttitor vitae, blandit volutpat, interdum vel, enim. Cras sagittis bibendum neque. Proin eu est. Fusce arcu. Aliquam elit nisi, malesuada eget, dignissim sed, ultricies vel, purus. Maecenas accumsan diam id nisi.\n\nPhasellus et nunc. Vivamus sem felis, dignissim non, lacinia id, accumsan quis, ligula. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed scelerisque nulla sit amet mi. Nulla consequat, elit vitae tempus vulputate, sem libero rhoncus leo, vulputate viverra nulla purus nec turpis. Nam turpis sem, tincidunt non, congue lobortis, fermentum a, ipsum. Nulla facilisi. Aenean facilisis. Maecenas a quam eu nibh lacinia ultricies. Morbi malesuada orci quis tellus.\n\nSed eu leo. Donec in turpis. Donec non neque nec ante tincidunt posuere. Pellentesque blandit. Ut vehicula vestibulum risus. Maecenas commodo placerat est. Integer massa nunc, luctus at, accumsan non, pulvinar sed, odio. Pellentesque eget libero iaculis dui iaculis vehicula. Curabitur quis nulla vel felis ullamcorper varius. Sed suscipit pulvinar lectus. \n </textarea>\n\n </form>\n\n <p id=\"tip\">Here I Am!!</p>\n </body>\n</html>\n"
},
{
"answer_id": 13079085,
"author": "Halcyon",
"author_id": 722762,
"author_profile": "https://Stackoverflow.com/users/722762",
"pm_score": 0,
"selected": false,
"text": "textarea div contenteditable Range // get active selection\nvar selection = window.getSelection();\n// get the range (you might want to check selection.rangeCount\n// to see if it's popuplated)\nvar range = selection.getRangeAt(0);\n\n// will give you top, left, width, height\nconsole.log(range.getBoundingClientRect());\n \"#hash\" h # n contenteditable rangy"
},
{
"answer_id": 13083337,
"author": "Ma Jerez",
"author_id": 1316510,
"author_profile": "https://Stackoverflow.com/users/1316510",
"pm_score": 2,
"selected": false,
"text": "<html><head>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n <title>- jsFiddle demo by mjerez</title>\n <script type=\"text/javascript\" src=\"http://code.jquery.com/jquery-1.8.2.js\"></script>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"http://jsfiddle.net/css/normalize.css\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"http://jsfiddle.net/css/result-light.css\"> \n <script type=\"text/javascript\" src=\"https://raw.github.com/beviz/jquery-caret-position-getter/master/jquery.caretposition.js\"></script> \n <style type=\"text/css\">\n body{position:relative;font:normal 100% Verdana, Geneva, sans-serif;padding:10px;}\n .aux{background:#ccc;opacity: 0.5;width:50%;padding:5px;border:solid 1px #aaa;}\n .hidden{display:none}\n .show{display:block; position:absolute; top:0px; left:0px;}\n </style>\n <script type=\"text/javascript\">//<![CDATA[ \n $(document).keypress(function(e) {\n if ($(e.target).is('input, textarea')) {\n var key = String.fromCharCode(e.which);\n var ctrl = e.ctrlKey;\n if (ctrl) {\n var display = $(\"#autocomplete\");\n var editArea = $('#editArea'); \n var pos = editArea.getCaretPosition();\n var offset = editArea.offset();\n // now you can use left, top(they are relative position)\n display.css({\n left: offset.left + pos.left,\n top: offset.top + pos.top,\n color : \"#449\"\n })\n display.toggleClass(\"show\");\n return false;\n }\n }\n\n });\n window.onload = (function() {\n $(\"#editArea\").blur(function() {\n if ($(\"#autocomplete\").hasClass(\"show\")) $(\"#autocomplete\").toggleClass(\"show\");\n })\n });\n //]]> \n </script>\n</head>\n<body>\n <p>Click ctrl+space to while you write to diplay the autocmplete pannel.</p>\n </br>\n <textarea id=\"editArea\" rows=\"4\" cols=\"50\"></textarea>\n </br>\n </br>\n </br>\n <div id=\"autocomplete\" class=\"aux hidden \">\n <ol>\n <li>Option a</li>\n <li>Option b</li>\n <li>Option c</li>\n <li>Option d</li>\n </ol>\n </div>\n</body>\n"
},
{
"answer_id": 13104080,
"author": "lrsjng",
"author_id": 1184032,
"author_profile": "https://Stackoverflow.com/users/1184032",
"pm_score": 1,
"selected": false,
"text": "getCaret()"
},
{
"answer_id": 13111593,
"author": "echo_Me",
"author_id": 998158,
"author_profile": "https://Stackoverflow.com/users/998158",
"pm_score": 0,
"selected": false,
"text": " <form>\n <p>\n <input type=\"button\" onclick=\"evalOnce();\" value=\"Get Selection\">\ntimer:\n<input id=\"eval_switch\" type=\"checkbox\" onclick=\"evalSwitchClicked(this)\">\n<input id=\"eval_time\" type=\"text\" value=\"200\" size=\"6\">\nms\n</p>\n<textarea id=\"code\" cols=\"50\" rows=\"20\">01234567890123456789012345678901234567890123456789 01234567890123456789012345678901234567890123456789 01234567890123456789012345678901234567890123456789 01234567890123456789012345678901234567890123456789 01234567890123456789012345678901234567890123456789 Sample text area. Please select above text. </textarea>\n<textarea id=\"out\" cols=\"50\" rows=\"20\"></textarea>\n</form>\n<div id=\"test\"></div>\n<script>\n\nfunction Selection(textareaElement) {\nthis.element = textareaElement;\n}\nSelection.prototype.create = function() {\nif (document.selection != null && this.element.selectionStart == null) {\nreturn this._ieGetSelection();\n} else {\nreturn this._mozillaGetSelection();\n}\n}\nSelection.prototype._mozillaGetSelection = function() {\nreturn {\nstart: this.element.selectionStart,\nend: this.element.selectionEnd\n };\n }\nSelection.prototype._ieGetSelection = function() {\nthis.element.focus();\nvar range = document.selection.createRange();\nvar bookmark = range.getBookmark();\nvar contents = this.element.value;\nvar originalContents = contents;\nvar marker = this._createSelectionMarker();\nwhile(contents.indexOf(marker) != -1) {\nmarker = this._createSelectionMarker();\n }\nvar parent = range.parentElement();\nif (parent == null || parent.type != \"textarea\") {\nreturn { start: 0, end: 0 };\n}\nrange.text = marker + range.text + marker;\ncontents = this.element.value;\nvar result = {};\nresult.start = contents.indexOf(marker);\ncontents = contents.replace(marker, \"\");\nresult.end = contents.indexOf(marker);\nthis.element.value = originalContents;\nrange.moveToBookmark(bookmark);\nrange.select();\nreturn result;\n}\nSelection.prototype._createSelectionMarker = function() {\nreturn \"##SELECTION_MARKER_\" + Math.random() + \"##\";\n}\n\nvar timer;\nvar buffer = \"\";\nfunction evalSwitchClicked(e) {\nif (e.checked) {\nevalStart();\n} else {\nevalStop();\n}\n}\nfunction evalStart() {\nvar o = document.getElementById(\"eval_time\");\ntimer = setTimeout(timerHandler, o.value);\n}\nfunction evalStop() {\nclearTimeout(timer);\n}\nfunction timerHandler() {\nclearTimeout(timer);\nvar sw = document.getElementById(\"eval_switch\");\nif (sw.checked) {\nevalOnce();\nevalStart();\n}\n}\nfunction evalOnce() {\ntry {\nvar selection = new Selection(document.getElementById(\"code\"));\nvar s = selection.create();\nvar result = s.start + \":\" + s.end;\nbuffer += result;\nflush();\n } catch (ex) {\nbuffer = ex;\nflush();\n}\n}\nfunction getCode() {\n// var s.create()\n// return document.getElementById(\"code\").value;\n}\nfunction clear() {\nvar out = document.getElementById(\"out\");\nout.value = \"\";\n}\nfunction print(str) {\nbuffer += str + \"\\n\";\n}\nfunction flush() {\nvar out = document.getElementById(\"out\");\nout.value = buffer;\nbuffer = \"\";\n } \n</script>\n"
},
{
"answer_id": 13146099,
"author": "Andrey Sbrodov",
"author_id": 1648497,
"author_profile": "https://Stackoverflow.com/users/1648497",
"pm_score": 0,
"selected": false,
"text": "contenteditable"
},
{
"answer_id": 13151607,
"author": "Satyajit",
"author_id": 168762,
"author_profile": "https://Stackoverflow.com/users/168762",
"pm_score": -1,
"selected": false,
"text": "// http://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea\nvar map = [];\nvar pan = '<span>|</span>'\n\n//found @ http://davidwalsh.name/detect-scrollbar-width\n\nfunction getScrollbarWidth() {\n var scrollDiv = document.createElement(\"div\");\n scrollDiv.className = \"scrollbar-measure\";\n document.body.appendChild(scrollDiv);\n\n // Get the scrollbar width\n var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;\n\n // Delete the DIV \n document.body.removeChild(scrollDiv);\n\n return scrollbarWidth;\n}\n\nfunction getCaret(el) {\n if (el.selectionStart) {\n return el.selectionStart;\n } else if (document.selection) {\n el.focus();\n\n var r = document.selection.createRange();\n if (r == null) {\n return 0;\n }\n\n var re = el.createTextRange(),\n rc = re.duplicate();\n re.moveToBookmark(r.getBookmark());\n rc.setEndPoint('EndToStart', re);\n\n return rc.text.length;\n }\n return 0;\n}\n\n\n$(function() {\n var span = $('#pos span');\n var textarea = $('textarea');\n\n var note = $('#note');\n\n css = getComputedStyle(document.getElementById('textarea'));\n try {\n for (i in css) note.css(css[i]) && (css[i] != 'width' && css[i] != 'height') && note.css(css[i], css.getPropertyValue(css[i]));\n } catch (e) {}\n\n note.css('max-width', '300px');\n document.getElementById('note').style.visibility = 'hidden';\n var height = note.height();\n var fakeCursor, hidePrompt;\n\n textarea.on('keyup click', function(e) {\n if (document.getElementById('textarea').scrollHeight > 100) {\n note.css('max-width', 300 - getScrollbarWidth());\n }\n\n var pos = getCaret(textarea[0]);\n\n note.text(textarea.val().substring(0, pos));\n $(pan).appendTo(note);\n span.text(pos);\n\n if (hidePrompt) {\n hidePrompt.remove();\n }\n if (fakeCursor) {\n fakeCursor.remove();\n }\n\n fakeCursor = $(\"<div style='width:5px;height:30px;background-color: #777;position: absolute;z-index:10000'> </div>\");\n\n fakeCursor.css('opacity', 0.5);\n fakeCursor.css('left', $('#note span').offset().left + 'px');\n fakeCursor.css('top', textarea.offset().top + note.height() - (30 + textarea.scrollTop()) + 'px');\n\n hidePrompt = fakeCursor.clone();\n hidePrompt.css({\n 'width': '2px',\n 'background-color': 'white',\n 'z-index': '1000',\n 'opacity': '1'\n });\n\n hidePrompt.appendTo(textarea.parent());\n fakeCursor.appendTo(textarea.parent());\n\n\n\n return true;\n });\n});\n"
},
{
"answer_id": 22454744,
"author": "Dan Dascalescu",
"author_id": 1269037,
"author_profile": "https://Stackoverflow.com/users/1269037",
"pm_score": 2,
"selected": false,
"text": "<div> <textarea> <span>"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19990/"
] |
128,343
|
<p>I am currently initializing a Hashtable in the following way:</p>
<pre><code>Hashtable filter = new Hashtable();
filter.Add("building", "A-51");
filter.Add("apartment", "210");
</code></pre>
<p>I am looking for a nicer way to do this.</p>
<p>I tried something like </p>
<pre><code>Hashtable filter2 = new Hashtable() {
{"building", "A-51"},
{"apartment", "210"}
};
</code></pre>
<p>However the above code does not compile.</p>
|
[
{
"answer_id": 128367,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 3,
"selected": false,
"text": "Hashtable table = new Hashtable {{1, 1}, {2, 2}};\n"
},
{
"answer_id": 128409,
"author": "Paul Batum",
"author_id": 48281,
"author_profile": "https://Stackoverflow.com/users/48281",
"pm_score": 6,
"selected": true,
"text": " Hashtable filter2 = new Hashtable()\n {\n {\"building\", \"A-51\"},\n {\"apartment\", \"210\"}\n };\n Hashtable filter2 = new Hashtable();\n filter2[\"building\"] = \"A-51\";\n filter2[\"apartment\"] = \"210\";\n"
},
{
"answer_id": 128484,
"author": "Ta01",
"author_id": 7280,
"author_profile": "https://Stackoverflow.com/users/7280",
"pm_score": 0,
"selected": false,
"text": "Hashtable table = new Hashtable {{1, 1}, {2, 2}}; class MyHashTable : System.Collections.Hashtable \n{\n public MyHashTable(string [,] values)\n {\n for (int i = 0; i < (values.Length)/2; i++)\n {\n this.Add(values[i,0], values[i,1]);\n }\n }\n}\n class Program\n{\n static void Main(string[] args)\n {\n string[,] initialize = { { \"building\", \"A-51\" }, { \"apartment\", \"210\" }, {\"wow\", \"nerf Druids\"}};\n\n\n\n MyHashTable myhashTable = new MyHashTable(initialize);\n Console.WriteLine(myhashTable[\"building\"].ToString());\n Console.WriteLine(myhashTable[\"apartment\"].ToString());\n Console.WriteLine(myhashTable[\"wow\"].ToString());\n Console.ReadKey();\n\n\n }\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14755/"
] |
128,348
|
<p>If I have a series of points as longitude and latitude, how would I calculate the center of all of those points?</p>
|
[
{
"answer_id": 128384,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 2,
"selected": false,
"text": "A. .B\n A. C. .B\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19235/"
] |
128,349
|
<p>Date coming out of a database, need to format as "mm/dd/yy"</p>
<pre><code>For Each dr as DataRow in ds.Tables(0).Rows
Response.Write(dr("CreateDate"))
Next
</code></pre>
|
[
{
"answer_id": 128356,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 0,
"selected": false,
"text": "Response.Write(DateTime.Parse(dr(\"CreateDate\").ToString()).ToString(\"MM/dd/yyyy\"))\n"
},
{
"answer_id": 128364,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 0,
"selected": false,
"text": "((DateTime)dr[\"CreateDate\"]).ToString(\"MM/dd/yyyy\")\n if (! DBNull.Value.Equals(dr[\"CreateDate\"])) // blah blah\n"
},
{
"answer_id": 128370,
"author": "Greg",
"author_id": 12601,
"author_profile": "https://Stackoverflow.com/users/12601",
"pm_score": 5,
"selected": true,
"text": "string.Format( \"{0:MM/dd/yy}\", dr(\"CreateDate\") )\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/70/"
] |
128,350
|
<p>I'm writing an <code>RSS</code> to <code>JSON parser</code> and as a part of that, I need to use <code>htmlentities()</code> on any tag found inside the description tag. Currently, I'm trying to use <code>preg_replace()</code>, but I'm struggling a little with it. My current (non-working) code looks like:</p>
<pre><code>$pattern[0] = "/\<description\>(.*?)\<\/description\>/is";
$replace[0] = '<description>'.htmlentities("$1").'</description>';
$rawFeed = preg_replace($pattern, $replace, $rawFeed);
</code></pre>
<p>If you have a more elegant solution to this as well, please share. Thanks.</p>
|
[
{
"answer_id": 128373,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 4,
"selected": true,
"text": "preg_replace_callback function _handle_match($match)\n{\n return '<description>' . htmlentities($match[1]) . '</description>';\n}\n\n$pattern = \"/\\<description\\>(.*?)\\<\\/description\\>/is\";\n$rawFeed = preg_replace_callback($pattern, '_handle_match', $rawFeed);\n"
},
{
"answer_id": 128418,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 0,
"selected": false,
"text": "<?php\n$rss = file_get_contents('http://rss.slashdot.org/Slashdot/slashdot');\n$xml = simplexml_load_string($rss);\n\nforeach ($xml->item as $item) {\n echo \"{$item->description}\\n\\n\";\n}\n?>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13281/"
] |
128,365
|
<p>I have a server access log, with timestamps of each http request, I'd like to obtain a count of the number of requests at each second. Using <code>sed</code>, and <code>cut -c</code>, so far I've managed to cut the file down to just the timestamps, such as:</p>
<blockquote>
<p>22-Sep-2008 20:00:21 +0000<br>
22-Sep-2008 20:00:22 +0000<br>
22-Sep-2008 20:00:22 +0000<br>
22-Sep-2008 20:00:22 +0000<br>
22-Sep-2008 20:00:24 +0000<br>
22-Sep-2008 20:00:24 +0000</p>
</blockquote>
<p>What I'd love to get is the number of times each unique timestamp appears in the file. For example, with the above example, I'd like to get output that looks like:</p>
<blockquote>
<p>22-Sep-2008 20:00:21 +0000: 1<br>
22-Sep-2008 20:00:22 +0000: 3<br>
22-Sep-2008 20:00:24 +0000: 2</p>
</blockquote>
<p>I've used <code>sort -u</code> to filter the list of timestamps down to a list of unique tokens, hoping that I could use grep like</p>
<pre><code>grep -c -f <file containing patterns> <file>
</code></pre>
<p>but this just produces a single line of a grand total of matching lines.</p>
<p>I know this can be done in a single line, stringing a few utilities together ... but I can't think of which. Anyone know?</p>
|
[
{
"answer_id": 128394,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 6,
"selected": true,
"text": "uniq --count\n"
},
{
"answer_id": 128446,
"author": "Remo.D",
"author_id": 16827,
"author_profile": "https://Stackoverflow.com/users/16827",
"pm_score": 1,
"selected": false,
"text": "uniq -c logfile | sed 's/\\([0-9]+\\)\\(.*\\)/\\2: \\1/'\n"
},
{
"answer_id": 161306,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 0,
"selected": false,
"text": "cat file.txt | awk '{count[$1 \" \" $2]++;} \\\n END {for(w in count){print w \": \" count[w]};}'\n"
},
{
"answer_id": 32888355,
"author": "Bity",
"author_id": 3797933,
"author_profile": "https://Stackoverflow.com/users/3797933",
"pm_score": 0,
"selected": false,
"text": "awk '{count[$1 \" \" $2]++;} END {for(w in count){print w \": \" count[w]};}' file.txt\n name1 \nname2 \nname3 \nname2 \nname2 \nname3 \nname1\n uniq 1 name1 \n1 name2 \n1 name3 \n2 name2 \n1 name3 \n1 name1\n name1:2 \nname2:3 \nname3:2\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
] |
128,377
|
<p>I have an application - more like a utility - that sits in a corner and updates two different databases periodically. </p>
<p>It is a little standalone app that has been built with a Spring Application Context. The context has two Hibernate Session Factories configured in it, in turn using Commons DBCP data sources configured in Spring. </p>
<p>Currently there is no transaction management, but I would like to add some. The update to one database depends on a successful update to the other.</p>
<p>The app does not sit in a Java EE container - it is bootstrapped by a static launcher class called from a shell script. The launcher class instantiates the Application Context and then invokes a method on one of its beans. </p>
<p>What is the 'best' way to put transactionality around the database updates?</p>
<p>I will leave the definition of 'best' to you, but I think it should be some function of 'easy to set up', 'easy to configure', 'inexpensive', and 'easy to package and redistribute'. Naturally FOSS would be good.</p>
|
[
{
"answer_id": 128473,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "try { \n TransactionTemplate tt = new TransactionTemplate(txManager);\n\n tt.execute(new TransactionCallbackWithoutResult(){\n protected void doInTransactionWithoutResult(\n TransactionStatus status) {\n updateDb1();\n updateDb2();\n }\n} catch (TransactionException ex) {\n // handle \n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15452/"
] |
128,389
|
<p>This is something that I always find a bit hard to explain to others:
Why do XML namespaces exist?
When should we use them and when should we not?
What are the common pitfalls when working with namespaces in XML? </p>
<p>Also, how do they relate to XML schemas? Should XSD schemas always be associated with a namespace?</p>
|
[
{
"answer_id": 128444,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 1,
"selected": false,
"text": "<sampleDoc>\n <header title=\"Hello world!\">\n <items>\n <item name=\"Volvo\" color=\"Blue\"/>\n </items>\n </header>\n</sampleDoc>\n <sampleDoc>\n <header title=\"Hello world!\">\n <items>\n <item name=\"Volvo\" color=\"White\" my_unique_namespace:color=\"#FFFFFF\"/>\n </items>\n </header>\n</sampleDoc>\n"
},
{
"answer_id": 128503,
"author": "stephbu",
"author_id": 12702,
"author_profile": "https://Stackoverflow.com/users/12702",
"pm_score": 4,
"selected": false,
"text": "<a xmlns=\"uri:foo\"/>\n<foo:a xmlns:foo=\"uri:foo\"/>\n<bar:a xmlns:bar=\"uri:foo\"/>\n"
},
{
"answer_id": 670432,
"author": "paulmurray",
"author_id": 63189,
"author_profile": "https://Stackoverflow.com/users/63189",
"pm_score": 2,
"selected": false,
"text": "accounts:account overdue accounts:warning message personnel:payment vehicle:status"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3389/"
] |
128,412
|
<p>We are using SQL Server 2005, but this question can be for any <a href="http://en.wikipedia.org/wiki/Relational_database_management_system" rel="noreferrer">RDBMS</a>.</p>
<p>Which of the following is more efficient, when selecting all columns from a view?</p>
<pre><code>Select * from view
</code></pre>
<p>or </p>
<pre><code>Select col1, col2, ..., colN from view
</code></pre>
|
[
{
"answer_id": 4202807,
"author": "Simon",
"author_id": 510552,
"author_profile": "https://Stackoverflow.com/users/510552",
"pm_score": 1,
"selected": false,
"text": "create view v_fruit as select F.id, S.strain from F key join S; \ncreate view v_apples as select v_fruit.*, C.colour from v_fruit key join C;\n"
},
{
"answer_id": 11009381,
"author": "Alireza Masali",
"author_id": 1450585,
"author_profile": "https://Stackoverflow.com/users/1450585",
"pm_score": 0,
"selected": false,
"text": "select \ncolumn1\n,column2\n,column3\n.\n.\n.\nfrom Your-View\n select *\nfrom Your View \n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2539/"
] |
128,443
|
<p>Does anyone know how I can get a format string to use <a href="http://en.wikipedia.org/wiki/Rounding#Round-to-even_method" rel="nofollow noreferrer">bankers rounding</a>? I have been using "{0:c}" but that doesn't round the same way that bankers rounding does. The <a href="http://msdn.microsoft.com/en-us/library/system.math.round.aspx" rel="nofollow noreferrer"><code>Math.Round()</code></a> method does bankers rounding. I just need to be able to duplicate how it rounds using a format string.</p>
<hr>
<p>
<strong>Note:</strong> the original question was rather misleading, and answers mentioning regex derive from that.
</p>
|
[
{
"answer_id": 128539,
"author": "Zach Lute",
"author_id": 21374,
"author_profile": "https://Stackoverflow.com/users/21374",
"pm_score": 3,
"selected": true,
"text": "string s = string.Format(\"{0:c}\", 12345.6789);\n string s = string.Format(\"{0:c}\", Math.Round(12345.6789));\n"
},
{
"answer_id": 129470,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "//midpoint always goes 'up': 2.5 -> 3\nMath.Round( input, MidpointRounding.AwayFromZero );\n\n//midpoint always goes to nearest even: 2.5 -> 2, 5.5 -> 6\n//aka bankers' rounding\nMath.Round( input, MidpointRounding.ToEven );\n //defaults to banker's\nMath.Round( input );\n"
},
{
"answer_id": 129587,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": 0,
"selected": false,
"text": "public static class DoubleExtensions\n{\n public static string Format(this double d)\n {\n return String.Format(\"{0:c}\", Math.Round(d));\n }\n}\n 12345.6789.Format();\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21767/"
] |
128,450
|
<p>I have some controller methods I'd like to share. What is the best practice for doing this in ruby on rails? Should I create an abstract class that my controllers extend, or should I create module and add it in to each controller? Below are the controller methods I want to share:</p>
<pre><code>def driving_directions
@address_to = params[:address_to]
@address_from = params[:address_from]
@map_center = params[:map_center_start]
# if we were not given a center point to start our map on
# let's create one.
if !@map_center && @address_to
@map_center = GeoKit::Geocoders::MultiGeocoder.geocode(@address_to).ll
elsif !@map_center && @address_from
@map_center = GeoKit::Geocoders::MultiGeocoder.geocode(@address_from).ll
end
end
def printer_friendly
starting_point = params[:starting_point].split(',').collect{|e|e.to_f}
ne = params[:ne].split(',').collect{|e|e.to_f}
sw = params[:sw].split(',').collect{|e|e.to_f}
size = params[:size].split(',').collect{|e|e.to_f}
address = params[:address]
@markers = retrieve_points(ne,sw,size,false)
@map = initialize_map([[sw[0],sw[1]],[ne[0],ne[1]]],[starting_point[0],starting_point[1]],false,@markers,true)
@address_string = address
end
</code></pre>
|
[
{
"answer_id": 130821,
"author": "Ian Terrell",
"author_id": 9269,
"author_profile": "https://Stackoverflow.com/users/9269",
"pm_score": 8,
"selected": true,
"text": "Maps Maps::driving_directions class MapController < ApplicationController params"
},
{
"answer_id": 136426,
"author": "Alan",
"author_id": 17205,
"author_profile": "https://Stackoverflow.com/users/17205",
"pm_score": 0,
"selected": false,
"text": "model lib model model"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1486/"
] |
128,463
|
<p>I am looking for a method to place some text onto the clipboard with <a href="http://en.wikipedia.org/wiki/VBScript" rel="noreferrer">VBScript</a>. The VBScript in question will be deployed as part of our login script. I would like to avoid using anything that isn't available on a clean Windows XP system.</p>
<p><strong>Edit:</strong>
In answer to the questions about what this is for.</p>
<p>We wanted to encourage users inside our organization to use the file server to transfer documents instead of constantly sending attachments by email. One of the biggest barriers to this is that it isn't always obvious to people what the correct network path is to a file/folder. We developed a quick script, and attached it to the Windows context menu so that a user can right click on any file/folder, and get a URL that they can email to someone within our organization.</p>
<p>I want the URL displayed in the dialog box to also be placed onto the clipboard.</p>
<p><a href="http://francyci.googlepages.com/getnetworkpath" rel="noreferrer">GetNetworkPath</a></p>
|
[
{
"answer_id": 128482,
"author": "Zoredache",
"author_id": 20267,
"author_profile": "https://Stackoverflow.com/users/20267",
"pm_score": 4,
"selected": false,
"text": "Set objIE = CreateObject(\"InternetExplorer.Application\")\nobjIE.Navigate(\"about:blank\")\nobjIE.document.parentwindow.clipboardData.SetData \"text\", \"Hello This Is A Test\"\nobjIE.Quit\n"
},
{
"answer_id": 137065,
"author": "Zoredache",
"author_id": 20267,
"author_profile": "https://Stackoverflow.com/users/20267",
"pm_score": 5,
"selected": false,
"text": "Set WshShell = WScript.CreateObject(\"WScript.Shell\")\nWshShell.Run \"cmd.exe /c echo hello world | clip\", 0, TRUE\n Dim string\nString = \"text here\" &chr(13)& \"more text here\"\nSet WshShell = WScript.CreateObject(\"WScript.Shell\")\nWshShell.Run \"cmd.exe /c echo \" & String & \" | clip\", 0, TRUE\n"
},
{
"answer_id": 140800,
"author": "unrealtrip",
"author_id": 11130,
"author_profile": "https://Stackoverflow.com/users/11130",
"pm_score": 3,
"selected": false,
"text": "' Set what you want to put in the clipboard '\nstrMessage = \"Imagine that, it works!\"\n\n' Declare an object for the word application '\nSet objWord = CreateObject(\"Word.Application\")\n\n' Using the object '\nWith objWord\n .Visible = False ' Don't show word '\n .Documents.Add ' Create a document '\n .Selection.TypeText strMessage ' Put text into it '\n .Selection.WholeStory ' Select everything in the doc '\n .Selection.Copy ' Copy contents to clipboard '\n .Quit False ' Close Word, don't save ' \nEnd With\n"
},
{
"answer_id": 174725,
"author": "tloach",
"author_id": 14092,
"author_profile": "https://Stackoverflow.com/users/14092",
"pm_score": 4,
"selected": true,
"text": "'clipboard'"
},
{
"answer_id": 174739,
"author": "Jeffery Hicks",
"author_id": 25508,
"author_profile": "https://Stackoverflow.com/users/25508",
"pm_score": 0,
"selected": false,
"text": "SendKeys()"
},
{
"answer_id": 6060661,
"author": "Peter Talbot",
"author_id": 761305,
"author_profile": "https://Stackoverflow.com/users/761305",
"pm_score": 3,
"selected": false,
"text": "strA= \"some character string\"\n Set objShell = WScript.CreateObject(\"WScript.Shell\")\nobjShell.Run \"cmd /C echo . | set /p x=\" & strA & \"| c:\\clip.exe\", 2\n s = \"String: \"\"\" & strA & \"\"\" is on the clipboard.\"\nWscript.Echo s\n C:\\"
},
{
"answer_id": 8565085,
"author": "swyx",
"author_id": 1106414,
"author_profile": "https://Stackoverflow.com/users/1106414",
"pm_score": 3,
"selected": false,
"text": "'create a clipboard thing\n Dim ClipBoard\n Set Clipboard = New cClipBoard\n\n ClipBoard.Clear \n ClipBoard.Data = \"Test\"\n\nClass cClipBoard\n Private objHTML\n\n Private Sub Class_Initialize\n Set objHTML = CreateObject(\"htmlfile\")\n End Sub\n\n Public Sub Clear()\n objHTML.ParentWindow.ClipboardData.ClearData()\n End Sub\n\n Public Property Let Data(Value)\n objHTML.ParentWindow.ClipboardData.SetData \"Text\" , Value\n End Property\n\n Public Property Get Data()\n Data = objHTML.ParentWindow.ClipboardData.GetData(\"Text\")\n End Property\n\n Private Sub Class_Terminate\n Set objHTML = Nothing\n End Sub\n\nEnd Class\n ' Create scripting object\nDim WShell, lRunUninstall\nSet WShell = CreateObject(\"WScript.Shell\")\nWShell.sendkeys \"^c\"\nWScript.Sleep 250\nbWindowFound = WShell.AppActivate(\"Microsoft Excel\")\n WShell.sendkeys ClipBoard.Data\n"
},
{
"answer_id": 10610111,
"author": "klaatu",
"author_id": 1397219,
"author_profile": "https://Stackoverflow.com/users/1397219",
"pm_score": 4,
"selected": false,
"text": "Set WshShell = CreateObject(\"WScript.Shell\")\nSet oExec = WshShell.Exec(\"clip\")\nSet oIn = oExec.stdIn\noIn.WriteLine \"Something One\"\noIn.WriteLine \"Something Two\"\noIn.WriteLine \"Something Three\"\noIn.Close\n ' loop until we're finished working.\nDo While oExec.Status = 0\n WScript.Sleep 100\nLoop\n Set oIn = Nothing\nSet oExec = Nothing\n"
},
{
"answer_id": 16216602,
"author": "Srikanth P",
"author_id": 2320060,
"author_profile": "https://Stackoverflow.com/users/2320060",
"pm_score": 2,
"selected": false,
"text": "function CopyText(sTxt) {\n var oIe = WScript.CreateObject('InternetExplorer.Application');\n oIe.silent = true;\n oIe.Navigate('about:blank');\n while(oIe.ReadyState!=4) WScript.Sleep(20);\n while(oIe.document.readyState!='complete') WSript.Sleep(20);\n oIe.document.body.innerHTML = \"<textarea id=txtArea wrap=off></textarea>\";\n var oTb = oIe.document.getElementById('txtArea');\n oTb.value = sTxt;\n oTb.select();\n oTb = null;\n oIe.ExecWB(12,0);\n oIe.Quit();\n oIe = null;\n}\n"
},
{
"answer_id": 19297281,
"author": "Nive Auverleih",
"author_id": 2867274,
"author_profile": "https://Stackoverflow.com/users/2867274",
"pm_score": 2,
"selected": false,
"text": "function SetClipBoard(sTxt)\n Set oIe = WScript.CreateObject(\"InternetExplorer.Application\")\n oIe.silent = true\n oIe.Navigate(\"about:blank\")\n do while oIe.ReadyState <> 4\n WScript.Sleep 20\n loop\n\n do while oIe.document.readyState <> \"complete\"\n WScript.Sleep 20\n loop\n\n oIe.document.body.innerHTML = \"<textarea id=txtArea wrap=off></textarea>\"\n set oTb = oIe.document.getElementById(\"txtArea\")\n oTb.value = sTxt\n oTb.select\n set oTb = nothing\n oIe.ExecWB 12,0\n oIe.Quit\n Set oIe = nothing\nEnd function\n\n\nfunction GetClipBoard()\n set oIe = WScript.CreateObject(\"InternetExplorer.Application\")\n oIe.silent = true\n oIe.Navigate(\"about:blank\")\n do while oIe.ReadyState <> 4\n WScript.Sleep 20\n loop\n\n do while oIe.document.readyState <> \"complete\"\n WScript.Sleep 20\n loop \n\n oIe.document.body.innerHTML = \"<textarea id=txtArea wrap=off></textarea>\"\n set oTb = oIe.document.getElementById(\"txtArea\")\n oTb.focus \n oIe.ExecWB 13,0\n GetClipBoard = oTb.value\n oTb.select\n set oTb = nothing\n oIe.Quit\n Set oIe = nothing\nEnd function\n"
},
{
"answer_id": 25765888,
"author": "Alkis",
"author_id": 3310466,
"author_profile": "https://Stackoverflow.com/users/3310466",
"pm_score": 1,
"selected": false,
"text": "ClipBoard Clipboard"
},
{
"answer_id": 27541807,
"author": "n3rd4i",
"author_id": 2692448,
"author_profile": "https://Stackoverflow.com/users/2692448",
"pm_score": 2,
"selected": false,
"text": "Function CopyToClipboard( sInputString )\n\n Dim oShell: Set oShell = CreateObject(\"WScript.Shell\")\n Dim sTempFolder: sTempFolder = oShell.ExpandEnvironmentStrings(\"%TEMP%\")\n Dim sFullFilePath: sFullFilePath = sTempFolder & \"\\\" & \"temp_file.txt\"\n\n Const iForWriting = 2, bCreateFile = True\n Dim oFSO: Set oFSO = CreateObject(\"Scripting.FileSystemObject\")\n With oFSO.OpenTextFile(sFullFilePath, iForWriting, bCreateFile)\n .Write sInputString\n .Close\n End With\n\n Const iHideWindow = 0, bWaitOnReturnTrue = True\n Dim sCommand: sCommand = \"CMD /C TYPE \" & sFullFilePath & \"|CLIP\"\n oShell.Run sCommand, iHideWindow, bWaitOnReturnTrue\n\n Set oShell = Nothing\n Set oFSO = Nothing\n\nEnd Function\n\nSub Main\n\n Call CopyToClipboard( \"Text1\" & vbNewLine & \"Text2\" )\n\nEnd Sub\n\nCall Main\n"
},
{
"answer_id": 36991258,
"author": "omegastripes",
"author_id": 2165759,
"author_profile": "https://Stackoverflow.com/users/2165759",
"pm_score": 2,
"selected": false,
"text": "mshta.exe sText = \"Text Content\"\nCreateObject(\"WScript.Shell\").Run \"mshta.exe \"\"javascript:clipboardData.setData('text','\" & Replace(Replace(sText, \"\\\", \"\\\\\"), \"'\", \"\\'\") & \"');close();\"\"\", 0, True\n \" sText = \"Text Content and double quote \"\" char\"\nCreateObject(\"WScript.Shell\").Run \"mshta.exe \"\"javascript:clipboardData.setData('text','\" & Replace(Replace(Replace(sText, \"\\\", \"\\\\\"), \"\"\"\", \"\"\"\"\"\"), \"'\", \"\\'\") & \"'.replace('\"\"\"\"',String.fromCharCode(34)));close();\"\"\", 0, True\n"
},
{
"answer_id": 45906330,
"author": "cmoiquoi",
"author_id": 8523775,
"author_profile": "https://Stackoverflow.com/users/8523775",
"pm_score": 0,
"selected": false,
"text": "' value to put in Clipboard\nmavaleur = \"YEAH\"\n\n' current Dir\npath = WScript.ScriptFullName\nGetPath = Left(path, InStrRev(path, \"\\\"))\n\n' Put the value in a file\nSet objFSO=CreateObject(\"Scripting.FileSystemObject\")\noutFile=GetPath & \"fichier.valeur\"\nSet objFile = objFSO.CreateTextFile(outFile,True)\nobjFile.Write mavaleur\nobjFile.Close\n\n' Put the file in the Clipboard\nSet WshShell = WScript.CreateObject(\"WScript.Shell\")\nWshShell.Run \"cmd.exe /c clip < \" & outFile, 0, TRUE\n\n' Erase the file\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\nobjFSO.DeleteFile outFile\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20267/"
] |
128,466
|
<p>Should I try to actually upgrade my existing app, or just rewrite it mostly from scratch, saving what pieces (templates, etc) I can?</p>
|
[
{
"answer_id": 128483,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "__str__() __unicode__() admin.py"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8002/"
] |
128,478
|
<p><a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP 8</a> states:</p>
<blockquote>
<p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p>
</blockquote>
<p>However if the class/method/function that I am importing is only used in rare cases, surely it is more efficient to do the import when it is needed?</p>
<p>Isn't this:</p>
<pre><code>class SomeClass(object):
def not_often_called(self)
from datetime import datetime
self.datetime = datetime.now()
</code></pre>
<p>more efficient than this?</p>
<pre><code>from datetime import datetime
class SomeClass(object):
def not_often_called(self)
self.datetime = datetime.now()
</code></pre>
|
[
{
"answer_id": 128525,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 3,
"selected": false,
"text": "do_something_with_x(x)\n from pprint import pprint\npprint(x)\ndo_something_with_x(x)\n"
},
{
"answer_id": 128532,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 6,
"selected": false,
"text": "if __name__ == '__main__':\n import foo\n aa = foo.xyz() # initiate something for the test\n if [condition]:\n import foo as plugin_api\nelse:\n import bar as plugin_api\nxx = plugin_api.Plugin()\n[...]\n"
},
{
"answer_id": 128549,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 3,
"selected": false,
"text": "__import__ ImportError"
},
{
"answer_id": 128577,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 10,
"selected": true,
"text": "__init__.py bzrlib"
},
{
"answer_id": 128641,
"author": "giltay",
"author_id": 21106,
"author_profile": "https://Stackoverflow.com/users/21106",
"pm_score": 3,
"selected": false,
"text": "import os\n# ...\ntry:\n kill = os.kill # will raise AttributeError on Windows\n from signal import SIGTERM\n def terminate(process):\n kill(process.pid, SIGTERM)\nexcept (AttributeError, ImportError):\n try:\n from win32api import TerminateProcess # use win32api if available\n def terminate(process):\n TerminateProcess(int(process._handle), -1)\n except ImportError:\n def terminate(process):\n raise NotImplementedError # define a dummy function\n"
},
{
"answer_id": 128655,
"author": "Drew Stephens",
"author_id": 17339,
"author_profile": "https://Stackoverflow.com/users/17339",
"pm_score": 3,
"selected": false,
"text": "from foo import bar\nfrom baz import qux\n# Note: datetime is imported in SomeClass below\n"
},
{
"answer_id": 128859,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "sys if __name__=='__main__' sys.argv[1:] main() main sys"
},
{
"answer_id": 17407169,
"author": "Caumons",
"author_id": 955619,
"author_profile": "https://Stackoverflow.com/users/955619",
"pm_score": 2,
"selected": false,
"text": "a.py b.py x() y() from imports from imports from imports import a"
},
{
"answer_id": 50282333,
"author": "TextGeek",
"author_id": 266371,
"author_profile": "https://Stackoverflow.com/users/266371",
"pm_score": 3,
"selected": false,
"text": " 0 foo: 14429.0924 µs\n 1 foo: 63.8962 µs\n 2 foo: 10.0136 µs\n 3 foo: 7.1526 µs\n 4 foo: 7.8678 µs\n 0 bar: 9.0599 µs\n 1 bar: 6.9141 µs\n 2 bar: 7.1526 µs\n 3 bar: 7.8678 µs\n 4 bar: 7.1526 µs\n from __future__ import print_function\nfrom time import time\n\ndef foo():\n import collections\n import re\n import string\n import math\n import subprocess\n return\n\ndef bar():\n import collections\n import re\n import string\n import math\n import subprocess\n return\n\nt0 = time()\nfor i in xrange(5):\n foo()\n t1 = time()\n print(\" %2d foo: %12.4f \\xC2\\xB5s\" % (i, (t1-t0)*1E6))\n t0 = t1\nfor i in xrange(5):\n bar()\n t1 = time()\n print(\" %2d bar: %12.4f \\xC2\\xB5s\" % (i, (t1-t0)*1E6))\n t0 = t1\n"
},
{
"answer_id": 53168846,
"author": "quiet_penguin",
"author_id": 1086143,
"author_profile": "https://Stackoverflow.com/users/1086143",
"pm_score": 1,
"selected": false,
"text": "X=10\nY=11\nZ=12\ndef add(i):\n i = i + 10\n from test import add, X, Y, Z\n\n def callme():\n x=X\n y=Y\n z=Z\n ladd=add \n for i in range(100000000):\n ladd(i)\n x+y+z\n\n callme()\n from test import add, X, Y, Z\n\ndef callme():\n for i in range(100000000):\n add(i)\n X+Y+Z\n\ncallme()\n /usr/bin/time -f \"\\t%E real,\\t%U user,\\t%S sys\" python run.py \n 0:17.80 real, 17.77 user, 0.01 sys\n/tmp/test$ /usr/bin/time -f \"\\t%E real,\\t%U user,\\t%S sys\" python runlocal.py \n 0:14.23 real, 14.22 user, 0.01 sys\n"
},
{
"answer_id": 57953097,
"author": "LJHW",
"author_id": 8502603,
"author_profile": "https://Stackoverflow.com/users/8502603",
"pm_score": 0,
"selected": false,
"text": "django.setup() django.setup()"
},
{
"answer_id": 59812974,
"author": "WinEunuuchs2Unix",
"author_id": 6929343,
"author_profile": "https://Stackoverflow.com/users/6929343",
"pm_score": 2,
"selected": false,
"text": "import listdata.append(['tk font version', font_version])\nlistdata.append(['Gtk version', str(Gtk.get_major_version())+\".\"+\n str(Gtk.get_minor_version())+\".\"+\n str(Gtk.get_micro_version())])\n\nimport xml.etree.ElementTree as ET\n\nxmltree = ET.parse('/usr/share/gnome/gnome-version.xml')\nxmlroot = xmltree.getroot()\nresult = []\nfor child in xmlroot:\n result.append(child.text)\nlistdata.append(['Gnome version', result[0]+\".\"+result[1]+\".\"+\n result[2]+\" \"+result[3]])\n import ET import import"
},
{
"answer_id": 69928434,
"author": "Patrick",
"author_id": 38281,
"author_profile": "https://Stackoverflow.com/users/38281",
"pm_score": 3,
"selected": false,
"text": "ImportError __name__ == \"__main__\""
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15676/"
] |
128,502
|
<p>I've just updated my ruby installation on my gentoo server to ruby 1.8.6 patchlevel 287 and have started getting an error on one of my eRuby apps. The error given in the apache error_log file is:</p>
<pre><code>[error] mod_ruby: /usr/lib/ruby/1.8/cgi.rb:774: superclass mismatch for class Cookie (TypeError)
</code></pre>
<p>The strange thing is that it seems to work sometimes - but other times I get that error. Anyone any ideas?</p>
|
[
{
"answer_id": 211049,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 3,
"selected": false,
"text": "class Cookie\nend\n % irb\nirb(main):001:0> class C < String; end\n=> nil\nirb(main):002:0> class C; end\n=> nil\nirb(main):003:0> exit\n% irb\nirb(main):001:0> class C; end\n=> nil\nirb(main):002:0> class C < String; end\nTypeError: superclass mismatch for class C\n from (irb):2\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1912/"
] |
128,512
|
<p>If I have a subclass that has yet to implement a function provided by the base class, I can override that function and have it throw a <code>NotSupportedException</code>. Is there a way to generate a compile-time error for this to avoid only hitting this at runtime?</p>
<p>Update: I can't make the base class abstract.</p>
|
[
{
"answer_id": 128528,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": 2,
"selected": false,
"text": "abstract class Foo\n{\n public abstract void Bar();\n}\n Bar()"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815/"
] |
128,527
|
<p>We have our JBoss and Oracle on separate servers. The connections seem to be dropped and is causing issues with JBoss. How can I have the JBoss reconnect to Oracle if the connection is bad while we figure out why the connections are being dropped in the first place?</p>
|
[
{
"answer_id": 129333,
"author": "Steve K",
"author_id": 739,
"author_profile": "https://Stackoverflow.com/users/739",
"pm_score": 6,
"selected": true,
"text": "<check-valid-connection-sql>select 1 from dual</check-valid-connection-sql>\n"
},
{
"answer_id": 145889,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 5,
"selected": false,
"text": "<valid-connection-checker-class-name>\n org.jboss.resource.adapter.jdbc.vendor.OracleValidConnectionChecker\n</valid-connection-checker-class-name>\n background-validation-millis"
},
{
"answer_id": 11164723,
"author": "arviarya",
"author_id": 409410,
"author_profile": "https://Stackoverflow.com/users/409410",
"pm_score": 3,
"selected": false,
"text": "<background-validation>true</background-validation> <background-validation-minutes>1</background-validation-minutes>\n org.jboss.resource.adapter.jdbc.ValidConnectionChecker isValidConnection() public class OracleValidConnectionChecker implements ValidConnectionChecker, Serializable {\n\n private Method ping;\n\n // The timeout (apparently the timeout is ignored?)\n private static Object[] params = new Object[] { new Integer(5000) };\n\n public SQLException isValidConnection(Connection c) {\n\n try {\n Integer status = (Integer) ping.invoke(c, params);\n\n if (status.intValue() < 0) {\n return new SQLException(\"pingDatabase failed status=\" + status);\n }\n\n }\n catch (Exception e) {\n log.warn(\"Unexpected error in pingDatabase\", e);\n }\n\n // OK\n return null;\n }\n}\n"
},
{
"answer_id": 24332194,
"author": "abh",
"author_id": 311003,
"author_profile": "https://Stackoverflow.com/users/311003",
"pm_score": 3,
"selected": false,
"text": "'Select 1 from dual' org.jboss.resource.adapter.jdbc.vendor.OracleValidConnectionChecker 'Select 'x' from dual'"
},
{
"answer_id": 27361193,
"author": "Jakub Godoniuk",
"author_id": 995623,
"author_profile": "https://Stackoverflow.com/users/995623",
"pm_score": 2,
"selected": false,
"text": "<valid-connection-checker class-name=\"org.jboss.jca.adapters.jdbc.extensions.oracle.OracleValidConnectionChecker\" />"
},
{
"answer_id": 32844258,
"author": "Vadzim",
"author_id": 603516,
"author_profile": "https://Stackoverflow.com/users/603516",
"pm_score": 2,
"selected": false,
"text": "DBMS_LOCK <check-valid-connection-sql>select case when 30/60/24 > sysdate-LOGON_TIME then 1 else 1/0 end \nfrom V$SESSION where AUDSID = userenv('SESSIONID')</check-valid-connection-sql>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6013/"
] |
128,537
|
<p>How do I make an asynchronous call to a web service using the <code>PHP SOAP Extension</code>?</p>
|
[
{
"answer_id": 19150921,
"author": "quickshiftin",
"author_id": 680920,
"author_profile": "https://Stackoverflow.com/users/680920",
"pm_score": 1,
"selected": false,
"text": "class NonBlockingSoapServer extends SoapServer\n{\n public function handle()\n {\n // this script can run forever\n set_time_limit(0);\n\n // tell the client the request has finished processing\n header('Location: index.php'); // redirect (optional)\n header('Status: 200'); // status code\n header('Connection: close'); // disconnect\n\n // clear ob stack \n @ob_end_clean();\n\n // continue processing once client disconnects\n ignore_user_abort();\n\n ob_start();\n /* ------------------------------------------*/\n /* this is where regular request code goes.. */\n $result = parent::handle();\n /* end where regular request code runs.. */\n /* ------------------------------------------*/\n $iSize = ob_get_length();\n header(\"Content-Length: $iSize\");\n\n // if the session needs to be closed, persist it\n // before closing the connection to avoid race\n // conditions in the case of a redirect above\n session_write_close();\n\n // send the response payload to the client\n @ob_end_flush();\n flush();\n\n /* ------------------------------------------*/\n /* code here runs after the client diconnect */\n /* YOUR ASYNC CODE HERE ...... */\n\n return $result;\n }\n}\n"
},
{
"answer_id": 20262679,
"author": "user3045279",
"author_id": 3045279,
"author_profile": "https://Stackoverflow.com/users/3045279",
"pm_score": 1,
"selected": false,
"text": "select() SoapClient __doRequest $client1 = new SoapClientAsync('some-systems-wsdl', $options);\n$client2 = new SoapClientAsync('another-systems-wsdl', $options);\n$client1->someFunction($arguments);\n$client2->anotherFunction($arguments);\nsoap_dispatch();\n$result1 = $client1->someFunction($arguments);\n$result2 = $client1->anotherFunction($arguments);\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
128,560
|
<p>When is it a good idea to use <a href="http://us3.php.net/manual/en/reserved.constants.php" rel="noreferrer"><code>PHP_EOL</code></a>?</p>
<p>I sometimes see this in code samples of PHP. Does this handle DOS/Mac/Unix endline issues?</p>
|
[
{
"answer_id": 128564,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 10,
"selected": true,
"text": "PHP_EOL"
},
{
"answer_id": 129370,
"author": "Zoredache",
"author_id": 20267,
"author_profile": "https://Stackoverflow.com/users/20267",
"pm_score": 6,
"selected": false,
"text": "PHP_EOL <br /> PHP_EOL"
},
{
"answer_id": 2854211,
"author": "Allan",
"author_id": 343610,
"author_profile": "https://Stackoverflow.com/users/343610",
"pm_score": 0,
"selected": false,
"text": "$csv_output .= \"\\n\"; $csv_output .= \"n\";"
},
{
"answer_id": 3853511,
"author": "ip bastola",
"author_id": 453444,
"author_profile": "https://Stackoverflow.com/users/453444",
"pm_score": 3,
"selected": false,
"text": "<?php\n\n$output = 'This is line 1' . PHP_EOL .\n 'This is line 2' . PHP_EOL .\n 'This is line 3';\n\n$file = \"filename.txt\";\n\nif (is_writable($file)) {\n // In our example we're opening $file in append mode.\n // The file pointer is at the bottom of the file hence\n // that's where $output will go when we fwrite() it.\n if (!$handle = fopen($file, 'a')) {\n echo \"Cannot open file ($file)\";\n exit;\n }\n // Write $output to our opened file.\n if (fwrite($handle, $output) === FALSE) {\n echo \"Cannot write to file ($file)\";\n exit;\n }\n echo \"Success, content ($output) wrote to file ($file)\";\n fclose($handle);\n} else {\n echo \"The file $file is not writable\";\n}\n?>\n"
},
{
"answer_id": 4943980,
"author": "SjH",
"author_id": 609611,
"author_profile": "https://Stackoverflow.com/users/609611",
"pm_score": 2,
"selected": false,
"text": "echo 'A $variable_literal that I have'.PHP_EOL.'looks better than'.PHP_EOL; \necho 'this other $one'.\"\\n\";\n"
},
{
"answer_id": 6666554,
"author": "AlexV",
"author_id": 239801,
"author_profile": "https://Stackoverflow.com/users/239801",
"pm_score": 7,
"selected": false,
"text": "main/php.h #ifdef PHP_WIN32\n# include \"tsrm_win32.h\"\n# include \"win95nt.h\"\n# ifdef PHP_EXPORTS\n# define PHPAPI __declspec(dllexport)\n# else\n# define PHPAPI __declspec(dllimport)\n# endif\n# define PHP_DIR_SEPARATOR '\\\\'\n# define PHP_EOL \"\\r\\n\"\n#else\n# if defined(__GNUC__) && __GNUC__ >= 4\n# define PHPAPI __attribute__ ((visibility(\"default\")))\n# else\n# define PHPAPI\n# endif\n# define THREAD_LS\n# define PHP_DIR_SEPARATOR '/'\n# define PHP_EOL \"\\n\"\n#endif\n PHP_EOL \"\\r\\n\" \"\\n\" PHP_EOL \"\\r\" PHP_EOL PHP_EOL"
},
{
"answer_id": 14196620,
"author": "Salman A",
"author_id": 87015,
"author_profile": "https://Stackoverflow.com/users/87015",
"pm_score": 5,
"selected": false,
"text": "\\r\\n \\r\\n"
},
{
"answer_id": 15384593,
"author": "Vasu_Sharma",
"author_id": 1796184,
"author_profile": "https://Stackoverflow.com/users/1796184",
"pm_score": 1,
"selected": false,
"text": "echo 'A $variable_literal that I have'.PHP_EOL.'looks better than'.PHP_EOL; \necho 'this other $one'.\"\\n\";\n"
},
{
"answer_id": 16563688,
"author": "Iain Collins",
"author_id": 28884,
"author_profile": "https://Stackoverflow.com/users/28884",
"pm_score": 4,
"selected": false,
"text": "<textarea> <pre> <code> \\n PHP_EOL \\r"
},
{
"answer_id": 55086172,
"author": "Alessandro",
"author_id": 3584233,
"author_profile": "https://Stackoverflow.com/users/3584233",
"pm_score": 0,
"selected": false,
"text": "<?php\n if (!defined('PHP_EOL')) {\n if (strtoupper(substr(PHP_OS,0,3) == 'WIN')) {\n define('PHP_EOL',\"\\r\\n\");\n } elseif (strtoupper(substr(PHP_OS,0,3) == 'MAC')) {\n define('PHP_EOL',\"\\r\");\n } elseif (strtoupper(substr(PHP_OS,0,3) == 'DAR')) {\n define('PHP_EOL',\"\\n\");\n } else {\n define('PHP_EOL',\"\\n\");\n }\n }\n?>\n 1) on Unix LN == \\n\n2) on Mac CR == \\r\n3) on Windows CR+LN == \\r\\n\n"
},
{
"answer_id": 71810083,
"author": "DaCuteRaccoon",
"author_id": 17585064,
"author_profile": "https://Stackoverflow.com/users/17585064",
"pm_score": -1,
"selected": false,
"text": "PHP_EOL <?php\necho $n = PHP_EOL;\n?>\n $n PHP_EOL <br> $n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3757/"
] |
128,561
|
<p>I have a new application written in WPF that needs to support an old API that allows it to receive a message that has been posted to a hidden window. Typically another application uses FindWindow to identify the hidden window using the name of its custom window class.</p>
<p><strong>1) I assume to implement a custom window class I need to use old school win32 calls?</strong></p>
<p>My old c++ application used RegisterClass and CreateWindow to make the simplest possible invisible window.</p>
<p>I believe I should be able to do the same all within c#. I don't want my project to have to compile any unmanaged code.</p>
<p>I have tried inheriting from System.Windows.Interop.HwndHost and using System.Runtime.InteropServices.DllImport to pull in the above API methods.</p>
<p>Doing this I can successfully host a standard win32 window e.g. "listbox" inside WPF.
However when I call CreateWindowEx for my custom window it always returns null.</p>
<p>My call to RegisterClass succeeds but I am not sure what I should be setting the
WNDCLASS.lpfnWndProc member to.</p>
<p><strong>2) Does anyone know how to do this successfully?</strong></p>
|
[
{
"answer_id": 128622,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 0,
"selected": false,
"text": "protected override void WndProc(ref System.Windows.Forms.Message m)\n{\n // *always* let the base class process the message\n base.WndProc(ref m);\n\n const int WM_NCHITTEST = 0x84;\n const int HTCAPTION = 2;\n const int HTCLIENT = 1;\n\n // if Windows is querying where the mouse is and the base form class said\n // it's on the client area, let's cheat and say it's on the title bar instead\n if ( m.Msg == WM_NCHITTEST && m.Result.ToInt32() == HTCLIENT )\n m.Result = new IntPtr(HTCAPTION);\n}\n"
},
{
"answer_id": 138468,
"author": "morechilli",
"author_id": 5427,
"author_profile": "https://Stackoverflow.com/users/5427",
"pm_score": 6,
"selected": true,
"text": "class CustomWindow : IDisposable\n{\n delegate IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);\n\n [System.Runtime.InteropServices.StructLayout(\n System.Runtime.InteropServices.LayoutKind.Sequential,\n CharSet = System.Runtime.InteropServices.CharSet.Unicode\n )]\n struct WNDCLASS\n {\n public uint style;\n public IntPtr lpfnWndProc;\n public int cbClsExtra;\n public int cbWndExtra;\n public IntPtr hInstance;\n public IntPtr hIcon;\n public IntPtr hCursor;\n public IntPtr hbrBackground;\n [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]\n public string lpszMenuName;\n [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]\n public string lpszClassName;\n }\n\n [System.Runtime.InteropServices.DllImport(\"user32.dll\", SetLastError = true)]\n static extern System.UInt16 RegisterClassW(\n [System.Runtime.InteropServices.In] ref WNDCLASS lpWndClass\n );\n\n [System.Runtime.InteropServices.DllImport(\"user32.dll\", SetLastError = true)]\n static extern IntPtr CreateWindowExW(\n UInt32 dwExStyle,\n [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]\n string lpClassName,\n [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]\n string lpWindowName,\n UInt32 dwStyle,\n Int32 x,\n Int32 y,\n Int32 nWidth,\n Int32 nHeight,\n IntPtr hWndParent,\n IntPtr hMenu,\n IntPtr hInstance,\n IntPtr lpParam\n );\n\n [System.Runtime.InteropServices.DllImport(\"user32.dll\", SetLastError = true)]\n static extern System.IntPtr DefWindowProcW(\n IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam\n );\n\n [System.Runtime.InteropServices.DllImport(\"user32.dll\", SetLastError = true)]\n static extern bool DestroyWindow(\n IntPtr hWnd\n );\n\n private const int ERROR_CLASS_ALREADY_EXISTS = 1410;\n\n private bool m_disposed;\n private IntPtr m_hwnd;\n\n public void Dispose() \n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n private void Dispose(bool disposing) \n {\n if (!m_disposed) {\n if (disposing) {\n // Dispose managed resources\n }\n\n // Dispose unmanaged resources\n if (m_hwnd != IntPtr.Zero) {\n DestroyWindow(m_hwnd);\n m_hwnd = IntPtr.Zero;\n }\n\n }\n }\n\n public CustomWindow(string class_name){\n\n if (class_name == null) throw new System.Exception(\"class_name is null\");\n if (class_name == String.Empty) throw new System.Exception(\"class_name is empty\");\n\n m_wnd_proc_delegate = CustomWndProc;\n\n // Create WNDCLASS\n WNDCLASS wind_class = new WNDCLASS();\n wind_class.lpszClassName = class_name;\n wind_class.lpfnWndProc = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(m_wnd_proc_delegate);\n\n UInt16 class_atom = RegisterClassW(ref wind_class);\n\n int last_error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();\n\n if (class_atom == 0 && last_error != ERROR_CLASS_ALREADY_EXISTS) {\n throw new System.Exception(\"Could not register window class\");\n }\n\n // Create window\n m_hwnd = CreateWindowExW(\n 0,\n class_name,\n String.Empty,\n 0,\n 0,\n 0,\n 0,\n 0,\n IntPtr.Zero,\n IntPtr.Zero,\n IntPtr.Zero,\n IntPtr.Zero\n );\n }\n\n private static IntPtr CustomWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) \n {\n return DefWindowProcW(hWnd, msg, wParam, lParam);\n }\n\n private WndProc m_wnd_proc_delegate;\n}\n"
},
{
"answer_id": 18056924,
"author": "Martini Bianco",
"author_id": 2062574,
"author_profile": "https://Stackoverflow.com/users/2062574",
"pm_score": 1,
"selected": false,
"text": "public CustomWindow(string class_name){\n\n if (class_name == null) throw new System.Exception(\"class_name is null\");\n if (class_name == String.Empty) throw new System.Exception(\"class_name is empty\");\n\n // Create WNDCLASS\n WNDCLASS wind_class = new WNDCLASS();\n wind_class.lpszClassName = class_name;\n wind_class.lpfnWndProc = CustomWndProc;\n\n UInt16 class_atom = RegisterClassW(ref wind_class);\n\n int last_error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();\n\n if (class_atom == 0 && last_error != ERROR_CLASS_ALREADY_EXISTS) {\n throw new System.Exception(\"Could not register window class\");\n }\n\n // Create window\n m_hwnd = CreateWindowExW(\n 0,\n class_name,\n String.Empty,\n 0,\n 0,\n 0,\n 0,\n 0,\n IntPtr.Zero,\n IntPtr.Zero,\n IntPtr.Zero,\n IntPtr.Zero\n );\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5427/"
] |
128,573
|
<p>I have a class with two class methods (using the <code>classmethod()</code> function) for getting and setting what is essentially a static variable. I tried to use the <code>property()</code> function with these, but it results in an error. I was able to reproduce the error with the following in the interpreter:</p>
<pre><code>class Foo(object):
_var = 5
@classmethod
def getvar(cls):
return cls._var
@classmethod
def setvar(cls, value):
cls._var = value
var = property(getvar, setvar)
</code></pre>
<p>I can demonstrate the class methods, but they don't work as properties:</p>
<pre><code>>>> f = Foo()
>>> f.getvar()
5
>>> f.setvar(4)
>>> f.getvar()
4
>>> f.var
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
>>> f.var=5
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
</code></pre>
<p>Is it possible to use the <code>property()</code> function with <code>@classmethod</code> decorated functions?</p>
|
[
{
"answer_id": 128812,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 2,
"selected": false,
"text": "class ClassProperty(object):\n def __init__(self, fget, fset):\n self.fget = fget\n self.fset = fset\n\n def __get__(self, instance, owner):\n return self.fget()\n\n def __set__(self, instance, value):\n self.fset(value)\n\nclass Foo(object):\n _bar = 1\n def get_bar():\n print 'getting'\n return Foo._bar\n\n def set_bar(value):\n print 'setting'\n Foo._bar = value\n\n bar = ClassProperty(get_bar, set_bar)\n\nf = Foo()\n#__get__ works\nf.bar\nFoo.bar\n\nf.bar = 2\nFoo.bar = 3 #__set__ does not\n"
},
{
"answer_id": 129819,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 4,
"selected": false,
"text": "class ClassProperty(object):\n def __init__(self, getter, setter):\n self.getter = getter\n self.setter = setter\n def __get__(self, cls, owner):\n return getattr(cls, self.getter)()\n def __set__(self, cls, value):\n getattr(cls, self.setter)(value)\n\nclass MetaFoo(type):\n var = ClassProperty('getvar', 'setvar')\n\nclass Foo(object):\n __metaclass__ = MetaFoo\n _var = 5\n @classmethod\n def getvar(cls):\n print \"Getting var =\", cls._var\n return cls._var\n @classmethod\n def setvar(cls, value):\n print \"Setting var =\", value\n cls._var = value\n\nx = Foo.var\nprint \"Foo.var = \", x\nFoo.var = 42\nx = Foo.var\nprint \"Foo.var = \", x\n"
},
{
"answer_id": 129868,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "class MyClass (object):\n __var = None\n\n def _set_var (self, value):\n type (self).__var = value\n\n def _get_var (self):\n return self.__var\n\n var = property (_get_var, _set_var)\n\na = MyClass ()\nb = MyClass ()\na.var = \"foo\"\nprint b.var\n"
},
{
"answer_id": 130090,
"author": "Sufian",
"author_id": 9241,
"author_profile": "https://Stackoverflow.com/users/9241",
"pm_score": 2,
"selected": false,
"text": ">>> class foo(object):\n... _var = 5\n... def getvar(cls):\n... return cls._var\n... getvar = classmethod(getvar)\n... def setvar(cls, value):\n... cls._var = value\n... setvar = classmethod(setvar)\n... var = property(lambda self: self.getvar(), lambda self, val: self.setvar(val))\n...\n>>> f = foo()\n>>> f.var\n5\n>>> f.var = 3\n>>> f.var\n3\n property callable"
},
{
"answer_id": 1383402,
"author": "Jason R. Coombs",
"author_id": 70170,
"author_profile": "https://Stackoverflow.com/users/70170",
"pm_score": 6,
"selected": false,
"text": "class ClassProperty(property):\n def __get__(self, cls, owner):\n return self.fget.__get__(None, owner)()\n\nclass foo(object):\n _var=5\n def getvar(cls):\n return cls._var\n getvar=classmethod(getvar)\n def setvar(cls,value):\n cls._var=value\n setvar=classmethod(setvar)\n var=ClassProperty(getvar,setvar)\n\nassert foo.getvar() == 5\nfoo.setvar(4)\nassert foo.getvar() == 4\nassert foo.var == 4\nfoo.var = 3\nassert foo.var == 3\n foo.var = 4\nassert foo.var == foo._var # raises AssertionError\n foo._var ClassProperty class foo(object):\n _var = 5\n\n @ClassProperty\n @classmethod\n def var(cls):\n return cls._var\n\n @var.setter\n @classmethod\n def var(cls, value):\n cls._var = value\n\nassert foo.var == 5\n"
},
{
"answer_id": 1800999,
"author": "A. Coady",
"author_id": 36433,
"author_profile": "https://Stackoverflow.com/users/36433",
"pm_score": 7,
"selected": false,
"text": "classmethod >>> class foo(object):\n... _var = 5\n... class __metaclass__(type): # Python 2 syntax for metaclasses\n... pass\n... @classmethod\n... def getvar(cls):\n... return cls._var\n... @classmethod\n... def setvar(cls, value):\n... cls._var = value\n... \n>>> foo.__metaclass__.var = property(foo.getvar.im_func, foo.setvar.im_func)\n>>> foo.var\n5\n>>> foo.var = 3\n>>> foo.var\n3\n >>> class foo(object):\n... _var = 5\n... class __metaclass__(type): # Python 2 syntax for metaclasses\n... @property\n... def var(cls):\n... return cls._var\n... @var.setter\n... def var(cls, value):\n... cls._var = value\n... \n>>> foo.var\n5\n>>> foo.var = 3\n>>> foo.var\n3\n metaclass=... foo _var >>> class foo_meta(type):\n... def __init__(cls, *args, **kwargs):\n... cls._var = 5\n... @property\n... def var(cls):\n... return cls._var\n... @var.setter\n... def var(cls, value):\n... cls._var = value\n...\n>>> class foo(metaclass=foo_meta):\n... pass\n...\n>>> foo.var\n5\n>>> foo.var = 3\n>>> foo.var\n3\n"
},
{
"answer_id": 2544313,
"author": "Nils Philippsen",
"author_id": 304979,
"author_profile": "https://Stackoverflow.com/users/304979",
"pm_score": 3,
"selected": false,
"text": "#!/usr/bin/python\n\nclass classproperty(property):\n def __get__(self, obj, type_):\n return self.fget.__get__(None, type_)()\n\n def __set__(self, obj, value):\n cls = type(obj)\n return self.fset.__get__(None, cls)(value)\n\nclass A (object):\n\n _foo = 1\n\n @classproperty\n @classmethod\n def foo(cls):\n return cls._foo\n\n @foo.setter\n @classmethod\n def foo(cls, value):\n cls.foo = value\n\na = A()\n\nprint a.foo\n\nb = A()\n\nprint b.foo\n\nb.foo = 5\n\nprint a.foo\n\nA.foo = 10\n\nprint b.foo\n\nprint A.foo\n"
},
{
"answer_id": 13624858,
"author": "Denis Ryzhkov",
"author_id": 350937,
"author_profile": "https://Stackoverflow.com/users/350937",
"pm_score": 6,
"selected": false,
"text": "@classproperty class classproperty(property):\n def __get__(self, owner_self, owner_cls):\n return self.fget(owner_cls)\n\nclass C(object):\n\n @classproperty\n def x(cls):\n return 1\n\nassert C.x == 1\nassert C().x == 1\n"
},
{
"answer_id": 39542816,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 6,
"selected": false,
"text": "property class Example(object):\n _class_property = None\n @property\n def class_property(self):\n return self._class_property\n @class_property.setter\n def class_property(self, value):\n type(self)._class_property = value\n @class_property.deleter\n def class_property(self):\n del type(self)._class_property\n ex1 = Example()\nex2 = Example()\nex1.class_property = None\nex2.class_property = 'Example'\nassert ex1.class_property is ex2.class_property\ndel ex2.class_property\nassert not hasattr(ex1, 'class_property')\n @classproperty classproperty property class classproperty(property):\n def __get__(self, obj, objtype=None):\n return super(classproperty, self).__get__(objtype)\n def __set__(self, obj, value):\n super(classproperty, self).__set__(type(obj), value)\n def __delete__(self, obj):\n super(classproperty, self).__delete__(type(obj))\n class Foo(object):\n _bar = 5\n @classproperty\n def bar(cls):\n \"\"\"this is the bar attribute - each subclass of Foo gets its own.\n Lookups should follow the method resolution order.\n \"\"\"\n return cls._bar\n @bar.setter\n def bar(cls, value):\n cls._bar = value\n @bar.deleter\n def bar(cls):\n del cls._bar\n def main():\n f = Foo()\n print(f.bar)\n f.bar = 4\n print(f.bar)\n del f.bar\n try:\n f.bar\n except AttributeError:\n pass\n else:\n raise RuntimeError('f.bar must have worked - inconceivable!')\n help(f) # includes the Foo.bar help.\n f.bar = 5\n\n class Bar(Foo):\n \"a subclass of Foo, nothing more\"\n help(Bar) # includes the Foo.bar help!\n b = Bar()\n b.bar = 'baz'\n print(b.bar) # prints baz\n del b.bar\n print(b.bar) # prints 5 - looked up from Foo!\n\n \nif __name__ == '__main__':\n main()\n __dict__ __dict__ class MetaWithFooClassProperty(type):\n @property\n def foo(cls):\n \"\"\"The foo property is a function of the class -\n in this case, the trivial case of the identity function.\n \"\"\"\n return cls\n class FooClassProperty(metaclass=MetaWithFooClassProperty):\n @property\n def foo(self):\n \"\"\"access the class's property\"\"\"\n return type(self).foo\n >>> FooClassProperty().foo\n<class '__main__.FooClassProperty'>\n >>> FooClassProperty.foo\n<class '__main__.FooClassProperty'>\n"
},
{
"answer_id": 44811984,
"author": "papercrane",
"author_id": 892621,
"author_profile": "https://Stackoverflow.com/users/892621",
"pm_score": 2,
"selected": false,
"text": "In [1]: class ClassPropertyMeta(type):\n ...: @property\n ...: def prop(cls):\n ...: return cls._prop\n ...: def __new__(cls, name, parents, dct):\n ...: # This makes overriding __getattr__ and __setattr__ in the class impossible, but should be fixable\n ...: dct['__getattr__'] = classmethod(lambda cls, attr: getattr(cls, attr))\n ...: dct['__setattr__'] = classmethod(lambda cls, attr, val: setattr(cls, attr, val))\n ...: return super(ClassPropertyMeta, cls).__new__(cls, name, parents, dct)\n ...:\n\nIn [2]: class ClassProperty(object):\n ...: __metaclass__ = ClassPropertyMeta\n ...: _prop = 42\n ...: def __getattr__(self, attr):\n ...: raise Exception('Never gets called')\n ...:\n\nIn [3]: ClassProperty.prop\nOut[3]: 42\n\nIn [4]: ClassProperty.prop = 1\n---------------------------------------------------------------------------\nAttributeError Traceback (most recent call last)\n<ipython-input-4-e2e8b423818a> in <module>()\n----> 1 ClassProperty.prop = 1\n\nAttributeError: can't set attribute\n\nIn [5]: cp = ClassProperty()\n\nIn [6]: cp.prop\nOut[6]: 42\n\nIn [7]: cp.prop = 1\n---------------------------------------------------------------------------\nAttributeError Traceback (most recent call last)\n<ipython-input-7-e8284a3ee950> in <module>()\n----> 1 cp.prop = 1\n\n<ipython-input-1-16b7c320d521> in <lambda>(cls, attr, val)\n 6 # This makes overriding __getattr__ and __setattr__ in the class impossible, but should be fixable\n 7 dct['__getattr__'] = classmethod(lambda cls, attr: getattr(cls, attr))\n----> 8 dct['__setattr__'] = classmethod(lambda cls, attr, val: setattr(cls, attr, val))\n 9 return super(ClassPropertyMeta, cls).__new__(cls, name, parents, dct)\n\nAttributeError: can't set attribute\n"
},
{
"answer_id": 46818912,
"author": "alex",
"author_id": 4444742,
"author_profile": "https://Stackoverflow.com/users/4444742",
"pm_score": 0,
"selected": false,
"text": "from future.utils import with_metaclass\n\nclass BuilderMetaClass(type):\n @property\n def load_namespaces(self):\n return (self.__sourcepath__)\n\nclass BuilderMixin(with_metaclass(BuilderMetaClass, object)):\n __sourcepath__ = 'sp' \n\nprint(BuilderMixin.load_namespaces)\n"
},
{
"answer_id": 47334224,
"author": "OJFord",
"author_id": 1446048,
"author_profile": "https://Stackoverflow.com/users/1446048",
"pm_score": 5,
"selected": false,
"text": "metaclass class FooProperties(type):\n \n @property\n def var(cls):\n return cls._var\n\nclass Foo(object, metaclass=FooProperties):\n _var = 'FOO!'\n >>> Foo.var"
},
{
"answer_id": 64510457,
"author": "spacether",
"author_id": 4175822,
"author_profile": "https://Stackoverflow.com/users/4175822",
"pm_score": -1,
"selected": false,
"text": "class class_property(object):\n # this caches the result of the function call for fn with cls input\n # use this as a decorator on function methods that you want converted\n # into cached properties\n\n def __init__(self, fn):\n self._fn_name = fn.__name__\n if not isinstance(fn, (classmethod, staticmethod)):\n fn = classmethod(fn)\n self._fn = fn\n\n def __get__(self, obj, cls=None):\n if cls is None:\n cls = type(obj)\n if (\n self._fn_name in vars(cls) and\n type(vars(cls)[self._fn_name]).__name__ != \"class_property\"\n ):\n return vars(cls)[self._fn_name]\n else:\n value = self._fn.__get__(obj, cls)()\n setattr(cls, self._fn_name, value)\n return value\n"
},
{
"answer_id": 64738850,
"author": "Amit Portnoy",
"author_id": 990421,
"author_profile": "https://Stackoverflow.com/users/990421",
"pm_score": 7,
"selected": false,
"text": "class G:\n @classmethod\n @property\n def __doc__(cls):\n return f'A doc for {cls.__name__!r}'\n @classmethod"
},
{
"answer_id": 68349052,
"author": "Emma Brown",
"author_id": 13649935,
"author_profile": "https://Stackoverflow.com/users/13649935",
"pm_score": 2,
"selected": false,
"text": "pip install classutilities import classutilities\n\nclass SomeClass(classutilities.ClassPropertiesMixin):\n _some_variable = 8 # Some encapsulated class variable\n\n @classutilities.classproperty\n def some_variable(cls): # class property getter\n return cls._some_variable\n\n @some_variable.setter\n def some_variable(cls, value): # class property setter\n cls._some_variable = value\n # Getter on class level:\nvalue = SomeClass.some_variable\nprint(value) # >>> 8\n# Getter on instance level\ninst = SomeClass()\nvalue = inst.some_variable\nprint(value) # >>> 8\n\n# Setter on class level:\nnew_value = 9\nSomeClass.some_variable = new_value\nprint(SomeClass.some_variable) # >>> 9\nprint(SomeClass._some_variable) # >>> 9\n# Setter on instance level\ninst = SomeClass()\ninst.some_variable = new_value\nprint(SomeClass.some_variable) # >>> 9\nprint(SomeClass._some_variable) # >>> 9\nprint(inst.some_variable) # >>> 9\nprint(inst._some_variable) # >>> 9\n"
},
{
"answer_id": 69936409,
"author": "user2290820",
"author_id": 2290820,
"author_profile": "https://Stackoverflow.com/users/2290820",
"pm_score": 1,
"selected": false,
"text": "\nclass MetaProperty(type):\n\n def __init__(cls, *args, **kwargs):\n super()\n\n @property\n def praparty(cls):\n return cls._var\n\n @praparty.setter\n def praparty(cls, val):\n cls._var = val\n\n\nclass A(metaclass=MetaProperty):\n _var = 5\n\n\nprint(A.praparty)\nA.praparty = 6\nprint(A.praparty)\n"
},
{
"answer_id": 70311457,
"author": "Shawn Martin",
"author_id": 17648663,
"author_profile": "https://Stackoverflow.com/users/17648663",
"pm_score": 1,
"selected": false,
"text": "def classproperty(fget):\n return type(\n 'classproperty',\n (),\n {'__get__': lambda self, _, cls: fget(cls), '__module__': None}\n )()\n \nclass Item:\n a = 47\n\n @classproperty\n def x(cls):\n return cls.a\n\nItem.x\n"
},
{
"answer_id": 71479873,
"author": "eugene-bright",
"author_id": 2657676,
"author_profile": "https://Stackoverflow.com/users/2657676",
"pm_score": 0,
"selected": false,
"text": "from typing import (\n Callable,\n Generic,\n TypeVar,\n)\n\n\nT = TypeVar('T')\n\n\nclass classproperty(Generic[T]):\n \"\"\"Converts a method to a class property.\n \"\"\"\n\n def __init__(self, f: Callable[..., T]):\n self.fget = f\n\n def __get__(self, instance, owner) -> T:\n return self.fget(owner)\n\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9940/"
] |
128,580
|
<p>I'm trying to get the contents of a XML document element, but the element has a colon in it's name.</p>
<p>This line works for every element but the ones with a colon in the name:</p>
<pre><code>$(this).find("geo:lat").text();
</code></pre>
<p>I assume that the colon needs escaping. How do I fix this?</p>
|
[
{
"answer_id": 128598,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 6,
"selected": true,
"text": "$(this).find(\"geo\\\\:lat\").text();\n"
},
{
"answer_id": 128640,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 4,
"selected": false,
"text": "$(this).find(\"lat\").text();\n filter() var NS = \"http://example.com/whatever-the-namespace-is-for-geo\";\n$(this).find(\"lat\").filter(function() { return this.namespaceURI == NS; }).text();\n filter() var NS = \"http://example.com/whatever-the-namespace-is-for-geo\";\n$(this).find(\"geo\\\\:lat\").filter(function() { return this.namespaceURI == NS; }).text();\n"
},
{
"answer_id": 2478484,
"author": "simon",
"author_id": 297453,
"author_profile": "https://Stackoverflow.com/users/297453",
"pm_score": 2,
"selected": false,
"text": "$(this).find('[nodeName=geo:lat]').text();\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/399/"
] |
128,584
|
<p>The following simple "calculator expression" grammar (BNF) can be easily parsed with the a trivial recursive-descent parser, which is predictive LL(1):</p>
<pre><code><expr> := <term> + <term>
| <term> - <term>
| <term>
<term> := <factor> * <factor>
<factor> / <factor>
<factor>
<factor> := <number>
| <id>
| ( <expr> )
<number> := \d+
<id> := [a-zA-Z_]\w+
</code></pre>
<p>Because it is always enough to see the next token in order to know the rule to pick. However, suppose that I add the following rule:</p>
<pre><code><command> := <expr>
| <id> = <expr>
</code></pre>
<p>For the purpose of interacting with the calculator on the command line, with variables, like this:</p>
<pre><code>calc> 5+5
=> 10
calc> x = 8
calc> 6 * x + 1
=> 49
</code></pre>
<p>Is it true that I can not use a simple LL(1) predictive parser to parse <code><command></code> rules ? I tried to write the parser for it, but it seems that I need to know more tokens forward. Is the solution to use backtracking, or can I just implement LL(2) and always look two tokens forward ?</p>
<p>How to RD parser generators handle this problem (ANTLR, for instance)?</p>
|
[
{
"answer_id": 128661,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 2,
"selected": false,
"text": "\n<command> := <expr>\n | <id> = <expr>\n"
},
{
"answer_id": 128724,
"author": "Remo.D",
"author_id": 16827,
"author_profile": "https://Stackoverflow.com/users/16827",
"pm_score": 4,
"selected": true,
"text": "<command> := <expr>\n | <id> = <expr>\n <id> <factor> let x = 8 <command> := <expr>\n | \"let\" <id> \"=\" <expr>\n = <command> := \"=\" <expr>\n | <id> \"=\" <expr>\n"
},
{
"answer_id": 3922949,
"author": "Sven",
"author_id": 431526,
"author_profile": "https://Stackoverflow.com/users/431526",
"pm_score": 3,
"selected": false,
"text": "command() {\n if (currentToken() == id && lookaheadToken() == '=') {\n return assignment();\n } else {\n return expr();\n }\n}\n command() {\n savedLocation = scanLocation();\n if (accept( id )) {\n identifier = acceptedTokenValue();\n if (!accept( '=' )) {\n setScanLocation( savedLocation );\n return expr();\n }\n return new assignment( identifier, expr() );\n } else {\n return expr();\n }\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8206/"
] |
128,588
|
<p>Seems so basic, I can't believe I don't know this! I just need a scratch folder to dump some temporary files to. I don't care if it gets wiped out between usages or not, and I don't think I should have to go through the hassle of creating one and maintaining it myself from within my application. Is that too much to ask?</p>
|
[
{
"answer_id": 128596,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 5,
"selected": true,
"text": "System.IO.Path.GetTempPath()"
},
{
"answer_id": 128605,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 3,
"selected": false,
"text": "Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)"
},
{
"answer_id": 128614,
"author": "Teme64",
"author_id": 16482,
"author_profile": "https://Stackoverflow.com/users/16482",
"pm_score": 2,
"selected": false,
"text": "My.Computer.FileSystem.SpecialDirectories.Temp\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
] |
128,618
|
<p>Is there any easy way to create a class that uses <strong>IFormatProvider</strong> that writes out a user-friendly file-size?</p>
<pre><code>public static string GetFileSizeString(string filePath)
{
FileInfo info = new FileInfo(@"c:\windows\notepad.exe");
long size = info.Length;
string sizeString = size.ToString(FileSizeFormatProvider); // This is where the class does its magic...
}
</code></pre>
<p>It should result in strings formatted something like "<em>2,5 MB</em>", "<em>3,9 GB</em>", "<em>670 bytes</em>" and so on.</p>
|
[
{
"answer_id": 128683,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 8,
"selected": true,
"text": "public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter\n{\n public object GetFormat(Type formatType)\n {\n if (formatType == typeof(ICustomFormatter)) return this;\n return null;\n }\n\n private const string fileSizeFormat = \"fs\";\n private const Decimal OneKiloByte = 1024M;\n private const Decimal OneMegaByte = OneKiloByte * 1024M;\n private const Decimal OneGigaByte = OneMegaByte * 1024M;\n\n public string Format(string format, object arg, IFormatProvider formatProvider)\n { \n if (format == null || !format.StartsWith(fileSizeFormat)) \n { \n return defaultFormat(format, arg, formatProvider); \n }\n\n if (arg is string) \n { \n return defaultFormat(format, arg, formatProvider); \n }\n\n Decimal size;\n\n try \n { \n size = Convert.ToDecimal(arg); \n } \n catch (InvalidCastException) \n { \n return defaultFormat(format, arg, formatProvider); \n }\n\n string suffix;\n if (size > OneGigaByte)\n {\n size /= OneGigaByte;\n suffix = \"GB\";\n }\n else if (size > OneMegaByte)\n {\n size /= OneMegaByte;\n suffix = \"MB\";\n }\n else if (size > OneKiloByte)\n {\n size /= OneKiloByte;\n suffix = \"kB\";\n }\n else\n {\n suffix = \" B\";\n }\n\n string precision = format.Substring(2);\n if (String.IsNullOrEmpty(precision)) precision = \"2\";\n return String.Format(\"{0:N\" + precision + \"}{1}\", size, suffix);\n\n }\n\n private static string defaultFormat(string format, object arg, IFormatProvider formatProvider)\n {\n IFormattable formattableArg = arg as IFormattable;\n if (formattableArg != null)\n {\n return formattableArg.ToString(format, formatProvider);\n }\n return arg.ToString();\n }\n\n}\n Console.WriteLine(String.Format(new FileSizeFormatProvider(), \"File size: {0:fs}\", 100));\nConsole.WriteLine(String.Format(new FileSizeFormatProvider(), \"File size: {0:fs}\", 10000));\n public static class ExtensionMethods\n{\n public static string ToFileSize(this long l)\n {\n return String.Format(new FileSizeFormatProvider(), \"{0:fs}\", l);\n }\n}\n long l = 100000000;\nConsole.WriteLine(l.ToFileSize());\n"
},
{
"answer_id": 129110,
"author": "Shaun Austin",
"author_id": 1120,
"author_profile": "https://Stackoverflow.com/users/1120",
"pm_score": 6,
"selected": false,
"text": "[DllImport(\"Shlwapi.dll\", CharSet = CharSet.Auto)]\npublic static extern long StrFormatByteSize( long fileSize, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder buffer, int bufferSize );\n"
},
{
"answer_id": 1756525,
"author": "ariso",
"author_id": 97775,
"author_profile": "https://Stackoverflow.com/users/97775",
"pm_score": 3,
"selected": false,
"text": "[DllImport(\"Shlwapi.dll\", CharSet = CharSet.Auto)]\npublic static extern long StrFormatByteSize(long fileSize, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder buffer, int bufferSize);\n\npublic void getFileInfo(string filename)\n{\n System.IO.FileInfo fileinfo = new FileInfo(filename);\n this.FileName.Text = fileinfo.Name;\n StringBuilder buffer = new StringBuilder();\n StrFormatByteSize(fileinfo.Length, buffer, 100);\n this.FileSize.Text = buffer.ToString();\n}\n"
},
{
"answer_id": 2467447,
"author": "Tyler Durden",
"author_id": 296147,
"author_profile": "https://Stackoverflow.com/users/296147",
"pm_score": 1,
"selected": false,
"text": "public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter\n{\n public object GetFormat(Type formatType)\n {\n if (formatType == typeof(ICustomFormatter))\n {\n return this;\n }\n\n return null;\n }\n\n private const string fileSizeFormat = \"FS\";\n private const string kiloByteFormat = \"KB\";\n private const string megaByteFormat = \"MB\";\n private const string gigaByteFormat = \"GB\";\n private const string byteFormat = \"B\";\n private const Decimal oneKiloByte = 1024M;\n private const Decimal oneMegaByte = oneKiloByte * 1024M;\n private const Decimal oneGigaByte = oneMegaByte * 1024M;\n\n public string Format(string format, object arg, IFormatProvider formatProvider)\n {\n //\n // Ensure the format provided is supported\n //\n if (String.IsNullOrEmpty(format) || !(format.StartsWith(fileSizeFormat, StringComparison.OrdinalIgnoreCase) ||\n format.StartsWith(kiloByteFormat, StringComparison.OrdinalIgnoreCase) ||\n format.StartsWith(megaByteFormat, StringComparison.OrdinalIgnoreCase) ||\n format.StartsWith(gigaByteFormat, StringComparison.OrdinalIgnoreCase)))\n {\n return DefaultFormat(format, arg, formatProvider);\n }\n\n //\n // Ensure the argument type is supported\n //\n if (!(arg is long || arg is decimal || arg is int))\n {\n return DefaultFormat(format, arg, formatProvider);\n }\n\n //\n // Try and convert the argument to decimal\n //\n Decimal size;\n\n try\n {\n size = Convert.ToDecimal(arg);\n }\n catch (InvalidCastException)\n {\n return DefaultFormat(format, arg, formatProvider);\n }\n\n //\n // Determine the suffix to use and convert the argument to the requested size\n //\n string suffix;\n\n switch (format.Substring(0, 2).ToUpper())\n {\n case kiloByteFormat:\n size = size / oneKiloByte;\n suffix = kiloByteFormat;\n break;\n case megaByteFormat:\n size = size / oneMegaByte;\n suffix = megaByteFormat;\n break;\n case gigaByteFormat:\n size = size / oneGigaByte;\n suffix = gigaByteFormat;\n break;\n case fileSizeFormat:\n if (size > oneGigaByte)\n {\n size /= oneGigaByte;\n suffix = gigaByteFormat;\n }\n else if (size > oneMegaByte)\n {\n size /= oneMegaByte;\n suffix = megaByteFormat;\n }\n else if (size > oneKiloByte)\n {\n size /= oneKiloByte;\n suffix = kiloByteFormat;\n }\n else\n {\n suffix = byteFormat;\n }\n break;\n default:\n suffix = byteFormat;\n break;\n }\n\n //\n // Determine the precision to use\n //\n string precision = format.Substring(2);\n\n if (String.IsNullOrEmpty(precision))\n {\n precision = \"2\";\n }\n\n return String.Format(\"{0:N\" + precision + \"}{1}\", size, suffix);\n }\n\n private static string DefaultFormat(string format, object arg, IFormatProvider formatProvider)\n {\n IFormattable formattableArg = arg as IFormattable;\n\n if (formattableArg != null)\n {\n return formattableArg.ToString(format, formatProvider);\n }\n\n return arg.ToString();\n }\n}\n"
},
{
"answer_id": 3968504,
"author": "mindplay.dk",
"author_id": 283851,
"author_profile": "https://Stackoverflow.com/users/283851",
"pm_score": 5,
"selected": false,
"text": "using System.Globalization;\n\npublic struct FileSize : IFormattable\n{\n private ulong _value;\n\n private const int DEFAULT_PRECISION = 2;\n\n private static IList<string> Units;\n\n static FileSize()\n {\n Units = new List<string>(){\n \"B\", \"KB\", \"MB\", \"GB\", \"TB\"\n };\n }\n\n public FileSize(ulong value)\n {\n _value = value;\n }\n\n public static explicit operator FileSize(ulong value)\n {\n return new FileSize(value);\n }\n\n override public string ToString()\n {\n return ToString(null, null);\n }\n\n public string ToString(string format)\n {\n return ToString(format, null);\n }\n\n public string ToString(string format, IFormatProvider formatProvider)\n {\n int precision;\n\n if (String.IsNullOrEmpty(format))\n return ToString(DEFAULT_PRECISION);\n else if (int.TryParse(format, out precision))\n return ToString(precision);\n else\n return _value.ToString(format, formatProvider);\n }\n\n /// <summary>\n /// Formats the FileSize using the given number of decimals.\n /// </summary>\n public string ToString(int precision)\n {\n double pow = Math.Floor((_value > 0 ? Math.Log(_value) : 0) / Math.Log(1024));\n pow = Math.Min(pow, Units.Count - 1);\n double value = (double)_value / Math.Pow(1024, pow);\n return value.ToString(pow == 0 ? \"F0\" : \"F\" + precision.ToString()) + \" \" + Units[(int)pow];\n }\n}\n [Test]\n public void CanUseFileSizeFormatProvider()\n {\n Assert.AreEqual(String.Format(\"{0}\", (FileSize)128), \"128 B\");\n Assert.AreEqual(String.Format(\"{0}\", (FileSize)1024), \"1.00 KB\");\n Assert.AreEqual(String.Format(\"{0:0}\", (FileSize)10240), \"10 KB\");\n Assert.AreEqual(String.Format(\"{0:1}\", (FileSize)102400), \"100.0 KB\");\n Assert.AreEqual(String.Format(\"{0}\", (FileSize)1048576), \"1.00 MB\");\n Assert.AreEqual(String.Format(\"{0:D}\", (FileSize)123456), \"123456\");\n\n // You can also manually invoke ToString(), optionally with the precision specified as an integer:\n Assert.AreEqual(((FileSize)111111).ToString(2), \"108.51 KB\");\n }\n public static class IntToBytesExtension\n{\n private const int PRECISION = 2;\n\n private static IList<string> Units;\n\n static IntToBytesExtension()\n {\n Units = new List<string>(){\n \"B\", \"KB\", \"MB\", \"GB\", \"TB\"\n };\n }\n\n /// <summary>\n /// Formats the value as a filesize in bytes (KB, MB, etc.)\n /// </summary>\n /// <param name=\"bytes\">This value.</param>\n /// <returns>Filesize and quantifier formatted as a string.</returns>\n public static string ToBytes(this int bytes)\n {\n double pow = Math.Floor((bytes>0 ? Math.Log(bytes) : 0) / Math.Log(1024));\n pow = Math.Min(pow, Units.Count-1);\n double value = (double)bytes / Math.Pow(1024, pow);\n return value.ToString(pow==0 ? \"F0\" : \"F\" + PRECISION.ToString()) + \" \" + Units[(int)pow];\n }\n}\n [Test]\n public void CanFormatFileSizes()\n {\n Assert.AreEqual(\"128 B\", (128).ToBytes());\n Assert.AreEqual(\"1.00 KB\", (1024).ToBytes());\n Assert.AreEqual(\"10.00 KB\", (10240).ToBytes());\n Assert.AreEqual(\"100.00 KB\", (102400).ToBytes());\n Assert.AreEqual(\"1.00 MB\", (1048576).ToBytes());\n }\n"
},
{
"answer_id": 13777868,
"author": "wvd_vegt",
"author_id": 1034074,
"author_profile": "https://Stackoverflow.com/users/1034074",
"pm_score": 1,
"selected": false,
"text": " if (String.IsNullOrEmpty(precision))\n {\n precision = \"2\";\n }\n if (String.IsNullOrEmpty(precision))\n {\n if (size < 10)\n {\n precision = \"2\";\n }\n else if (size < 100)\n {\n precision = \"1\";\n }\n else\n {\n precision = \"0\";\n }\n }\n"
},
{
"answer_id": 15340481,
"author": "fubo",
"author_id": 1315444,
"author_profile": "https://Stackoverflow.com/users/1315444",
"pm_score": 2,
"selected": false,
"text": "public static string ToFileSize(this long size)\n{\n if (size < 1024)\n {\n return (size).ToString(\"F0\") + \" bytes\";\n }\n else if ((size >> 10) < 1024)\n {\n return (size/(float)1024).ToString(\"F1\") + \" KB\";\n }\n else if ((size >> 20) < 1024)\n {\n return ((size >> 10) / (float)1024).ToString(\"F1\") + \" MB\";\n }\n else if ((size >> 30) < 1024)\n {\n return ((size >> 20) / (float)1024).ToString(\"F1\") + \" GB\";\n }\n else if ((size >> 40) < 1024)\n {\n return ((size >> 30) / (float)1024).ToString(\"F1\") + \" TB\";\n }\n else if ((size >> 50) < 1024)\n {\n return ((size >> 40) / (float)1024).ToString(\"F1\") + \" PB\";\n }\n else\n {\n return ((size >> 50) / (float)1024).ToString(\"F0\") + \" EB\";\n }\n}\n"
},
{
"answer_id": 18331628,
"author": "Simon Mourier",
"author_id": 403671,
"author_profile": "https://Stackoverflow.com/users/403671",
"pm_score": 2,
"selected": false,
"text": "// force \"en-US\" culture for tests\nThread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(1033); \n\n// Displays \"8.00 EB\"\nConsole.WriteLine(FormatFileSize(long.MaxValue)); \n\n// Use \"fr-FR\" culture. Displays \"20,74 ko\", o is for \"octet\"\nConsole.WriteLine(FormatFileSize(21234, \"o\", null, CultureInfo.GetCultureInfo(1036)));\n /// <summary>\n /// Converts a numeric value into a string that represents the number expressed as a size value in bytes, kilobytes, megabytes, gigabytes, terabytes, petabytes or exabytes, depending on the size\n /// </summary>\n /// <param name=\"size\">The size.</param>\n /// <returns>\n /// The number converted.\n /// </returns>\n public static string FormatFileSize(long size)\n {\n return FormatFileSize(size, null, null, null);\n }\n\n /// <summary>\n /// Converts a numeric value into a string that represents the number expressed as a size value in bytes, kilobytes, megabytes, gigabytes, terabytes, petabytes or exabytes, depending on the size\n /// </summary>\n /// <param name=\"size\">The size.</param>\n /// <param name=\"byteName\">The string used for the byte name. If null is passed, \"B\" will be used.</param>\n /// <param name=\"numberFormat\">The number format. If null is passed, \"N2\" will be used.</param>\n /// <param name=\"formatProvider\">The format provider. May be null to use current culture.</param>\n /// <returns>The number converted.</returns>\n public static string FormatFileSize(long size, string byteName, string numberFormat, IFormatProvider formatProvider)\n {\n if (size < 0)\n throw new ArgumentException(null, \"size\");\n\n if (byteName == null)\n {\n byteName = \"B\";\n }\n\n if (string.IsNullOrEmpty(numberFormat))\n {\n numberFormat = \"N2\";\n }\n\n const decimal K = 1024;\n const decimal M = K * K;\n const decimal G = M * K;\n const decimal T = G * K;\n const decimal P = T * K;\n const decimal E = P * K;\n\n decimal dsize = size;\n\n string suffix = null;\n if (dsize >= E)\n {\n dsize /= E;\n suffix = \"E\";\n }\n else if (dsize >= P)\n {\n dsize /= P;\n suffix = \"P\";\n }\n else if (dsize >= T)\n {\n dsize /= T;\n suffix = \"T\";\n }\n else if (dsize >= G)\n {\n dsize /= G;\n suffix = \"G\";\n }\n else if (dsize >= M)\n {\n dsize /= M;\n suffix = \"M\";\n }\n else if (dsize >= K)\n {\n dsize /= K;\n suffix = \"k\";\n }\n if (suffix != null)\n {\n suffix = \" \" + suffix;\n }\n return string.Format(formatProvider, \"{0:\" + numberFormat + \"}\" + suffix + byteName, dsize);\n }\n"
},
{
"answer_id": 21175211,
"author": "Christian Moser",
"author_id": 1452507,
"author_profile": "https://Stackoverflow.com/users/1452507",
"pm_score": 4,
"selected": false,
"text": "public string SizeText\n{\n get\n {\n var units = new[] { \"B\", \"KB\", \"MB\", \"GB\", \"TB\" };\n var index = 0;\n double size = Size;\n while (size > 1024)\n {\n size /= 1024;\n index++;\n }\n return string.Format(\"{0:2} {1}\", size, units[index]);\n }\n}\n"
},
{
"answer_id": 27162235,
"author": "Michel Tomassini",
"author_id": 4298319,
"author_profile": "https://Stackoverflow.com/users/4298319",
"pm_score": 2,
"selected": false,
"text": " public static string FileSizeFormat(this long lSize)\n {\n double size = lSize;\n int index = 0;\n for(; size > 1024; index++)\n size /= 1024;\n return size.ToString(\"0.000 \" + new[] { \"B\", \"KB\", \"MB\", \"GB\", \"TB\" }[index]); \n }\n"
},
{
"answer_id": 67771566,
"author": "JRoger",
"author_id": 3670782,
"author_profile": "https://Stackoverflow.com/users/3670782",
"pm_score": 0,
"selected": false,
"text": "public static string ToFormatSize(ulong size)\n{\n return size switch\n {\n ulong s when s < 1024 => $\"{size} bytes\",\n ulong s when s < (1024 << 10) => $\"{Math.Round(size / 1024D, 2)} KB\",\n ulong s when s < (1024 << 20) => $\"{Math.Round(size * 1D / (1024 << 10), 2)} MB\",\n ulong s when s < (1024 << 30) => $\"{Math.Round(size * 1D / (1024L << 20), 2)} GB\",\n ulong s when s < (1024 << 40) => $\"{Math.Round(size * 1D / (1024L << 30), 2)} TB\",\n ulong s when s < (1024 << 50) => $\"{Math.Round(size * 1D / (1024L << 40), 2)} PB\",\n ulong s when s < (1024 << 60) => $\"{Math.Round(size * 1D / (1024L << 50), 2)} EB\",\n _ => $\"{size} bytes\"\n };\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2429/"
] |
128,623
|
<p>How can I disable all table constrains in Oracle with a single command?
This can be either for a single table, a list of tables, or for all tables.</p>
|
[
{
"answer_id": 128786,
"author": "Mike McAllister",
"author_id": 16247,
"author_profile": "https://Stackoverflow.com/users/16247",
"pm_score": 3,
"selected": false,
"text": "set heading off\n\nspool drop_constraints.out\n\nselect\n 'alter table ' || \n owner || '.' || \n table_name || \n ' disable constraint ' || -- or 'drop' if you want to permanently remove\n constraint_name || ';'\nfrom\n user_constraints;\n\nspool off\n\nset heading on\n\n@drop_constraints.out\n"
},
{
"answer_id": 131595,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 8,
"selected": true,
"text": "BEGIN\n FOR c IN\n (SELECT c.owner, c.table_name, c.constraint_name\n FROM user_constraints c, user_tables t\n WHERE c.table_name = t.table_name\n AND c.status = 'ENABLED'\n AND NOT (t.iot_type IS NOT NULL AND c.constraint_type = 'P')\n ORDER BY c.constraint_type DESC)\n LOOP\n dbms_utility.exec_ddl_statement('alter table \"' || c.owner || '\".\"' || c.table_name || '\" disable constraint ' || c.constraint_name);\n END LOOP;\nEND;\n/\n BEGIN\n FOR c IN\n (SELECT c.owner, c.table_name, c.constraint_name\n FROM user_constraints c, user_tables t\n WHERE c.table_name = t.table_name\n AND c.status = 'DISABLED'\n ORDER BY c.constraint_type)\n LOOP\n dbms_utility.exec_ddl_statement('alter table \"' || c.owner || '\".\"' || c.table_name || '\" enable constraint ' || c.constraint_name);\n END LOOP;\nEND;\n/\n"
},
{
"answer_id": 1101073,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "ORDER BY c.constraint_type DESC, c.last_change DESC\n"
},
{
"answer_id": 4014154,
"author": "user486360",
"author_id": 486360,
"author_profile": "https://Stackoverflow.com/users/486360",
"pm_score": 3,
"selected": false,
"text": "DECLARE\n\ncursor r1 is select * from user_constraints;\ncursor r2 is select * from user_tables;\n\nBEGIN\n FOR c1 IN r1\n loop\n for c2 in r2\n loop\n if c1.table_name = c2.table_name and c1.status = 'ENABLED' THEN\n dbms_utility.exec_ddl_statement('alter table ' || c1.owner || '.' || c1.table_name || ' disable constraint ' || c1.constraint_name);\n end if;\n end loop;\n END LOOP;\nEND;\n/\n"
},
{
"answer_id": 5075815,
"author": "Cyryl1972",
"author_id": 627962,
"author_profile": "https://Stackoverflow.com/users/627962",
"pm_score": 4,
"selected": false,
"text": "SET Serveroutput ON\nBEGIN\n FOR c IN\n (SELECT c.owner,c.table_name,c.constraint_name\n FROM user_constraints c,user_tables t\n WHERE c.table_name=t.table_name\n AND c.status='ENABLED'\n ORDER BY c.constraint_type DESC,c.last_change DESC\n )\n LOOP\n FOR D IN\n (SELECT P.Table_Name Parent_Table,C1.Table_Name Child_Table,C1.Owner,P.Constraint_Name Parent_Constraint,\n c1.constraint_name Child_Constraint\n FROM user_constraints p\n JOIN user_constraints c1 ON(p.constraint_name=c1.r_constraint_name)\n WHERE(p.constraint_type='P'\n OR p.constraint_type='U')\n AND c1.constraint_type='R'\n AND p.table_name=UPPER(c.table_name)\n )\n LOOP\n dbms_output.put_line('. Disable the constraint ' || d.Child_Constraint ||' (on table '||d.owner || '.' ||\n d.Child_Table || ')') ;\n dbms_utility.exec_ddl_statement('alter table ' || d.owner || '.' ||d.Child_Table || ' disable constraint ' ||\n d.Child_Constraint) ;\n END LOOP;\n END LOOP;\nEND;\n/\n"
},
{
"answer_id": 28367033,
"author": "Ankireddy Polu",
"author_id": 950212,
"author_profile": "https://Stackoverflow.com/users/950212",
"pm_score": 1,
"selected": false,
"text": "SELECT 'ALTER TABLE '||substr(c.table_name,1,35)|| \n' DISABLE CONSTRAINT '||constraint_name||' ;' \nFROM user_constraints c, user_tables u \nWHERE c.table_name = u.table_name; \n"
},
{
"answer_id": 40281408,
"author": "Cyryl1972",
"author_id": 627962,
"author_profile": "https://Stackoverflow.com/users/627962",
"pm_score": 0,
"selected": false,
"text": "WITH qry0 AS\n (SELECT 'ALTER TABLE '\n || child_tname\n || ' DISABLE CONSTRAINT '\n || child_cons_name\n disable_fk\n , 'ALTER TABLE '\n || parent_tname\n || ' DISABLE CONSTRAINT '\n || parent.parent_cons_name\n disable_pk\n FROM (SELECT a.table_name child_tname\n ,a.constraint_name child_cons_name\n ,b.r_constraint_name parent_cons_name\n ,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) child_columns\n FROM user_cons_columns a\n ,user_constraints b\n WHERE a.constraint_name = b.constraint_name AND b.constraint_type = 'R'\n GROUP BY a.table_name, a.constraint_name\n ,b.r_constraint_name) child\n ,(SELECT a.constraint_name parent_cons_name\n ,a.table_name parent_tname\n ,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) parent_columns\n FROM user_cons_columns a\n ,user_constraints b\n WHERE a.constraint_name = b.constraint_name AND b.constraint_type IN ('P', 'U')\n GROUP BY a.table_name, a.constraint_name) parent\n WHERE child.parent_cons_name = parent.parent_cons_name\n AND (parent.parent_tname LIKE 'V2_%' OR child.child_tname LIKE 'V2_%'))\nSELECT DISTINCT disable_pk\n FROM qry0\nUNION\nSELECT DISTINCT disable_fk\n FROM qry0;\n"
},
{
"answer_id": 51173286,
"author": "diaphol",
"author_id": 9654615,
"author_profile": "https://Stackoverflow.com/users/9654615",
"pm_score": 0,
"selected": false,
"text": "declare\n constr all_constraints.constraint_name%TYPE;\nbegin\n for constr in\n (select constraint_name from all_constraints\n where table_name = 'D'\n and owner = 'TRANEE')\n loop\n execute immediate 'alter table D disable constraint '||constr.constraint_name;\n end loop;\nend;\n/\n"
},
{
"answer_id": 52968518,
"author": "Cristina Bazar",
"author_id": 10551854,
"author_profile": "https://Stackoverflow.com/users/10551854",
"pm_score": 0,
"selected": false,
"text": "select 'ALTER TABLE '||substr(c.table_name,1,35)|| \n' DISABLE CONSTRAINT '||constraint_name||' ;' \nfrom user_constraints c\n--where c.table_name = 'TABLE_NAME' ;\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9435/"
] |
128,636
|
<p>.NET has a lot of complex data structures. Unfortunately, some of them are quite similar and I'm not always sure when to use one and when to use another. Most of my C# and VB books talk about them to a certain extent, but they never really go into any real detail.</p>
<p>What's the difference between Array, ArrayList, List, Hashtable, Dictionary, SortedList, and SortedDictionary?</p>
<p>Which ones are enumerable (IList -- can do 'foreach' loops)? Which ones use key/value pairs (IDict)?</p>
<p>What about memory footprint? Insertion speed? Retrieval speed?</p>
<p>Are there any other data structures worth mentioning?</p>
<p>I'm still searching for more details on memory usage and speed (Big-O notation)</p>
|
[
{
"answer_id": 128754,
"author": "Sam Schutte",
"author_id": 146,
"author_profile": "https://Stackoverflow.com/users/146",
"pm_score": 8,
"selected": true,
"text": "Array type[] ArrayList List List<string> ArrayList Hashtable Dictionary Dictionary<string, string> SortedList List Dictionary KeyValuePair SortedDictionary"
},
{
"answer_id": 128788,
"author": "blackwing",
"author_id": 9107,
"author_profile": "https://Stackoverflow.com/users/9107",
"pm_score": 4,
"selected": false,
"text": "foreach IEnumerable IList IEnumberable Count Item IDictionary Array ArrayList List IList Dictionary SortedDictionary Hashtable IDictionary System.Collections"
},
{
"answer_id": 26342943,
"author": "Thomas",
"author_id": 3469725,
"author_profile": "https://Stackoverflow.com/users/3469725",
"pm_score": 4,
"selected": false,
"text": "System.Collections Dim _array As Int32() = New Int32(100) _array List(Of T) IList Object[] List(Of T) Int32 Int32 Object"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21244/"
] |
128,659
|
<p>I keep getting this error when trying to re-order items in my ReorderList control.</p>
<p>"Reorder failed, see details below.</p>
<p>Can't access data source. It does not a DataSource and does not implement IList."</p>
<p>I'm setting the datasource to a DataTable right now, and am currently trying to use an ArrayList datasource instead, but am discouraged because of <a href="http://www.codeplex.com/AjaxControlToolkit/WorkItem/View.aspx?WorkItemId=7589" rel="nofollow noreferrer">this post</a> on the internet elsewhere. The control exists within an update panel, but no other events are subscribed to. Should there be something special with the OnItemReorder event? Just confused as to how it works.</p>
<p>My question is, does anyone have any direct experience with this issue?</p>
|
[
{
"answer_id": 128831,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " <cc1:ReorderList id=\"ReorderList1\" runat=\"server\" CssClass=\"Sortables\" Width=\"400\" >\n <ItemTemplate>\n <div class=\"sortablelineitem\">\n <a href=\"#\" class=\"albmCvr\" id=\"song13\">\n <img src=\"/images/plalbumcvr.jpg\" alt=\"Name of Album\" class=\"cvrAlbum\" width=\"10\"\n height=\"10\" />\n Song 1 <span>by</span> Artist 1 </a>\n <asp:ImageButton ID=\"ImageButton13\" runat=\"server\" ImageUrl=\"/images/btn_play_icon.gif\"\n ToolTip=\"Play Clip\" CssClass=\"playClip\" />\n </div>\n </ItemTemplate>\n <EditItemTemplate>\n <h1>WHOA THE ITEM IS BEING DRAGGED!!</h1>\n </EditItemTemplate>\n <ReorderTemplate>\n <div style=\"width:400px; height:20px; border:dashed 2px #CCC;\"></div>\n </ReorderTemplate>\n <DragHandleTemplate>\n <div style=\"height:15px; width:15px; background-color:Black;\"></div>\n </DragHandleTemplate>\n <EmptyListTemplate>\n There are no items in this playlist yet...\n </EmptyListTemplate>\n </cc1:ReorderList>\n\n </ContentTemplate>\n </asp:UpdatePanel>\n ReorderList1.DataSource = ds.Tables[1];\nReorderList1.DataBind();\n"
},
{
"answer_id": 12340017,
"author": "miron gerstmann",
"author_id": 1658273,
"author_profile": "https://Stackoverflow.com/users/1658273",
"pm_score": 1,
"selected": false,
"text": "SortOrder"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
128,674
|
<p>Pretty simple scenario. I have a web service that receives a byte array that is to be saved as a particular file type on disk. What is the most efficient way to do this in C#?</p>
|
[
{
"answer_id": 128692,
"author": "Maurice",
"author_id": 19676,
"author_profile": "https://Stackoverflow.com/users/19676",
"pm_score": 8,
"selected": true,
"text": "File.WriteAllBytes()"
},
{
"answer_id": 128694,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": 6,
"selected": false,
"text": "System.IO.File.WriteAllBytes(path, data)"
},
{
"answer_id": 132576,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 4,
"selected": false,
"text": "using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))\n{\n stream.Write(bytes, 0, bytes.Length);\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
] |
128,699
|
<p>I'm looking for a way to visualize a piece of GML I'm receiving. What is the best freely available java library to use for this task?</p>
|
[
{
"answer_id": 5602710,
"author": "Jody Garnett",
"author_id": 287743,
"author_profile": "https://Stackoverflow.com/users/287743",
"pm_score": 0,
"selected": false,
"text": " URL url = TestData.getResource(this, \"states.gml\");\n InputStream in = url.openStream();\n\n GML gml = new GML(Version.GML3);\n SimpleFeatureCollection featureCollection = gml.decodeFeatureCollection(in);\n MapContext map = new DefaultMapContext();\n map.setTitle(\"Quickstart\");\n map.addLayer(featureCollection, null);\n\n // Now display the map\n JMapFrame.showMap(map);\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18702/"
] |
128,783
|
<p>Is it possible to use AIX's mksysb and savevg to create a bootable tape with the rootvg and then append all the other VGs?</p>
|
[
{
"answer_id": 129951,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "savevg -f /tmp/vgname\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
128,796
|
<p>I really enjoy having "pretty" URLs (e.g. <code>/Products/Edit/1</code> instead of <code>/products.aspx?productID=1</code>) but I'm at a loss on how to do this for pages that let you search by a large number of variables.</p>
<p>For instance, let's say you have a page that lets a user search for all products of a particular type with a certain name and near a specific address. Would you do this with really long "pretty" URLs</p>
<pre><code>/Products/Search/Type/{producttype}/Name/{name}/Address/{address}
</code></pre>
<p>or just resort to using url params</p>
<pre><code>/Products/Search?productType={producttype}&name={name}&address={address}
</code></pre>
|
[
{
"answer_id": 128881,
"author": "chrisntr",
"author_id": 4455,
"author_profile": "https://Stackoverflow.com/users/4455",
"pm_score": 1,
"selected": false,
"text": "http://example.com/search/?productType={producttype}&name={name}&address={address}"
},
{
"answer_id": 128882,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 3,
"selected": false,
"text": "/Products/Search/Type/{producttype}/Name_{name}/Address_{address}\n RewriteRule ^Products/Search/Type/([a-z]+)(.*)?$ product_lookup.php?type=$1¶ms=$2 [NC,L]\n product_lookup $type = {producttype}\n$params = \"/Name_{name}/Address_{address}\"\n product_lookup.php $params // Split request params first on /, then figure out key->val pairs\n$query_parts = explode(\"/\", $params);\nforeach($params as $param)\n{\n $param_parts = explode(\"_\", $param);\n // Build up associative array of params\n $query[$param_parts[0]] = $param_parts[1];\n}\n// $query should now contain the search parameters in an assoc. array, e.g.\n// $query['Name'] = {name};\n http://www.property.ie/property-for-sale/dublin/ashington/price_200000-550000/beds_1/"
},
{
"answer_id": 128912,
"author": "Nick",
"author_id": 5222,
"author_profile": "https://Stackoverflow.com/users/5222",
"pm_score": 3,
"selected": false,
"text": "/weblog/entries/2008\n/weblog/entries/2008/11\n/weblog/entries/2008/11/22\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
] |
128,815
|
<p>I'd like to set a cookie via Django with that has several different values to it, similar to .NET's <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcookie_members(VS.80).aspx" rel="nofollow noreferrer">HttpCookie.Values</a> property. Looking at the <a href="http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpResponse.set_cookie" rel="nofollow noreferrer">documentation</a>, I can't tell if this is possible. It looks like it just takes a string, so is there another way?</p>
<p>I've tried passing it an array (<code>[10, 20, 30]</code>) and dictionary (<code>{'name': 'Scott', 'id': 1}</code>) but they just get converted to their string format. My current solution is to just use an arbitrary separator and then parse it when reading it in, which feels icky. If multi-values aren't possible, is there a better way? I'd rather not use lots of cookies, because that would get annoying.</p>
|
[
{
"answer_id": 2383482,
"author": "Jordan Reiter",
"author_id": 255918,
"author_profile": "https://Stackoverflow.com/users/255918",
"pm_score": 1,
"selected": false,
"text": "import pickle\nclass MultiCookie():\n def __init__(self,cookie=None,values=None):\n if cookie != None:\n try:\n self.values = pickle.loads(cookie)\n except:\n # assume that it used to just hold a string value\n self.values = cookie\n elif values != None:\n self.values = values\n else:\n self.values = None\n\n def __str__(self):\n return pickle.dumps(self.values)\n newcookie = MultiCookie(cookie=request.COOKIES.get('multi'))\nvalues_for_cookie = newcookie.values\n mylist = [ 1, 2, 3 ]\nnewcookie = MultiCookie(values=mylist)\nrequest.set_cookie('multi',value=newcookie)\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/736/"
] |
128,818
|
<p>I have seen people say that it is bad form to use catch with no arguments, especially if that catch doesn't do anything:</p>
<pre><code>StreamReader reader=new StreamReader("myfile.txt");
try
{
int i = 5 / 0;
}
catch // No args, so it will catch any exception
{}
reader.Close();
</code></pre>
<p>However, this is considered good form:</p>
<pre><code>StreamReader reader=new StreamReader("myfile.txt");
try
{
int i = 5 / 0;
}
finally // Will execute despite any exception
{
reader.Close();
}
</code></pre>
<p>As far as I can tell, the only difference between putting cleanup code in a finally block and putting cleanup code after the try..catch blocks is if you have return statements in your try block (in that case, the cleanup code in finally will run, but code after the try..catch will not).</p>
<p>Otherwise, what's so special about finally?</p>
|
[
{
"answer_id": 128829,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": 10,
"selected": true,
"text": "try...catch try..finally"
},
{
"answer_id": 128845,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 5,
"selected": false,
"text": "reader.Close()"
},
{
"answer_id": 128852,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 4,
"selected": false,
"text": "using (StreamReader reader=new StreamReader(\"myfile.txt\"))\n{\n}\n"
},
{
"answer_id": 128858,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 2,
"selected": false,
"text": "finally StackOverflowException OutOfMemoryException"
},
{
"answer_id": 128916,
"author": "Jared",
"author_id": 7388,
"author_profile": "https://Stackoverflow.com/users/7388",
"pm_score": 0,
"selected": false,
"text": "using (StreamReader reader = new StreamReader(\"myfile.txt\"))\n{\n int i = 5 / 0;\n}\n"
},
{
"answer_id": 128917,
"author": "Chris Lawlor",
"author_id": 21245,
"author_profile": "https://Stackoverflow.com/users/21245",
"pm_score": 3,
"selected": false,
"text": "using (StreamReader reader = new StreamReader('myfile.txt'))\n{\n // do stuff here\n} // reader.dispose() is called automatically\n"
},
{
"answer_id": 129916,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 3,
"selected": false,
"text": "try\n{\n int i = 1/0; \n}\ncatch\n{\n reader.Close();\n throw;\n}\n\ntry\n{\n int i = 1/0;\n}\nfinally\n{\n reader.Close();\n}\n"
},
{
"answer_id": 36936022,
"author": "dr.Crow",
"author_id": 2530448,
"author_profile": "https://Stackoverflow.com/users/2530448",
"pm_score": 2,
"selected": false,
"text": "try.. finally.. catch finally finally try\n{\n StreamReader reader=new StreamReader(\"myfile.txt\");\n //do other stuff\n}\ncatch(Exception ex){\n // Create log, or show notification\n generic.Createlog(\"Error\", ex.message);\n}\nfinally // Will execute despite any exception\n{\n reader.Close();\n}\n"
},
{
"answer_id": 39586676,
"author": "manjuv",
"author_id": 3509222,
"author_profile": "https://Stackoverflow.com/users/3509222",
"pm_score": 3,
"selected": false,
"text": "Try..Catch..Finally Try..Finally Try..Finally"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21727/"
] |
128,853
|
<p>I'm sure there's some trivial one-liner with perl, ruby, bash whatever that would let me run a command in a loop until I observe some string in stdout, then stop. Ideally, I'd like to capture stdout as well, but if it's going to console, that might be enough. </p>
<p>The particular environment in question at the moment is RedHat Linux but need same thing on Mac sometimes too. So something, generic and *nixy would be best. Don't care about Windows - presumably a *nixy thing would work under cygwin.</p>
<p>UPDATE: Note that by "observe some string" I mean "stdout contains some string" not "stdout IS some string". </p>
|
[
{
"answer_id": 128872,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 4,
"selected": false,
"text": "OUTPUT=\"\"; \nwhile [ `echo $OUTPUT | grep -c somestring` = 0 ]; do \n OUTPUT=`$cmd`; \ndone\n function run_until () {\n OUTPUT=\"\";\n while [ `echo $OUTPUT | grep -c $2` = 0 ]; do\n OUTPUT=`$1`;\n echo $OUTPUT;\n done\n}\n OUTPUT=0; \nwhile [ \"$OUTPUT\" = 0 ]; do \n OUTPUT=`$cmd | grep -c somestring`;\ndone\n function run_until () {\n OUTPUT=0; \n while [ \"$OUTPUT\" = 0 ]; do \n OUTPUT=`$1 | grep -c $2`; \n done\n}\n"
},
{
"answer_id": 128875,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 0,
"selected": false,
"text": "while (/bin/true); do\n OUTPUT=`/some/command`\n if [[ \"x$OUTPUT\" != \"x\" ]]; then\n echo $OUTPUT\n break\n fi\n\n sleep 1\ndone\n"
},
{
"answer_id": 128886,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 1,
"selected": false,
"text": "MATCH=''; while [[ \"e$MATCH\" == \"e\" ]]; do MATCH=`COMMAND | grep \"SOME_STRING\"`; done; echo $MATCH\n RUN=''; while [[ \"e$RUN\" == \"e\" ]]; do RUN=`XXXX`; done ; echo $RUN\n"
},
{
"answer_id": 128905,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 5,
"selected": true,
"text": "#!/usr/local/bin/perl -w\n\nif (@ARGV != 2)\n{\n print \"Usage: watchit.pl <cmd> <str>\\n\";\n exit(1);\n}\n\n$cmd = $ARGV[0];\n$str = $ARGV[1];\n\nwhile (1)\n{\n my $output = `$cmd`;\n print $output; # or dump to file if desired\n if ($output =~ /$str/)\n {\n exit(0);\n }\n}\n [bash$] ./watchit.pl ls stop\nwatchit.pl\nwatchit.pl~\nwatchit.pl\nwatchit.pl~\n... # from another terminal type \"touch stop\"\nstop \nwatchit.pl\nwatchit.pl~\n"
},
{
"answer_id": 130406,
"author": "skoob",
"author_id": 20708,
"author_profile": "https://Stackoverflow.com/users/20708",
"pm_score": 1,
"selected": false,
"text": "CONT=1; while [ $CONT -gt 0 ]; do $CMD | tee -a $FILE | grep -q $REGEXP; CONT=$? ; done\n -a grep -q return 0 1 $? $CONT"
},
{
"answer_id": 130521,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 1,
"selected": false,
"text": "until `/some/command`\ndo\n sleep 1\ndone\n until"
},
{
"answer_id": 133040,
"author": "ordnungswidrig",
"author_id": 9069,
"author_profile": "https://Stackoverflow.com/users/9069",
"pm_score": 3,
"selected": false,
"text": "grep -c 99999 while true; do /some/command | grep expected -C 99999 && break; done\n until /some/command | grep expected -C 9999; do echo -n .; done\n"
},
{
"answer_id": 160803,
"author": "markets",
"author_id": 4662,
"author_profile": "https://Stackoverflow.com/users/4662",
"pm_score": 3,
"selected": false,
"text": "perl -e 'do { sleep(1); $_ = `command`; print $_; } until (m/search/);'\n m/search/ m#search /es#"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7671/"
] |
128,857
|
<p>I have a user reporting that when they use the back button to return to a web page that they come back as a different person. It seems like they may be accessing a different users profile.</p>
<p>Here are the important parts of the code:</p>
<pre><code>//here's the code on the web page
public static WebProfile p = null;
protected void Page_Load(object sender, EventArgs e)
{
p = ProfileController.GetWebProfile();
if (!this.IsPostBack)
{
PopulateForm();
}
}
//here's the code in the "ProfileController" (probably misnamed)
public static WebProfile GetWebProfile()
{
//get shopperID from cookie
string mscsShopperID = GetShopperID();
string userName = new tpw.Shopper(Shopper.Columns.ShopperId, mscsShopperID).Email;
p = WebProfile.GetProfile(userName);
return p;
}
</code></pre>
<p>I'm using static methods and a <code>static WebProfile</code> because I need to use the profile object in a <code>static WebMethod</code> (ajax <code>pageMethod</code>). </p>
<ul>
<li>Could this lead to the profile object being "shared" by different users? </li>
<li>Am I not using static methods and objects correctly?</li>
</ul>
<hr>
<p>The reason I changed <code>WebProfile</code> object to a <code>static</code> object was because I need to access the profile object within a <code>[WebMethod]</code> (called from javascript on the page). </p>
<ul>
<li>Is there a way to access a profile object within a <code>[WebMethod]</code>? </li>
<li>If not, what choices do I have?</li>
</ul>
|
[
{
"answer_id": 128872,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 4,
"selected": false,
"text": "OUTPUT=\"\"; \nwhile [ `echo $OUTPUT | grep -c somestring` = 0 ]; do \n OUTPUT=`$cmd`; \ndone\n function run_until () {\n OUTPUT=\"\";\n while [ `echo $OUTPUT | grep -c $2` = 0 ]; do\n OUTPUT=`$1`;\n echo $OUTPUT;\n done\n}\n OUTPUT=0; \nwhile [ \"$OUTPUT\" = 0 ]; do \n OUTPUT=`$cmd | grep -c somestring`;\ndone\n function run_until () {\n OUTPUT=0; \n while [ \"$OUTPUT\" = 0 ]; do \n OUTPUT=`$1 | grep -c $2`; \n done\n}\n"
},
{
"answer_id": 128875,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 0,
"selected": false,
"text": "while (/bin/true); do\n OUTPUT=`/some/command`\n if [[ \"x$OUTPUT\" != \"x\" ]]; then\n echo $OUTPUT\n break\n fi\n\n sleep 1\ndone\n"
},
{
"answer_id": 128886,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 1,
"selected": false,
"text": "MATCH=''; while [[ \"e$MATCH\" == \"e\" ]]; do MATCH=`COMMAND | grep \"SOME_STRING\"`; done; echo $MATCH\n RUN=''; while [[ \"e$RUN\" == \"e\" ]]; do RUN=`XXXX`; done ; echo $RUN\n"
},
{
"answer_id": 128905,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 5,
"selected": true,
"text": "#!/usr/local/bin/perl -w\n\nif (@ARGV != 2)\n{\n print \"Usage: watchit.pl <cmd> <str>\\n\";\n exit(1);\n}\n\n$cmd = $ARGV[0];\n$str = $ARGV[1];\n\nwhile (1)\n{\n my $output = `$cmd`;\n print $output; # or dump to file if desired\n if ($output =~ /$str/)\n {\n exit(0);\n }\n}\n [bash$] ./watchit.pl ls stop\nwatchit.pl\nwatchit.pl~\nwatchit.pl\nwatchit.pl~\n... # from another terminal type \"touch stop\"\nstop \nwatchit.pl\nwatchit.pl~\n"
},
{
"answer_id": 130406,
"author": "skoob",
"author_id": 20708,
"author_profile": "https://Stackoverflow.com/users/20708",
"pm_score": 1,
"selected": false,
"text": "CONT=1; while [ $CONT -gt 0 ]; do $CMD | tee -a $FILE | grep -q $REGEXP; CONT=$? ; done\n -a grep -q return 0 1 $? $CONT"
},
{
"answer_id": 130521,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 1,
"selected": false,
"text": "until `/some/command`\ndo\n sleep 1\ndone\n until"
},
{
"answer_id": 133040,
"author": "ordnungswidrig",
"author_id": 9069,
"author_profile": "https://Stackoverflow.com/users/9069",
"pm_score": 3,
"selected": false,
"text": "grep -c 99999 while true; do /some/command | grep expected -C 99999 && break; done\n until /some/command | grep expected -C 9999; do echo -n .; done\n"
},
{
"answer_id": 160803,
"author": "markets",
"author_id": 4662,
"author_profile": "https://Stackoverflow.com/users/4662",
"pm_score": 3,
"selected": false,
"text": "perl -e 'do { sleep(1); $_ = `command`; print $_; } until (m/search/);'\n m/search/ m#search /es#"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4888/"
] |
128,888
|
<p>In Java, I have a subclass <code>Vertex</code> of the Java3D class <code>Point3f</code>. Now <code>Point3f</code> computes <code>equals()</code> based on the values of its coordinates, but for my <code>Vertex</code> class I want to be stricter: two vertices are only equal if they are the same object. So far, so good:</p>
<pre><code>class Vertex extends Point3f {
// ...
public boolean equals(Object other) {
return this == other;
}
}
</code></pre>
<p>I know this violates the contract of <code>equals()</code>, but since I'll only compare vertices to other vertices this is not a problem.</p>
<p>Now, to be able to put vertices into a <code>HashMap</code>, the <code>hashCode()</code> method must return results consistent with <code>equals()</code>. It currently does that, but probably bases its return value on the fields of the <code>Point3f</code>, and therefore will give hash collisions for different <code>Vertex</code> objects with the same coordinates.</p>
<p>Therefore I would like to base the <code>hashCode()</code> on the object's address, instead of computing it from the <code>Vertex</code>'s fields. I know that the <code>Object</code> class does this, but I cannot call its <code>hashCode()</code> method because <code>Point3f</code> overrides it.</p>
<p>So, actually my question is twofold:</p>
<ul>
<li>Should I even want such a shallow <code>equals()</code>?</li>
<li>If yes, then, how do I get the object's address to compute the hash code from?</li>
</ul>
<p>Edit: I just thought of something... I could generate a random <code>int</code> value on object creation, and use that for the hash code. Is that a good idea? Why (not)?</p>
|
[
{
"answer_id": 128940,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 1,
"selected": false,
"text": "System.identityHashCode() hashCode() hashCode()"
},
{
"answer_id": 128982,
"author": "Jay R.",
"author_id": 5074,
"author_profile": "https://Stackoverflow.com/users/5074",
"pm_score": 0,
"selected": false,
"text": "\nclass Vertex extends Point3f{\n private final Object equalsDelegate = new Object();\n public boolean equals(Object vertex){\n if(vertex instanceof Vertex){\n return this.equalsDelegate.equals(((Vertex)vertex).equalsDelegate);\n }\n else{\n return super.equals(vertex);\n }\n }\n public int hashCode(){\n return this.equalsDelegate.hashCode();\n }\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14637/"
] |
128,914
|
<p>Several months ago my work deployed an in-house function that wraps the standard, php, mysql_query() function with additional options and abilities. A sample feature would be some handy debugging tools we can turn on/off. </p>
<p>I was wondering how popular query handlers are and what features people like to build into them.</p>
|
[
{
"answer_id": 128962,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 1,
"selected": false,
"text": "<?php\n$query = \"SELECT * FROM table\";\n$result = mysql_query($query);\nif (!$result) {\n echo mysql_error();\n} else {\n if (mysql_num_rows($result) > 0) {\n while ($row = mysql_fetch_obj($result)) {\n ...\n }\n }\n}\n?>\n <?php\ntry {\n $result = $db->fetchAll(\"SELECT * FROM table\");\n foreach($result as $row) {\n ...\n }\n} catch (Zend_Exception $e) {\n echo $e->getMessage();\n}\n?>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14959/"
] |
128,923
|
<p>Many times I've seen links like these in HTML pages:</p>
<pre><code><a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a>
</code></pre>
<p>What's the effect of the <code>return false</code> in there?</p>
<p>Also, I don't usually see that in buttons.</p>
<p>Is this specified anywhere? In some spec in w3.org?</p>
|
[
{
"answer_id": 128939,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 3,
"selected": false,
"text": "<a href>"
},
{
"answer_id": 128966,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 9,
"selected": true,
"text": "event.preventDefault()"
},
{
"answer_id": 129500,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 5,
"selected": false,
"text": "// Prevents event bubble up or any usage after this is called.\neventCancel = function (e)\n{\n if (!e)\n if (window.event) e = window.event;\n else return;\n if (e.cancelBubble != null) e.cancelBubble = true;\n if (e.stopPropagation) e.stopPropagation();\n if (e.preventDefault) e.preventDefault();\n if (window.event) e.returnValue = false;\n if (e.cancel != null) e.cancel = true;\n}\n // Handles the click event for each tab\nTabstrip.tabstripLinkElement_click = function (evt, context) \n{\n // Find the tabStrip element (we know it's the parent element of this link)\n var tabstripElement = this.parentNode;\n Tabstrip.showTabByLink(tabstripElement, this);\n return eventCancel(evt);\n}\n"
},
{
"answer_id": 132396,
"author": "HoboBen",
"author_id": 840,
"author_profile": "https://Stackoverflow.com/users/840",
"pm_score": 8,
"selected": false,
"text": "<a href=\"http://www.google.co.uk/\" onclick=\"return (confirm('Follow this link?'))\">Google</a>\n"
},
{
"answer_id": 22270882,
"author": "Dmitri Zaitsev",
"author_id": 1614973,
"author_profile": "https://Stackoverflow.com/users/1614973",
"pm_score": 2,
"selected": false,
"text": "onmousedown onclick onclick='return false' mousedown onmousedown='return false' mousedown click click mousedown mousedown"
},
{
"answer_id": 25377783,
"author": "kamesh",
"author_id": 3007335,
"author_profile": "https://Stackoverflow.com/users/3007335",
"pm_score": 5,
"selected": false,
"text": "<a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a>\n"
},
{
"answer_id": 36315459,
"author": "Shivakrishna",
"author_id": 5485645,
"author_profile": "https://Stackoverflow.com/users/5485645",
"pm_score": 2,
"selected": false,
"text": "return false onclick=\"return false\"\n"
},
{
"answer_id": 59011450,
"author": "Panu Logic",
"author_id": 1639918,
"author_profile": "https://Stackoverflow.com/users/1639918",
"pm_score": 2,
"selected": false,
"text": "<a href = \"\" \nonclick = \"setBodyHtml ('new content'); return false; \"\n> click here </a>\n function setBodyHtml (s)\n{ document.body.innerHTML = s;\n}\n"
},
{
"answer_id": 59419315,
"author": "Allan",
"author_id": 2952113,
"author_profile": "https://Stackoverflow.com/users/2952113",
"pm_score": 1,
"selected": false,
"text": "function checkForm() {\n // return true to submit, return false to prevent submitting\n}\n<form onsubmit=\"return checkForm()\">\n ...\n</form>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15649/"
] |
128,933
|
<p>I am putting together a Samba-based server as a Primary Domain Controller, and ran into a cute little problem that should have been solved many times over. But a number of searches did not yield a result. I need to be able to remove an existing user from an existing group with a command line script. It appears that the usermod easily allows me to add a user to a supplementary group with this command:</p>
<pre><code>usermod -a -G supgroup1,supgroup2 username
</code></pre>
<p>Without the "-a" option, if the user is currently a member of a group which is not listed, the user will be removed from the group. Does anyone have a perl (or Python) script that allows the specification of a user and group for removal? Am I missing an obvious existing command, or well-known solution forthis? Thanks in advance!</p>
<p>Thanks to J.J. for the pointer to the Unix::Group module, which is part of Unix-ConfigFile. It looks like the command deluser would do what I want, but was not in any of my existing repositories. I went ahead and wrote the perl script using the Unix:Group Module. Here is the script for your sysadmining pleasure.</p>
<pre><code>#!/usr/bin/perl
#
# Usage: removegroup.pl login group
# Purpose: Removes a user from a group while retaining current primary and
# supplementary groups.
# Notes: There is a Debian specific utility that can do this called deluser,
# but I did not want any cross-distribution dependencies
#
# Date: 25 September 2008
# Validate Arguments (correct number, format etc.)
if ( ($#ARGV < 1) || (2 < $#ARGV) ) {
print "\nUsage: removegroup.pl login group\n\n";
print "EXIT VALUES\n";
print " The removeuser.pl script exits with the following values:\n\n";
print " 0 success\n\n";
print " 1 Invalid number of arguments\n\n";
print " 2 Login or Group name supplied greater than 16 characters\n\n";
print " 3 Login and/or Group name contains invalid characters\n\n";
exit 1;
}
# Check for well formed group and login names
if ((16 < length($ARGV[0])) ||(16 < length($ARGV[1])))
{
print "Usage: removegroup.pl login group\n";
print "ERROR: Login and Group names must be less than 16 Characters\n";
exit 2;
}
if ( ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$}) || ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$} ) )
{
print "Usage: removegroup.pl login group\n";
print "ERROR: Login and/or Group name contains invalid characters\n";
exit 3;
}
# Set some variables for readability
$login=$ARGV[0];
$group=$ARGV[1];
# Requires the GroupFile interface from perl-Unix-Configfile
use Unix::GroupFile;
$grp = new Unix::GroupFile "/etc/group";
$grp->remove_user("$group", "$login");
$grp->commit();
undef $grp;
exit 0;
</code></pre>
|
[
{
"answer_id": 129468,
"author": "innaM",
"author_id": 7498,
"author_profile": "https://Stackoverflow.com/users/7498",
"pm_score": 1,
"selected": false,
"text": "my $user = 'user';\nmy $groupNoMore = 'somegroup';\nmy $groups = join ',', grep { $_ ne $groupNoMore } split /\\s/, `groups $user`;\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2346/"
] |
128,938
|
<p>I want to install a gem on all my application servers, but gem install requires sudo access - how can I enable sudo only for running this capistrano command? </p>
<p>In other words, I don't wish to use sudo for all my deployment recipes, just when I invoke this command on the command line.</p>
|
[
{
"answer_id": 12591986,
"author": "New Alexandria",
"author_id": 263858,
"author_profile": "https://Stackoverflow.com/users/263858",
"pm_score": 0,
"selected": false,
"text": "run \"sudo do_something\""
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21788/"
] |
128,949
|
<p>Templates are a pretty healthy business in established programming languages, but are there any good ones that can be processed in JavaScript?</p>
<p>By "template" I mean a document that accepts a data object as input, inserts the data into some kind of serialized markup language, and outputs the markup. Well-known examples are <a href="http://en.wikipedia.org/wiki/JavaServer_Pages" rel="nofollow noreferrer">JSP</a>, the original PHP, <a href="http://en.wikipedia.org/wiki/XSLT" rel="nofollow noreferrer">XSLT</a>.</p>
<p>By "good" I mean that it's declarative and easy for an HTML author to write, that it's robust, and that it's supported in other languages too. Something better than the options I know about. Some examples of "not good":</p>
<hr>
<p>String math:</p>
<pre><code>element.innerHTML = "<p>Name: " + data.name
+ "</p><p>Email: " + data.email + "</p>";
</code></pre>
<p>clearly too unwieldy, HTML structure not apparent.</p>
<hr>
<p>XSLT:</p>
<pre><code><p><xsl:text>Name: </xsl:text><xsl:value-of select="//data/name"></p>
<p><xsl:text>Email: </xsl:text><xsl:value-of select="//data/email"></p>
</code></pre>
<p>// Structurally this works well, but let's face it, XSLT confuses HTML developers.</p>
<hr>
<p>Trimpath:</p>
<pre><code><p>Name: ${data.name}</p><p>Email: ${data.email}</p>
</code></pre>
<p>// This is nice, but the processor is only supported in JavaScript, and the language is sort of primitive (<a href="http://code.google.com/p/trimpath/wiki/JavaScriptTemplateSyntax" rel="nofollow noreferrer">http://code.google.com/p/trimpath/wiki/JavaScriptTemplateSyntax</a>).</p>
<hr>
<p>I'd love to see a subset of JSP or ASP or PHP ported to the browser, but I haven't found that.</p>
<p>What are people using these days in JavaScript for their templating?</p>
<h2>Addendum 1 (2008)</h2>
<p>After a few months there have been plenty of workable template languages posted here, but most of them aren't usable in any other language. Most of these templates couldn't be used outside a JavaScript engine.</p>
<p>The exception is Microsoft's -- you can process the same ASP either in the browser or in any other ASP engine. That has its own set of portability problems, since you're bound to Microsoft systems. I marked that as the answer, but am still interested in more portable solutions.</p>
<h2>Addendum 2 (2020)</h2>
<p>Dusting off this old question, it's ten years later, and Mustache is widely supported in dozens of languages. It is now the current answer, in case anyone is still reading this.</p>
|
[
{
"answer_id": 11573000,
"author": "Kernel James",
"author_id": 1203580,
"author_profile": "https://Stackoverflow.com/users/1203580",
"pm_score": 0,
"selected": false,
"text": "<p>Name: <span data-qtext=\"data.name\"></span></p>\n<p>Email: <span data-qtext=\"data.email\"></span></p>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8735/"
] |
128,954
|
<p>I have code to create another "row" (div with inputs) on a button click. I am creating new input elements and everything works fine, however, I can't find a way to access these new elements.</p>
<p>Example: I have input element (name_1 below). Then I create another input element (name_2 below), by using the javascript's <code>createElement</code> function.</p>
<pre><code><input type='text' id='name_1' name="name_1" />
<input type='text' id='name_2' name="name_2" />
</code></pre>
<p>Again, I create the element fine, but I want to be able to access the value of name_2 after it has been created and modified by the user. Example: <code>document.getElementById('name_2');</code></p>
<p>This doesn't work. How do I make the DOM recognize the new element? Is it possible?</p>
<p>My code sample (utilizing jQuery):</p>
<pre><code>function addName(){
var parentDiv = document.createElement("div");
$(parentDiv).attr( "id", "lp_" + id );
var col1 = document.createElement("div");
var input1 = $( 'input[name="lp_name_1"]').clone(true);
$(input1).attr( "name", "lp_name_" + id );
$(col1).attr( "class", "span-4" );
$(col1).append( input1 );
$(parentDiv).append( col1 );
$('#main_div').append(parentDiv);
}
</code></pre>
<p>I have used both jQuery and JavaScript selectors. Example: <code>$('#lp_2').html()</code> returns null. So does <code>document.getElementById('lp_2');</code></p>
|
[
{
"answer_id": 129186,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 0,
"selected": false,
"text": "$(\"#lp_1\")"
},
{
"answer_id": 129199,
"author": "Athena",
"author_id": 17846,
"author_profile": "https://Stackoverflow.com/users/17846",
"pm_score": 0,
"selected": false,
"text": "var input1 = $( 'input[name=\"lp_name_1\"]').clone(true);\n var input1 = $( 'input[@name=\"lp_name_1\"]').clone(true);\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16437/"
] |
128,965
|
<p>When I started writing database queries I didn't know the JOIN keyword yet and naturally I just extended what I already knew and wrote queries like this:</p>
<pre><code>SELECT a.someRow, b.someRow
FROM tableA AS a, tableB AS b
WHERE a.ID=b.ID AND b.ID= $someVar
</code></pre>
<p>Now that I know that this is the same as an INNER JOIN I find all these queries in my code and ask myself if I should rewrite them. Is there something smelly about them or are they just fine?</p>
<hr />
<p><strong>My answer summary</strong>: There is nothing wrong with this query BUT using the keywords will most probably make the code more readable/maintainable.</p>
<p><strong>My conclusion</strong>: I will not change my old queries but I will correct my writing style and use the keywords in the future.</p>
|
[
{
"answer_id": 129005,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 3,
"selected": false,
"text": "SELECT a.someRow, b.someRow\nFROM tableA AS a\nINNER JOIN tableB AS b\n ON a.ID = b.ID\nWHERE b.ID = ?\n"
},
{
"answer_id": 129006,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 3,
"selected": false,
"text": "INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN"
},
{
"answer_id": 129076,
"author": "Meff",
"author_id": 9647,
"author_profile": "https://Stackoverflow.com/users/9647",
"pm_score": 3,
"selected": false,
"text": "SET SHOWPLAN_ALL ON\nGO\n\nDECLARE @TABLE_A TABLE\n(\n ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,\n Data VARCHAR(10) NOT NULL\n)\nINSERT INTO @TABLE_A\nSELECT 'ABC' UNION \nSELECT 'DEF' UNION\nSELECT 'GHI' UNION\nSELECT 'JKL' \n\nDECLARE @TABLE_B TABLE\n(\n ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,\n Data VARCHAR(10) NOT NULL\n)\nINSERT INTO @TABLE_B\nSELECT 'ABC' UNION \nSELECT 'DEF' UNION\nSELECT 'GHI' UNION\nSELECT 'JKL' \n\nSELECT A.Data, B.Data\nFROM\n @TABLE_A AS A, @TABLE_B AS B\nWHERE\n A.ID = B.ID\n\nSELECT A.Data, B.Data\nFROM\n @TABLE_A AS A\n INNER JOIN @TABLE_B AS B ON A.ID = B.ID\n SELECT A.Data, B.Data FROM @TABLE_A AS A, @TABLE_B AS B WHERE A.ID = B.ID\n |--Nested Loops(Inner Join, OUTER REFERENCES:([A].[ID]))\n |--Clustered Index Scan(OBJECT:(@TABLE_A AS [A]))\n |--Clustered Index Seek(OBJECT:(@TABLE_B AS [B]), SEEK:([B].[ID]=@TABLE_A.[ID] as [A].[ID]) ORDERED FORWARD)\n SELECT A.Data, B.Data FROM @TABLE_A AS A INNER JOIN @TABLE_B AS B ON A.ID = B.ID\n |--Nested Loops(Inner Join, OUTER REFERENCES:([A].[ID]))\n |--Clustered Index Scan(OBJECT:(@TABLE_A AS [A]))\n |--Clustered Index Seek(OBJECT:(@TABLE_B AS [B]), SEEK:([B].[ID]=@TABLE_A.[ID] as [A].[ID]) ORDERED FORWARD)\n"
},
{
"answer_id": 129410,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 6,
"selected": true,
"text": "WHERE SELECT * FROM people p, companies c \n WHERE p.companyID = c.id AND p.firstName = 'Daniel'\n people companies companyID id JOIN SELECT * FROM people p JOIN companies c ON p.companyID = c.id\n WHERE p.firstName = 'Daniel'\n ON JOIN JOIN"
},
{
"answer_id": 129443,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "SELECT *\nFROM table1 AS a, table2 AS b\n LEFT OUTER JOIN table3 AS c ON a.column1 = c.column1\nWHERE a.column2 = b.column2;\n SELECT *\nFROM table1 AS a\n INNER JOIN table2 AS b ON a.column2 = b.column2\n LEFT OUTER JOIN table3 AS c ON a.column1 = c.column1;\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11995/"
] |
128,981
|
<p>I'm writing a program and am having trouble using the scanf and fopen working together.</p>
<p>From what I can tell my erroneous lines seems to be:</p>
<pre><code>FiLE * DataFile
DataFile = fopen("StcWx.txt","r");
scanf(DataFile, "%i %i %i %.2f %i %i", &Year, &Month, &Day, &Precip, &High, &Low);
</code></pre>
<p>The file it opens from has a list of weather data that looks like this:</p>
<pre><code>1944 4 12 0 58 24
1944 4 13 0.4 58 29
1944 4 14 0.54 42 29
1944 4 15 0 43 27
</code></pre>
<p>(Those spaces are tabs)</p>
<p>The error that is displayed is "[Warning] passing arg 1 of `scanf' from incompatible pointer type"</p>
<p>Can anyone help me?</p>
|
[
{
"answer_id": 128993,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 1,
"selected": false,
"text": "fscanf"
},
{
"answer_id": 54590680,
"author": "Vừng Nhỏ ",
"author_id": 5137968,
"author_profile": "https://Stackoverflow.com/users/5137968",
"pm_score": 0,
"selected": false,
"text": "freopen (\"StcWx.txt\",\"r\",stdin); scanf(\"%i %i %i %.2f %i %i\", &Year, &Month, &Day, &Precip, &High, &Low);"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
128,990
|
<p>I have a base URL :</p>
<pre><code>http://my.server.com/folder/directory/sample
</code></pre>
<p>And a relative one :</p>
<pre><code>../../other/path
</code></pre>
<p>How to get the absolute URL from this ? It's pretty straighforward using string manipulation, but I would like to do this in a secure way, using the <code>Uri</code> class or something similar.</p>
<p>It's for a standard a C# app, not an ASP.NET one.</p>
|
[
{
"answer_id": 129003,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 7,
"selected": true,
"text": "var baseUri = new Uri(\"http://my.server.com/folder/directory/sample\");\nvar absoluteUri = new Uri(baseUri,\"../../other/path\");\n Uri uri;\nif ( Uri.TryCreate(\"http://base/\",\"../relative\", out uri) ) doSomething(uri);\n"
},
{
"answer_id": 38462625,
"author": "Matas Vaitkevicius",
"author_id": 1509764,
"author_profile": "https://Stackoverflow.com/users/1509764",
"pm_score": 0,
"selected": false,
"text": "var absoluteUrl = function(href) {\n var link = document.createElement(\"a\");\n link.href = href;\n return link.href;\n} \n absoluteUrl(\"http://google.com\") http://google.com/ absoluteUrl(\"../../absolute\") http://stackoverflow.com/absolute"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4687/"
] |
128,998
|
<p>I usually format my project directory like J-P Boodhoo. a main dir containing solution file, then a lib folder for all third-party lib, a src dir, a tools lib for third-party that wont be deployed.... <a href="http://blog.jpboodhoo.com/DirectoryStructureForProjects.aspx" rel="noreferrer">For more info look here</a></p>
<p>I set in my project the reference path for all the needed folder, but if a developper checkout the trunk, he have to set all the reference path. Is there a way to simplify this ?</p>
<p>And am I using Visual Studio 2008.</p>
<p>Thank you.</p>
|
[
{
"answer_id": 129102,
"author": "jwfearn",
"author_id": 10559,
"author_profile": "https://Stackoverflow.com/users/10559",
"pm_score": 3,
"selected": true,
"text": ".vcproj .sln .vsprops"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7419/"
] |
129,013
|
<p>This is only happening on the live server. On multiply development servers the image is being created as expected.</p>
<p>LIVE:
Red Hat</p>
<pre><code>$ php --version
PHP 5.2.6 (cli) (built: May 16 2008 21:56:34)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
</code></pre>
<p>GD Support => enabled
GD Version => bundled (2.0.34 compatible)</p>
<p>DEV:
Ubuntu 8</p>
<pre><code>$ php --version
PHP 5.2.4-2ubuntu5.3 with Suhosin-Patch 0.9.6.2 (cli) (built: Jul 23 2008 06:44:49)
Copyright (c) 1997-2007 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
</code></pre>
<p>GD Support => enabled
GD Version => 2.0 or higher</p>
<pre><code><?php
$image = imagecreatetruecolor($width, $height);
// Colors in RGB
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, $width, $height, $white);
imagettftext($image, $fontSize, 0, 0, 50, $black, $font, $text);
imagegif($image, $file_path);
?>
</code></pre>
<p>In a perfect world I would like the live server and the dev server to be running the same distro, but the live server must be Red Hat. </p>
<p>My question is does anyone know the specific differences that would cause the right most part of an image to be cut off using the bundled version of GD?</p>
<p>EDIT: I am not running out of memory. There are no errors being generated in the logs files. As far as php is concerned the image is being generated correctly. That is why I believe it to be a GD specific problem with the bundled version.</p>
|
[
{
"answer_id": 851769,
"author": "Darkerstar",
"author_id": 73565,
"author_profile": "https://Stackoverflow.com/users/73565",
"pm_score": 0,
"selected": false,
"text": "imagettftext($image, $fontSize, 0, 0, 50, $black, $font, $text);\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1797/"
] |
129,019
|
<p>I would like something that I can use as follows</p>
<pre><code>var msg = new NonStaticMessageBox();
if(msg.Show("MyMessage", "MyCaption", MessageBoxButtons.OkCancel) == DialogResult.Ok)
{....}
</code></pre>
<p>But specifically non-static (I need to pass a reference to it around) does anyone know if/where such an object exists?</p>
|
[
{
"answer_id": 132654,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public class MessageBox\n{\n private Form _messageForm = null;\n\n public void Show(string title,...) {...}\n}\n"
},
{
"answer_id": 594890,
"author": "Tristan Warner-Smith",
"author_id": 29553,
"author_profile": "https://Stackoverflow.com/users/29553",
"pm_score": 0,
"selected": false,
"text": "MyFactory.GetMyCustomDialogWithInterfacesOrSomesuch myDialog = new ...\nmyDialog.ShowDialog() == DialogResult.Ok;\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
129,023
|
<p>I have a questionable coding practice. </p>
<p>When I need to iterate through a small list of items whose count limit is under <code>32000</code>, I use <code>Int16</code> for my <em>i</em> variable type instead of <code>Integer</code>. I do this because I assume using the <code>Int16</code> is more efficient than a full blown <code>Integer</code>. </p>
<p>Am I wrong? Is there no effective performance difference between using an <code>Int16</code> vs an <code>Integer</code>? Should I stop using <code>Int16</code> and just stick with <code>Integer</code> for all my counting/iteration needs?</p>
|
[
{
"answer_id": 129817,
"author": "Alex Lyman",
"author_id": 5897,
"author_profile": "https://Stackoverflow.com/users/5897",
"pm_score": 7,
"selected": false,
"text": "Int32 Int64 UInt32 UInt64 Int32 Int16 Int32 Int32 Int64 Byte SByte UInt16 Int16 UInt32 UInt64 for (short i = 0; i < 32000; i++) {\n ...\n}\n short i = 0 i<32000 i++ Int16 i = 0;\nLOOP:\n Int32 temp0 = Convert_I16_To_I32(i); // !!!\n if (temp0 >= 32000) goto END;\n ...\n Int32 temp1 = Convert_I16_To_I32(i); // !!!\n Int32 temp2 = temp1 + 1;\n i = Convert_I32_To_I16(temp2); // !!!\n goto LOOP;\nEND:\n Int32 Int64"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17235/"
] |
129,036
|
<p>I am writing a component that, given a ZIP file, needs to:</p>
<ol>
<li>Unzip the file.</li>
<li>Find a specific dll among the unzipped files.</li>
<li>Load that dll through reflection and invoke a method on it.</li>
</ol>
<p>I'd like to unit test this component.</p>
<p>I'm tempted to write code that deals directly with the file system:</p>
<pre class="lang-cs prettyprint-override"><code>void DoIt()
{
Zip.Unzip(theZipFile, "C:\\foo\\Unzipped");
System.IO.File myDll = File.Open("C:\\foo\\Unzipped\\SuperSecret.bar");
myDll.InvokeSomeSpecialMethod();
}
</code></pre>
<p>But folks often say, "Don't write unit tests that rely on the file system, database, network, etc."</p>
<p>If I were to write this in a unit-test friendly way, I suppose it would look like this:</p>
<pre class="lang-cs prettyprint-override"><code>void DoIt(IZipper zipper, IFileSystem fileSystem, IDllRunner runner)
{
string path = zipper.Unzip(theZipFile);
IFakeFile file = fileSystem.Open(path);
runner.Run(file);
}
</code></pre>
<p>Yay! Now it's testable; I can feed in test doubles (mocks) to the DoIt method. But at what cost? I've now had to define 3 new interfaces just to make this testable. And what, exactly, am I testing? I'm testing that my DoIt function properly interacts with its dependencies. It doesn't test that the zip file was unzipped properly, etc.</p>
<p>It doesn't feel like I'm testing functionality anymore. It feels like I'm just testing class interactions.</p>
<p><strong>My question is this</strong>: what's the proper way to unit test something that is dependent on the file system?</p>
<p><em>edit</em> I'm using .NET, but the concept could apply Java or native code too.</p>
|
[
{
"answer_id": 129204,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 7,
"selected": true,
"text": "chdir() chdir()"
},
{
"answer_id": 23124879,
"author": "Christopher Perry",
"author_id": 413414,
"author_profile": "https://Stackoverflow.com/users/413414",
"pm_score": 6,
"selected": false,
"text": "void DoIt(IZipper zipper, IFileSystem fileSystem, IDllRunner runner)\n{\n string path = zipper.Unzip(theZipFile);\n IFakeFile file = fileSystem.Open(path);\n runner.Run(file);\n}\n // Assuming that zipper, fileSystem, and runner are mocks\nvoid testDoIt()\n{\n // mock behavior of the mock objects\n when(zipper.Unzip(any(File.class)).thenReturn(\"some path\");\n when(fileSystem.Open(\"some path\")).thenReturn(mock(IFakeFile.class));\n\n // run the test\n someObject.DoIt(zipper, fileSystem, runner);\n\n // verify things were called\n verify(zipper).Unzip(any(File.class));\n verify(fileSystem).Open(\"some path\"));\n verify(runner).Run(file);\n}\n DoIt() byte[] interface StreamFactory {\n OutputStream outStream();\n InputStream inStream();\n}\n\nclass Base64FileWriter {\n public void write(byte[] contents, StreamFactory streamFactory) {\n OutputStream outputStream = streamFactory.outStream();\n outputStream.write(Base64.encodeBase64(contents));\n }\n}\n\n@Test\npublic void save_shouldBase64EncodeContents() {\n OutputStream outputStream = new ByteArrayOutputStream();\n StreamFactory streamFactory = mock(StreamFactory.class);\n when(streamFactory.outStream()).thenReturn(outputStream);\n\n // Run the method under test\n Base64FileWriter fileWriter = new Base64FileWriter();\n fileWriter.write(\"Man\".getBytes(), streamFactory);\n\n // Assert we saved the base64 encoded contents\n assertThat(outputStream.toString()).isEqualTo(\"TWFu\");\n}\n ByteArrayOutputStream FileOutputStream outputStream() File write DoIt()"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/536/"
] |
129,043
|
<p>I have a bash script that creates a Subversion patch file for the current directory. I want to modify it to zip the produced file, if <code>-z</code> is given as an argument to the script.</p>
<p>Here's the relevant part:</p>
<pre><code>zipped=''
zipcommand='>'
if [ "$1" = "-z" ]
then
zipped='zipped '
filename="${filename}.zip"
zipcommand='| zip >'
fi
echo "Creating ${zipped}patch file $filename..."
svn diff $zipcommand $filename
</code></pre>
<p>This doesn't work because it passes the <code>|</code> or <code>></code> contained in <code>$zipcommand</code> as an argument to <code>svn</code>.</p>
<p>I can easily work around this, but the question is whether it's ever possible to use these kinds of operators when they're contained in variables.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 129132,
"author": "Keeth",
"author_id": 20588,
"author_profile": "https://Stackoverflow.com/users/20588",
"pm_score": 4,
"selected": true,
"text": "zipped=''\nzipcommand='>'\n\nif [ \"$1\" = \"-z\" ]\nthen\n zipped='zipped '\n filename=\"${filename}.zip\"\n zipcommand='| zip -@'\nfi\n\necho \"Creating ${zipped}patch file $filename...\"\n\neval \"svn diff $zipcommand $filename\"\n# this also works: \n# bash -c \"svn diff $zipcommand $filename\"\n zipcommand='| zip -@'\n zipcommand='| zip - - >'\n"
},
{
"answer_id": 129149,
"author": "Daniel Bungert",
"author_id": 21093,
"author_profile": "https://Stackoverflow.com/users/21093",
"pm_score": 2,
"selected": false,
"text": "# eval 'printf \"foo\\nbar\" | grep bar'\nbar\n"
},
{
"answer_id": 132267,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 0,
"selected": false,
"text": "zsh alias -g L='| less'\nalias -g S='| sort'\nalias -g U='| uniq -c'\n ./somecommand.sh S U L\n"
},
{
"answer_id": 33428179,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 0,
"selected": false,
"text": "svn diff if [ \"$1\" = \"-z\" ]; then\n zipped='zipped '\n filename=$filename.zip\n exec 3> >(zip > \"$filename\")\nelse\n exec 3> \"$filename\"\nfi\n\necho \"Creating ${zipped}patch file $filename\"\nsvn diff >&3\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
] |
129,046
|
<p>How would I disable and later enable all indexes in a given schema/database in Oracle?</p>
<p>Note: This is to make sqlldr run faster.</p>
|
[
{
"answer_id": 129163,
"author": "Dmitry Khalatov",
"author_id": 18174,
"author_profile": "https://Stackoverflow.com/users/18174",
"pm_score": 2,
"selected": false,
"text": "alter session set skip_unusable_indexes = true; alter index your_index unusable; alter index your_index rebuild [online];"
},
{
"answer_id": 129227,
"author": "Brian Deterling",
"author_id": 14619,
"author_profile": "https://Stackoverflow.com/users/14619",
"pm_score": 2,
"selected": false,
"text": "select dbms_metadata.get_ddl('INDEX', u.index_name) from user_indexes u;\n"
},
{
"answer_id": 129313,
"author": "oneself",
"author_id": 9435,
"author_profile": "https://Stackoverflow.com/users/9435",
"pm_score": 1,
"selected": false,
"text": "alter session set skip_unusable_indexes = true;\nselect 'alter index ' || u.index_name || ' unusable;' from user_indexes u;\n select 'alter index ' || u.index_name || ' rebuild online;' from user_indexes u;\n"
},
{
"answer_id": 136612,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "set pagesize 0\n\nalter session set skip_unusable_indexes = true;\nspool c:\\temp\\disable_indexes.sql\nselect 'alter index ' || u.index_name || ' unusable;' from user_indexes u;\nspool off\n@c:\\temp\\disable_indexes.sql\n select 'alter index ' || u.index_name || \n' rebuild online;' from user_indexes u;\n"
},
{
"answer_id": 3526027,
"author": "jmc",
"author_id": 425739,
"author_profile": "https://Stackoverflow.com/users/425739",
"pm_score": 5,
"selected": true,
"text": "DECLARE\n CURSOR usr_idxs IS select * from user_indexes;\n cur_idx usr_idxs% ROWTYPE;\n v_sql VARCHAR2(1024);\n\nBEGIN\n OPEN usr_idxs;\n LOOP\n FETCH usr_idxs INTO cur_idx;\n EXIT WHEN NOT usr_idxs%FOUND;\n\n v_sql:= 'ALTER INDEX ' || cur_idx.index_name || ' UNUSABLE';\n EXECUTE IMMEDIATE v_sql;\n END LOOP;\n CLOSE usr_idxs;\nEND;\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9435/"
] |
129,053
|
<p>How does Google's API make cross-domain requests back to Google, when it's on your website?</p>
|
[
{
"answer_id": 131317,
"author": "Burke",
"author_id": 21980,
"author_profile": "https://Stackoverflow.com/users/21980",
"pm_score": 0,
"selected": false,
"text": "window.name"
},
{
"answer_id": 15170008,
"author": "jpillora",
"author_id": 977939,
"author_profile": "https://Stackoverflow.com/users/977939",
"pm_score": 2,
"selected": false,
"text": "<iframe name=\"oauth2relay678\" id=\"oauth2relay678\" \n src=\"https://accounts.google.com/o/oauth2/postmessageRelay?\n parent=https%3A%2F%2Fwww.example.com.au#rpctoken=12345&forcesecure=1\" \n style=\"width: 1px; height: 1px; position: absolute; left: -100px;\">\n</iframe>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16628/"
] |
129,077
|
<p>This issue came up when I got different records counts for what I thought were identical queries one using a <code>not in</code> <code>where</code> constraint and the other a <code>left join</code>. The table in the <code>not in</code> constraint had one null value (bad data) which caused that query to return a count of 0 records. I sort of understand why but I could use some help fully grasping the concept.</p>
<p>To state it simply, why does query A return a result but B doesn't?</p>
<pre><code>A: select 'true' where 3 in (1, 2, 3, null)
B: select 'true' where 3 not in (1, 2, null)
</code></pre>
<p>This was on SQL Server 2005. I also found that calling <code>set ansi_nulls off</code> causes B to return a result.</p>
|
[
{
"answer_id": 129151,
"author": "YonahW",
"author_id": 3821,
"author_profile": "https://Stackoverflow.com/users/3821",
"pm_score": 6,
"selected": false,
"text": "NOT IN NULL NOT IN NULL NULL 0 NULL"
},
{
"answer_id": 129152,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 9,
"selected": true,
"text": "select 'true' where 3 = 1 or 3 = 2 or 3 = 3 or 3 = null\n 3 = 3 select 'true' where 3 <> 1 and 3 <> 2 and 3 <> null\n ansi_nulls 3 <> null ansi_nulls 3 <> null"
},
{
"answer_id": 132402,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 6,
"selected": false,
"text": " 3 = 1 or 3 = 2 or 3 = 3 or 3 = null\nwhich is:\n FALSE or FALSE or TRUE or UNKNOWN\nwhich evaluates to \n TRUE\n 3 <> 1 and 3 <> 2 and 3 <> null\nwhich evaluates to:\n TRUE and TRUE and UNKNOWN\nwhich evaluates to:\n UNKNOWN\n select 'true' where 3 <> null\nselect 'true' where not (3 <> null)\n"
},
{
"answer_id": 1031653,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "select party_code \nfrom abc as a\nwhere party_code not in (select party_code \n from xyz \n where party_code = a.party_code);\n"
},
{
"answer_id": 7526344,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 3,
"selected": false,
"text": "SELECT CONSTRAINT DECLARE @T TABLE \n(\n true CHAR(4) DEFAULT 'true' NOT NULL, \n CHECK ( 3 IN (1, 2, 3, NULL )), \n CHECK ( 3 NOT IN (1, 2, NULL ))\n);\n\nINSERT INTO @T VALUES ('true');\n\nSELECT COUNT(*) AS tally FROM @T;\n IN NOT IN WHERE"
},
{
"answer_id": 7571289,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 3,
"selected": false,
"text": "NOT IN (subquery) NOT EXISTS NOT IN NOT EXISTS sp sno pno qty VALUES ('S1', 'P1', NULL), \n ('S2', 'P1', 200),\n ('S3', 'P1', 1000)\n NOT IN WITH sp AS \n ( SELECT * \n FROM ( VALUES ( 'S1', 'P1', NULL ), \n ( 'S2', 'P1', 200 ),\n ( 'S3', 'P1', 1000 ) )\n AS T ( sno, pno, qty )\n )\nSELECT DISTINCT spx.sno\n FROM sp spx\n WHERE spx.pno = 'P1'\n AND 1000 NOT IN (\n SELECT spy.qty\n FROM sp spy\n WHERE spy.sno = spx.sno\n AND spy.pno = 'P1'\n );\n NOT EXISTS WITH sp AS \n ( SELECT * \n FROM ( VALUES ( 'S1', 'P1', NULL ), \n ( 'S2', 'P1', 200 ),\n ( 'S3', 'P1', 1000 ) )\n AS T ( sno, pno, qty )\n )\nSELECT DISTINCT spx.sno\n FROM sp spx\n WHERE spx.pno = 'P1'\n AND NOT EXISTS (\n SELECT *\n FROM sp spy\n WHERE spy.sno = spx.sno\n AND spy.pno = 'P1'\n AND spy.qty = 1000\n );\n NOT EXISTS sp spq spq sp EXCEPT WITH sp AS \n ( SELECT * \n FROM ( VALUES ( 'S1', 'P1' ), \n ( 'S2', 'P1' ),\n ( 'S3', 'P1' ) )\n AS T ( sno, pno )\n ),\n spq AS \n ( SELECT * \n FROM ( VALUES ( 'S2', 'P1', 200 ),\n ( 'S3', 'P1', 1000 ) )\n AS T ( sno, pno, qty )\n )\nSELECT sno\n FROM spq\n WHERE pno = 'P1'\nEXCEPT \nSELECT sno\n FROM spq\n WHERE pno = 'P1'\n AND qty = 1000;\n"
},
{
"answer_id": 26684098,
"author": "Mihai",
"author_id": 1745672,
"author_profile": "https://Stackoverflow.com/users/1745672",
"pm_score": 3,
"selected": false,
"text": "SELECT blah FROM t WHERE blah NOT IN\n (SELECT someotherBlah FROM t2 WHERE someotherBlah IS NOT NULL )\n"
},
{
"answer_id": 59084753,
"author": "Salman A",
"author_id": 87015,
"author_profile": "https://Stackoverflow.com/users/87015",
"pm_score": 3,
"selected": false,
"text": "IN SELECT * FROM (VALUES (1), (2)) AS tbl(col) WHERE col IN (NULL, 1)\n-- returns first row\n NOT SELECT * FROM (VALUES (1), (2)) AS tbl(col) WHERE NOT col IN (NULL, 1)\n-- returns zero rows\n SELECT * FROM (VALUES (1), (2)) AS tbl(col) WHERE NOT (col = NULL OR col = 1)\n | col | col = NULL⁽¹⁾ | col = 1 | col = NULL OR col = 1 | NOT (col = NULL OR col = 1) |\n|-----|----------------|---------|-----------------------|-----------------------------|\n| 1 | UNKNOWN | TRUE | TRUE | FALSE |\n| 2 | UNKNOWN | FALSE | UNKNOWN⁽²⁾ | UNKNOWN⁽³⁾ |\n NULL UNKNOWN OR TRUE UNKNOWN UNKNOWN NOT UNKNOWN UNKNOWN NULL"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12752/"
] |
129,088
|
<p>I am writing a script for MS PowerShell. This script uses the <code>Copy-Item</code> command. One of the optional arguments to this command is "<code>-container</code>". The documentation for the argument states that specifying this argument "Preserves container objects during the copy operation."</p>
<p>This is all well and good, for I would be the last person to want unpreserved container objects during a copy operation. But in all seriousness, what does this argument do? Particularly in the case where I am copying a disk directory tree from one place to another, what difference does this make to the behavior of the <code>Copy-Item</code> command?</p>
|
[
{
"answer_id": 129385,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 6,
"selected": true,
"text": "-container: $false"
},
{
"answer_id": 21798660,
"author": "bouvierr",
"author_id": 542417,
"author_profile": "https://Stackoverflow.com/users/542417",
"pm_score": 6,
"selected": false,
"text": "-Container -Recurse -Container -Container: $true # X:.\n# ├───destination\n# └───source\n# │ source.1.txt\n# │ source.2.txt\n# │\n# └───source.1\n# source.1.1.txt\n X:\\ Copy-Item -Path source -Destination .\\destination\nCopy-Item -Path source -Destination .\\destination -Container\n# X:.\n# ├───destination\n# │ └───source\n# └───source (...)\n Copy-Item -Path source -Destination .\\destination -Container: $false\n# Exception: Container cannot be copied to another container. \n# The -Recurse or -Container parameter is not specified. \n Copy-Item -Path source -Destination .\\destination -Recurse\nCopy-Item -Path source -Destination .\\destination -Recurse -Container\n# X:.\n# ├───destination\n# │ └───source\n# │ │ source.1.txt\n# │ │ source.2.txt\n# │ │\n# │ └───source.1\n# │ source.1.1.txt\n# └───source (...) \n Copy-Item -Path source -Destination .\\destination -Recurse -Container: $false\n# X:.\n# ├───destination\n# │ │ source.1.1.txt\n# │ │ source.1.txt\n# │ │ source.2.txt\n# │ │\n# │ └───source.1\n# └───source (...)\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9117/"
] |
129,120
|
<p>I've been a professional software engineer for about a year now, having graduated with a CS degree. I've known about assertions for a while in C++ and C, but had no idea they existed in C# and .NET at all until recently.</p>
<p>Our production code contains no asserts whatsoever and my question is this...</p>
<p>Should I begin using Asserts in our production code? And if so, When is its use most appropriate? Would it make more sense to do</p>
<pre><code>Debug.Assert(val != null);
</code></pre>
<p>or</p>
<pre><code>if ( val == null )
throw new exception();
</code></pre>
|
[
{
"answer_id": 129136,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 7,
"selected": false,
"text": "Debug.Assert() DEBUG Debug.Assert() Debug.Assert()"
},
{
"answer_id": 129179,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 5,
"selected": false,
"text": "Debug.Assert(val != null);\nif ( val == null )\n throw new exception();\n if ( val == null )\n{\n Debug.Assert(false,\"breakpoint if val== null\");\n throw new exception();\n}\n"
},
{
"answer_id": 129535,
"author": "devlord",
"author_id": 16454,
"author_profile": "https://Stackoverflow.com/users/16454",
"pm_score": 3,
"selected": false,
"text": "using System.Diagnostics;\n\nobject GetObject()\n{...}\n\nobject someObject = GetObject();\nDebug.Assert(someObject != null);\n"
},
{
"answer_id": 5031211,
"author": "Nicholas Piasecki",
"author_id": 32187,
"author_profile": "https://Stackoverflow.com/users/32187",
"pm_score": 6,
"selected": false,
"text": "if () { throw; } Debug.Assert()"
},
{
"answer_id": 20715592,
"author": "shannon",
"author_id": 608220,
"author_profile": "https://Stackoverflow.com/users/608220",
"pm_score": 2,
"selected": false,
"text": "String.Find -1 -2 -1"
},
{
"answer_id": 20830932,
"author": "Jon Hanna",
"author_id": 400547,
"author_profile": "https://Stackoverflow.com/users/400547",
"pm_score": 3,
"selected": false,
"text": "Debug.Assert(true);\n public static void ConsumeEnumeration<T>(this IEnumerable<T> source)\n{\n if(source != null)\n using(var en = source.GetEnumerator())\n RunThroughEnumerator(en);\n}\npublic static T GetFirstAndConsume<T>(this IEnumerable<T> source)\n{\n if(source == null)\n throw new ArgumentNullException(\"source\");\n using(var en = source.GetEnumerator())\n {\n if(!en.MoveNext())\n throw new InvalidOperationException(\"Empty sequence\");\n T ret = en.Current;\n RunThroughEnumerator(en);\n return ret;\n }\n}\nprivate static void RunThroughEnumerator<T>(IEnumerator<T> en)\n{\n Debug.Assert(en != null);\n while(en.MoveNext());\n}\n GetFirstAndConsume en != null Debug.Assert(true) en != null true"
},
{
"answer_id": 26407624,
"author": "StuartLC",
"author_id": 314291,
"author_profile": "https://Stackoverflow.com/users/314291",
"pm_score": 4,
"selected": false,
"text": "Asserts Asserts Asserts Asserts Asserts Asserts Debug Debug.Assert Asserts? Assert Assert Debug.Assert Contract.Requires Contract.Ensures Invariant Contract.Assumes"
},
{
"answer_id": 31746164,
"author": "AlexDev",
"author_id": 733760,
"author_profile": "https://Stackoverflow.com/users/733760",
"pm_score": 0,
"selected": false,
"text": "Debug.Assert Trace.Assert using System.Diagnostics;\n\npublic class ExceptionTraceListener : DefaultTraceListener\n{\n [DebuggerStepThrough]\n public override void Fail(string message, string detailMessage)\n {\n throw new AssertException(message);\n }\n}\n\npublic class AssertException : Exception\n{\n public AssertException(string message) : base(message) { }\n}\n <system.diagnostics>\n <trace>\n <listeners>\n <remove name=\"Default\"/>\n <add name=\"ExceptionListener\" type=\"Namespace.ExceptionTraceListener,AssemblyName\"/>\n </listeners>\n </trace>\n </system.diagnostics>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8945/"
] |
129,133
|
<p>How do I view the SQL that is generated by nHibernate? version 1.2</p>
|
[
{
"answer_id": 129818,
"author": "mathieu",
"author_id": 971,
"author_profile": "https://Stackoverflow.com/users/971",
"pm_score": 6,
"selected": true,
"text": "<section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler,log4net\"/>\n <log4net>\n <appender name=\"NHibernateFileLog\" type=\"log4net.Appender.FileAppender\">\n <file value=\"logs/nhibernate.txt\" />\n <appendToFile value=\"false\" />\n <layout type=\"log4net.Layout.PatternLayout\">\n <conversionPattern value=\"%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n\" />\n </layout>\n </appender>\n <logger name=\"NHibernate.SQL\" additivity=\"false\">\n <level value=\"DEBUG\"/>\n <appender-ref ref=\"NHibernateFileLog\"/>\n </logger>\n</log4net>\n log4net.Config.XmlConfigurator.Configure();\n [assembly: log4net.Config.XmlConfigurator(Watch=true)]\n"
},
{
"answer_id": 36732969,
"author": "Alexander",
"author_id": 1456567,
"author_profile": "https://Stackoverflow.com/users/1456567",
"pm_score": 5,
"selected": false,
"text": "using NHibernate;\n\nnamespace WebApplication2.Infrastructure\n{\n public class SQLDebugOutput : EmptyInterceptor, IInterceptor\n {\n public override NHibernate.SqlCommand.SqlString\n OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)\n {\n System.Diagnostics.Debug.WriteLine(\"NH: \" + sql);\n\n return base.OnPrepareStatement(sql);\n }\n }\n}\n public static void OpenSession() {\n\n#if DEBUG\n HttpContext.Current.Items[SessionKey] = _sessionFactory.OpenSession(new SQLDebugOutput());\n\n#else\n HttpContext.Current.Items[SessionKey] = _sessionFactory.OpenSession();\n \n#endif\n}\n var totalPostsCount = Database.Session.Query<Post>().Count();\n \n var currentPostPage = Database.Session.Query<Post>()\n .OrderByDescending(c => c.CreatedAt)\n .Skip((page - 1) * PostsPerPage)\n .Take(PostsPerPage)\n .ToList();\n"
},
{
"answer_id": 62440063,
"author": "Formalist",
"author_id": 12154974,
"author_profile": "https://Stackoverflow.com/users/12154974",
"pm_score": 0,
"selected": false,
"text": "private String NHibernateSql(IQueryable queryable)\n{\n var prov = queryable.Provider as DefaultQueryProvider;\n var session = prov.Session as ISession;\n\n var sessionImpl = session.GetSessionImplementation();\n var factory = sessionImpl.Factory;\n var nhLinqExpression = new NhLinqExpression(queryable.Expression, factory);\n var translatorFactory = new NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory();\n var translator = translatorFactory.CreateQueryTranslators(nhLinqExpression, null, false, sessionImpl.EnabledFilters, factory).First();\n var sql = translator.SQLString;\n\n var parameters = nhLinqExpression.ParameterValuesByName;\n if ( (parameters?.Count ?? 0) > 0)\n {\n sql += \"\\r\\n\\r\\n-- Parameters:\\r\\n\";\n foreach (var par in parameters)\n {\n sql += \"-- \" + par.Key.ToString() + \" - \" + par.Value.ToString() + \"\\r\\n\";\n }\n }\n\n return sql;\n}\n NHibernate var query = from a in session.Query<MyRecord>()\n where a.Id == \"123456\" \n orderby a.Name\n select a;\n\nvar sql = NHibernateSql(query);\n"
},
{
"answer_id": 65579330,
"author": "Amit Joshi",
"author_id": 5779732,
"author_profile": "https://Stackoverflow.com/users/5779732",
"pm_score": 0,
"selected": false,
"text": "Configuration configuration = new Configuration();\n\nconfiguration.SetProperty(NHibernate.Cfg.Environment.Dialect, ......);\n//Set other configuration.SetProperty as per need\nconfiguration.SetProperty(NHibernate.Cfg.Environment.ShowSql, \"true\"); //Enable ShowSql\nconfiguration.SetProperty(NHibernate.Cfg.Environment.FormatSql, \"true\"); //Enable FormatSql to make the log readable; optional.\n\nconfiguration.AddMapping(......);\nconfiguration.BuildMappings();\n\nISessionFactory sessionFactory = configuration.BuildSessionFactory();\n\n//ISessionFactory is setup so far. Now, configure logging.\nHierarchy hierarchy = (Hierarchy)LogManager.GetRepository(Assembly.GetEntryAssembly());\nhierarchy.Root.RemoveAllAppenders();\n\nFileAppender fileAppender = new FileAppender();\nfileAppender.Name = \"NHFileAppender\";\nfileAppender.File = logFilePath;\nfileAppender.AppendToFile = true;\nfileAppender.LockingModel = new FileAppender.MinimalLock();\nfileAppender.Layout = new PatternLayout(\"%d{yyyy-MM-dd HH:mm:ss}:%m%n%n\");\nfileAppender.ActivateOptions();\n\nLogger logger = hierarchy.GetLogger(\"NHibernate.SQL\") as Logger;\nlogger.Additivity = false;\nlogger.Level = Level.Debug;\nlogger.AddAppender(fileAppender);\n\nhierarchy.Configured = true;\n FileAppender Logger"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1642688/"
] |
129,144
|
<p>Sometimes I find myself in the situation where I want to execute several sequential commands like such:</p>
<pre><code>try:
foo(a, b)
except Exception, e:
baz(e)
try:
bar(c, d)
except Exception, e:
baz(e)
...
</code></pre>
<p>This same pattern occurs when exceptions simply need to be ignored.</p>
<p>This feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code.</p>
<p>In C, I would have solved this type of problem easily with a macro, but unfortunately, this cannot be done in straight python.</p>
<p>Question: How can I best reduce the code footprint and increase code readability when coming across this pattern?</p>
|
[
{
"answer_id": 129172,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "lambda for cmd in [\n (lambda: foo (a, b)),\n (lambda: bar (c, d)),\n]:\n try:\n cmd ()\n except StandardError, e:\n baz (e)\n ignore_errors (baz, [\n (lambda: foo (a, b)),\n (lambda: bar (c, d)),\n])\n"
},
{
"answer_id": 129174,
"author": "Sufian",
"author_id": 9241,
"author_profile": "https://Stackoverflow.com/users/9241",
"pm_score": 2,
"selected": false,
"text": "def handle_exception(function, reaction, *args, **kwargs):\n try:\n result = function(*args, **kwargs)\n except Exception, e:\n result = reaction(e)\n return result\n handle_exception(foo, baz, a, b)\nhandle_exception(bar, baz, c, d)\n"
},
{
"answer_id": 129176,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": -1,
"selected": false,
"text": "try:\n foo(a, b)\n bar(c, d)\nexcept Exception, e:\n baz(e)\n try:\n foo_bar() # This function can throw at several places\nexcept Exception, e:\n baz(e)\n"
},
{
"answer_id": 129177,
"author": "Ryan",
"author_id": 8819,
"author_profile": "https://Stackoverflow.com/users/8819",
"pm_score": 7,
"selected": true,
"text": "with from __future__ import with_statement\nimport contextlib\n\n@contextlib.contextmanager\ndef handler():\n try:\n yield\n except Exception, e:\n baz(e)\n with handler():\n foo(a, b)\nwith handler():\n bar(c, d)\n"
},
{
"answer_id": 129626,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "class TryOrBaz( object ):\n def __init__( self, that ):\n self.that= that\n def __call__( self, *args ):\n try:\n return self.that( *args )\n except Exception, e:\n baz( e )\n\nTryOrBaz( foo )( a, b )\nTryOrBaz( bar )( c, d )\n"
},
{
"answer_id": 133336,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 4,
"selected": false,
"text": "def handle_exception(handler):\n def decorate(func):\n def call_function(*args, **kwargs):\n try:\n func(*args, **kwargs)\n except Exception, e:\n handler(e)\n return call_function\n return decorate\n\ndef baz(e):\n print(e)\n\n@handle_exception(baz)\ndef foo(a, b):\n return a + b\n\n@handle_exception(baz)\ndef bar(c, d):\n return c.index(d)\n >>> foo(1, '2')\nunsupported operand type(s) for +: 'int' and 'str'\n>>> bar('steve', 'cheese')\nsubstring not found\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9241/"
] |
129,160
|
<p>The resource definition in tomcat's <code>server.xml</code> looks something like this...</p>
<pre class="lang-xml prettyprint-override"><code><Resource
name="jdbc/tox"
scope="Shareable"
type="javax.sql.DataSource"
url="jdbc:oracle:thin:@yourDBserver.yourCompany.com:1521:yourDBsid"
driverClassName="oracle.jdbc.pool.OracleDataSource"
username="tox"
password="toxbaby"
maxIdle="3"
maxActive="10"
removeAbandoned="true"
removeAbandonedTimeout="60"
testOnBorrow="true"
validationQuery="select * from dual"
logAbandoned="true"
debug="99"/>
</code></pre>
<p>The password is in the clear. How to avoid this?</p>
|
[
{
"answer_id": 129268,
"author": "Brad8118",
"author_id": 7617,
"author_profile": "https://Stackoverflow.com/users/7617",
"pm_score": -1,
"selected": false,
"text": "print(SHA1CryptoServiceProvider sHA1Hasher = new SHA1CryptoServiceProvider();\n ASCIIEncoding enc = new ASCIIEncoding();\n\n byte[] arrbytHashValue = sHA1Hasher.ComputeHash(enc.GetBytes(clearTextPW));\n string HashData = System.BitConverter.ToString(arrbytHashValue);\n HashData = HashData.Replace(\"-\", \"\");\n if (HashData == databaseHashedPassWO)\n {\n return true;\n }\n else\n {\n return false;\n });\n"
},
{
"answer_id": 140358,
"author": "gameame",
"author_id": 6259,
"author_profile": "https://Stackoverflow.com/users/6259",
"pm_score": 2,
"selected": false,
"text": "server.xml server.xml"
},
{
"answer_id": 355758,
"author": "Jerome Delattre",
"author_id": 27762,
"author_profile": "https://Stackoverflow.com/users/27762",
"pm_score": 5,
"selected": false,
"text": "server.xml yourapp.xml BasicDataSourceFactory <Resource\n name=\"jdbc/myDataSource\"\n auth=\"Container\"\n type=\"javax.sql.DataSource\"\n username=\"user\"\n password=\"encryptedpassword\"\n driverClassName=\"driverClass\"\n factory=\"mypackage.MyCustomBasicDataSourceFactory\"\n url=\"jdbc:blabla://...\"/>\n package mypackage;\n\n....\n\npublic class MyCustomBasicDataSourceFactory extends org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory {\n\n@Override\npublic Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception {\n Object o = super.getObjectInstance(obj, name, nameCtx, environment);\n if (o != null) {\n BasicDataSource ds = (BasicDataSource) o;\n if (ds.getPassword() != null && ds.getPassword().length() > 0) {\n String pwd = MyPasswordUtilClass.unscramblePassword(ds.getPassword());\n ds.setPassword(pwd);\n }\n return ds;\n } else {\n return null;\n }\n}\n"
},
{
"answer_id": 39298913,
"author": "JustinKSU",
"author_id": 724835,
"author_profile": "https://Stackoverflow.com/users/724835",
"pm_score": 2,
"selected": false,
"text": "public class MyEncryptedPasswordFactory extends BasicDataSourceFactory {\n\n @Override\n public Object getObjectInstance(Object obj, Name name, Context context, Hashtable<?, ?> environment)\n throws Exception {\n if (obj instanceof Reference) {\n Reference ref = (Reference) obj;\n DecryptPasswordUtil.replacePasswordWithDecrypted(ref, \"password\");\n return super.getObjectInstance(obj, name, context, environment);\n } else {\n throw new IllegalArgumentException(\n \"Expecting javax.naming.Reference as object type not \" + obj.getClass().getName());\n }\n }\n}\n public class MyEncryptedAtomikosPasswordFactory extends EnhancedTomcatAtomikosBeanFactory {\n @Override\n public Object getObjectInstance(Object obj, Name name, Context context, Hashtable<?, ?> environment)\n throws NamingException {\n if (obj instanceof Reference) {\n Reference ref = (Reference) obj;\n DecryptPasswordUtil.replacePasswordWithDecrypted(ref, \"xaProperties.password\");\n return super.getObjectInstance(obj, name, context, environment);\n } else {\n throw new IllegalArgumentException(\n \"Expecting javax.naming.Reference as object type not \" + obj.getClass().getName());\n }\n }\n}\n public class DecryptPasswordUtil {\n\n public static void replacePasswordWithDecrypted(Reference reference, String passwordKey) {\n if(reference == null) {\n throw new IllegalArgumentException(\"Reference object must not be null\");\n }\n\n // Search for password addr and replace with decrypted\n for (int i = 0; i < reference.size(); i++) {\n RefAddr addr = reference.get(i);\n if (passwordKey.equals(addr.getType())) {\n if (addr.getContent() == null) {\n throw new IllegalArgumentException(\"Password must not be null for key \" + passwordKey);\n }\n String decrypted = yourDecryptionMethod(addr.getContent().toString());\n reference.remove(i);\n reference.add(i, new StringRefAddr(passwordKey, decrypted));\n break;\n }\n }\n }\n}\n <Resource factory=\"com.mycompany.MyEncryptedPasswordFactory\" username=\"user\" password=\"encryptedPassword\" ...other options... />\n\n<Resource factory=\"com.mycompany.MyEncryptedAtomikosPasswordFactory\" type=\"com.atomikos.jdbc.AtomikosDataSourceBean\" xaProperties.user=\"user\" xaProperties.password=\"encryptedPassword\" ...other options... />\n"
},
{
"answer_id": 48179892,
"author": "HolloW",
"author_id": 752900,
"author_profile": "https://Stackoverflow.com/users/752900",
"pm_score": 2,
"selected": false,
"text": "<Resource\n name=\"jdbc/myDataSource\"\n auth=\"Container\"\n type=\"javax.sql.DataSource\"\n username=\"user\"\n password=\"encryptedpassword\"\n driverClassName=\"driverClass\"\n factory=\"mypackage.MyCustomBasicDataSourceFactory\"\n url=\"jdbc:blabla://...\"/>\n package mypackage;\n\npublic class MyCustomBasicDataSourceFactory extends org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory {\n @Override\n public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception {\n Object o = super.getObjectInstance(obj, name, nameCtx, environment);\n if (o != null) {\n BasicDataSource ds = (BasicDataSource) o;\n if (ds.getPassword() != null && ds.getPassword().length() > 0) {\n String pwd = MyPasswordUtilClass.unscramblePassword(ds.getPassword());\n ds.setPassword(pwd);\n }\n return ds;\n } else {\n return null;\n }\n }\n}\n @Bean\npublic DataSource dataSource() {\n DataSource ds = null;\n JndiTemplate jndi = new JndiTemplate();\n try {\n ds = jndi.lookup(\"java:comp/env/jdbc/myDataSource\", DataSource.class);\n } catch (NamingException e) {\n log.error(\"NamingException for java:comp/env/jdbc/myDataSource\", e);\n }\n return ds;\n}\n"
},
{
"answer_id": 50167074,
"author": "Gawri Edussuriya",
"author_id": 9738900,
"author_profile": "https://Stackoverflow.com/users/9738900",
"pm_score": 2,
"selected": false,
"text": "public class MyDataSourceFactory extends DataSourceFactory{\n\nprivate static WinDPAPI winDPAPI;\n\nprotected static final String DATA_SOURCE_FACTORY_PROP_PASSWORD = \"password\";\n\n@Override\npublic Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception{\n\n Reference ref = (Reference) obj;\n for (int i = 0; i < ref.size(); i++) {\n RefAddr ra = ref.get(i);\n if (ra.getType().equals(DATA_SOURCE_FACTORY_PROP_PASSWORD)) {\n\n if (ra.getContent() != null && ra.getContent().toString().length() > 0) {\n String pwd = getUnprotectedData(ra.getContent().toString());\n ref.remove(i);\n ref.add(i, new StringRefAddr(DATA_SOURCE_FACTORY_PROP_PASSWORD, pwd));\n }\n\n break;\n }\n }\n\n return super.getObjectInstance(obj, name, nameCtx, environment);\n }\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13930/"
] |
129,171
|
<p>What's the most efficient way to read a stream into another stream? In this case, I'm trying to read data in a Filestream into a generic stream. I know I could do the following:<br>
1. read line by line and write the data to the stream<br>
2. read chunks of bytes and write to the stream<br>
3. etc</p>
<p>I'm just trying to find the most efficient way.</p>
<p>Thanks</p>
|
[
{
"answer_id": 129185,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 1,
"selected": false,
"text": "ReadLine()"
},
{
"answer_id": 129925,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 3,
"selected": false,
"text": "public static class StreamCopier\n{\n private const long DefaultStreamChunkSize = 0x1000;\n\n public static void CopyTo(this Stream from, Stream to)\n {\n if (!from.CanRead || !to.CanWrite)\n {\n return;\n }\n\n var buffer = from.CanSeek\n ? new byte[from.Length]\n : new byte[DefaultStreamChunkSize];\n int read;\n\n while ((read = from.Read(buffer, 0, buffer.Length)) > 0)\n {\n to.Write(buffer, 0, read);\n }\n }\n}\n using (var input = File.OpenRead(@\"C:\\wrnpc12.txt\"))\n using (var output = File.OpenWrite(@\"C:\\wrnpc12.bak\"))\n {\n input.CopyTo(output);\n }\n CopyFrom()"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21829/"
] |
129,178
|
<p>I have recently been thinking about the difference between the two ways of defining an array:</p>
<ol>
<li><code>int[] array</code></li>
<li><code>int array[]</code></li>
</ol>
<p>Is there a difference?</p>
|
[
{
"answer_id": 129188,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 9,
"selected": true,
"text": "int array[] int[] array"
},
{
"answer_id": 129198,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 2,
"selected": false,
"text": "int [] array int array[]"
},
{
"answer_id": 129212,
"author": "George Strother",
"author_id": 16472,
"author_profile": "https://Stackoverflow.com/users/16472",
"pm_score": 5,
"selected": false,
"text": "int[] arrayOne, arrayTwo; //both arrays\n\nint arrayOne[], intOne; //one array one int \n"
},
{
"answer_id": 129225,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 8,
"selected": false,
"text": "int[] a, b; // Both a and b are arrays of type int\nint c[], d; // WARNING: c is an array, but d is just a regular int\n d"
},
{
"answer_id": 454928,
"author": "Luke Woodward",
"author_id": 48503,
"author_profile": "https://Stackoverflow.com/users/48503",
"pm_score": 4,
"selected": false,
"text": "int"
},
{
"answer_id": 454932,
"author": "Yuval Adam",
"author_id": 24545,
"author_profile": "https://Stackoverflow.com/users/24545",
"pm_score": 4,
"selected": false,
"text": "[] byte[] rowvector, colvector, matrix[]; byte rowvector[], colvector[], matrix[][];"
},
{
"answer_id": 587589,
"author": "TofuBeer",
"author_id": 65868,
"author_profile": "https://Stackoverflow.com/users/65868",
"pm_score": 6,
"selected": false,
"text": "type[] name int[] foo, bar; // both are arrays\nint foo[], bar; // foo is an array, bar is an int.\n"
},
{
"answer_id": 587594,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 4,
"selected": false,
"text": "double[] items = new double[10];\n"
},
{
"answer_id": 3846092,
"author": "Bozho",
"author_id": 203907,
"author_profile": "https://Stackoverflow.com/users/203907",
"pm_score": 2,
"selected": false,
"text": "int[] a int[] a"
},
{
"answer_id": 3846097,
"author": "Kdeveloper",
"author_id": 306276,
"author_profile": "https://Stackoverflow.com/users/306276",
"pm_score": 2,
"selected": false,
"text": "The [] may appear as part of the type at the beginning of the declaration,\nor as part of the declarator for a particular variable, or both, as in this\nexample:\n\nbyte[] rowvector, colvector, matrix[];\n\nThis declaration is equivalent to:\n\nbyte rowvector[], colvector[], matrix[][];\n"
},
{
"answer_id": 3846105,
"author": "Ishtar",
"author_id": 336355,
"author_profile": "https://Stackoverflow.com/users/336355",
"pm_score": 5,
"selected": false,
"text": "byte[] rowvector, colvector, matrix[];\n byte rowvector[], colvector[], matrix[][];\n int a[],b;\nint[] a,b;\n int[] a;\nint[] b;\n"
},
{
"answer_id": 3846111,
"author": "YoK",
"author_id": 388299,
"author_profile": "https://Stackoverflow.com/users/388299",
"pm_score": 2,
"selected": false,
"text": "int[] a"
},
{
"answer_id": 3846113,
"author": "Michael Borgwardt",
"author_id": 16883,
"author_profile": "https://Stackoverflow.com/users/16883",
"pm_score": 2,
"selected": false,
"text": "int[] a, b[];\n int[] a;\nint[][] b;\n"
},
{
"answer_id": 4007790,
"author": "David Watson",
"author_id": 438589,
"author_profile": "https://Stackoverflow.com/users/438589",
"pm_score": 1,
"selected": false,
"text": "int[] integers; \n int integers[];\n"
},
{
"answer_id": 4007805,
"author": "Patrick",
"author_id": 116249,
"author_profile": "https://Stackoverflow.com/users/116249",
"pm_score": 2,
"selected": false,
"text": "// 1.\nint regular, array[];\n// 2.\nint[] regular, array;\n"
},
{
"answer_id": 4008077,
"author": "Kos",
"author_id": 399317,
"author_profile": "https://Stackoverflow.com/users/399317",
"pm_score": 0,
"selected": false,
"text": "int integers[] int[] integers"
},
{
"answer_id": 7521915,
"author": "Bohemian",
"author_id": 256196,
"author_profile": "https://Stackoverflow.com/users/256196",
"pm_score": 3,
"selected": false,
"text": "C main public static void main(String[] args) public static void main(String args[]) public static void main(String... args)"
},
{
"answer_id": 7521922,
"author": "BalusC",
"author_id": 157882,
"author_profile": "https://Stackoverflow.com/users/157882",
"pm_score": 3,
"selected": false,
"text": "int puzzle[] int[] puzzle byte[] anArrayOfBytes;\nshort[] anArrayOfShorts;\nlong[] anArrayOfLongs;\nfloat[] anArrayOfFloats;\ndouble[] anArrayOfDoubles;\nboolean[] anArrayOfBooleans;\nchar[] anArrayOfChars;\nString[] anArrayOfStrings;\n float anArrayOfFloats[]; // this form is discouraged\n"
},
{
"answer_id": 7521936,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": false,
"text": " byte[] rowvector, colvector, matrix[];\n byte rowvector[], colvector[], matrix[][];\n String[] rectangular[] = new String[10][10];\n"
},
{
"answer_id": 41458626,
"author": "PoornaChandra",
"author_id": 2699523,
"author_profile": "https://Stackoverflow.com/users/2699523",
"pm_score": 1,
"selected": false,
"text": "int a[]; // comfortable to programmers who migrated from C/C++\nint[] a; // standard java notation \n int a[],b[],c[]; // three array references\nint[] a,b,c; // three array references\n"
},
{
"answer_id": 41855244,
"author": "Robert Hume",
"author_id": 3260495,
"author_profile": "https://Stackoverflow.com/users/3260495",
"pm_score": 2,
"selected": false,
"text": "int matrix[][]; // Noncompliant\nint[] matrix[]; // Noncompliant\n int[][] matrix; // Compliant\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21199/"
] |
129,181
|
<p>Is there a way to format a UTC time into any arbitrary string format I want in java? Basically I was thinking of having some class take the timestamp and I pass it is string telling it how I want it formated, and it returns the formatted string for me. Is there a way to do this?</p>
|
[
{
"answer_id": 129229,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 5,
"selected": false,
"text": "String date = new java.text.SimpleDateFormat(\"dd/MM/yyyy HH:mm:ss\").format(new java.util.Date (epoch*1000));\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2328/"
] |
129,207
|
<p>Is there a way to statically/globally request a copy of the ApplicationContext in a Spring application?</p>
<p>Assuming the main class starts up and initializes the application context, does it need to pass that down through the call stack to any classes that need it, or is there a way for a class to ask for the previously created context? (Which I assume has to be a singleton?)</p>
|
[
{
"answer_id": 144545,
"author": "stian",
"author_id": 17542,
"author_profile": "https://Stackoverflow.com/users/17542",
"pm_score": 4,
"selected": false,
"text": "<bean id=\"mainContext\" class=\"org.springframework.context.support.ClassPathXmlApplicationContext\">\n <constructor-arg>\n <list>\n <value>../applicationContext.xml</value>\n </list>\n </constructor-arg>\n </bean>\n BeanFactoryLocator bfl = SingletonBeanFactoryLocator.getInstance();\nBeanFactoryReference bf = bfl.useBeanFactory(\"mainContext\");\nSomeService someService = (SomeService) bf.getFactory().getBean(\"someService\");\n"
},
{
"answer_id": 10582462,
"author": "omnomnom",
"author_id": 577812,
"author_profile": "https://Stackoverflow.com/users/577812",
"pm_score": 7,
"selected": false,
"text": "ApplicationContextAware @Autowired public class SpringBean {\n @Autowired\n private ApplicationContext appContext;\n}\n SpringBean ApplicationContext main application context <- (child) MVC context\n SpringBean"
},
{
"answer_id": 21906984,
"author": "gogstad",
"author_id": 1576149,
"author_profile": "https://Stackoverflow.com/users/1576149",
"pm_score": 2,
"selected": false,
"text": "ApplicationContext ApplicationContext @ContextConfiguration({\"classpath:foo.xml\"}) @ContextConfiguration({\"classpath:foo.xml\", \"classpath:bar.xml}) @ContextConfiguration({\"classpath:foo.xml\"}) ApplicationContext ApplicationContextAware ApplicationContext ApplicationContext TestContext ApplicationContext ApplicationContext"
},
{
"answer_id": 40969417,
"author": "Kanagavelu Sugumar",
"author_id": 912319,
"author_profile": "https://Stackoverflow.com/users/912319",
"pm_score": 0,
"selected": false,
"text": "private static final ApplicationContext context = \n new ClassPathXmlApplicationContext(\"beans.xml\");\n beans.xml src/main/resources WEB_INF/classes applicationContext.xml Web.xml <context-param>\n <param-name>contextConfigLocation</param-name>\n <param-value>META-INF/spring/applicationContext.xml</param-value>\n</context-param>\n applicationContext.xml ClassPathXmlApplicationContext ClassPathXmlApplicationContext(\"META-INF/spring/applicationContext.xml\") @Component\npublic class OperatorRequestHandlerFactory {\n\n public static ApplicationContext context;\n\n @Autowired\n public void setApplicationContext(ApplicationContext applicationContext) {\n context = applicationContext;\n }\n}\n"
},
{
"answer_id": 43537419,
"author": "Vanessa Schissato",
"author_id": 1504977,
"author_profile": "https://Stackoverflow.com/users/1504977",
"pm_score": 3,
"selected": false,
"text": "SpringApplicationContext.java\n\nimport org.springframework.beans.BeansException;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.ApplicationContextAware;\n\n/**\n * Wrapper to always return a reference to the Spring Application \nContext from\n * within non-Spring enabled beans. Unlike Spring MVC's \nWebApplicationContextUtils\n * we do not need a reference to the Servlet context for this. All we need is\n * for this bean to be initialized during application startup.\n */\npublic class SpringApplicationContext implements \nApplicationContextAware {\n\n private static ApplicationContext CONTEXT;\n\n /**\n * This method is called from within the ApplicationContext once it is \n * done starting up, it will stick a reference to itself into this bean.\n * @param context a reference to the ApplicationContext.\n */\n public void setApplicationContext(ApplicationContext context) throws BeansException {\n CONTEXT = context;\n }\n\n /**\n * This is about the same as context.getBean(\"beanName\"), except it has its\n * own static handle to the Spring context, so calling this method statically\n * will give access to the beans by name in the Spring application context.\n * As in the context.getBean(\"beanName\") call, the caller must cast to the\n * appropriate target class. If the bean does not exist, then a Runtime error\n * will be thrown.\n * @param beanName the name of the bean to get.\n * @return an Object reference to the named bean.\n */\n public static Object getBean(String beanName) {\n return CONTEXT.getBean(beanName);\n }\n}\n"
},
{
"answer_id": 51073072,
"author": "John John Pichler",
"author_id": 399113,
"author_profile": "https://Stackoverflow.com/users/399113",
"pm_score": -1,
"selected": false,
"text": "package com.company.web.spring\n\nimport com.company.jpa.spring.MyBusinessAppConfig\nimport org.springframework.beans.factory.annotation.Autowired\nimport org.springframework.context.ApplicationContext\nimport org.springframework.context.annotation.AnnotationConfigApplicationContext\nimport org.springframework.context.annotation.ComponentScan\nimport org.springframework.context.annotation.Configuration\nimport org.springframework.context.annotation.Import\nimport org.springframework.stereotype.Component\nimport org.springframework.web.context.ContextLoader\nimport org.springframework.web.context.WebApplicationContext\nimport org.springframework.web.context.support.WebApplicationContextUtils\nimport javax.servlet.http.HttpServlet\n\n@Configuration\n@Import(value = [MyBusinessAppConfig::class])\n@ComponentScan(basePackageClasses = [SpringUtils::class])\nopen class WebAppConfig {\n}\n\n/**\n *\n * Singleton object to create (only if necessary), return and reuse a Spring Application Context.\n *\n * When you instantiates a class by yourself, spring context does not autowire its properties, but you can wire by yourself.\n * This class helps to find a context or create a new one, so you can wire properties inside objects that are not\n * created by Spring (e.g.: Servlets, usually created by the web server).\n *\n * Sometimes a SpringContext is created inside jUnit tests, or in the application server, or just manually. Independent\n * where it was created, I recommend you to configure your spring configuration to scan this SpringUtils package, so the 'springAppContext'\n * property will be used and autowired at the SpringUtils object the start of your spring context, and you will have just one instance of spring context public available.\n *\n *Ps: Even if your spring configuration doesn't include the SpringUtils @Component, it will works tto, but it will create a second Spring Context o your application.\n */\n@Component\nobject SpringUtils {\n\n var springAppContext: ApplicationContext? = null\n @Autowired\n set(value) {\n field = value\n }\n\n\n\n /**\n * Tries to find and reuse the Application Spring Context. If none found, creates one and save for reuse.\n * @return returns a Spring Context.\n */\n fun ctx(): ApplicationContext {\n if (springAppContext!= null) {\n println(\"achou\")\n return springAppContext as ApplicationContext;\n }\n\n //springcontext not autowired. Trying to find on the thread...\n val webContext = ContextLoader.getCurrentWebApplicationContext()\n if (webContext != null) {\n springAppContext = webContext;\n println(\"achou no servidor\")\n return springAppContext as WebApplicationContext;\n }\n\n println(\"nao achou, vai criar\")\n //None spring context found. Start creating a new one...\n val applicationContext = AnnotationConfigApplicationContext ( WebAppConfig::class.java )\n\n //saving the context for reusing next time\n springAppContext = applicationContext\n return applicationContext\n }\n\n /**\n * @return a Spring context of the WebApplication.\n * @param createNewWhenNotFound when true, creates a new Spring Context to return, when no one found in the ServletContext.\n * @param httpServlet the @WebServlet.\n */\n fun ctx(httpServlet: HttpServlet, createNewWhenNotFound: Boolean): ApplicationContext {\n try {\n val webContext = WebApplicationContextUtils.findWebApplicationContext(httpServlet.servletContext)\n if (webContext != null) {\n return webContext\n }\n if (createNewWhenNotFound) {\n //creates a new one\n return ctx()\n } else {\n throw NullPointerException(\"Cannot found a Spring Application Context.\");\n }\n }catch (er: IllegalStateException){\n if (createNewWhenNotFound) {\n //creates a new one\n return ctx()\n }\n throw er;\n }\n }\n}\n @WebServlet(name = \"MyWebHook\", value = \"/WebHook\")\npublic class MyWebServlet extends HttpServlet {\n\n\n private MyBean byBean\n = SpringUtils.INSTANCE.ctx(this, true).getBean(MyBean.class);\n\n\n public MyWebServlet() {\n\n }\n}\n"
},
{
"answer_id": 52850865,
"author": "Md. Sajedul Karim",
"author_id": 3073945,
"author_profile": "https://Stackoverflow.com/users/3073945",
"pm_score": 3,
"selected": false,
"text": "import org.springframework.beans.BeansException;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.ApplicationContextAware;\n\npublic class AppContextProvider implements ApplicationContextAware {\n\nprivate ApplicationContext applicationContext;\n\n@Override\npublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n this.applicationContext = applicationContext;\n}\n}\n setApplicationContext(ApplicationContext applicationContext) @Autowired\nprivate ApplicationContext applicationContext;\n @Autowired"
},
{
"answer_id": 53875813,
"author": "Chloe",
"author_id": 148844,
"author_profile": "https://Stackoverflow.com/users/148844",
"pm_score": 1,
"selected": false,
"text": "@Autowire @SpringBootApplication\npublic class Application extends SpringBootServletInitializer {\n private static ApplicationContext context;\n\n // I believe this only runs during an embedded Tomcat with `mvn spring-boot:run`. \n // I don't believe it runs when deploying to Tomcat on AWS.\n public static void main(String[] args) {\n context = SpringApplication.run(Application.class, args);\n DataSource dataSource = context.getBean(javax.sql.DataSource.class);\n Logger.getLogger(\"Application\").info(\"DATASOURCE = \" + dataSource);\n"
},
{
"answer_id": 55015981,
"author": "Sandeep Jain",
"author_id": 6433161,
"author_profile": "https://Stackoverflow.com/users/6433161",
"pm_score": 0,
"selected": false,
"text": "@Autowired\nprivate ApplicationContext appContext;\n ApplicationContext"
},
{
"answer_id": 60911858,
"author": "Hari Krishna",
"author_id": 3302424,
"author_profile": "https://Stackoverflow.com/users/3302424",
"pm_score": 0,
"selected": false,
"text": "@Component\npublic class ApplicationContextProvider implements ApplicationContextAware {\n\n private ApplicationContext applicationContext;\n\n public ApplicationContext getApplicationContext() {\n return applicationContext;\n }\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n this.applicationContext = applicationContext;\n }\n}\n @Component\npublic class SpringBean {\n @Autowired\n private ApplicationContext appContext;\n}\n"
},
{
"answer_id": 62777726,
"author": "Aman Malhotra",
"author_id": 6628440,
"author_profile": "https://Stackoverflow.com/users/6628440",
"pm_score": -1,
"selected": false,
"text": "@Component\npublic class SpringContext implements ApplicationContextAware{\n\n private static ApplicationContext applicationContext;\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws \n BeansException {\n this.applicationContext=applicationContext;\n }\n }\n applicationContext.getBean(String serviceName,Interface.Class)\n"
},
{
"answer_id": 66512158,
"author": "CryptoFool",
"author_id": 7631480,
"author_profile": "https://Stackoverflow.com/users/7631480",
"pm_score": 1,
"selected": false,
"text": "this @Component\npublic class MyBean {\n ...\n\n private static MyBean singleton = null;\n\n public MyBean() {\n ...\n singleton = this;\n }\n\n ...\n \n public void someMethod() {\n ...\n }\n\n ...\n\n public static MyBean get() {\n return singleton;\n }\n}\n someMethod MyBean.get().someMethod();\n ApplicationContext ApplicationContext ApplicationContext"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14057/"
] |
129,208
|
<p>On the advice of a more experienced developer, I have always coded my web pages that require user input (form processing, database administration, etc.) as self-referential pages. For PHP pages, I set the action of the form to the <code>'PHP_SELF'</code> element of the <code>$_SERVER</code> predefined variable, and depending on the arguments that I pass the page logic determines which code block(s) to execute.</p>
<p>I like that all of the code is contained in one file, and not spread around to various result pages. The one issue I've found is that my stats parsing programs can't differentiate between the first view of the page, and subsequent views (e.g. when the form has been submitted). A long time ago, when I used CGI or CF to create the pages, I directed the user to a different result page, which showed very neatly how many times the form was actually used.</p>
<p>What is the best practice for these types of pages in web development? Are there other, more compelling reasons for using (or not using) self-referential pages?</p>
|
[
{
"answer_id": 129256,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 0,
"selected": false,
"text": "RewriteEngine on\nRewriteRule ^form$ form.php [QSA]\nRewriteRule ^form/submit$ form.php [QSA]\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8161/"
] |
129,248
|
<p>I have a many to many index table, and I want to do an include/exclude type query on it.</p>
<p>fid is really a integer index, but here as letters for easier understanding. Here's a sample table :</p>
<p>table t</p>
<pre><code>eid | fid
----+----
1 | A
1 | B
1 | C
2 | B
2 | C
3 | A
3 | C
4 | A
4 | B
5 | B
</code></pre>
<p>Here are some sample queries I want.</p>
<ol>
<li>What eids have fid B, and NOT A? (Answer eid 2 and 5)</li>
<li>What eids have fid C, and NOT A? (Answer eid 2)</li>
</ol>
<p>I can't seem to figure out a query that will do this. </p>
<p>I've tried a self join like this:</p>
<pre><code>select *
from t as t1
join t as t2
where t1.eid=t2.eid
and t1.fid!=t2.fid
and t1.fid=B and t2.fid!=A
</code></pre>
<p>That won't work, because it will still return rows where eid=1 and fid=C.</p>
<p>Am I clear on what I want?</p>
|
[
{
"answer_id": 129260,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 3,
"selected": false,
"text": "Select eid from t where fid = 'B' \nEXCEPT\nselect eid from t where fid = 'A'\n"
},
{
"answer_id": 129302,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 3,
"selected": true,
"text": "select t1.eid\n from t t1\n where t1.fid = 'B'\n and not exists\n (select 1\n from t t2\n where t2.eid = t1.eid\n and t2.fid = 'A')\n"
},
{
"answer_id": 129770,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 0,
"selected": false,
"text": "SELECT DISTINCT t1.eid\nFROM table1 AS t1\n LEFT JOIN table1 AS t2 ON (t1.eid = t2.eid AND t2.fid = 'A')\nWHERE t2.eid IS NULL\n AND t1.fid = 'B';\n"
},
{
"answer_id": 129976,
"author": "Walter Mitty",
"author_id": 19937,
"author_profile": "https://Stackoverflow.com/users/19937",
"pm_score": 0,
"selected": false,
"text": "select eid \nfrom t\nwhere fid = 'A'\nminus\nselect eid\nfrom t\nwhere fid = 'B'\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21838/"
] |
129,257
|
<p>How Do I Get Eclipse Style Function Completions in Emacs for C, C++ and JAVA?
I love the power of the Emacs text editor but the lack of an "intellisense" feature
leaves me using Eclipse.</p>
|
[
{
"answer_id": 129390,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 2,
"selected": false,
"text": "complete-tab M-Tab"
},
{
"answer_id": 130111,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 4,
"selected": false,
"text": "M-/"
},
{
"answer_id": 25310185,
"author": "Átila Neves",
"author_id": 828046,
"author_profile": "https://Stackoverflow.com/users/828046",
"pm_score": 0,
"selected": false,
"text": "-I -D"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
129,265
|
<p>I have a Postgresql database on which I want to do a few cascading deletes. However, the tables aren't set up with the ON DELETE CASCADE rule. Is there any way I can perform a delete and tell Postgresql to cascade it just this once? Something equivalent to</p>
<pre><code>DELETE FROM some_table CASCADE;
</code></pre>
<p>The answers to <a href="https://stackoverflow.com/questions/45611/cascading-deletes-in-postgresql">this older question</a> make it seem like no such solution exists, but I figured I'd ask this question explicitly just to be sure.</p>
|
[
{
"answer_id": 129300,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 9,
"selected": true,
"text": "DELETE FROM some_child_table WHERE some_fk_field IN (SELECT some_id FROM some_Table);\nDELETE FROM some_table;\n"
},
{
"answer_id": 160411,
"author": "Ryszard Szopa",
"author_id": 19922,
"author_profile": "https://Stackoverflow.com/users/19922",
"pm_score": 4,
"selected": false,
"text": "testing=# create table a (id integer primary key);\nNOTICE: CREATE TABLE / PRIMARY KEY will create implicit index \"a_pkey\" for table \"a\"\nCREATE TABLE\ntesting=# create table b (id integer references a);\nCREATE TABLE\n\n-- put some data in the table\ntesting=# insert into a values(1);\nINSERT 0 1\ntesting=# insert into a values(2);\nINSERT 0 1\ntesting=# insert into b values(2);\nINSERT 0 1\ntesting=# insert into b values(1);\nINSERT 0 1\n\n-- restricting works\ntesting=# delete from a where id=1;\nERROR: update or delete on table \"a\" violates foreign key constraint \"b_id_fkey\" on table \"b\"\nDETAIL: Key (id)=(1) is still referenced from table \"b\".\n\n-- find the name of the constraint\ntesting=# \\d b;\n Table \"public.b\"\n Column | Type | Modifiers \n--------+---------+-----------\n id | integer | \nForeign-key constraints:\n \"b_id_fkey\" FOREIGN KEY (id) REFERENCES a(id)\n\n-- drop the constraint\ntesting=# alter table b drop constraint b_a_id_fkey;\nALTER TABLE\n\n-- create a cascading one\ntesting=# alter table b add FOREIGN KEY (id) references a(id) on delete cascade; \nALTER TABLE\n\ntesting=# delete from a where id=1;\nDELETE 1\ntesting=# select * from a;\n id \n----\n 2\n(1 row)\n\ntesting=# select * from b;\n id \n----\n 2\n(1 row)\n\n-- it works, do your stuff.\n-- [stuff]\n\n-- recreate the previous state\ntesting=# \\d b;\n Table \"public.b\"\n Column | Type | Modifiers \n--------+---------+-----------\n id | integer | \nForeign-key constraints:\n \"b_id_fkey\" FOREIGN KEY (id) REFERENCES a(id) ON DELETE CASCADE\n\ntesting=# alter table b drop constraint b_id_fkey;\nALTER TABLE\ntesting=# alter table b add FOREIGN KEY (id) references a(id) on delete restrict; \nALTER TABLE\n"
},
{
"answer_id": 1409458,
"author": "DanC",
"author_id": 120202,
"author_profile": "https://Stackoverflow.com/users/120202",
"pm_score": 6,
"selected": false,
"text": "DELETE FROM some_table CASCADE; some_table TRUNCATE DELETE CASCADE where TRUNCATE some_table CASCADE TRUNCATE some_table CASCADE;\n"
},
{
"answer_id": 19103574,
"author": "Joe Love",
"author_id": 2283954,
"author_profile": "https://Stackoverflow.com/users/2283954",
"pm_score": 5,
"selected": false,
"text": "select delete_cascade('public','my_table','1'); create or replace function delete_cascade(p_schema varchar, p_table varchar, p_key varchar, p_recursion varchar[] default null)\n returns integer as $$\ndeclare\n rx record;\n rd record;\n v_sql varchar;\n v_recursion_key varchar;\n recnum integer;\n v_primary_key varchar;\n v_rows integer;\nbegin\n recnum := 0;\n select ccu.column_name into v_primary_key\n from\n information_schema.table_constraints tc\n join information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name and ccu.constraint_schema=tc.constraint_schema\n and tc.constraint_type='PRIMARY KEY'\n and tc.table_name=p_table\n and tc.table_schema=p_schema;\n\n for rx in (\n select kcu.table_name as foreign_table_name, \n kcu.column_name as foreign_column_name, \n kcu.table_schema foreign_table_schema,\n kcu2.column_name as foreign_table_primary_key\n from information_schema.constraint_column_usage ccu\n join information_schema.table_constraints tc on tc.constraint_name=ccu.constraint_name and tc.constraint_catalog=ccu.constraint_catalog and ccu.constraint_schema=ccu.constraint_schema \n join information_schema.key_column_usage kcu on kcu.constraint_name=ccu.constraint_name and kcu.constraint_catalog=ccu.constraint_catalog and kcu.constraint_schema=ccu.constraint_schema\n join information_schema.table_constraints tc2 on tc2.table_name=kcu.table_name and tc2.table_schema=kcu.table_schema\n join information_schema.key_column_usage kcu2 on kcu2.constraint_name=tc2.constraint_name and kcu2.constraint_catalog=tc2.constraint_catalog and kcu2.constraint_schema=tc2.constraint_schema\n where ccu.table_name=p_table and ccu.table_schema=p_schema\n and TC.CONSTRAINT_TYPE='FOREIGN KEY'\n and tc2.constraint_type='PRIMARY KEY'\n)\n loop\n v_sql := 'select '||rx.foreign_table_primary_key||' as key from '||rx.foreign_table_schema||'.'||rx.foreign_table_name||'\n where '||rx.foreign_column_name||'='||quote_literal(p_key)||' for update';\n --raise notice '%',v_sql;\n --found a foreign key, now find the primary keys for any data that exists in any of those tables.\n for rd in execute v_sql\n loop\n v_recursion_key=rx.foreign_table_schema||'.'||rx.foreign_table_name||'.'||rx.foreign_column_name||'='||rd.key;\n if (v_recursion_key = any (p_recursion)) then\n --raise notice 'Avoiding infinite loop';\n else\n --raise notice 'Recursing to %,%',rx.foreign_table_name, rd.key;\n recnum:= recnum +delete_cascade(rx.foreign_table_schema::varchar, rx.foreign_table_name::varchar, rd.key::varchar, p_recursion||v_recursion_key);\n end if;\n end loop;\n end loop;\n begin\n --actually delete original record.\n v_sql := 'delete from '||p_schema||'.'||p_table||' where '||v_primary_key||'='||quote_literal(p_key);\n execute v_sql;\n get diagnostics v_rows= row_count;\n --raise notice 'Deleting %.% %=%',p_schema,p_table,v_primary_key,p_key;\n recnum:= recnum +v_rows;\n exception when others then recnum=0;\n end;\n\n return recnum;\nend;\n$$\nlanguage PLPGSQL;\n"
},
{
"answer_id": 37165401,
"author": "atiruz",
"author_id": 1491512,
"author_profile": "https://Stackoverflow.com/users/1491512",
"pm_score": 2,
"selected": false,
"text": "ON DELETE CASCADE CASCADE"
},
{
"answer_id": 45209745,
"author": "Grzegorz Grabek",
"author_id": 5135120,
"author_profile": "https://Stackoverflow.com/users/5135120",
"pm_score": 3,
"selected": false,
"text": "DELETE FROM some_child_table sct \n WHERE exists (SELECT FROM some_Table st \n WHERE sct.some_fk_fiel=st.some_id);\n\nDELETE FROM some_table;\n"
},
{
"answer_id": 50842421,
"author": "Thomas C. G. de Vilhena",
"author_id": 1205339,
"author_profile": "https://Stackoverflow.com/users/1205339",
"pm_score": 3,
"selected": false,
"text": "IN = create or replace function delete_cascade(p_schema varchar, p_table varchar, p_keys varchar, p_subquery varchar default null, p_foreign_keys varchar[] default array[]::varchar[])\n returns integer as $$\ndeclare\n\n rx record;\n rd record;\n v_sql varchar;\n v_subquery varchar;\n v_primary_key varchar;\n v_foreign_key varchar;\n v_rows integer;\n recnum integer;\n\nbegin\n\n recnum := 0;\n select ccu.column_name into v_primary_key\n from\n information_schema.table_constraints tc\n join information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name and ccu.constraint_schema=tc.constraint_schema\n and tc.constraint_type='PRIMARY KEY'\n and tc.table_name=p_table\n and tc.table_schema=p_schema;\n\n for rx in (\n select kcu.table_name as foreign_table_name, \n kcu.column_name as foreign_column_name, \n kcu.table_schema foreign_table_schema,\n kcu2.column_name as foreign_table_primary_key\n from information_schema.constraint_column_usage ccu\n join information_schema.table_constraints tc on tc.constraint_name=ccu.constraint_name and tc.constraint_catalog=ccu.constraint_catalog and ccu.constraint_schema=ccu.constraint_schema \n join information_schema.key_column_usage kcu on kcu.constraint_name=ccu.constraint_name and kcu.constraint_catalog=ccu.constraint_catalog and kcu.constraint_schema=ccu.constraint_schema\n join information_schema.table_constraints tc2 on tc2.table_name=kcu.table_name and tc2.table_schema=kcu.table_schema\n join information_schema.key_column_usage kcu2 on kcu2.constraint_name=tc2.constraint_name and kcu2.constraint_catalog=tc2.constraint_catalog and kcu2.constraint_schema=tc2.constraint_schema\n where ccu.table_name=p_table and ccu.table_schema=p_schema\n and TC.CONSTRAINT_TYPE='FOREIGN KEY'\n and tc2.constraint_type='PRIMARY KEY'\n)\n loop\n v_foreign_key := rx.foreign_table_schema||'.'||rx.foreign_table_name||'.'||rx.foreign_column_name;\n v_subquery := 'select \"'||rx.foreign_table_primary_key||'\" as key from '||rx.foreign_table_schema||'.\"'||rx.foreign_table_name||'\"\n where \"'||rx.foreign_column_name||'\"in('||coalesce(p_keys, p_subquery)||') for update';\n if p_foreign_keys @> ARRAY[v_foreign_key] then\n --raise notice 'circular recursion detected';\n else\n p_foreign_keys := array_append(p_foreign_keys, v_foreign_key);\n recnum:= recnum + delete_cascade(rx.foreign_table_schema, rx.foreign_table_name, null, v_subquery, p_foreign_keys);\n p_foreign_keys := array_remove(p_foreign_keys, v_foreign_key);\n end if;\n end loop;\n\n begin\n if (coalesce(p_keys, p_subquery) <> '') then\n v_sql := 'delete from '||p_schema||'.\"'||p_table||'\" where \"'||v_primary_key||'\"in('||coalesce(p_keys, p_subquery)||')';\n --raise notice '%',v_sql;\n execute v_sql;\n get diagnostics v_rows = row_count;\n recnum := recnum + v_rows;\n end if;\n exception when others then recnum=0;\n end;\n\n return recnum;\n\nend;\n$$\nlanguage PLPGSQL;\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
] |
129,267
|
<p>There have been a few questions asked here about why you can't define static methods within interfaces, but none of them address a basic inconsistency: why can you define static fields and static inner types within an interface, but not static methods?</p>
<p>Static inner types perhaps aren't a fair comparison, since that's just syntactic sugar that generates a new class, but why fields but not methods?</p>
<p>An argument against static methods within interfaces is that it breaks the virtual table resolution strategy used by the JVM, but shouldn't that apply equally to static fields, i.e. the compiler can just inline it?</p>
<p>Consistency is what I desire, and Java should have either supported no statics of any form within an interface, or it should be consistent and allow them. </p>
|
[
{
"answer_id": 129934,
"author": "DJClayworth",
"author_id": 19276,
"author_profile": "https://Stackoverflow.com/users/19276",
"pm_score": 4,
"selected": false,
"text": "MyInterface var = new MyImplementingClass();\nvar.staticMethod();\n"
},
{
"answer_id": 130023,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 2,
"selected": false,
"text": "interface HtmlConstants {\n static String OPEN = \"<\";\n static String SLASH_OPEN = \"</\";\n static String CLOSE = \">\";\n static String SLASH_CLOSE = \" />\";\n static String HTML = \"html\";\n static String BODY = \"body\";\n ...\n}\n\npublic class HtmlBuilder implements HtmlConstants { // implements ?!?\n public String buildHtml() {\n StringBuffer sb = new StringBuffer();\n sb.append(OPEN).append(HTML).append(CLOSE);\n sb.append(OPEN).append(BODY).append(CLOSE);\n ...\n sb.append(SLASH_OPEN).append(BODY).append(CLOSE);\n sb.append(SLASH_OPEN).append(HTML).append(CLOSE);\n return sb.toString();\n }\n}\n private final class HtmlConstants {\n ...\n private HtmlConstants() { /* empty */ }\n}\n\nimport static HtmlConstants.*;\npublic class HtmlBuilder { // no longer uses implements\n ...\n}\n"
},
{
"answer_id": 130109,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 3,
"selected": false,
"text": "final fields static final"
},
{
"answer_id": 646416,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 7,
"selected": true,
"text": "Collections List List"
},
{
"answer_id": 46665474,
"author": "Ashish Sharma",
"author_id": 7503961,
"author_profile": "https://Stackoverflow.com/users/7503961",
"pm_score": 0,
"selected": false,
"text": "public class InterfaceExample implements exp1 {\n\n @Override\n public void method() {\n System.out.println(\"From method()\");\n }\n\n public static void main(String[] args) {\n new InterfaceExample().method2();\n InterfaceExample.methodSta2(); // <--------------------------- would not compile\n // methodSta1(); // <--------------------------- would not compile\n exp1.methodSta1();\n }\n\n static void methodSta2() { // <-- it compile successfully but it can't be overridden in child classes\n System.out.println(\"========= InterfaceExample :: from methodSta2() ======\");\n }\n}\n\n\ninterface exp1 {\n\n void method();\n //protected void method1(); // <-- error\n //private void method2(); // <-- error\n //static void methodSta1(); // <-- error it require body in java 1.8\n\n static void methodSta1() { // <-- it compile successfully but it can't be overridden in child classes\n System.out.println(\"========= exp1:: from methodSta1() ======\");\n }\n\n static void methodSta2() { // <-- it compile successfully but it can't be overridden in child classes\n System.out.println(\"========= exp1:: from methodSta2() ======\");\n }\n\n default void method2() { System.out.println(\"--- exp1:: from method2() ---\");}\n //synchronized default void method3() { System.out.println(\"---\");} // <-- Illegal modifier for the interface method method3; only public, abstract, default, static \n // and strictfp are permitted\n //final default void method3() { System.out.println(\"---\");} // <-- error\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21234/"
] |
129,277
|
<p>This is likely going to be an easy answer and I'm just missing something, but here goes...If I have a Type, (that is, an actual System.Type...not an instance) how do I tell if it inherits from another specific base type?</p>
|
[
{
"answer_id": 129294,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 5,
"selected": false,
"text": "// Returns true if \"type\" inherits from \"baseType\"\npublic static bool Inherits(Type type, Type baseType) {\n return baseType.IsAssignableFrom(type)\n}\n"
},
{
"answer_id": 496407,
"author": "STW",
"author_id": 60724,
"author_profile": "https://Stackoverflow.com/users/60724",
"pm_score": 5,
"selected": false,
"text": "Type.IsSubTypeOf() Type.IsAssignableFrom() IsSubType() true false IsAssignableFrom() true BaseClass DerivedClass BaseClass BaseClassInstance.GetType.IsSubTypeOf(GetType(BaseClass)) = FALSE\nBaseClassInstance.GetType.IsAssignableFrom(GetType(BaseClass)) = TRUE\n\nDerivedClassInstance.GetType.IsSubTypeOf(GetType(BaseClass)) = TRUE\nDerivedClassInstance.GetType.IsAssignableFrom(GetType(BaseClass)) = TRUE\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
] |
129,283
|
<p>Forgive the vague title, I wasn't sure how to describe it.</p>
<p>If you have a generic model "Archive", how do you show different views/forms based on a user selected 'type'?</p>
<p>For example, the user creates a new "Archive", then gets the choice of video, book, audio etc. From there they get different forms based on the archive type.</p>
<p>Or would it be better to split them into different models - Video, Book, Audio? </p>
<p>Or can models inherit (like Video extends Archive). I guess this is basic OOP / classes, but have no idea how to apply that here.</p>
<p>Examples from any MVC framework are welcome!</p>
|
[
{
"answer_id": 129293,
"author": "Iain Holder",
"author_id": 1122,
"author_profile": "https://Stackoverflow.com/users/1122",
"pm_score": 2,
"selected": false,
"text": "public class Video : Archive\n{ \n public int Id {get;set}\n public string Name {get;set;} \n ...\n}\n public class VideoController : Controller\n{\n public object Edit(int id)\n {\n Video myVideo = GetVideo(id);\n return View(\"Edit\", myVideo);\n }\n ...\n}\n public class Edit : View<Video>\n{\n ...\n}\n"
},
{
"answer_id": 129341,
"author": "Mladen Mihajlovic",
"author_id": 11421,
"author_profile": "https://Stackoverflow.com/users/11421",
"pm_score": 2,
"selected": false,
"text": "return View();\n return View(\"VideoArchive\");\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196/"
] |
129,285
|
<p>Is it possible to add attributes at runtime or to change the value of an attribute at runtime?</p>
|
[
{
"answer_id": 129340,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 7,
"selected": true,
"text": "System.Type"
},
{
"answer_id": 46117780,
"author": "Eric Ouellet",
"author_id": 452845,
"author_profile": "https://Stackoverflow.com/users/452845",
"pm_score": 1,
"selected": false,
"text": " // ************************************************************************\n public static void SetObjectPropertyDescription(this Type typeOfObject, string propertyName, string description)\n {\n PropertyDescriptor pd = TypeDescriptor.GetProperties(typeOfObject)[propertyName];\n var att = pd.Attributes[typeof(DescriptionAttribute)] as DescriptionAttribute;\n if (att != null)\n {\n var fieldDescription = att.GetType().GetField(\"description\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (fieldDescription != null)\n {\n fieldDescription.SetValue(att, description);\n }\n }\n }\n\n // ************************************************************************\n public static void SetPropertyAttributReadOnly(this Type typeOfObject, string propertyName, bool isReadOnly)\n {\n PropertyDescriptor pd = TypeDescriptor.GetProperties(typeOfObject)[propertyName];\n var att = pd.Attributes[typeof(ReadOnlyAttribute)] as ReadOnlyAttribute;\n if (att != null)\n {\n var fieldDescription = att.GetType().GetField(\"isReadOnly\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (fieldDescription != null)\n {\n fieldDescription.SetValue(att, isReadOnly);\n }\n }\n }\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16979/"
] |
129,297
|
<p>I have a laptop running Ubuntu to which I connect an external monitor when I'm at the office. Usually this requires me to run <code>xrandr --auto</code> in order for the laptop to re-size the display to match the external monitor. It would be nice if this could be done automatically, either triggered when the monitor is connected, but it would be enough to actually run <code>xrandr --auto</code> when the laptop wakes up from suspend/hibernate.</p>
<p>I created a script <code>/etc/pm/sleep.d/00xrandr.sh</code> containing the line</p>
<pre><code>xrandr --auto
</code></pre>
<p>but this fails since the script does not have access to the X display.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 154960,
"author": "matli",
"author_id": 23896,
"author_profile": "https://Stackoverflow.com/users/23896",
"pm_score": 3,
"selected": true,
"text": "xauth merge /home/your_username/.Xauthority\nexport DISPLAY=:0.0\nxrandr --auto\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13051/"
] |
129,305
|
<p>I often run into the problem that I have one stream full of data and want to write everything of it into another stream.</p>
<p>All code-examples out there use a buffer in form of a byte-array.</p>
<p>Is there a more elegant way to this?</p>
<p>If not, what's the ideal size of the buffer. Which factors make up this value?</p>
|
[
{
"answer_id": 129344,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": false,
"text": "static void CopyStream(Stream input, Stream output){\n byte[] buffer = new byte[0x1000];\n int read;\n while ((read = input.Read(buffer, 0, buffer.Length)) > 0) \n output.Write(buffer, 0, read);\n}\n"
},
{
"answer_id": 1608755,
"author": "Thomas Danecker",
"author_id": 9632,
"author_profile": "https://Stackoverflow.com/users/9632",
"pm_score": 6,
"selected": false,
"text": "Stream.CopyTo"
},
{
"answer_id": 65877015,
"author": "Ivan Koshelev",
"author_id": 882936,
"author_profile": "https://Stackoverflow.com/users/882936",
"pm_score": 0,
"selected": false,
"text": "CopyTo CopyToAsync 30303 8085 using System.Net;\nusing System.Net.Sockets;\nusing System.Threading.Tasks;\n\nnamespace ConsoleApp1\n{\n class Program\n {\n static async Task Main(string[] args)\n {\n var externalConnectionListener = new TcpListener(IPAddress.Any, 30303);\n externalConnectionListener.Start();\n\n while (true)\n {\n var externalConnection = await externalConnectionListener.AcceptTcpClientAsync().ConfigureAwait(false);\n\n _ = Task.Factory.StartNew(async () =>\n {\n using NetworkStream externalConnectionStream = externalConnection.GetStream();\n using TcpClient internalConnection = new TcpClient(\"127.0.0.1\", 8085);\n using NetworkStream internalConnectionStream = internalConnection.GetStream();\n\n await Task.WhenAny(\n externalConnectionStream.CopyToAsync(internalConnectionStream),\n internalConnectionStream.CopyToAsync(externalConnectionStream)).ConfigureAwait(false);\n\n });\n\n }\n }\n }\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9632/"
] |
129,310
|
<p>I use the <a href="https://addons.mozilla.org/en-US/firefox/addon/6543" rel="nofollow noreferrer">Nightly Tester Tools</a> for Firefox and <a href="http://fiddlertool.com/fiddler/" rel="nofollow noreferrer">Fiddler</a> for IE. What do you use?</p>
|
[
{
"answer_id": 602455,
"author": "random",
"author_id": 9314,
"author_profile": "https://Stackoverflow.com/users/9314",
"pm_score": 0,
"selected": false,
"text": "CTRL+SHIFT+ALT+U"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14770/"
] |
129,329
|
<p>I understand the differences between optimistic and pessimistic locking. Now, could someone explain to me when I would use either one in general?</p>
<p>And does the answer to this question change depending on whether or not I'm using a stored procedure to perform the query?</p>
<p>But just to check, optimistic means "don't lock the table while reading" and pessimistic means "lock the table while reading."</p>
|
[
{
"answer_id": 58952004,
"author": "Vlad Mihalcea",
"author_id": 1025118,
"author_profile": "https://Stackoverflow.com/users/1025118",
"pm_score": 8,
"selected": false,
"text": "account account account 1 account UPDATE version version version OptimisticLockException"
},
{
"answer_id": 73669255,
"author": "Yilmaz",
"author_id": 10262805,
"author_profile": "https://Stackoverflow.com/users/10262805",
"pm_score": 2,
"selected": false,
"text": "pessimistic locking optimistic locking quantity=queantity-1 race condition"
},
{
"answer_id": 74071741,
"author": "Kai - Kazuya Ito",
"author_id": 8172439,
"author_profile": "https://Stackoverflow.com/users/8172439",
"pm_score": 2,
"selected": false,
"text": "SELECT FOR UPDATE SELECT FOR UPDATE SELECT FOR UPDATE)"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
129,335
|
<p>When you call <code>RedirectToAction</code> within a controller, it automatically redirects using an HTTP GET. How do I explicitly tell it to use an HTTP POST?</p>
<p>I have an action that accepts both GET and POST requests, and I want to be able to <code>RedirectToAction</code> using POST and send it some values.</p>
<p>Like this:</p>
<pre><code>this.RedirectToAction(
"actionname",
new RouteValueDictionary(new { someValue = 2, anotherValue = "text" })
);
</code></pre>
<p>I want the <code>someValue</code> and <code>anotherValue</code> values to be sent using an HTTP POST instead of a GET. Does anyone know how to do this?</p>
|
[
{
"answer_id": 1343182,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 7,
"selected": false,
"text": "[AcceptVerbs(HttpVerbs.Get)]\npublic ActionResult Index() {\n // obviously these values might come from somewhere non-trivial\n return Index(2, \"text\");\n}\n\n[AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult Index(int someValue, string anotherValue) {\n // would probably do something non-trivial here with the param values\n return View();\n}\n"
},
{
"answer_id": 19378717,
"author": "Otto Kanellis",
"author_id": 1210599,
"author_profile": "https://Stackoverflow.com/users/1210599",
"pm_score": 5,
"selected": false,
"text": "TempData[\"datacontainer\"] = modelData; var modelData= TempData[\"datacontainer\"] as ModelDataType; \n"
},
{
"answer_id": 29889782,
"author": "vicky",
"author_id": 1805776,
"author_profile": "https://Stackoverflow.com/users/1805776",
"pm_score": 4,
"selected": false,
"text": "return Content(\"<form action='actionname' id='frmTest' method='post'><input type='hidden' name='someValue' value='\" + someValue + \"' /><input type='hidden' name='anotherValue' value='\" + anotherValue + \"' /></form><script>document.getElementById('frmTest').submit();</script>\");\n"
},
{
"answer_id": 37805314,
"author": "Yitzhak Weinberg",
"author_id": 4871015,
"author_profile": "https://Stackoverflow.com/users/4871015",
"pm_score": 3,
"selected": false,
"text": "ActionResult action = new SampelController().Index(2, \"text\");\nreturn action;\n"
},
{
"answer_id": 71077754,
"author": "PowerMan2015",
"author_id": 2339034,
"author_profile": "https://Stackoverflow.com/users/2339034",
"pm_score": 0,
"selected": false,
"text": "return await ResendConfirmationEmail(new ResendConfirmationEmailViewModel() { Email = input.Email });\n [HttpPost]\n[AllowAnonymous]\npublic async Task<IActionResult> ResendConfirmationEmail(ResendConfirmationEmailViewModel input)\n{\n ...\n \n return View(\"ResendConfirmationEmailConfirmed\");\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7831/"
] |
129,345
|
<p>How can I pass arguments to a constructor in an IOC-framework?
I want to do something like: (Trying to be IOC-framework agnostic ;) )</p>
<pre><code>object objectToLogFor = xxx;
container.Resolve<ILogging>(objectToLogFor);
public class MyLogging : ILogging
{
public MyLogging(object objectToLogFor){}
}
</code></pre>
<p>It seems that this is not possible in StructureMap. But I would love to see someone prove me wrong.</p>
<p>Are other frameworks more feature-rich? Or am I using the IOC-framework in the wrong way?</p>
|
[
{
"answer_id": 573438,
"author": "Edward Wilde",
"author_id": 5182,
"author_profile": "https://Stackoverflow.com/users/5182",
"pm_score": 4,
"selected": true,
"text": "string objectToLogFor = \"PolicyName\";\nObjectFactory.With<string>(objectToLogFor).GetInstance<ILogging>();\n"
},
{
"answer_id": 586144,
"author": "Remco Ros",
"author_id": 70315,
"author_profile": "https://Stackoverflow.com/users/70315",
"pm_score": 3,
"selected": false,
"text": "var foo = \"foo\";\nvar service = this.container.Resolve<TContract>(new { constructorArg1 = foo });\n var foo = \"foo\";\nvar service = container.With(foo).GetInstance<TContract>();\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21733/"
] |
129,360
|
<p>I'm working with jQuery for the first time and need some help. I have html that looks like the following:</p>
<pre><code><div id='comment-8' class='comment'>
<p>Blah blah</p>
<div class='tools'></div>
</div>
<div id='comment-9' class='comment'>
<p>Blah blah something else</p>
<div class='tools'></div>
</div>
</code></pre>
<p>I'm trying to use jQuery to add spans to the .tools divs that call variouis functions when clicked. The functions needs to receive the id (either the entire 'comment-8' or just the '8' part) of the parent comment so I can then show a form or other information about the comment.</p>
<p>What I have thus far is:</p>
<pre><code><script type='text/javascript'>
$(function() {
var actionSpan = $('<span>[Do Something]</span>');
actionSpan.bind('click', doSomething);
$('.tools').append(actionSpan);
});
function doSomething(commentId) { alert(commentId); }
</script>
</code></pre>
<p>I'm stuck on how to populate the commentId parameter for doSomething. Perhaps instead of the id, I should be passing in a reference to the span that was clicked. That would probably be fine as well, but I'm unsure of how to accomplish that.</p>
<p>Thanks,
Brian</p>
|
[
{
"answer_id": 129420,
"author": "andy",
"author_id": 6152,
"author_profile": "https://Stackoverflow.com/users/6152",
"pm_score": 1,
"selected": false,
"text": "<tt>parent()</tt> <tt>$(this).parent().attr('id')</tt>; <tt>$(this).parents('div:eq(0)').attr('id')</tt> <tt>\"comment\"</tt>"
},
{
"answer_id": 129430,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 0,
"selected": false,
"text": "function doSomething() { \n var commentId = $(this).parent().attr('id');\n alert(commentId); \n}\n"
},
{
"answer_id": 129439,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 4,
"selected": true,
"text": "target this function doSomething(event)\n{\n var id = $(event.target).parents(\".tools\").attr(\"id\");\n id = substring(id.indexOf(\"-\")+1);\n alert(id);\n}\n function doSomething(event)\n{\n var id = $(this).parents(\".tools\").attr(\"id\");\n id = substring(id.indexOf(\"-\")+1);\n alert(id);\n}\n"
},
{
"answer_id": 129524,
"author": "Nick",
"author_id": 21399,
"author_profile": "https://Stackoverflow.com/users/21399",
"pm_score": 0,
"selected": false,
"text": "<script type='text/javascript'>\n\n$(function() {\n $('.comment').each(function(comment) {\n $('.tools', comment).append(\n $('<span>[Do Something]</span>')\n .click(commentTool(comment.id));\n );\n });\n});\n\nfunction commentTool(commentId) {\n return function() {\n alert('Do cool stuff to ' + commentId);\n }\n}\n\n</script>\n"
},
{
"answer_id": 129561,
"author": "neouser99",
"author_id": 10669,
"author_profile": "https://Stackoverflow.com/users/10669",
"pm_score": 0,
"selected": false,
"text": "var tool = $('<span>[Tool]</span>');\n\nvar action = function (id) {\n return function () {\n alert('id');\n }\n}\n\n$('div.comment').each(function () {\n var id = $(this).attr('id');\n\n var child = tool.clone();\n child.click(action(id));\n\n $('.tools', this).append(child);\n});\n"
},
{
"answer_id": 129565,
"author": "Victor",
"author_id": 14514,
"author_profile": "https://Stackoverflow.com/users/14514",
"pm_score": 0,
"selected": false,
"text": "function doSomething(eventObject) { \n var elComment = eventObject.parentNode.parentNode; //or something like that, \n //didn't test it\n var commentId= elComment.getAttribute('commentId')\n alert(commentId); \n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2656/"
] |
129,362
|
<p>I'm writing a WinForms application and one of the tabs in my TabControl has a SplitContainer. I'm saving the SplitterDistance in the user's application settings, but the restore is inconsistent. If the tab page with the splitter is visible, then the restore works and the splitter distance is as I left it. If some other tab is selected, then the splitter distance is wrong.</p>
|
[
{
"answer_id": 983325,
"author": "Robert Jeppesen",
"author_id": 9436,
"author_profile": "https://Stackoverflow.com/users/9436",
"pm_score": 2,
"selected": false,
"text": " var fullDistance = \n new Func<SplitContainer, int>(\n c => c.Orientation == \n Orientation.Horizontal ? c.Size.Height : c.Size.Width);\n\n // Store as percentage if FixedPanel.None\n int distanceToStore =\n spl.FixedPanel == FixedPanel.Panel1 ? spl.SplitterDistance :\n spl.FixedPanel == FixedPanel.Panel2 ? fullDistance(spl) - spl.SplitterDistance :\n (int)(((double)spl.SplitterDistance) / ((double)fullDistance(spl))) * 100;\n // calculate splitter distance with regard to current control size\n int distanceToRestore =\n spl.FixedPanel == FixedPanel.Panel1 ? storedDistance:\n spl.FixedPanel == FixedPanel.Panel2 ? fullDistance(spl) - storedDistance :\n storedDistance * fullDistance(spl) / 100;\n"
},
{
"answer_id": 16006968,
"author": "Andark",
"author_id": 1896751,
"author_profile": "https://Stackoverflow.com/users/1896751",
"pm_score": 3,
"selected": false,
"text": "private void MainForm_Load(object sender, EventArgs e)\n{\n splitContainerControl.Paint += new PaintEventHandler(splitContainerControl_Paint);\n}\n\nvoid splitContainerControl_Paint(object sender, PaintEventArgs e)\n{\n splitContainerControl.Paint -= splitContainerControl_Paint;\n // Handle restoration here\n}\n"
},
{
"answer_id": 26806862,
"author": "Steve Ostlind",
"author_id": 4228028,
"author_profile": "https://Stackoverflow.com/users/4228028",
"pm_score": 2,
"selected": false,
"text": " /// <summary>\n /// Gets or sets the relative size of the top and bottom split window panes.\n /// </summary>\n [Browsable(false)]\n [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\n [UserScopedSetting]\n [DefaultSettingValue(\".5\")]\n public double SplitterDistancePercent\n {\n get { return (double)toplevelSplitContainer.SplitterDistance / toplevelSplitContainer.Size.Height; }\n set { toplevelSplitContainer.SplitterDistance = (int)((double)toplevelSplitContainer.Size.Height * value); }\n }\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4794/"
] |
129,388
|
<p>I am writing a webpage in C# .NET. In javascript there is a function called GetElementsByTagName... this is nice for javascript invoked from the .aspx page. My question is, is there any way I can have this kind of functionality from my C# code-behind?</p>
<p>--</p>
<p>The scenario for those curious: I used an asp:repeater to generate a lot of buttons, and now I'm essentially trying to make a button that clicks them all. I tried storing all the buttons in a list as I created them, but the list is getting cleared during every postback, so I thought I could try the above method.</p>
|
[
{
"answer_id": 129400,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 2,
"selected": false,
"text": "For each ctl as Control in Me.Controls\n If ctl.Name = whatYouWant Then\n do stuff\nNext 'ctl\n Dim ctl as New Control()\nctl.ID = \"blah1\"\n"
},
{
"answer_id": 129442,
"author": "devlord",
"author_id": 16454,
"author_profile": "https://Stackoverflow.com/users/16454",
"pm_score": 2,
"selected": false,
"text": "foreach (Control ctl in myRepeater.Controls)\n{ \n if (ctl is Button)\n {\n ((Button)ctl).Click();\n }\n}\n"
},
{
"answer_id": 129456,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 0,
"selected": false,
"text": "protected void Page_Load(object sender, EventArgs e)\n{\n\n foreach (Control control in GetControlsByType(this, typeof(TextBox)))\n { \n //Do something?\n }\n\n}\npublic static System.Collections.Generic.List<Control> GetControlsByType(Control ctrl, Type t)\n{\n System.Collections.Generic.List<Control> cntrls = new System.Collections.Generic.List<Control>();\n\n\n foreach (Control child in ctrl.Controls)\n {\n if (t == child.GetType())\n cntrls.Add(child);\n cntrls.AddRange(GetControlsByType(child, t));\n }\n return cntrls;\n}\n"
},
{
"answer_id": 129571,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 0,
"selected": false,
"text": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"Default.aspx.cs\" Inherits=\"_Default\" %>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head runat=\"server\">\n <title>Untitled Page</title>\n </head>\n\n <body>\n <form id=\"form1\" runat=\"server\">\n <asp:Repeater runat=\"server\" ID=\"Repeater1\">\n <ItemTemplate>\n <asp:Button runat=\"server\" ID=\"Button1\" Text=\"I was NOT changed\" />\n </ItemTemplate>\n </asp:Repeater>\n </form>\n </body>\n</html>\n using System;\nusing System.Data;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\n\n\npublic partial class _Default : System.Web.UI.Page\n{\n protected void Page_Load(Object sender, EventArgs e)\n {\n DataTable dt = new DataTable();\n\n dt.Columns.Add(new DataColumn(\"column\"));\n\n DataRow dr = null;\n\n for (Int32 i = 0; i < 10; i++)\n {\n dr = dt.NewRow();\n\n dr[\"column\"] = \"\";\n\n dt.Rows.Add(dr);\n }\n\n this.Repeater1.DataSource = dt;\n this.Repeater1.DataBind();\n\n\n foreach (RepeaterItem ri in this.Repeater1.Controls)\n {\n foreach (Control c in ri.Controls)\n {\n Button b = new Button();\n\n\n try\n {\n b = (Button)c;\n }\n\n catch (Exception exc)\n {\n }\n\n\n b.Text = \"I was found and changed\";\n }\n }\n }\n}\n"
},
{
"answer_id": 129645,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Data;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Collections.Generic;\n\n\npublic partial class _Default : System.Web.UI.Page\n{\n protected void Page_Load(Object sender, EventArgs e)\n {\n #region Fill Repeater1 with some dummy data\n DataTable dt = new DataTable();\n\n dt.Columns.Add(new DataColumn(\"column\"));\n\n DataRow dr = null;\n\n for (Int32 i = 0; i < 10; i++)\n {\n dr = dt.NewRow();\n\n dr[\"column\"] = \"\";\n\n dt.Rows.Add(dr);\n }\n\n this.Repeater1.DataSource = dt;\n this.Repeater1.DataBind();\n #endregion\n\n\n foreach (Button b in this.FindButtonsInRepeater(ref this.Repeater1))\n {\n b.Text = \"I was found and changed\";\n }\n }\n\n\n private List<Button> FindButtonsInRepeater(ref Repeater repeater)\n {\n List<Button> buttonsFound = new List<Button>();\n\n\n foreach (RepeaterItem ri in repeater.Controls)\n {\n foreach (Control c in ri.Controls)\n {\n try\n {\n buttonsFound.Add((Button)c);\n }\n\n catch (Exception exc)\n {\n }\n }\n }\n\n\n return buttonsFound;\n }\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13732/"
] |
129,389
|
<p>I want a true deep copy. In Java, this was easy, but how do you do it in C#?</p>
|
[
{
"answer_id": 129395,
"author": "Kilhoffer",
"author_id": 5469,
"author_profile": "https://Stackoverflow.com/users/5469",
"pm_score": 10,
"selected": true,
"text": "public static T DeepClone<T>(this T obj)\n{\n using (var ms = new MemoryStream())\n {\n var formatter = new BinaryFormatter();\n formatter.Serialize(ms, obj);\n ms.Position = 0;\n\n return (T) formatter.Deserialize(ms);\n }\n}\n [Serializable] using System.Runtime.Serialization.Formatters.Binary;\n using System.IO;\n"
},
{
"answer_id": 1213649,
"author": "Neil",
"author_id": 148593,
"author_profile": "https://Stackoverflow.com/users/148593",
"pm_score": 7,
"selected": false,
"text": "public static class ExtensionMethods\n{\n // Deep clone\n public static T DeepClone<T>(this T a)\n {\n using (MemoryStream stream = new MemoryStream())\n {\n BinaryFormatter formatter = new BinaryFormatter();\n formatter.Serialize(stream, a);\n stream.Position = 0;\n return (T) formatter.Deserialize(stream);\n }\n }\n}\n MyClass copy = obj.DeepClone();\n"
},
{
"answer_id": 4320823,
"author": "David Thornley",
"author_id": 196390,
"author_profile": "https://Stackoverflow.com/users/196390",
"pm_score": 2,
"selected": false,
"text": "Object.MemberWiseClone() MemberWiseClone()"
},
{
"answer_id": 6572475,
"author": "Basil",
"author_id": 828241,
"author_profile": "https://Stackoverflow.com/users/828241",
"pm_score": 0,
"selected": false,
"text": " public static object CopyObject(object input)\n {\n if (input != null)\n {\n object result = Activator.CreateInstance(input.GetType());\n foreach (FieldInfo field in input.GetType().GetFields(Consts.AppConsts.FullBindingList))\n {\n if (field.FieldType.GetInterface(\"IList\", false) == null)\n {\n field.SetValue(result, field.GetValue(input));\n }\n else\n {\n IList listObject = (IList)field.GetValue(result);\n if (listObject != null)\n {\n foreach (object item in ((IList)field.GetValue(input)))\n {\n listObject.Add(CopyObject(item));\n }\n }\n }\n }\n return result;\n }\n else\n {\n return null;\n }\n }\n BinarySerialization [Serializable]"
},
{
"answer_id": 8683002,
"author": "Contango",
"author_id": 107409,
"author_profile": "https://Stackoverflow.com/users/107409",
"pm_score": 6,
"selected": false,
"text": " Demo of shallow and deep copy, using classes and MemberwiseClone:\n Create Bob\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Clone Bob >> BobsSon\n Adjust BobsSon details\n BobsSon.Age=2, BobsSon.Purchase.Description=Toy car\n Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Elapsed time: 00:00:04.7795670,30000000\n Demo of shallow and deep copy, using structs and value copying:\n Create Bob\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Clone Bob >> BobsSon\n Adjust BobsSon details:\n BobsSon.Age=2, BobsSon.Purchase.Description=Toy car\n Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Elapsed time: 00:00:01.0875454,30000000\n Demo of deep copy, using class and serialize/deserialize:\n Elapsed time: 00:00:39.9339425,30000000\n // Nested MemberwiseClone example. \n// Added to demo how to deep copy a reference class.\n[Serializable] // Not required if using MemberwiseClone, only used for speed comparison using serialization.\npublic class Person\n{\n public Person(int age, string description)\n {\n this.Age = age;\n this.Purchase.Description = description;\n }\n [Serializable] // Not required if using MemberwiseClone\n public class PurchaseType\n {\n public string Description;\n public PurchaseType ShallowCopy()\n {\n return (PurchaseType)this.MemberwiseClone();\n }\n }\n public PurchaseType Purchase = new PurchaseType();\n public int Age;\n // Add this if using nested MemberwiseClone.\n // This is a class, which is a reference type, so cloning is more difficult.\n public Person ShallowCopy()\n {\n return (Person)this.MemberwiseClone();\n }\n // Add this if using nested MemberwiseClone.\n // This is a class, which is a reference type, so cloning is more difficult.\n public Person DeepCopy()\n {\n // Clone the root ...\n Person other = (Person) this.MemberwiseClone();\n // ... then clone the nested class.\n other.Purchase = this.Purchase.ShallowCopy();\n return other;\n }\n}\n// Added to demo how to copy a value struct (this is easy - a deep copy happens by default)\npublic struct PersonStruct\n{\n public PersonStruct(int age, string description)\n {\n this.Age = age;\n this.Purchase.Description = description;\n }\n public struct PurchaseType\n {\n public string Description;\n }\n public PurchaseType Purchase;\n public int Age;\n // This is a struct, which is a value type, so everything is a clone by default.\n public PersonStruct ShallowCopy()\n {\n return (PersonStruct)this;\n }\n // This is a struct, which is a value type, so everything is a clone by default.\n public PersonStruct DeepCopy()\n {\n return (PersonStruct)this;\n }\n}\n// Added only for a speed comparison.\npublic class MyDeepCopy\n{\n public static T DeepCopy<T>(T obj)\n {\n object result = null;\n using (var ms = new MemoryStream())\n {\n var formatter = new BinaryFormatter();\n formatter.Serialize(ms, obj);\n ms.Position = 0;\n result = (T)formatter.Deserialize(ms);\n ms.Close();\n }\n return (T)result;\n }\n}\n void MyMain(string[] args)\n {\n {\n Console.Write(\"Demo of shallow and deep copy, using classes and MemberwiseCopy:\\n\");\n var Bob = new Person(30, \"Lamborghini\");\n Console.Write(\" Create Bob\\n\");\n Console.Write(\" Bob.Age={0}, Bob.Purchase.Description={1}\\n\", Bob.Age, Bob.Purchase.Description);\n Console.Write(\" Clone Bob >> BobsSon\\n\");\n var BobsSon = Bob.DeepCopy();\n Console.Write(\" Adjust BobsSon details\\n\");\n BobsSon.Age = 2;\n BobsSon.Purchase.Description = \"Toy car\";\n Console.Write(\" BobsSon.Age={0}, BobsSon.Purchase.Description={1}\\n\", BobsSon.Age, BobsSon.Purchase.Description);\n Console.Write(\" Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\\n\");\n Console.Write(\" Bob.Age={0}, Bob.Purchase.Description={1}\\n\", Bob.Age, Bob.Purchase.Description);\n Debug.Assert(Bob.Age == 30);\n Debug.Assert(Bob.Purchase.Description == \"Lamborghini\");\n var sw = new Stopwatch();\n sw.Start();\n int total = 0;\n for (int i = 0; i < 100000; i++)\n {\n var n = Bob.DeepCopy();\n total += n.Age;\n }\n Console.Write(\" Elapsed time: {0},{1}\\n\", sw.Elapsed, total);\n }\n { \n Console.Write(\"Demo of shallow and deep copy, using structs:\\n\");\n var Bob = new PersonStruct(30, \"Lamborghini\");\n Console.Write(\" Create Bob\\n\");\n Console.Write(\" Bob.Age={0}, Bob.Purchase.Description={1}\\n\", Bob.Age, Bob.Purchase.Description);\n Console.Write(\" Clone Bob >> BobsSon\\n\");\n var BobsSon = Bob.DeepCopy();\n Console.Write(\" Adjust BobsSon details:\\n\");\n BobsSon.Age = 2;\n BobsSon.Purchase.Description = \"Toy car\";\n Console.Write(\" BobsSon.Age={0}, BobsSon.Purchase.Description={1}\\n\", BobsSon.Age, BobsSon.Purchase.Description);\n Console.Write(\" Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\\n\");\n Console.Write(\" Bob.Age={0}, Bob.Purchase.Description={1}\\n\", Bob.Age, Bob.Purchase.Description); \n Debug.Assert(Bob.Age == 30);\n Debug.Assert(Bob.Purchase.Description == \"Lamborghini\");\n var sw = new Stopwatch();\n sw.Start();\n int total = 0;\n for (int i = 0; i < 100000; i++)\n {\n var n = Bob.DeepCopy();\n total += n.Age;\n }\n Console.Write(\" Elapsed time: {0},{1}\\n\", sw.Elapsed, total);\n }\n {\n Console.Write(\"Demo of deep copy, using class and serialize/deserialize:\\n\");\n int total = 0;\n var sw = new Stopwatch();\n sw.Start();\n var Bob = new Person(30, \"Lamborghini\");\n for (int i = 0; i < 100000; i++)\n {\n var BobsSon = MyDeepCopy.DeepCopy<Person>(Bob);\n total += BobsSon.Age;\n }\n Console.Write(\" Elapsed time: {0},{1}\\n\", sw.Elapsed, total);\n }\n Console.ReadKey();\n }\n"
},
{
"answer_id": 8708249,
"author": "Kurt Richardson",
"author_id": 1013542,
"author_profile": "https://Stackoverflow.com/users/1013542",
"pm_score": 4,
"selected": false,
"text": "public static void deepCopy<T>(ref T object2Copy, ref T objectCopy)\n{\n using (var stream = new MemoryStream())\n {\n Serializer.Serialize(stream, object2Copy);\n stream.Position = 0;\n objectCopy = Serializer.Deserialize<T>(stream);\n }\n}\n public void DeepCopy<T>(ref T object2Copy, ref T objectCopy)\n{\n using (var stream = new MemoryStream())\n {\n var serializer = new XS.XmlSerializer(typeof(T));\n\n serializer.Serialize(stream, object2Copy);\n stream.Position = 0;\n objectCopy = (T)serializer.Deserialize(stream);\n }\n}\n"
},
{
"answer_id": 9961788,
"author": "Suresh Kumar Veluswamy",
"author_id": 1305119,
"author_profile": "https://Stackoverflow.com/users/1305119",
"pm_score": 3,
"selected": false,
"text": " public static object DeepCopy(object obj)\n {\n if (obj == null)\n return null;\n Type type = obj.GetType();\n\n if (type.IsValueType || type == typeof(string))\n {\n return obj;\n }\n else if (type.IsArray)\n {\n Type elementType = Type.GetType(\n type.FullName.Replace(\"[]\", string.Empty));\n var array = obj as Array;\n Array copied = Array.CreateInstance(elementType, array.Length);\n for (int i = 0; i < array.Length; i++)\n {\n copied.SetValue(DeepCopy(array.GetValue(i)), i);\n }\n return Convert.ChangeType(copied, obj.GetType());\n }\n else if (type.IsClass)\n {\n\n object toret = Activator.CreateInstance(obj.GetType());\n FieldInfo[] fields = type.GetFields(BindingFlags.Public |\n BindingFlags.NonPublic | BindingFlags.Instance);\n foreach (FieldInfo field in fields)\n {\n object fieldValue = field.GetValue(obj);\n if (fieldValue == null)\n continue;\n field.SetValue(toret, DeepCopy(fieldValue));\n }\n return toret;\n }\n else\n throw new ArgumentException(\"Unknown type\");\n }\n"
},
{
"answer_id": 10267513,
"author": "alex",
"author_id": 1349430,
"author_profile": "https://Stackoverflow.com/users/1349430",
"pm_score": 2,
"selected": false,
"text": " public interface IDeepClonable<T> where T : class\n {\n T DeepClone();\n }\n\n public class MyObj : IDeepClonable<MyObj>\n {\n public MyObj Clone()\n {\n var myObj = new MyObj();\n myObj._field1 = _field1;//value type\n myObj._field2 = _field2;//value type\n myObj._field3 = _field3;//value type\n\n if (_child != null)\n {\n myObj._child = _child.DeepClone(); //reference type .DeepClone() that does the same\n }\n\n int len = _array.Length;\n myObj._array = new MyObj[len]; // array / collection\n for (int i = 0; i < len; i++)\n {\n myObj._array[i] = _array[i];\n }\n\n return myObj;\n }\n\n private bool _field1;\n public bool Field1\n {\n get { return _field1; }\n set { _field1 = value; }\n }\n\n private int _field2;\n public int Property2\n {\n get { return _field2; }\n set { _field2 = value; }\n }\n\n private string _field3;\n public string Property3\n {\n get { return _field3; }\n set { _field3 = value; }\n }\n\n private MyObj _child;\n private MyObj Child\n {\n get { return _child; }\n set { _child = value; }\n }\n\n private MyObj[] _array = new MyObj[4];\n }\n"
},
{
"answer_id": 11308879,
"author": "Alex Burtsev",
"author_id": 235715,
"author_profile": "https://Stackoverflow.com/users/235715",
"pm_score": 9,
"selected": false,
"text": "using System.Collections.Generic;\nusing System.Reflection;\nusing System.ArrayExtensions;\n\nnamespace System\n{\n public static class ObjectExtensions\n {\n private static readonly MethodInfo CloneMethod = typeof(Object).GetMethod(\"MemberwiseClone\", BindingFlags.NonPublic | BindingFlags.Instance);\n\n public static bool IsPrimitive(this Type type)\n {\n if (type == typeof(String)) return true;\n return (type.IsValueType & type.IsPrimitive);\n }\n\n public static Object Copy(this Object originalObject)\n {\n return InternalCopy(originalObject, new Dictionary<Object, Object>(new ReferenceEqualityComparer()));\n }\n private static Object InternalCopy(Object originalObject, IDictionary<Object, Object> visited)\n {\n if (originalObject == null) return null;\n var typeToReflect = originalObject.GetType();\n if (IsPrimitive(typeToReflect)) return originalObject;\n if (visited.ContainsKey(originalObject)) return visited[originalObject];\n if (typeof(Delegate).IsAssignableFrom(typeToReflect)) return null;\n var cloneObject = CloneMethod.Invoke(originalObject, null);\n if (typeToReflect.IsArray)\n {\n var arrayType = typeToReflect.GetElementType();\n if (IsPrimitive(arrayType) == false)\n {\n Array clonedArray = (Array)cloneObject;\n clonedArray.ForEach((array, indices) => array.SetValue(InternalCopy(clonedArray.GetValue(indices), visited), indices));\n }\n\n }\n visited.Add(originalObject, cloneObject);\n CopyFields(originalObject, visited, cloneObject, typeToReflect);\n RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect);\n return cloneObject;\n }\n\n private static void RecursiveCopyBaseTypePrivateFields(object originalObject, IDictionary<object, object> visited, object cloneObject, Type typeToReflect)\n {\n if (typeToReflect.BaseType != null)\n {\n RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect.BaseType);\n CopyFields(originalObject, visited, cloneObject, typeToReflect.BaseType, BindingFlags.Instance | BindingFlags.NonPublic, info => info.IsPrivate);\n }\n }\n\n private static void CopyFields(object originalObject, IDictionary<object, object> visited, object cloneObject, Type typeToReflect, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy, Func<FieldInfo, bool> filter = null)\n {\n foreach (FieldInfo fieldInfo in typeToReflect.GetFields(bindingFlags))\n {\n if (filter != null && filter(fieldInfo) == false) continue;\n if (IsPrimitive(fieldInfo.FieldType)) continue;\n var originalFieldValue = fieldInfo.GetValue(originalObject);\n var clonedFieldValue = InternalCopy(originalFieldValue, visited);\n fieldInfo.SetValue(cloneObject, clonedFieldValue);\n }\n }\n public static T Copy<T>(this T original)\n {\n return (T)Copy((Object)original);\n }\n }\n\n public class ReferenceEqualityComparer : EqualityComparer<Object>\n {\n public override bool Equals(object x, object y)\n {\n return ReferenceEquals(x, y);\n }\n public override int GetHashCode(object obj)\n {\n if (obj == null) return 0;\n return obj.GetHashCode();\n }\n }\n\n namespace ArrayExtensions\n {\n public static class ArrayExtensions\n {\n public static void ForEach(this Array array, Action<Array, int[]> action)\n {\n if (array.LongLength == 0) return;\n ArrayTraverse walker = new ArrayTraverse(array);\n do action(array, walker.Position);\n while (walker.Step());\n }\n }\n\n internal class ArrayTraverse\n {\n public int[] Position;\n private int[] maxLengths;\n\n public ArrayTraverse(Array array)\n {\n maxLengths = new int[array.Rank];\n for (int i = 0; i < array.Rank; ++i)\n {\n maxLengths[i] = array.GetLength(i) - 1;\n }\n Position = new int[array.Rank];\n }\n\n public bool Step()\n {\n for (int i = 0; i < Position.Length; ++i)\n {\n if (Position[i] < maxLengths[i])\n {\n Position[i]++;\n for (int j = 0; j < i; j++)\n {\n Position[j] = 0;\n }\n return true;\n }\n }\n return false;\n }\n }\n }\n\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18931/"
] |
129,405
|
<p>How do I Configuring DoxyGen to document ActionScript files?</p>
<p>I've included the *.as and *.asi files in doxygen's search pattern, but the classes, functions and variables don't show there.</p>
|
[
{
"answer_id": 139745,
"author": "Eliram",
"author_id": 18790,
"author_profile": "https://Stackoverflow.com/users/18790",
"pm_score": 2,
"selected": false,
"text": "OPTIMIZE_OUTPUT_JAVA = YES\nEXTRACT_ALL = YES\nHIDE_UNDOC_MEMBERS = NO\nHIDE_UNDOC_CLASSES = NO\n package myPackage {\n /// @cond\npackage myPackage {\n/// @endcond\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18790/"
] |
129,406
|
<p>When my browser renders the following test case, there's a gap below the image. From my understanding of CSS, the bottom of the blue box should touch the bottom of the red box. But that's not the case. Why?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>foo</title>
</head>
<body>
<div style="border: solid blue 2px; padding: 0px;">
<img alt='' style="border: solid red 2px; margin: 0px;" src="http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png" />
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 129412,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 3,
"selected": false,
"text": "vertical-align: bottom;\n"
},
{
"answer_id": 129426,
"author": "tim_yates",
"author_id": 6509,
"author_profile": "https://Stackoverflow.com/users/6509",
"pm_score": 2,
"selected": false,
"text": "display: block\n"
},
{
"answer_id": 129459,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 2,
"selected": false,
"text": "line-height: 0; DIV"
},
{
"answer_id": 129982,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "font-size:0;"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
] |
129,417
|
<p>Coming from a desktop background I'm not sure exactly how to pass the exceptions I have caught to an Error page in order to avoid the standard exception screen being seen by my users. </p>
<p>My general question is how do I pass the exception from page X to my Error page in ASP.net?</p>
|
[
{
"answer_id": 129434,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 4,
"selected": true,
"text": " <customErrors mode=\"RemoteOnly\" defaultRedirect=\"/error.html\">\n <error statusCode=\"403\" redirect=\"/accessdenied.html\" />\n <error statusCode=\"404\" redirect=\"/pagenotfound.html\" />\n </customErrors>\n"
},
{
"answer_id": 129455,
"author": "Mladen Mihajlovic",
"author_id": 11421,
"author_profile": "https://Stackoverflow.com/users/11421",
"pm_score": 2,
"selected": false,
"text": "Server.GetLastError();\n"
},
{
"answer_id": 129463,
"author": "mattruma",
"author_id": 1768,
"author_profile": "https://Stackoverflow.com/users/1768",
"pm_score": 1,
"selected": false,
"text": " protected void Application_Error(object sender, EventArgs e)\n {\n Exception ex = Server.GetLastError();\n this.Session[CacheProvider.ToCacheKey(CacheKeys.LastError)] = ex;\n }\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20748/"
] |
129,437
|
<p>I have a SQL script that I want to output progress messages as it runs. Having it output messages between SQL statements is easy, however I have some very long running INSERT INTO SELECTs. Is there a way to have a select statement output messages as it goes, for example after every 1000 rows, or every 5 seconds?</p>
<p>Note: This is for SQL Anywhere, but answers in any SQL dialect will be fine.</p>
|
[
{
"answer_id": 161961,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 2,
"selected": false,
"text": "DECLARE @total_rows int\n\nSELECT @total_rows = count(*) \nFROM Source_Table\n\nWHILE @total_rows > (SELECT count(*) FROM Target_Table) \nBEGIN\n SET rowcount 1000 \n\n print 'inserting 1000 rows' \n\n INSERT Target_Table \n SELECT * \n FROM Source_Table s\n WHERE NOT EXISTS( SELECT 1 \n FROM Target_Table t\n WHERE t.id = s.id )\nEND\n\nset rowcount 0\nprint 'done'\n DECLARE @min_id int, \n @max_id int, \n @start_id int, \n @end_id int\n\nSELECT @min_id = min(id) , \n @max_id = max(id) \nFROM Source_Table\n\nSELECT @start_id = @min_id , \n @end_id = @min_id + 1000 \n\nWHILE @end_id <= @max_id \nBEGIN\n\n print 'inserting id range: ' + convert(varchar,@start_id) + ' to ' + convert(varchar,@end_id) \n\n INSERT Target_Table \n SELECT * \n FROM Source_Table s\n WHERE id BETWEEN @start_id AND @end_id\n\n SELECT @start_id = @end_id + 1, \n @end_id = @end_id + 1000 \nEND\n\nset rowcount 0\nprint 'done'\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3524/"
] |
129,445
|
<p>I'm new to postgreSQL and I have a simple question:</p>
<p>I'm trying to create a simple script that creates a DB so I can later call it like this:</p>
<pre><code>psql -f createDB.sql
</code></pre>
<p>I want the script to call other scripts (separate ones for creating tables, adding constraints, functions etc), like this:</p>
<pre><code>\i script1.sql
\i script2.sql
</code></pre>
<p>It works fine provided that createDB.sql is in the <strong>same dir</strong>.</p>
<p>But if I move script2 to a directory under the one with createDB, and modify the createDB so it looks like this:</p>
<pre><code>\i script1.sql
\i somedir\script2.sql
</code></pre>
<p>I get an error:</p>
<blockquote>
<p>psql:createDB.sql:2: somedir: Permission denied</p>
</blockquote>
<p>I'm using Postgres Plus 8.3 for windows, default postgres user.</p>
<p><strong>EDIT:</strong></p>
<p>Silly me, unix slashes solved the problem.</p>
|
[
{
"answer_id": 129496,
"author": "Steve K",
"author_id": 739,
"author_profile": "https://Stackoverflow.com/users/739",
"pm_score": 8,
"selected": true,
"text": "\\i somedir/script2.sql \n \\i c:/somedir/script2.sql\n \\i somedir\\\\script2.sql\n"
},
{
"answer_id": 15415502,
"author": "phipex",
"author_id": 1421953,
"author_profile": "https://Stackoverflow.com/users/1421953",
"pm_score": 2,
"selected": false,
"text": "\\i 'somedir\\\\script2.sql'\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21853/"
] |
129,451
|
<p>If you are using Java or JavaScript, is there a good way to do something like a String subtraction so that given two strings:</p>
<pre><code>org.company.project.component
org.company.project.component.sub_component
</code></pre>
<p>you just get:</p>
<pre><code>sub_component
</code></pre>
<p>I know that I could just write code to walk the string comparing characters, but I was hoping there was a way to do it in a really compact way. </p>
<p>Another use-case is to find the diff between the strings:</p>
<pre><code>org.company.project.component.diff
org.company.project.component.sub_component
</code></pre>
<p>I actually only want to remove the sections that are identical.</p>
|
[
{
"answer_id": 129461,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 3,
"selected": false,
"text": "String result = \"org.company.project.component.sub_component\".replace(\"org.company.project.component\",\"\")\n"
},
{
"answer_id": 129472,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 4,
"selected": true,
"text": "public static String sub(String a, String b) {\n if (b.startsWith(a)) {\n return b.subString(a.length());\n }\n\n if (b.endsWith(a)) {\n return b.subString(0, b.length() - a.length());\n }\n\n return \"\";\n}\n"
},
{
"answer_id": 129517,
"author": "Joshua Carmody",
"author_id": 8409,
"author_profile": "https://Stackoverflow.com/users/8409",
"pm_score": 0,
"selected": false,
"text": "var baseString = \"org.company.project.component.sub_component\";\nvar splitString = baseString.split(\".\");\nvar subString = splitString[splitString.length - 1];\n"
},
{
"answer_id": 147234,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javascript\">\nvar a = \"org.company.project.component.diff\";\nvar b = \"org.company.project.component.sub_component\";\nvar i = 0;\nwhile(a.charAt(i) == b.charAt(i)){\n i++;\n}\nalert(b.substring(i));\n</script>\n"
},
{
"answer_id": 147903,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 0,
"selected": false,
"text": "function sub(a, b) {\n return [a, b].join('\\x01').match(/^([^\\x01]*)[^\\x01]*\\x01\\1(.*)/)[2];\n}\n"
},
{
"answer_id": 34756652,
"author": "Jangofett2008",
"author_id": 5781728,
"author_profile": "https://Stackoverflow.com/users/5781728",
"pm_score": -1,
"selected": false,
"text": "String.prototype.contracat = function(string){\n var thing = this.valueOf();\n for(var i=0; i<string.length;i++){\n thing=thing.replace(string.charAt(i),\"\");\n }\n return thing\n};\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5412/"
] |
129,453
|
<p>Every time I start in deep in a C# project, I end up with lots of events that really just need to pass a single item. I stick with the <code>EventHandler</code>/<code>EventArgs</code> practice, but what I like to do is have something like:</p>
<pre><code>public delegate void EventHandler<T>(object src, EventArgs<T> args);
public class EventArgs<T>: EventArgs {
private T item;
public EventArgs(T item) {
this.item = item;
}
public T Item {
get { return item; }
}
}
</code></pre>
<p>Later, I can have my</p>
<pre><code>public event EventHandler<Foo> FooChanged;
public event EventHandler<Bar> BarChanged;
</code></pre>
<p>However, it seems that the standard for .NET is to create a new delegate and <code>EventArgs</code> subclass for each type of event. Is there something wrong with my generic approach?
<hr/>
EDIT: The reason for this post is that I just re-created this in a new project, and wanted to make sure it was ok. Actually, I was re-creating it as I posted. I found that there is a generic <code>EventHandler<TEventArgs></code>, so you don't need to create the generic delegate, but you still need the generic <code>EventArgs<T></code> class, because <code>TEventArgs: EventArgs</code>.
<hr/>
Another EDIT: One downside (to me) of the built-in solution is the extra verbosity:</p>
<pre><code>public event EventHandler<EventArgs<Foo>> FooChanged;
</code></pre>
<p>vs.</p>
<pre><code>public event EventHandler<Foo> FooChanged;
</code></pre>
<p>It can be a pain for clients to register for your events though, because the System namespace is imported by default, so they have to manually seek out your namespace, even with a fancy tool like Resharper... Anyone have any ideas pertaining to that?</p>
|
[
{
"answer_id": 129511,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 2,
"selected": false,
"text": "EventHandler<T>"
},
{
"answer_id": 129613,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 6,
"selected": true,
"text": "public delegate void EventHandler<TArgs>(object sender, TArgs args) where TArgs : EventArgs\n"
},
{
"answer_id": 129816,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 3,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<CodeSnippets xmlns=\"http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet\">\n <CodeSnippet Format=\"1.0.0\">\n <Header>\n <Title>Generic event with one type/argument.</Title>\n <Shortcut>ev1Generic</Shortcut>\n <Description>Code snippet for event handler and On method</Description>\n <Author>Ryan Lundy</Author>\n <SnippetTypes>\n <SnippetType>Expansion</SnippetType>\n </SnippetTypes>\n </Header>\n <Snippet>\n <Declarations>\n <Literal>\n <ID>type</ID>\n <ToolTip>Type of the property in the EventArgs subclass.</ToolTip>\n <Default>propertyType</Default>\n </Literal>\n <Literal>\n <ID>argName</ID>\n <ToolTip>Name of the argument in the EventArgs subclass constructor.</ToolTip>\n <Default>propertyName</Default>\n </Literal>\n <Literal>\n <ID>propertyName</ID>\n <ToolTip>Name of the property in the EventArgs subclass.</ToolTip>\n <Default>PropertyName</Default>\n </Literal>\n <Literal>\n <ID>eventName</ID>\n <ToolTip>Name of the event</ToolTip>\n <Default>NameOfEvent</Default>\n </Literal>\n </Declarations>\n <Code Language=\"CSharp\"><![CDATA[public class $eventName$EventArgs : System.EventArgs\n {\n public $eventName$EventArgs($type$ $argName$)\n {\n this.$propertyName$ = $argName$;\n }\n\n public $type$ $propertyName$ { get; private set; }\n }\n\n public event EventHandler<$eventName$EventArgs> $eventName$;\n protected virtual void On$eventName$($eventName$EventArgs e)\n {\n var handler = $eventName$;\n if (handler != null)\n handler(this, e);\n }]]>\n </Code>\n <Imports>\n <Import>\n <Namespace>System</Namespace>\n </Import>\n </Imports>\n </Snippet>\n </CodeSnippet>\n</CodeSnippets>\n <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<CodeSnippets xmlns=\"http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet\">\n <CodeSnippet Format=\"1.0.0\">\n <Header>\n <Title>Generic event with two types/arguments.</Title>\n <Shortcut>ev2Generic</Shortcut>\n <Description>Code snippet for event handler and On method</Description>\n <Author>Ryan Lundy</Author>\n <SnippetTypes>\n <SnippetType>Expansion</SnippetType>\n </SnippetTypes>\n </Header>\n <Snippet>\n <Declarations>\n <Literal>\n <ID>type1</ID>\n <ToolTip>Type of the first property in the EventArgs subclass.</ToolTip>\n <Default>propertyType1</Default>\n </Literal>\n <Literal>\n <ID>arg1Name</ID>\n <ToolTip>Name of the first argument in the EventArgs subclass constructor.</ToolTip>\n <Default>property1Name</Default>\n </Literal>\n <Literal>\n <ID>property1Name</ID>\n <ToolTip>Name of the first property in the EventArgs subclass.</ToolTip>\n <Default>Property1Name</Default>\n </Literal>\n <Literal>\n <ID>type2</ID>\n <ToolTip>Type of the second property in the EventArgs subclass.</ToolTip>\n <Default>propertyType1</Default>\n </Literal>\n <Literal>\n <ID>arg2Name</ID>\n <ToolTip>Name of the second argument in the EventArgs subclass constructor.</ToolTip>\n <Default>property1Name</Default>\n </Literal>\n <Literal>\n <ID>property2Name</ID>\n <ToolTip>Name of the second property in the EventArgs subclass.</ToolTip>\n <Default>Property2Name</Default>\n </Literal>\n <Literal>\n <ID>eventName</ID>\n <ToolTip>Name of the event</ToolTip>\n <Default>NameOfEvent</Default>\n </Literal>\n </Declarations>\n <Code Language=\"CSharp\">\n <![CDATA[public class $eventName$EventArgs : System.EventArgs\n {\n public $eventName$EventArgs($type1$ $arg1Name$, $type2$ $arg2Name$)\n {\n this.$property1Name$ = $arg1Name$;\n this.$property2Name$ = $arg2Name$;\n }\n\n public $type1$ $property1Name$ { get; private set; }\n public $type2$ $property2Name$ { get; private set; }\n }\n\n public event EventHandler<$eventName$EventArgs> $eventName$;\n protected virtual void On$eventName$($eventName$EventArgs e)\n {\n var handler = $eventName$;\n if (handler != null)\n handler(this, e);\n }]]>\n </Code>\n <Imports>\n <Import>\n <Namespace>System</Namespace>\n </Import>\n </Imports>\n </Snippet>\n </CodeSnippet>\n</CodeSnippets>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96/"
] |
129,498
|
<p>I am using the ADONetAppender to (try) to log data via a stored procedure (so that I may inject logic into the logging routine).</p>
<p>My configuration settings are listed below. Can anybody tell what I'm doing wrong?</p>
<pre class="lang-xml prettyprint-override"><code><appender name="ADONetAppender_SqlServer" type="log4net.Appender.ADONetAppender">
<bufferSize value="1" />
<threshold value="ALL"/>
<param name="ConnectionType" value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<param name="ConnectionString" value="<MyConnectionString>" />
<param name="UseTransactions" value="False" />
<commandText value="dbo.LogDetail_via_Log4Net" />
<commandType value="StoredProcedure" />
<parameter>
<parameterName value="@AppLogID"/>
<dbType value="String"/>
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{LoggingSessionId}" />
</layout>
</parameter>
<parameter>
<parameterName value="@CreateUser"/>
<dbType value="String"/>
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{HttpUser}" />
</layout>
</parameter>
<parameter>
<parameterName value="@Message"/>
<dbType value="String"/>
<size value="8000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="@LogLevel"/>
<dbType value="String"/>
<size value="50"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
</appender>
</code></pre>
|
[
{
"answer_id": 1037572,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "</configSections>\n<log4net>\n\n <appender name=\"AdoNetAppender\" type=\"log4net.Appender.AdoNetAppender\">\n\n <bufferSize value=\"1\"/>\n\n <connectionType value=\"System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089\"/>\n\n <connectionString value=\"Data Source=yourservername;initial Catalog=Databasename;User ID=sa;Password=xyz;\"/>\n\n\n\n <commandText value=\"INSERT INTO Log4Net ([Date], [Thread], [Level], [Logger], [Message], \n [Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)\"/>\n\n <parameter>\n\n <parameterName value=\"@log_date\"/>\n\n <dbType value=\"DateTime\"/>\n\n <layout type=\"log4net.Layout.RawTimeStampLayout\"/>\n\n </parameter>\n\n <parameter>\n\n <parameterName value=\"@thread\"/>\n\n <dbType value=\"String\"/>\n\n <size value=\"255\"/>\n\n <layout type=\"log4net.Layout.PatternLayout\">\n\n <conversionPattern value=\"%thread ip=%property{ip}\"/>\n\n </layout>\n\n </parameter>\n\n <parameter>\n\n <parameterName value=\"@log_level\"/>\n\n <dbType value=\"String\"/>\n\n <size value=\"50\"/>\n\n <layout type=\"log4net.Layout.PatternLayout\">\n\n <conversionPattern value=\"%level\"/>\n\n </layout>\n\n </parameter>\n\n <parameter>\n\n <parameterName value=\"@logger\"/>\n\n <dbType value=\"String\"/>\n\n <size value=\"255\"/>\n\n <layout type=\"log4net.Layout.PatternLayout\">\n\n <conversionPattern value=\"%logger\"/>\n\n </layout>\n\n </parameter>\n\n <parameter>\n\n <parameterName value=\"@message\"/>\n\n <dbType value=\"String\"/>\n\n <size value=\"4000\"/>\n\n <layout type=\"log4net.Layout.PatternLayout\">\n\n <conversionPattern value=\"%message\"/>\n\n </layout>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
129,502
|
<p>This is on iPhone 0S 2.0. Answers for 2.1 are fine too, though I am unaware of any differences regarding tables.</p>
<p>It feels like it should be possible to get text to wrap without creating a custom cell, since a <code>UITableViewCell</code> contains a <code>UILabel</code> by default. I know I can make it work if I create a custom cell, but that's not what I'm trying to achieve - I want to understand why my current approach doesn't work.</p>
<p>I've figured out that the label is created on demand (since the cell supports text and image access, so it doesn't create the data view until necessary), so if I do something like this:</p>
<pre><code>cell.text = @""; // create the label
UILabel* label = (UILabel*)[[cell.contentView subviews] objectAtIndex:0];
</code></pre>
<p>then I get a valid label, but setting <code>numberOfLines</code> on that (and lineBreakMode) doesn't work - I still get single line text. There is plenty of height in the <code>UILabel</code> for the text to display - I'm just returning a large value for the height in <code>heightForRowAtIndexPath</code>.</p>
|
[
{
"answer_id": 129743,
"author": "drewh",
"author_id": 1967,
"author_profile": "https://Stackoverflow.com/users/1967",
"pm_score": -1,
"selected": false,
"text": "UITableViewCell's UILabel UILabel numberOfLines sizeToFit UILabel* label = [[UILabel alloc] initWithFrame:cell.frame];\nlabel.numberOfLines = <...an appriate number of lines...>\nlabel.text = <...your text...>\n[label sizeToFit];\n[cell addSubview:label];\n[label release];\n"
},
{
"answer_id": 905565,
"author": "Tim Rupe",
"author_id": 92208,
"author_profile": "https://Stackoverflow.com/users/92208",
"pm_score": 9,
"selected": true,
"text": "cellForRowAtIndexPath: UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];\nif (cell == nil)\n{\n cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];\n cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;\n cell.textLabel.numberOfLines = 0;\n cell.textLabel.font = [UIFont fontWithName:@\"Helvetica\" size:17.0];\n}\n UITableViewCell heightForRowAtIndexPath - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath\n{\n NSString *cellText = @\"Go get some text for your cell.\";\n UIFont *cellFont = [UIFont fontWithName:@\"Helvetica\" size:17.0];\n CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);\n CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];\n\n return labelSize.height + 20;\n}\n"
},
{
"answer_id": 3054313,
"author": "dukz",
"author_id": 286105,
"author_profile": "https://Stackoverflow.com/users/286105",
"pm_score": 0,
"selected": false,
"text": "UILabel textLabel sizeToFit - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath\n{\n static NSString *CellIdentifier = @\"Cell\";\n\n UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];\n if (cell == nil)\n {\n cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];\n }\n\n // Configure the cell...\n cell.textLabel.text = @\"Whatever text you want to put here is ok\";\n cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;\n cell.textLabel.numberOfLines = 0;\n [cell.textLabel sizeToFit];\n\n return cell;\n}\n"
},
{
"answer_id": 10189219,
"author": "Arshad Parwez",
"author_id": 883657,
"author_profile": "https://Stackoverflow.com/users/883657",
"pm_score": 2,
"selected": false,
"text": "UITableView UILabels cellForRowAtIndexPath heightForRowAtIndexPath -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath\n{ \n static NSString *CellIdentifier = @\"Cell\";\n\n UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];\n\n if (cell == nil)\n {\n cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];\n }\n\n cell.textLabel.font = [UIFont fontWithName:@\"Helvetica\" size:16];\n cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;\n cell.textLabel.numberOfLines = 0;\n\n [cell setSelectionStyle:UITableViewCellSelectionStyleGray]; \n cell.textLabel.text = [mutArr objectAtIndex:indexPath.section];\n NSLog(@\"%@\",cell.textLabel.text);\n\n cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@\"arrow.png\" ]];\n\n return cell;\n\n}\n\n- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath\n{ \n CGSize labelSize = CGSizeMake(200.0, 20.0);\n\n NSString *strTemp = [mutArr objectAtIndex:indexPath.section];\n\n if ([strTemp length] > 0)\n labelSize = [strTemp sizeWithFont: [UIFont boldSystemFontOfSize: 14.0] constrainedToSize: CGSizeMake(labelSize.width, 1000) lineBreakMode: UILineBreakModeWordWrap];\n\n return (labelSize.height + 10);\n}\n mutArr mutArr= [[NSMutableArray alloc] init];\n\n[mutArr addObject:@\"HEMAN\"];\n[mutArr addObject:@\"SUPERMAN\"];\n[mutArr addObject:@\"Is SUPERMAN powerful than HEMAN\"];\n[mutArr addObject:@\"Well, if HEMAN is weaker than SUPERMAN, both are friends and we will never get to know who is more powerful than whom because they will never have a fight among them\"];\n[mutArr addObject:@\"Where are BATMAN and SPIDERMAN\"];\n"
},
{
"answer_id": 11135174,
"author": "Vincent",
"author_id": 1276622,
"author_profile": "https://Stackoverflow.com/users/1276622",
"pm_score": 1,
"selected": false,
"text": "-(NSString *)getHeaderData:(int)theSection {\n ...\n return rowText;\n}\n cellForRowAtIndexPath numberoflines - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath\n{\n static NSString *CellIdentifier = @\"Cell\";\n UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];\n\n UIFont *cellFont = [UIFont fontWithName:@\"Verdana\" size:12.0];\n cell.textLabel.text= [self getRowData:indexPath.section];\n cell.textLabel.font = cellFont;\n cell.textLabel.numberOfLines=0;\n return cell;\n}\n heightForRowAtIndexPath - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath\n{\n UIFont *cellFont = [UIFont fontWithName:@\"Verdana\" size:12.0];\n CGSize boundingSize = CGSizeMake(1024, CGFLOAT_MAX);\n CGSize requiredSize = [[self getRowData:indexPath.section] sizeWithFont:cellFont constrainedToSize:boundingSize lineBreakMode:UILineBreakModeWordWrap];\n return requiredSize.height; \n}\n"
},
{
"answer_id": 22235855,
"author": "ddiego",
"author_id": 589472,
"author_profile": "https://Stackoverflow.com/users/589472",
"pm_score": 4,
"selected": false,
"text": "UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];\nif (cell == nil)\n{\n cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;\n cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;\n cell.textLabel.numberOfLines = 0;\n cell.textLabel.font = [UIFont fontWithName:@\"Helvetica\" size:17.0];\n}\n\n- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath\n{\n NSString *cellText = @\"Go get some text for your cell.\";\n UIFont *cellFont = [UIFont fontWithName:@\"Helvetica\" size:17.0];\n\n NSAttributedString *attributedText =\n [[NSAttributedString alloc]\n initWithString:cellText\n attributes:@\n {\n NSFontAttributeName: cellFont\n }];\n CGRect rect = [attributedText boundingRectWithSize:CGSizeMake(tableView.bounds.size.width, CGFLOAT_MAX)\n options:NSStringDrawingUsesLineFragmentOrigin\n context:nil];\n return rect.size.height + 20;\n}\n"
},
{
"answer_id": 29225817,
"author": "Manish Kr. Shukla",
"author_id": 3860249,
"author_profile": "https://Stackoverflow.com/users/3860249",
"pm_score": 1,
"selected": false,
"text": "[self.tableView setRowHeight:whatEvereight.0f];\n [self.tableView setRowHeight:80.0f];\n"
},
{
"answer_id": 39989707,
"author": "Jason",
"author_id": 1066787,
"author_profile": "https://Stackoverflow.com/users/1066787",
"pm_score": 2,
"selected": false,
"text": "tableView.estimatedRowHeight = 85.0 //use an appropriate estimate\ntableView.rowHeight = UITableViewAutomaticDimension"
},
{
"answer_id": 54085798,
"author": "Naresh",
"author_id": 8090893,
"author_profile": "https://Stackoverflow.com/users/8090893",
"pm_score": 1,
"selected": false,
"text": "extension UILabel {\n func lblFunction() {\n //You can pass here all UILabel properties like Font, colour etc....\n numberOfLines = 0\n lineBreakMode = .byWordWrapping//If you want word wraping\n lineBreakMode = .byCharWrapping//If you want character wraping\n }\n}\n cell.textLabel.lblFunction()//Replace your label name \n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18017/"
] |
129,507
|
<p>How does one write a unittest that fails only if a function doesn't throw an expected exception?</p>
|
[
{
"answer_id": 129522,
"author": "Moe",
"author_id": 3051,
"author_profile": "https://Stackoverflow.com/users/3051",
"pm_score": 11,
"selected": true,
"text": "TestCase.assertRaises TestCase.failUnlessRaises import mymod\n\nclass MyTestCase(unittest.TestCase):\n def test1(self):\n self.assertRaises(SomeCoolException, mymod.myfunc)\n"
},
{
"answer_id": 129528,
"author": "Daryl Spitzer",
"author_id": 4766,
"author_profile": "https://Stackoverflow.com/users/4766",
"pm_score": 6,
"selected": false,
"text": "def test_afunction_throws_exception(self):\n try:\n afunction()\n except ExpectedException:\n pass\n except Exception:\n self.fail('unexpected exception raised')\n else:\n self.fail('ExpectedException not raised')\n assertRaises"
},
{
"answer_id": 129610,
"author": "Daryl Spitzer",
"author_id": 4766,
"author_profile": "https://Stackoverflow.com/users/4766",
"pm_score": 9,
"selected": false,
"text": "def test_afunction_throws_exception(self):\n self.assertRaises(ExpectedException, afunction)\n def test_afunction_throws_exception(self):\n self.assertRaises(ExpectedException, afunction, arg1, arg2)\n"
},
{
"answer_id": 132682,
"author": "pi.",
"author_id": 15274,
"author_profile": "https://Stackoverflow.com/users/15274",
"pm_score": 3,
"selected": false,
"text": "def throw_up(something, gowrong=False):\n \"\"\"\n >>> throw_up('Fish n Chips')\n Traceback (most recent call last):\n ...\n Exception: Fish n Chips\n\n >>> throw_up('Fish n Chips', gowrong=True)\n 'I feel fine!'\n \"\"\"\n if gowrong:\n return \"I feel fine!\"\n raise Exception(something)\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n"
},
{
"answer_id": 241809,
"author": "Daryl Spitzer",
"author_id": 4766,
"author_profile": "https://Stackoverflow.com/users/4766",
"pm_score": 3,
"selected": false,
"text": "from testcase import TestCase\n\nimport mymod\n\nclass MyTestCase(TestCase):\n def test1(self):\n self.assertRaisesWithMessage(SomeCoolException,\n 'expected message',\n mymod.myfunc)\n"
},
{
"answer_id": 3166985,
"author": "Art",
"author_id": 62194,
"author_profile": "https://Stackoverflow.com/users/62194",
"pm_score": 9,
"selected": false,
"text": "import unittest\n\ndef broken_function():\n raise Exception('This is broken')\n\nclass MyTestCase(unittest.TestCase):\n def test(self):\n with self.assertRaises(Exception) as context:\n broken_function()\n\n self.assertTrue('This is broken' in context.exception)\n\nif __name__ == '__main__':\n unittest.main()\n context.exception str TypeError self.assertTrue('This is broken' in str(context.exception))\n"
},
{
"answer_id": 3983323,
"author": "Bruno Carvalho",
"author_id": 482398,
"author_profile": "https://Stackoverflow.com/users/482398",
"pm_score": 3,
"selected": false,
"text": "import unittest\n\nclass TestClass():\n def raises_exception(self):\n raise Exception(\"test\")\n\nclass MyTestCase(unittest.TestCase):\n def test_if_method_raises_correct_exception(self):\n test_class = TestClass()\n # note that you dont use () when passing the method to assertRaises\n self.assertRaises(Exception, test_class.raises_exception)\n"
},
{
"answer_id": 14712903,
"author": "macm",
"author_id": 506038,
"author_profile": "https://Stackoverflow.com/users/506038",
"pm_score": 5,
"selected": false,
"text": "def square_value(a):\n \"\"\"\n Returns the square value of a.\n \"\"\"\n try:\n out = a*a\n except TypeError:\n raise TypeError(\"Input should be a string:\")\n\n return out\n import dum_function as df # import function module\nimport unittest\nclass Test(unittest.TestCase):\n \"\"\"\n The class inherits from unittest\n \"\"\"\n def setUp(self):\n \"\"\"\n This method is called before each test\n \"\"\"\n self.false_int = \"A\"\n\n def tearDown(self):\n \"\"\"\n This method is called after each test\n \"\"\"\n pass\n #---\n ## TESTS\n def test_square_value(self):\n # assertRaises(excClass, callableObj) prototype\n self.assertRaises(TypeError, df.square_value(self.false_int))\n\n if __name__ == \"__main__\":\n unittest.main()\n ======================================================================\nERROR: test_square_value (__main__.Test)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"test_dum_function.py\", line 22, in test_square_value\n self.assertRaises(TypeError, df.square_value(self.false_int))\n File \"/home/jlengrand/Desktop/function.py\", line 8, in square_value\n raise TypeError(\"Input should be a string:\")\nTypeError: Input should be a string:\n\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nFAILED (errors=1)\n self.assertRaises(TypeError, lambda: df.square_value(self.false_int))\n ----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK\n"
},
{
"answer_id": 23780046,
"author": "Pigueiras",
"author_id": 1004046,
"author_profile": "https://Stackoverflow.com/users/1004046",
"pm_score": 5,
"selected": false,
"text": "pytest pytest.raises(Exception) def test_div_zero():\n with pytest.raises(ZeroDivisionError):\n 1/0\n pigueiras@pigueiras$ py.test\n================= test session starts =================\nplatform linux2 -- Python 2.6.6 -- py-1.4.20 -- pytest-2.5.2 -- /usr/bin/python\ncollected 1 items \n\ntests/test_div_zero.py:6: test_div_zero PASSED\n contextmanager import contextlib\n\n@contextlib.contextmanager\ndef raises(exception):\n try:\n yield \n except exception as e:\n assert True\n else:\n assert False\n raises with raises(Exception):\n print \"Hola\" # Calls assert False\n\nwith raises(Exception):\n raise Exception # Calls assert True\n"
},
{
"answer_id": 28223420,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 7,
"selected": false,
"text": "self.assertRaises def test_1_cannot_add_int_and_str(self):\n with self.assertRaises(TypeError):\n 1 + '1'\n unittest import unittest\n unittest unittest import unittest2 as unittest\n class MyTestCase(unittest.TestCase):\n def test_1_cannot_add_int_and_str(self):\n with self.assertRaises(TypeError):\n 1 + '1'\n def test_2_cannot_add_int_and_str(self):\n import operator\n self.assertRaises(TypeError, operator.add, 1, '1')\n assertRaises unittest.main(exit=False)\n unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(MyTestCase))\n ..\n----------------------------------------------------------------------\nRan 2 tests in 0.007s\n\nOK\n<unittest2.runner.TextTestResult run=2 errors=0 failures=0>\n 1 '1' TypeError unittest.TextTestRunner(verbosity=2).run(unittest.TestLoader().loadTestsFromTestCase(MyTestCase))\n"
},
{
"answer_id": 56561182,
"author": "Arindam Roychowdhury",
"author_id": 1076965,
"author_profile": "https://Stackoverflow.com/users/1076965",
"pm_score": 3,
"selected": false,
"text": "import unittest\n\nclass DeviceException(Exception):\n def __init__(self, msg, code):\n self.msg = msg\n self.code = code\n def __str__(self):\n return repr(\"Error {}: {}\".format(self.code, self.msg))\n\nclass MyDevice(object):\n def __init__(self):\n self.name = 'DefaultName'\n\n def setParameter(self, param, value):\n if isinstance(value, str):\n setattr(self, param , value)\n else:\n raise DeviceException('Incorrect type of argument passed. Name expects a string', 100001)\n\n def getParameter(self, param):\n return getattr(self, param)\n\nclass TestMyDevice(unittest.TestCase):\n\n def setUp(self):\n self.dev1 = MyDevice()\n\n def tearDown(self):\n del self.dev1\n\n def test_name(self):\n \"\"\" Test for valid input for name parameter \"\"\"\n\n self.dev1.setParameter('name', 'MyDevice')\n name = self.dev1.getParameter('name')\n self.assertEqual(name, 'MyDevice')\n\n def test_invalid_name(self):\n \"\"\" Test to check if error is raised if invalid type of input is provided \"\"\"\n\n self.assertRaises(DeviceException, self.dev1.setParameter, 'name', 1234)\n\n def test_exception_message(self):\n \"\"\" Test to check if correct exception message and code is raised when incorrect value is passed \"\"\"\n\n with self.assertRaises(DeviceException) as cm:\n self.dev1.setParameter('name', 1234)\n self.assertEqual(cm.exception.msg, 'Incorrect type of argument passed. Name expects a string', 'mismatch in expected error message')\n self.assertEqual(cm.exception.code, 100001, 'mismatch in expected error code')\n\n\nif __name__ == '__main__':\n unittest.main()\n"
},
{
"answer_id": 58225392,
"author": "RUser4512",
"author_id": 4791408,
"author_profile": "https://Stackoverflow.com/users/4791408",
"pm_score": -1,
"selected": false,
"text": "def assert_error(e, x):\n try:\n e(x)\n except:\n return\n raise AssertionError()\n\ndef failing_function(x):\n raise ValueError()\n\ndef dummy_function(x):\n return x\n\nif __name__==\"__main__\":\n assert_error(failing_function, 0)\n assert_error(dummy_function, 0)\n Traceback (most recent call last):\n File \"assert_error.py\", line 16, in <module>\n assert_error(dummy_function, 0)\n File \"assert_error.py\", line 6, in assert_error\n raise AssertionError()\nAssertionError\n"
},
{
"answer_id": 62253324,
"author": "kriss",
"author_id": 168465,
"author_profile": "https://Stackoverflow.com/users/168465",
"pm_score": 5,
"selected": false,
"text": "TypeError with self.assertRaises(TypeError):\n function_raising_some_exception(parameters)\n TypeError IndexError with self.assertRaises((TypeError,IndexError)):\n function_raising_some_exception(parameters)\n # Here I catch any exception \nwith self.assertRaises(Exception) as e:\n function_raising_some_exception(parameters)\n\n# Here I check actual exception type (but I could\n# check anything else about that specific exception,\n# like it's actual message or values stored in the exception)\nself.assertTrue(type(e.exception) in [TypeError,MatrixIsSingular])\n"
},
{
"answer_id": 64540525,
"author": "Denis Biwott",
"author_id": 8173167,
"author_profile": "https://Stackoverflow.com/users/8173167",
"pm_score": 2,
"selected": false,
"text": "assertRaisesMessage with self.assertRaisesMessage(SomeException,'Some error message e.g 404 Not Found'):\n faulty_funtion()\n\n"
},
{
"answer_id": 65671324,
"author": "Stephan Schielke",
"author_id": 411718,
"author_profile": "https://Stackoverflow.com/users/411718",
"pm_score": 2,
"selected": false,
"text": "async def test_await_async_fail(self):\n with self.assertRaises(Exception) as e:\n await async_one()\n"
},
{
"answer_id": 67360753,
"author": "mobius-crypt",
"author_id": 5287734,
"author_profile": "https://Stackoverflow.com/users/5287734",
"pm_score": 2,
"selected": false,
"text": "def set_string(prop, value):\n if not isinstance(value, str):\n raise TypeError(\"i told you i take strings only \")\n return value\n\nclass BuyVolume(ndb.Model):\n stock_id = ndb.StringProperty(validator=set_string)\n\nfrom pytest import raises\nbuy_volume_instance: BuyVolume = BuyVolume()\nwith raises(TypeError):\n buy_volume_instance.stock_id = 25\n"
},
{
"answer_id": 69797577,
"author": "ifedapo olarewaju",
"author_id": 4088675,
"author_profile": "https://Stackoverflow.com/users/4088675",
"pm_score": 4,
"selected": false,
"text": "assertRaises msg import unittest\n\ndef your_function():\n raise RuntimeError('your exception message')\n\nclass YourTestCase(unittest.TestCase):\n def test(self):\n with self.assertRaises(RuntimeError, msg='your exception message'):\n your_function()\n\n\nif __name__ == '__main__':\n unittest.main()\n"
},
{
"answer_id": 70997465,
"author": "Dr. Joy Singhal",
"author_id": 15573016,
"author_profile": "https://Stackoverflow.com/users/15573016",
"pm_score": -1,
"selected": false,
"text": " try:\n bad_function()\n except ValueError as e:\n assert isinstance(e, ValueError)\n"
},
{
"answer_id": 72968206,
"author": "egvo",
"author_id": 7744106,
"author_profile": "https://Stackoverflow.com/users/7744106",
"pm_score": 2,
"selected": false,
"text": "def test_raises(self):\n with self.assertRaises(RuntimeError):\n raise RuntimeError()\n def test_raises(self):\n with self.assertRaises(RuntimeError) as error:\n raise RuntimeError(\"your exception message\")\n self.assertEqual(str(error.exception), \"your exception message\")\n def test_raises(self):\n self.assertRaises(RuntimeError, your_function)\n def test_raises_regex(self):\n with self.assertRaisesRegex(RuntimeError, r'.* exception message'):\n raise RuntimeError('your exception message')\n def test_raises_regex(self):\n self.assertRaisesRegex(RuntimeError, r'.* exception message', your_function)\n import unittest\n\ndef your_function():\n raise RuntimeError('your exception message')\n\nclass YourTestCase(unittest.TestCase):\n\n def test_1_raises_context_manager(self):\n with self.assertRaises(RuntimeError):\n your_function()\n\n def test_1b_raises_context_manager_and_error_message(self):\n with self.assertRaises(RuntimeError) as error:\n your_function()\n self.assertEqual(str(error.exception), \"your exception message\")\n\n def test_2_raises_oneliner(self):\n self.assertRaises(RuntimeError, your_function)\n\n def test_3_raises_regex_context_manager(self):\n with self.assertRaisesRegex(RuntimeError, r'.* exception message'):\n your_function()\n\n def test_4_raises_regex_oneliner(self):\n self.assertRaisesRegex(RuntimeError, r'.* exception message', your_function)\n\nif __name__ == '__main__':\n unittest.main()\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
] |
129,510
|
<p>I have an application I'm writing where I'm allowing the administrators to add aliases for pages, categories, etc, and I would like to use a different controller/action depending on the alias (without redirecting, and I've found that render doesn't actually call the method. I just renders the template). I have tried a catch all route, but I'm not crazy about causing and catching a DoubleRender exception that gets thrown everytime.</p>
<p>The solution for this I've come up with is dynamically generated routes when the server is started, and using callbacks from the Alias model to reload routes when an alias is created/updated/destroyed.
Here is the code from my routes.rb:</p>
<pre><code>Alias.find(:all).each do |alias_to_add|
map.connect alias_to_add.name,
:controller => alias_to_add.page_type.controller,
:action => alias_to_add.page_type.action,
:navigation_node_id => alias_to_add.navigation_node.id
end
</code></pre>
<p>I am using callbacks in my Alias model as follows:</p>
<pre><code>after_save :rebuild_routes
after_destroy :rebuild_routes
def rebuild_routes
ActionController::Routing::Routes.reload!
end
</code></pre>
<p>Is this against Rails best practices? Is there a better solution?</p>
|
[
{
"answer_id": 130750,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "method_missing class MyController\n def method_missing(sym, *args)\n aliased = Alias.find_by_action_name(sym)\n # sanity check here in case no alias\n\n self.send( aliased.real_action_name )\n # sanity check here in case the real action calls a different render explicitly\n render :action => aliased.real_action_name\n end\n\n def normal_action\n @thing = Things.find(params[:id])\n end\nend\n define_method method_missing"
},
{
"answer_id": 131325,
"author": "Patrick McKenzie",
"author_id": 15046,
"author_profile": "https://Stackoverflow.com/users/15046",
"pm_score": 4,
"selected": true,
"text": "url_for (:action_you_actually_executed /foo_action/bar_method\n /some-wonderful-alias\n"
},
{
"answer_id": 148997,
"author": "tomafro",
"author_id": 7126,
"author_profile": "https://Stackoverflow.com/users/7126",
"pm_score": 2,
"selected": false,
"text": "map.connect ':name', :controller => 'aliases', :action => 'show'\n class AliasesController < ApplicationController\n def show\n if alias = Alias.find_by_name(params[:name])\n render_component(:controller => alias.page_type.controller, \n :action => alias.page_type.action,\n :navigation_node_id => alias.navigation_node.id)\n else\n render :file => \"#{RAILS_ROOT}/public/404.html\", :status => :not_found\n end\n end\nend\n"
},
{
"answer_id": 4213087,
"author": "mjnissim",
"author_id": 348931,
"author_profile": "https://Stackoverflow.com/users/348931",
"pm_score": 4,
"selected": false,
"text": "MyNewApplication::Application.reload_routes!\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6705/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.