qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
204,576
|
<p>In my MFC program I am using a splitter to create two panes. I now want to split one of these panes in half again and put in another view, can someone talk me through how to do it or point me in the direction of some code?</p>
<p>I would prefer to code it myself so I am not interested in custom derived classes unless they are extremely basic.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 204662,
"author": "Rob",
"author_id": 9236,
"author_profile": "https://Stackoverflow.com/users/9236",
"pm_score": 4,
"selected": true,
"text": "CMainFrame::OnCreateClient // Create splitter with 2 rows and 1 col\nm_wndSplitter.CreateStatic(this, 2, 1);\n// Create a view in the top row\nm_wndSplitter.CreateView(0, 0, RUNTIME_CLASS(CView1), CSize(100, 100), pContext);\n// Create a 2 column splitter that will go in the bottom row of the first\nm_wndSplitter2.CreateStatic(&m_wndSplitter, 1, 2, WS_CHILD|WS_VISIBLE, m_wndSplitter.IdFromRowCol(1, 0));\n// Create views for the bottom splitter\nm_wndSplitter2.CreateView(0, 0, RUNTIME_CLASS(CView2), CSize(100, 100), pContext); \nm_wndSplitter2.CreateView(0, 1, RUNTIME_CLASS(CView3), CSize(100, 100), pContext);\n...\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18664/"
] |
204,606
|
<p>In my current 32-bit application, I check (very occasionally) for overflow by doing operations on 64-bit integers.</p>
<p>However, on 64-bit systems there does not seem to be a standard 128-bit integer. Is there a simple way of checking for overflow, or a way of getting 128-bit integers, which works on all OSes and compilers?</p>
<p>I tried using GMP as a more generic solution, but it is a little heavyweight for my requirements.</p>
<p>Efficiency is not too important, no processor specific-ASM is.</p>
|
[
{
"answer_id": 204808,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 1,
"selected": false,
"text": "int64 myint64::add (int64 a, int64 b) {\n if (MAX_INT64 - a > b) {\n // error condition here.\n }\n return a + b;\n}\nint64 myint64::mul (int64 a, int64 b) {\n if (MAX_INT64 / a > b) {\n // error condition here.\n }\n return a * b;\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27074/"
] |
204,611
|
<p>I am working with Crystal Reports and MS SQL Server.
I need to remap the crystal report to point to a different database on the same SQL Server. Is there an automated way of doing this, or do I have to remap for every single report? I am currently doing this by adding a new data connection, and then updating the stored procedure with the specified paramether to change database(catalog). Also, after remaping, the .asp that displays the report crashes like this:</p>
<p>Active Server Pages, ASP 0115 (0x80004005)
A trappable error (E06D7363) occurred in an external object. The script cannot continue running.</p>
<p>The code is: </p>
<p>Set mainReportTableCollection = Session("oRpt").Database.Tables</p>
<pre><code>For Each mnTable in mainReportTableCollection
With mnTable.ConnectionProperties
.Item("user ID") = "<some_login_name>"
.Item("Password") = "<some_password>"
.Item("DSN") = "<some_DSN>"
.Item("Database") ="<some_Database>"
End With
Next
</code></pre>
<p>It runs, however, if i comment out the last two assignations.</p>
<p>Thanks in advance.</p>
<p>Yours trully, Silviu.</p>
|
[
{
"answer_id": 209010,
"author": "Jas",
"author_id": 777,
"author_profile": "https://Stackoverflow.com/users/777",
"pm_score": 0,
"selected": false,
"text": "'SET REPORT CONNECTION INFO\nFor i = 0 To rsource.ReportDocument.DataSourceConnections.Count - 1\n rsource.ReportDocument.DataSourceConnections(i).SetConnection(crystalServer, crystalDB, crystalUser, crystalPassword)\nNext\n\nFor i = 0 To rsource.ReportDocument.Subreports.Count - 1\n For x = 0 To rsource.ReportDocument.Subreports(i).DataSourceConnections.Count - 1\n rsource.ReportDocument.OpenSubreport(rsource.ReportDocument.Subreports(i).Name).DataSourceConnections(x).SetConnection(crystalServer, crystalDB, crystalUser, crystalPassword)\n Next\nNext\n"
},
{
"answer_id": 217756,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 2,
"selected": false,
"text": "Public Function connectReportToDatabase( _\n P_report As CRAXDRT.Report)\n\nDim table As CRAXDRT.DatabaseTable, _\n\nFor Each table In P_report.Database.tables\n\n If table.DllName <> \"crdb_ado.dll\" Then\n table.DllName = \"crdb_ado.dll\"\n End If\n\n table.ConnectionProperties.DeleteAll\n\n table.ConnectionProperties.Add \"Provider\", P_currentConnection.Provider\n table.ConnectionProperties.Add \"Data source\", P_currentConnection.Properties(\"Data source\").Value\n table.ConnectionProperties.Add \"Database\", P_currentConnection.DefaultDatabase\n table.ConnectionProperties.Add \"Integrated security\", P_currentConnection.Properties(\"Integrated security\").Value\n table.ConnectionProperties.Add \"Persist Security Info\", P_currentConnection.Properties(\"Persist Security Info\").Value\n table.ConnectionProperties.Add \"Initial Catalog\", P_currentConnection.Properties(\"Initial Catalog\").Value\n\n table.SetTableLocation table.location, \"\", P_currentConnection.ConnectionString\n\n table.TestConnectivity\n\nNext table\n Dim crystal As CRAXDRT.Application, _\n m_report as CRAXDRT.report \n\nSet crystal = New CRAXDRT.Application\nSet m_rapport = crystal.OpenReport(nameOfTheReport & \".rpt\")\n\nconnectreportToDatabase(m_report)\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
204,612
|
<p>Trying to make a form wizard with <a href="http://docs.jquery.com/UI/Tabs" rel="nofollow noreferrer">jQuery tabs</a>.</p>
<p>Is it possible to have each step of the form in separate views, then load each via jQuery/AJAX tabs option? When I AJAX load the partial form, it has no way to access the js, css, etc.; as there are is no 'header' for the partial file. It doesn't seem to inherit from the parent page at all. As a workaround I have all the forms on one page, divided into tabs with <code><div></code>s.
This does the job, but with js turned off it doesn't make much sense (though the app relies on js, and will be used in-house only with js enabled browsers).</p>
<p>I'm using CodeIgniter, but I guess the question is valid for any MVC framework.</p>
|
[
{
"answer_id": 392306,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": " jQuery(document).ready(function(){\n var tabs = jQuery(\"#tabs > ul\").tabs().bind('tabsload', function( event, ui ){\n jQuery( 'form', ui.panel ).submit(function() {\n jQuery.ajax({\n type: 'post',\n url: $(this).attr('action'),\n data: $(this).serialize(),\n success: function( response ){\n if(response.match( /^http:\\/\\/.*$/ ))\n {\n tabs.tabs('url', ui.index, response );\n tabs.tabs('load', ui.index );\n }\n }\n });\n return false;\n });\n });\n ui.panel"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196/"
] |
204,616
|
<p>We are in the process of moving our SVN repositories from one machine to another one, and with it will come a new domain name for the new repo. The problem is, that within the repository, there are lots of svn:externals references to other projects within the repository. So for example, we have projectA, which has in the svn:externals properties:</p>
<pre><code>external/libraryA svn://oldserver.net/repo/libraryA
external/libraryB svn://oldserver.net/repo/libraryB
</code></pre>
<p>...and so on. All of the URL's reference this particular domain name, so it can be easily parsed. Having already learned my lesson, I will migrate these URLs to be "svn://localhost/", but I need to find a way to go through the repository history and rewrite all of the old URLs, so that we can still check out older revisions of these projects without having broken links.</p>
<p>How would I go about doing this?</p>
|
[
{
"answer_id": 234106,
"author": "yvandermeer",
"author_id": 31201,
"author_profile": "https://Stackoverflow.com/users/31201",
"pm_score": 4,
"selected": true,
"text": "$ svnadmin dump /path/to/repos > original-dumpfile\n* Dumped revision 0.\n* Dumped revision 1.\n* Dumped revision 2.\n* Dumped revision 3.\n $ svnadmin create newrepos\n$ svnadmin load newrepos < modified-dumpfile\n"
},
{
"answer_id": 3526100,
"author": "ldav1s",
"author_id": 425738,
"author_profile": "https://Stackoverflow.com/users/425738",
"pm_score": 4,
"selected": false,
"text": "svndumptool transform-prop svn:externals \"(\\S*) (|-r ?\\d* ?)http://oldserver.net(/\\S*)\" \"\\2\\3 \\1\" source.dumpfile source-fixed-externals.dumpfile\n external/libraryA svn://oldserver.net/repo/libraryA\n /repo/libraryA external/libraryA\n"
},
{
"answer_id": 35939092,
"author": "Leo",
"author_id": 221284,
"author_profile": "https://Stackoverflow.com/users/221284",
"pm_score": 1,
"selected": false,
"text": "thing.domain.net -> 192.168.0.1 svn relocate for /D %G in (*) do (\ncd ./%G\n& svn relocate http://thing.domain.net http://192.168.0.1\n& cd ..) Settings->Saved Data->URL history->Clear"
},
{
"answer_id": 43887534,
"author": "Axel Bregnsbo",
"author_id": 155425,
"author_profile": "https://Stackoverflow.com/users/155425",
"pm_score": 0,
"selected": false,
"text": "flow"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14302/"
] |
204,627
|
<p>I'm trying to start using LINQ and specifically LINQ to SQL but I'm having some difficulties</p>
<p>I've tried this with SqlMetal and now using the database table designer in Visual Studio and I keep getting similar errors, like in this code, using the data context I created with the database layout designer in VS2008.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
string usn = UserNameBox.Text;
string pss = PassBox.Text;
if (usn == "" || pss == "")
return;
DataClassesDataContext dc = new DataClassesDataContext();
var user = from u in User
where u.UserName == usn
select u;
}
}
}
</code></pre>
<p>I get an error on the where saying: Could not find an implementation of the query pattern for source type 'System.Security.Principal.IPrincipal'. And also: 'Where' not found.</p>
<p>I had something similar to this when I tried to use the results of SqlMetal. I deleted that source and started over using the designer. I must be missing something here but I can't figure out what. Shouldn't the tables implement what I need since I'm using LINQ to SQL, or do I need to do something extra to make that happen?</p>
|
[
{
"answer_id": 204631,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 2,
"selected": false,
"text": "protected void Page_Load(object sender, EventArgs e) \n{ \n if (Page.IsPostBack) \n {\n string usn = UserNameBox.Text; \n string pss = PassBox.Text; \n if (usn == \"\" || pss == \"\") \n return; \n DataClassesDataContext dc = new DataClassesDataContext(); \n var user = from u in dc.User where u.UserName == usn select u; \n } \n}\n"
},
{
"answer_id": 204632,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 3,
"selected": false,
"text": "User dc.User var user = from u in dc.User\n where u.UserName == usn\n select u;\n User"
},
{
"answer_id": 204633,
"author": "Joel Cunningham",
"author_id": 5360,
"author_profile": "https://Stackoverflow.com/users/5360",
"pm_score": 4,
"selected": true,
"text": "var user = from u in dc.User\n where u.UserName == usn\n select u;\n"
},
{
"answer_id": 204636,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "DataClassesDataContext dc = new DataClassesDataContext();\nvar user = from u in dc.User\n where u.UserName == usn\n select u;\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26140/"
] |
204,644
|
<p>What is the name of the technology behind Google Maps which allows the server to send only the part of the map requested from the user to enhance the performance, and is there any library to handle this?</p>
|
[
{
"answer_id": 204684,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 2,
"selected": false,
"text": "http://maps.google.com/maps?f=q&hl=en&sll=37.0625,-95.677068&sspn=53.345014,88.769531&ie=UTF8&ll=41.226264,-81.454246&spn=0.012507,0.021672&z=16\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459737/"
] |
204,646
|
<p>Does anyone have a simple, efficient way of checking that a string doesn't contain HTML? Basically, I want to check that certain fields only contain plain text. I thought about looking for the < character, but that can easily be used in plain text. Another way might be to create a new System.Xml.Linq.XElement using:</p>
<pre><code>XElement.Parse("<wrapper>" + MyString + "</wrapper>")
</code></pre>
<p>and check that the XElement contains no child elements, but this seems a little heavyweight for what I need.</p>
|
[
{
"answer_id": 204664,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 6,
"selected": false,
"text": "Regex tagRegex = new Regex(@\"<\\s*([^ >]+)[^>]*>.*?<\\s*/\\s*\\1\\s*>\");\n Regex tagRegex = new Regex(@\"<[^>]+>\");\n bool hasTags = tagRegex.IsMatch(myString);\n"
},
{
"answer_id": 204668,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 4,
"selected": false,
"text": "using System.Text.RegularExpressions;\nprivate bool ContainsHTML(string checkString)\n{\n return Regex.IsMatch(checkString, \"<(.|\\n)*?>\");\n}\n"
},
{
"answer_id": 204720,
"author": "J c",
"author_id": 25837,
"author_profile": "https://Stackoverflow.com/users/25837",
"pm_score": 5,
"selected": false,
"text": "bool containsHTML = (myString != HttpUtility.HtmlEncode(myString));\n"
},
{
"answer_id": 205353,
"author": "Ben Mills",
"author_id": 203,
"author_profile": "https://Stackoverflow.com/users/203",
"pm_score": 4,
"selected": true,
"text": "public static bool ContainsXHTML(this string input)\n{\n try\n {\n XElement x = XElement.Parse(\"<wrapper>\" + input + \"</wrapper>\");\n return !(x.DescendantNodes().Count() == 1 && x.DescendantNodes().First().NodeType == XmlNodeType.Text);\n }\n catch (XmlException ex)\n {\n return true;\n }\n}\n public static string ConvertXHTMLEntities(this string input)\n{\n // Convert all ampersands to the ampersand entity.\n string output = input;\n output = output.Replace(\"&\", \"amp_token\");\n output = output.Replace(\"&\", \"&\");\n output = output.Replace(\"amp_token\", \"&\");\n\n // Convert less than to the less than entity (without messing up tags).\n output = output.Replace(\"< \", \"< \");\n return output;\n}\n bool ContainsHTML = UserEnteredString.ConvertXHTMLEntities().ContainsXHTML();\n"
},
{
"answer_id": 27448890,
"author": "kns98",
"author_id": 3583192,
"author_profile": "https://Stackoverflow.com/users/3583192",
"pm_score": 3,
"selected": false,
"text": "internal static class HtmlExts\n{\n public static bool containsHtmlTag(this string text, string tag)\n {\n var pattern = @\"<\\s*\" + tag + @\"\\s*\\/?>\";\n return Regex.IsMatch(text, pattern, RegexOptions.IgnoreCase);\n }\n\n public static bool containsHtmlTags(this string text, string tags)\n {\n var ba = tags.Split('|').Select(x => new {tag = x, hastag = text.containsHtmlTag(x)}).Where(x => x.hastag);\n\n return ba.Count() > 0;\n }\n\n public static bool containsHtmlTags(this string text)\n {\n return\n text.containsHtmlTags(\n \"a|abbr|acronym|address|area|b|base|bdo|big|blockquote|body|br|button|caption|cite|code|col|colgroup|dd|del|dfn|div|dl|DOCTYPE|dt|em|fieldset|form|h1|h2|h3|h4|h5|h6|head|html|hr|i|img|input|ins|kbd|label|legend|li|link|map|meta|noscript|object|ol|optgroup|option|p|param|pre|q|samp|script|select|small|span|strong|style|sub|sup|table|tbody|td|textarea|tfoot|th|thead|title|tr|tt|ul|var\");\n }\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203/"
] |
204,653
|
<p>Using a web service is often an excellent architectural approach. And, with the advent of WCF in .Net, it's getting even better.</p>
<p>But, in my experience, some people seem to think that web services should always be used in the data access layer for calls to the database. I don't think that web services are the universal solution.</p>
<p>I am thinking of smaller intranet applications with a few dozen users. The web app and its web service are deployed to one web server, not a web farm. There isn't going to be another web app in the future that can use this particular web service. It seems to me that the cost of calling the web service unnecessarily increases the burden on the web server. There is a performance hit to inter-process calls. Maintaining and debugging the code for the web app and the web service is more complicated. So is deployment. I just don't see the advantages of using a web service here.</p>
<p>One could test this by creating two versions of the web app, with and without the web service, and do stress testing, but I haven't done it.</p>
<p>Do you have an opinion on using web services for small-scale web app's? Any other occasions when web services are not a good architectural choice?</p>
|
[
{
"answer_id": 204713,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 6,
"selected": true,
"text": " - someService.SaveOrder(order); // <-- bad\n // some other code for shipping, charging, emailing, etc\n\n - someService.FulfillOrder(order); //<-- better\n //the service encapsulates the entire process\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27637/"
] |
204,670
|
<p>If I query a table with a condition on the key field as in:</p>
<pre><code> var user = from u in dc.Users
where u.UserName == usn
select u;
</code></pre>
<p>I know that I will either get zero results or one result. Should I still go ahead and retrieve the results using a for-each or is there another preferred way to handle this kind of situation. </p>
|
[
{
"answer_id": 204678,
"author": "Danimal",
"author_id": 2757,
"author_profile": "https://Stackoverflow.com/users/2757",
"pm_score": 4,
"selected": false,
"text": "var user = dc.Users.SingleOrDefault(u=> u.UserName==usn);\n"
},
{
"answer_id": 204679,
"author": "Joel Cunningham",
"author_id": 5360,
"author_profile": "https://Stackoverflow.com/users/5360",
"pm_score": 1,
"selected": false,
"text": "var user = (from u in dc.Users\n where u.UserName == usn\n select u).SingleOrDefault();\n"
},
{
"answer_id": 204681,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 7,
"selected": true,
"text": "var user = (from u in dc.Users\n where u.UserName == usn\n select u).FirstOrDefault();\n"
},
{
"answer_id": 31032731,
"author": "Just Trying to Help",
"author_id": 5045632,
"author_profile": "https://Stackoverflow.com/users/5045632",
"pm_score": 0,
"selected": false,
"text": "var user = (from u in dc.UserInfo \n where u.Users.Contains(username) \n select u).SingleOrDefault();\n"
},
{
"answer_id": 74086619,
"author": "Abhishek Panchal",
"author_id": 20191073,
"author_profile": "https://Stackoverflow.com/users/20191073",
"pm_score": 0,
"selected": false,
"text": "First() FirstOrDefault() Single() SingleOrDefault()"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26140/"
] |
204,676
|
<p>I'm about to release a set of Eclipse plug-ins as Open Source and noticed that most source code released under the LGPL/EPL contains a header banner in each file that refers to the license or contains the license itself.</p>
<p>Since adding these banners to each file manually seems to be a daunting and error-prone task. How can I go about automating the insertion of these banners?</p>
<p><strong><em>Edit:</em></strong> I've eventually found <a href="https://marketplace.eclipse.org/content/copyright-wizard" rel="nofollow noreferrer">Copyright Wizard</a> and <a href="https://marketplace.eclipse.org/content/eclipse-copyright-generator" rel="nofollow noreferrer">Copyright Generator</a> which are Eclipse plug-ins which also allow for updating existing license banners.</p>
|
[
{
"answer_id": 204928,
"author": "idrosid",
"author_id": 17876,
"author_profile": "https://Stackoverflow.com/users/17876",
"pm_score": 3,
"selected": false,
"text": "ls \"*.java\" mkdir ~/outdir\nfor i in `find -type d | sed 's/\\.//' | grep -v \"^$\"`; do mkdir ~/outdir$i; done\nfor i in `find -name \"*.java\"`; do cat msg $i > ~/outdir/$i ; done\n"
},
{
"answer_id": 206602,
"author": "Chris R",
"author_id": 23309,
"author_profile": "https://Stackoverflow.com/users/23309",
"pm_score": 2,
"selected": false,
"text": "Windows->Preferences Java->Code Style->Code Templates Comments->Files"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4445/"
] |
204,682
|
<p>I want to limit the number of words a person can enter in a text field. How can I track the number of words (by using a second field) in that field as each word is entered?</p>
|
[
{
"answer_id": 2408592,
"author": "Phil Rykoff",
"author_id": 284364,
"author_profile": "https://Stackoverflow.com/users/284364",
"pm_score": 2,
"selected": false,
"text": "$('#newKeywords').bind('change', function() {\n\n $('#wordsLong').text($('#newKeywords').val().split(' ').length + 1);\n\n});\n <textarea id=\"newKeywords\"></textarea>\n<div>The text consists of <span id=\"wordsLong\"></span> keywords.</div>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
204,694
|
<p>I have worked on several distributed client/server projects recently, and one pain point that we always run into is translating the DTO objects into our entities and vice-versa. I was wondering if anyone has a "simple" solution to this time sink?</p>
<p>One thing I thought about was coming up with some sort of translation using reflection...I guess you'd have to make sure your property names were exactly the same on each side of the wire - but seems like it might work. </p>
<p>Just looking for a way to avoid some of this time sink in my development.</p>
<p>Thanks!!</p>
|
[
{
"answer_id": 3043781,
"author": "Omu",
"author_id": 112100,
"author_profile": "https://Stackoverflow.com/users/112100",
"pm_score": 0,
"selected": false,
"text": " object <-> object\n object <-> Form/WebForm\n DataReader -> object\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10589/"
] |
204,695
|
<p>I'm writing a page that can use a couple of different themes, and I'm going to store some information about each theme in the web.config. </p>
<p>Is it more efficient to create a new sectionGroup and store everything together, or just put everything in appSettings?</p>
<p><b>configSection solution</b></p>
<pre><code><configSections>
<sectionGroup name="SchedulerPage">
<section name="Providers" type="System.Configuration.NameValueSectionHandler"/>
<section name="Themes" type="System.Configuration.NameValueSectionHandler"/>
</sectionGroup>
</configSections>
<SchedulerPage>
<Themes>
<add key="PI" value="PISchedulerForm"/>
<add key="UB" value="UBSchedulerForm"/>
</Themes>
</SchedulerPage>
</code></pre>
<p>To access values in the configSection, I am using this code:</p>
<pre><code> NameValueCollection themes = ConfigurationManager.GetSection("SchedulerPage/Themes") as NameValueCollection;
String SchedulerTheme = themes["UB"];
</code></pre>
<p><b>appSettings solution</b></p>
<pre><code><appSettings>
<add key="PITheme" value="PISchedulerForm"/>
<add key="UBTheme" value="UBSchedulerForm"/>
</appSettings>
</code></pre>
<p>To access values in appSettings, I am using this code</p>
<pre><code> String SchedulerTheme = ConfigurationManager.AppSettings["UBSchedulerForm"].ToString();
</code></pre>
|
[
{
"answer_id": 204745,
"author": "Nick Allen",
"author_id": 12918,
"author_profile": "https://Stackoverflow.com/users/12918",
"pm_score": 5,
"selected": true,
"text": "<appMonitoring enabled=\"true\" smtpServer=\"xxx\">\n <alertRecipients>\n <add name=\"me\" email=\"me@me.com\"/>\n </alertRecipient>\n</appMonitoring>\n public class MonitoringConfig : ConfigurationSection\n{\n [ConfigurationProperty(\"smtp\", IsRequired = true)]\n public string Smtp\n {\n get { return this[\"smtp\"] as string; }\n }\n public static MonitoringConfig GetConfig()\n {\n return ConfigurationManager.GetSection(\"appMonitoring\") as MonitoringConfig\n }\n}\n string smtp = MonitoringConfig.GetConfig().Smtp;\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3018/"
] |
204,696
|
<p>My question is in regards to MySQL, but I also wonder how this affects other databases. I have several fields that are <code>varchar(255)</code> but my coworker insists if they were <code>varchar(30)</code> -- or any smaller size -- then queries would run faster. I'm not so sure, but if it's so I'll admit to it.</p>
|
[
{
"answer_id": 204767,
"author": "macbirdie",
"author_id": 5049,
"author_profile": "https://Stackoverflow.com/users/5049",
"pm_score": 0,
"selected": false,
"text": "tinytext varchar"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28240/"
] |
204,711
|
<p>Of the two methods below, which do you prefer to read?<br>
Is there another (better?) way to check if a flag is set?</p>
<pre><code> bool CheckFlag(FooFlag fooFlag)
{
return fooFlag == (this.Foo & fooFlag);
}
</code></pre>
<p>And</p>
<pre><code> bool CheckFlag(FooFlag fooFlag)
{
return (this.Foo & fooFlag) != 0;
}
</code></pre>
<p><hr/>
Please vote up the method you prefer.</p>
|
[
{
"answer_id": 204726,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 3,
"selected": false,
"text": "bool CheckFlag(FooFlag fooFlag)\n{\n return fooFlag == (this.Foo & fooFlag);\n}\n"
},
{
"answer_id": 204727,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 2,
"selected": false,
"text": "bool CheckFlag(FooFlag fooFlag)\n{\n return (this.Foo & fooFlag) != 0;\n}\n"
},
{
"answer_id": 204728,
"author": "Phil Reif",
"author_id": 20244,
"author_profile": "https://Stackoverflow.com/users/20244",
"pm_score": -1,
"selected": false,
"text": "bool CheckFlag(FooFlag fooFlag)\n{\n return this.Foo & fooFlag == 1;\n}\n"
},
{
"answer_id": 204772,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": true,
"text": "fooFlag == (this.Foo & fooFlag) // result is true iff all bits in fooFlag are set\n\n\n(this.Foo & fooFlag) != 0 // result is true if any bits in fooFlag are set\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14484/"
] |
204,733
|
<p>I am constructing a search page with a textbox and a button for now, and probably a dropdown to filter results later on. I have my button's PostBackUrl set to my search page (~/search.aspx). Is there an easy way to pass the value in the text box to the search page?</p>
|
[
{
"answer_id": 204816,
"author": "Andy May",
"author_id": 12367,
"author_profile": "https://Stackoverflow.com/users/12367",
"pm_score": 0,
"selected": false,
"text": "$(document).ready(function(){\n // Event Handlers to allow searching after pressing Enter key\n $(\"#myTextBoxID\").bind(\"keypress\", function(e){\n switch (e.keyCode){\n case (13):\n // Execute code here ...\n break;\n default:\n break;\n }\n });\n});\n"
},
{
"answer_id": 204917,
"author": "Adam Nofsinger",
"author_id": 18524,
"author_profile": "https://Stackoverflow.com/users/18524",
"pm_score": 4,
"selected": true,
"text": "if (Page.PreviousPage != null)\n{\n TextBox SourceTextBox = \n (TextBox)Page.PreviousPage.FindControl(\"TextBox1\");\n if (SourceTextBox != null)\n {\n Label1.Text = SourceTextBox.Text;\n }\n}\n <%@ PreviousPageType VirtualPath=\"~/SourcePage.aspx\" %> \n"
},
{
"answer_id": 204960,
"author": "Anders",
"author_id": 25515,
"author_profile": "https://Stackoverflow.com/users/25515",
"pm_score": 0,
"selected": false,
"text": "Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n If PreviousPage IsNot Nothing Then\n Dim txtBoxSrc As New TextBox\n txtBoxSrc = CType(Master.FindControl(\"searchbox\"), TextBox)\n If txtBoxSrc IsNot Nothing Then\n MsgBox(txtBoxSrc.Text)\n End If\n End If\nEnd Sub\n\n<div class=\"gsSearch\">\n <asp:TextBox ID=\"searchbox\" runat=\"server\"></asp:TextBox>\n <asp:Button ID=\"searchbutton\" runat=\"server\" Text=\"search\" \n UseSubmitBehavior=\"true\" PostBackUrl=\"~/search.aspx\" />\n</div>\n"
},
{
"answer_id": 205052,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 0,
"selected": false,
"text": "Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n If PreviousPage IsNot Nothing Then\n Dim txtBoxSrc As New Control\n txtBoxSrc = PreviousPage.FindControl(\"searchbox\")\n If txtBoxSrc IsNot Nothing Then\n MsgBox((CType(txtBoxSrc, TextBox)).Text)\n End If\n End If\nEnd Sub\n\n<div class=\"gsSearch\">\n <asp:TextBox ID=\"searchbox\" runat=\"server\"></asp:TextBox>\n <asp:Button ID=\"searchbutton\" runat=\"server\" Text=\"search\" \n UseSubmitBehavior=\"true\" PostBackUrl=\"~/search.aspx\" />\n</div>\n"
},
{
"answer_id": 10466356,
"author": "bgmCoder",
"author_id": 1038866,
"author_profile": "https://Stackoverflow.com/users/1038866",
"pm_score": 0,
"selected": false,
"text": "dim textval = SourceTextBox.text\ndim myparam = \"George\"\n\nsearchbutton.PostBackUrl = \"~/search.aspx?myparam=\" & myparam\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
204,737
|
<p>I have a lot of castle xml configs where properties like connectionstring are also held under .Net configuration sections.</p>
<p>I'd like to be able to read out the properties using the container but can't see a mechanism to do it.</p>
<p>ie </p>
<pre><code><castle>
<configuration>
<properties>
<connectionString>Data Source=MyServer;Initial Catalog=YadaYada;User ID=me;Password=IAmGod</connectionString>
</properties>
<components>
</code></pre>
<p>...</p>
<p>Obviously the properties are there as there are component dependencies on them. I can resolve the components but not the properties.</p>
<p>Sure I could new up a component just to read out the property castle injected it, or I could wrap all the properties in a component specialised simply to hold name/val pairs. But I would have thought there be a simple container.resolve("property.connectionstring") notation.</p>
<p>*Edit Not very good with markdown, above was meant to be a xml section.</p>
|
[
{
"answer_id": 204835,
"author": "Ronnie",
"author_id": 193,
"author_profile": "https://Stackoverflow.com/users/193",
"pm_score": 1,
"selected": false,
"text": "<component type=\"SessionManager\">\n <parameters>\n <connectionString>#{connectionString}</connectionString>\n </parameters>\n</component>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
204,739
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/203616/why-does-c-sharp-not-provide-the-c-style-friend-keyword">Why does C# not provide the C++ style ‘friend’ keyword?</a> </p>
</blockquote>
<p>I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes. </p>
<p>In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example?</p>
|
[
{
"answer_id": 204744,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 9,
"selected": true,
"text": "AssemblyInfo.cs [assembly: InternalsVisibleTo(\"OtherAssembly\")]\n"
},
{
"answer_id": 204782,
"author": "RobG",
"author_id": 28232,
"author_profile": "https://Stackoverflow.com/users/28232",
"pm_score": 4,
"selected": false,
"text": "public class Class1\n{\n private int CallMe()\n {\n return 1;\n }\n}\n Class1 c = new Class1();\nType class1Type = c.GetType();\nMethodInfo callMeMethod = class1Type.GetMethod(\"CallMe\", BindingFlags.Instance | BindingFlags.NonPublic);\n\nint result = (int)callMeMethod.Invoke(c, null);\n\nConsole.WriteLine(result);\n"
},
{
"answer_id": 10507130,
"author": "sjp",
"author_id": 1383194,
"author_profile": "https://Stackoverflow.com/users/1383194",
"pm_score": 7,
"selected": false,
"text": "class Outer\n{\n class Inner\n {\n // This class can access Outer's private members\n }\n}\n Outer.cs\npartial class Outer\n{\n}\n\n\nInner.cs\npartial class Outer\n{\n class Inner\n {\n // This class can access Outer's private members\n }\n}\n"
},
{
"answer_id": 12350279,
"author": "smartmobili",
"author_id": 1659923,
"author_profile": "https://Stackoverflow.com/users/1659923",
"pm_score": 3,
"selected": false,
"text": "// Expose the internal members to the types in the My.Tester assembly\n[assembly: InternalsVisibleTo(\"My.Tester, PublicKey=\" +\n\"012700000480000094000000060200000024000052534131000400000100010091ab9\" +\n\"ba23e07d4fb7404041ec4d81193cfa9d661e0e24bd2c03182e0e7fc75b265a092a3f8\" +\n\"52c672895e55b95611684ea090e787497b0d11b902b1eccd9bc9ea3c9a56740ecda8e\" +\n\"961c93c3960136eefcdf106955a4eb8fff2a97f66049cd0228854b24709c0c945b499\" +\n\"413d29a2801a39d4c4c30bab653ebc8bf604f5840c88\")]\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22185/"
] |
204,742
|
<p>Right now I'm working on a web application that receives a significant amount of data from a database that has a potential to return null results. When going through the cyclomatic complexity for the application a number of functions are weighing in between 10 - 30. For the most part the majority of the functions with the high numbers have a lot of lines similar to the following:</p>
<pre><code>If Not oraData.IsDBNull(4) Then row("Field") = oraData.GetString(4)
</code></pre>
<p>Which leads me to my question, what is the best way to go about trying to bring these numbers down? Right now I'm looking at having the majority of the functions below 10. </p>
|
[
{
"answer_id": 204783,
"author": "Barry Carr",
"author_id": 51820,
"author_profile": "https://Stackoverflow.com/users/51820",
"pm_score": 2,
"selected": false,
"text": "//Object Pascal\nprocedure UpdateIfNotNull( const fldName: String; fldIndex : integer );\nbegin\n if oraData.IsDBNull( fldIndex ) then\n row( fldName ) := oraData.GetString(fldIndex);\nend;\n"
},
{
"answer_id": 204857,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 3,
"selected": true,
"text": "Imports System.Runtime.CompilerServices\n\nModule Extensions\n\n <Extension()> _\n Public Function TryGetString(ByVal row As IDataRecord, i As Integer) As String\n If row.IsDBNull(i) Then\n Return null\n End If\n Return row.GetString(i);\n End Function\n\nEnd Module\n row(\"Field\") = oraData.TryGetString(4)\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1185/"
] |
204,746
|
<p>For a web application, I want to build a WHERE clause AND submit it to the server. There I will append it to a query. The clause will be something like</p>
<pre><code>LASTNAME LIKE 'Pep%' AND (DOB BETWEEN '19600101' AND '19601231 OR SALARY<35000)
</code></pre>
<p>Can you propose a regular expression to validate the clause before submitting it to SQL Server?</p>
<p>(Yes, of course, I would like a regex for the ORDER clause)</p>
|
[
{
"answer_id": 204750,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 4,
"selected": false,
"text": "LASTNAME LIKE 'Pep%'--\nDROP TABLE People\n--\n"
},
{
"answer_id": 204974,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 3,
"selected": false,
"text": "LASTNAME LIKE 'Pep%' AND (DOB BETWEEN '19600101' AND '19601231 OR SALARY<35000)\n LASTNAME LIKE @LastName AND (DOB BETWEEN @dobStart AND @dobEnd OR SALARY<@MaxSalary)\n"
},
{
"answer_id": 205388,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "LASTNAME LIKE 'Pep%' \n LASTNAME LIKE @LastName + '%'\n //create a place to keep parameters until we can construct the SqlCommand object\nList<SqlParameter> params = new List<SqlParameter>();\nSqlParameter p;\n\n// the StringBuilder is MUCH more efficient the concatenating strings\n// the 1=1 is a placeholder so you can always just append \" AND whatever\"\nStringBuilder sql = new StringBuilder(\"SELECT ... \\nFROM .... \\nWHERE 1=1\\n\");\n\n// Check and add a parameter for the LastName column if needed\nif (!String.IsNullOrEmpty(txtLastName.Text))\n{\n sql.AppendLine(\"AND LASTNAME LIKE @LastName + '%'\");\n p = new SqlParameter(\"@LastName\", SqlDbType.VarChar, 50); // use the actual datatype here\n p.Value = txtLastName.Text;\n params.Add(p); \n}\n\n// Check and add a parameter for another field if needed\nif (!String.IsNullOrEmpty(txtSomeOtherField.Text))\n{\n sql.AppendLine(\"AND OtherField LIKE @OtherParam + '%'\");\n p = new SqlParameter(\"@OtherParam\", SqlDbType.VarChar, 255);\n p.Value = txtSomeOtherField.Text;\n params.Add(p);\n}\n\n// ... You could also write a method to abstract the code in the if blocks ...\n\n// you haven't told us _how_ the user will specify the order, so I'm leaving that implementation detail out for now\nsql.Append(\" ORDER BY LastName, OtherField\"); \n\n// now we can finally get our SQL String and build the (SAFE!) SqlCommand object:\nSqlCommand cmd = new SqlCommand(sql.ToString(), YourSqlConnectionObjectHere);\ncmd.Parameters.AddRange(params.ToArray());\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28207/"
] |
204,759
|
<p>Is there a way to perform an HTTP GET request within a Visual Basic script? I need to get the contents of the response from a particular URL for processing.</p>
|
[
{
"answer_id": 204851,
"author": "Svante Svenson",
"author_id": 19707,
"author_profile": "https://Stackoverflow.com/users/19707",
"pm_score": 7,
"selected": true,
"text": "Dim o\nSet o = CreateObject(\"MSXML2.XMLHTTP\")\no.open \"GET\", \"http://www.example.com\", False\no.send\n' o.responseText now holds the response as a string.\n"
},
{
"answer_id": 208913,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 5,
"selected": false,
"text": "MSXML2.XMLHTTP MSXML2.XMLHTTP.3.0 responseBody responseStream IStream MSXML.ServerXMLHTTP.3.0 WinHttp.WinHttpRequest.5.1 Dim oXMLHTTP\nDim oStream\n\nSet oXMLHTTP = CreateObject(\"MSXML2.XMLHTTP.3.0\")\n\noXMLHTTP.Open \"GET\", \"http://someserver/folder/file.pdf\", False\noXMLHTTP.Send\n\nIf oXMLHTTP.Status = 200 Then\n Set oStream = CreateObject(\"ADODB.Stream\")\n oStream.Open\n oStream.Type = 1\n oStream.Write oXMLHTTP.responseBody\n oStream.SaveToFile \"c:\\somefolder\\file.pdf\"\n oStream.Close\nEnd If\n"
},
{
"answer_id": 9338465,
"author": "Jamie",
"author_id": 1217583,
"author_profile": "https://Stackoverflow.com/users/1217583",
"pm_score": 2,
"selected": false,
"text": "set ID = CreateObject(\"InternetExplorer.Application\")\nIE.visible = 0\nIE.navigate \"http://example.com/parser.php?key=\" & value & \"key2=\" & value2 \ndo while IE.Busy.... \n"
},
{
"answer_id": 37813009,
"author": "Rajkumar Joshua M",
"author_id": 6464616,
"author_profile": "https://Stackoverflow.com/users/6464616",
"pm_score": 0,
"selected": false,
"text": " strRequest = \"<soap:Envelope xmlns:soap=\"\"http://www.w3.org/2003/05/soap-envelope\"\" \" &_\n \"xmlns:tem=\"\"http://tempuri.org/\"\">\" &_\n \"<soap:Header/>\" &_\n \"<soap:Body>\" &_\n \"<tem:Authorization>\" &_\n \"<tem:strCC>\"&1234123412341234&\"</tem:strCC>\" &_\n \"<tem:strEXPMNTH>\"&11&\"</tem:strEXPMNTH>\" &_\n \"<tem:CVV2>\"&123&\"</tem:CVV2>\" &_\n \"<tem:strYR>\"&23&\"</tem:strYR>\" &_\n \"<tem:dblAmount>\"&1235&\"</tem:dblAmount>\" &_\n \"</tem:Authorization>\" &_\n \"</soap:Body>\" &_\n \"</soap:Envelope>\"\n\n EndPointLink = \"http://www.trainingrite.net/trainingrite_epaysystem\" &_\n \"/trainingrite_epaysystem/tr_epaysys.asmx\"\n\n\n\ndim http\nset http=createObject(\"Microsoft.XMLHTTP\")\nhttp.open \"POST\",EndPointLink,false\nhttp.setRequestHeader \"Content-Type\",\"text/xml\"\n\nmsgbox \"REQUEST : \" & strRequest\nhttp.send strRequest\n\nIf http.Status = 200 Then\n'msgbox \"RESPONSE : \" & http.responseXML.xml\nmsgbox \"RESPONSE : \" & http.responseText\nresponseText=http.responseText\nelse\nmsgbox \"ERRCODE : \" & http.status\nEnd If\n\nCall ParseTag(responseText,\"AuthorizationResult\")\n\nCall CreateXMLEvidence(responseText,strRequest)\n\n'Function to fetch the required message from a TAG\nFunction ParseTag(ResponseXML,SearchTag)\n\n ResponseMessage=split(split(split(ResponseXML,SearchTag)(1),\"</\")(0),\">\")(1)\n Msgbox ResponseMessage\n\nEnd Function\n\n'Function to create XML test evidence files\nFunction CreateXMLEvidence(ResponseXML,strRequest)\n\n Set fso=createobject(\"Scripting.FileSystemObject\")\n Set qfile=fso.CreateTextFile(\"C:\\Users\\RajkumarJoshua\\Desktop\\DCIM\\SampleResponse.xml\",2)\n Set qfile1=fso.CreateTextFile(\"C:\\Users\\RajkumarJoshua\\Desktop\\DCIM\\SampleReuest.xml\",2)\n\n qfile.write ResponseXML\n qfile.close\n\n qfile1.write strRequest\n qfile1.close\n\nEnd Function\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/271/"
] |
204,765
|
<p>For debugging purposes, I need to recursively search a directory for all files which start with a UTF-8 byte order mark (BOM). My current solution is a simple shell script:</p>
<pre><code>find -type f |
while read file
do
if [ "`head -c 3 -- "$file"`" == $'\xef\xbb\xbf' ]
then
echo "found BOM in: $file"
fi
done</code></pre>
<p>Or, if you prefer short, unreadable one-liners:</p>
<pre><code>find -type f|while read file;do [ "`head -c3 -- "$file"`" == $'\xef\xbb\xbf' ] && echo "found BOM in: $file";done</code></pre>
<p>It doesn't work with filenames that contain a line break,
but such files are not to be expected anyway.</p>
<p>Is there any shorter or more elegant solution?</p>
<p>Are there any interesting text editors or macros for text editors?</p>
|
[
{
"answer_id": 211855,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 3,
"selected": false,
"text": "fgrep -rl `echo -ne '\\xef\\xbb\\xbf'` .\n"
},
{
"answer_id": 212214,
"author": "Jonathan Wright",
"author_id": 28840,
"author_profile": "https://Stackoverflow.com/users/28840",
"pm_score": 2,
"selected": false,
"text": "find -type f -print0 | xargs -0 grep -l `printf '^\\xef\\xbb\\xbf'` | sed 's/^/found BOM in: /'\n find -print0 xargs -0 grep -l ^\\xeff\\xbb\\xbf"
},
{
"answer_id": 212312,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 3,
"selected": false,
"text": "grep -orHbm1 \"^`echo -ne '\\xef\\xbb\\xbf'`\" . | sed '/:0:/!d;s/:0:.*//'\n"
},
{
"answer_id": 2858757,
"author": "Denis",
"author_id": 344192,
"author_profile": "https://Stackoverflow.com/users/344192",
"pm_score": 9,
"selected": true,
"text": "find . -type f -exec sed '1s/^\\xEF\\xBB\\xBF//' -i {} \\;\n grep -rl $'\\xEF\\xBB\\xBF' .\n"
},
{
"answer_id": 2884935,
"author": "Aron Griffis",
"author_id": 347386,
"author_profile": "https://Stackoverflow.com/users/347386",
"pm_score": 4,
"selected": false,
"text": "find . -type f -print0 | xargs -0r awk '\n /^\\xEF\\xBB\\xBF/ {print FILENAME}\n {nextfile}'\n"
},
{
"answer_id": 7992682,
"author": "julien",
"author_id": 1027342,
"author_profile": "https://Stackoverflow.com/users/1027342",
"pm_score": 2,
"selected": false,
"text": "BOM"
},
{
"answer_id": 8584233,
"author": "mario",
"author_id": 345031,
"author_profile": "https://Stackoverflow.com/users/345031",
"pm_score": 2,
"selected": false,
"text": "phptags vi phptags --warn ./\n ./invalid.php: TRAILING whitespace (\"?>\\n\")\n./invalid.php: UTF-8 BOM alone (\"\\xEF\\xBB\\xBF\")\n --whitespace"
},
{
"answer_id": 9990179,
"author": "LLub",
"author_id": 945548,
"author_profile": "https://Stackoverflow.com/users/945548",
"pm_score": 2,
"selected": false,
"text": "find . -iname *.js -type f -exec sed 's/^\\xEF\\xBB\\xBF//' -i.bak {} \\; -exec rm {}.bak \\;\n"
},
{
"answer_id": 17624128,
"author": "theory",
"author_id": 79202,
"author_profile": "https://Stackoverflow.com/users/79202",
"pm_score": 3,
"selected": false,
"text": "grep grep -rl $'\\xEF\\xBB\\xBF' . | xargs perl -i -pe 's{\\xEF\\xBB\\xBF}{}'\n"
},
{
"answer_id": 26406896,
"author": "Mike Dotterer",
"author_id": 188452,
"author_profile": "https://Stackoverflow.com/users/188452",
"pm_score": 1,
"selected": false,
"text": "file *.php | grep UTF\n file */*.php | grep UTF\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19163/"
] |
204,779
|
<p>I'm VERY new to WPF, and still trying to wrap my head around binding in XAML.</p>
<p>I'd like to populate a combobox with the values of a string collection in my.settings. I can do it in code like this:</p>
<p>Me.ComboBox1.ItemsSource = My.Settings.MyCollectionOfStrings</p>
<p>...and it works.</p>
<p>How can I do this in my XAML? is it possible?</p>
<p>Thanks</p>
|
[
{
"answer_id": 204855,
"author": "Enrico Campidoglio",
"author_id": 26396,
"author_profile": "https://Stackoverflow.com/users/26396",
"pm_score": 5,
"selected": true,
"text": "<Window x:Class=\"WpfApplication1.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:p=\"clr-namespace:WpfApplication1.Properties\"\n Title=\"Window1\">\n <StackPanel>\n <ComboBox\n ItemsSource=\"{Binding Source={x:Static p:Settings.Default}, Path=MyCollectionOfStrings}\" />\n </StackPanel>\n</Window>\n"
},
{
"answer_id": 204856,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "IsExpanded=\"{Binding Source={StaticResource Settings}, Mode=TwoWay, Path=Default.ASettingValue}\"\n <!-- other namespaces removed for clarity -->\n<Application xmlns:settings=\"clr-namespace:DefaultNamespace.Properties\" >\n <Application.Resources>\n <ResourceDictionary>\n <settings:Settings x:Key=\"Settings\" />\n <!--stuff removed-->\n </ResourceDictionary>\n </Application.Resources>\n</Application>\n DefaultNamespace.Properties.Settings.Default.ASettingValue\n"
},
{
"answer_id": 205366,
"author": "Ben Brandt",
"author_id": 641985,
"author_profile": "https://Stackoverflow.com/users/641985",
"pm_score": 1,
"selected": false,
"text": "<Window x:Class=\"Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:p=\"clr-namespace:WpfApplication1\"\n Title=\"Window1\" Height=\"90\" Width=\"462\" Name=\"Window1\">\n <Grid>\n <ComboBox ItemsSource=\"{Binding Source={x:Static p:Settings.Default}, Path=MyCollectionOfStrings}\" />\n </Grid>\n</Window>\n"
},
{
"answer_id": 807799,
"author": "Thomas Levesque",
"author_id": 98713,
"author_profile": "https://Stackoverflow.com/users/98713",
"pm_score": 2,
"selected": false,
"text": "<Window x:Class=\"Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:my=\"clr-namespace:WpfApplication1\"\n Title=\"Window1\" Height=\"90\" Width=\"462\" Name=\"Window1\">\n <Grid>\n <ComboBox ItemsSource=\"{my:SettingBinding MyCollectionOfStrings}\" />\n </Grid>\n</Window>\n"
},
{
"answer_id": 1689281,
"author": "Echilon",
"author_id": 30512,
"author_profile": "https://Stackoverflow.com/users/30512",
"pm_score": 0,
"selected": false,
"text": "<ComboBox ItemsSource=\"{Binding Default.ImportHistory,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay,Converter={StaticResource StringToListConverter},ConverterParameter=|}\" IsEditable=\"True\">\n/// <summary>\n/// Converts a delimited set of strings to a list and back again. The parameter defines the delimiter\n/// </summary>\npublic class StringToListConverter : IValueConverter {\n /// <summary>\n /// Takes a string, returns a list seperated by {parameter}\n /// </summary>\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {\n string serializedList = (value ?? string.Empty).ToString(),\n splitter = (parameter ?? string.Empty).ToString();\n if(serializedList.Trim().Length == 0) {\n return value;\n }\n return serializedList.Split(new[] { splitter }, StringSplitOptions.RemoveEmptyEntries);\n }\n /// <summary>\n /// Takes a list, returns a string seperated by {parameter}\n /// </summary>\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {\n var items = value as IEnumerable;\n var splitter = (parameter ?? string.Empty).ToString();\n if(value == null || items == null) {\n return value;\n }\n StringBuilder buffer = new StringBuilder();\n foreach(var itm in items) {\n buffer.Append(itm.ToString()).Append(splitter);\n }\n return buffer.ToString(0, splitter.Length > 0 ? buffer.Length - splitter.Length : buffer.Length);\n }\n}\n var items = Settings.Default.ImportHistory.Split('|');\nif(!items.Contains(dlgOpen.FileNames[0])) {\n Settings.Default.ImportHistory += (\"|\" + dlgOpen.FileNames[0]);\n}\ncboFilename.SelectedValue = dlgOpen.FileNames[0];\nSettings.Default.Save();\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641985/"
] |
204,784
|
<p>Given two absolute paths, e.g.</p>
<pre><code>/var/data/stuff/xyz.dat
/var/data
</code></pre>
<p>How can one create a relative path that uses the second path as its base? In the example above, the result should be: <code>./stuff/xyz.dat</code></p>
|
[
{
"answer_id": 204847,
"author": "Keeg",
"author_id": 21059,
"author_profile": "https://Stackoverflow.com/users/21059",
"pm_score": 3,
"selected": false,
"text": "String s1 = \"/var/data/stuff/xyz.dat\";\nString s2 = \"/var/data\";\nString s3 = s1.substring(s2.length());\n String s3 = \".\".concat(s1.substring(s2.length()));\n"
},
{
"answer_id": 205495,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": -1,
"selected": false,
"text": "return \".\" + whicheverPathIsLonger.substring(commonPath.length);"
},
{
"answer_id": 205592,
"author": "Steve Armstrong",
"author_id": 28038,
"author_profile": "https://Stackoverflow.com/users/28038",
"pm_score": 2,
"selected": false,
"text": "public static String getRelativePath(String fromPath, String toPath) {\n\n // This weirdness is because a separator of '/' messes with String.split()\n String regexCharacter = File.separator;\n if (File.separatorChar == '\\\\') {\n regexCharacter = \"\\\\\\\\\";\n }\n\n String[] fromSplit = fromPath.split(regexCharacter);\n String[] toSplit = toPath.split(regexCharacter);\n\n // Find the common path\n int common = 0;\n while (fromSplit[common].equals(toSplit[common])) {\n common++;\n }\n\n StringBuffer result = new StringBuffer(\".\");\n\n // Work your way up the FROM path to common ground\n for (int i = common; i < fromSplit.length; i++) {\n result.append(File.separatorChar).append(\"..\");\n }\n\n // Work your way down the TO path\n for (int i = common; i < toSplit.length; i++) {\n result.append(File.separatorChar).append(toSplit[i]);\n }\n\n return result.toString();\n}\n"
},
{
"answer_id": 205621,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 2,
"selected": false,
"text": "public class RelativePathFinder {\n\n public static String getRelativePath(String targetPath, String basePath, \n String pathSeparator) {\n\n // find common path\n String[] target = targetPath.split(pathSeparator);\n String[] base = basePath.split(pathSeparator);\n\n String common = \"\";\n int commonIndex = 0;\n for (int i = 0; i < target.length && i < base.length; i++) {\n\n if (target[i].equals(base[i])) {\n common += target[i] + pathSeparator;\n commonIndex++;\n }\n }\n\n\n String relative = \"\";\n // is the target a child directory of the base directory?\n // i.e., target = /a/b/c/d, base = /a/b/\n if (commonIndex == base.length) {\n relative = \".\" + pathSeparator + targetPath.substring(common.length());\n }\n else {\n // determine how many directories we have to backtrack\n for (int i = 1; i <= commonIndex; i++) {\n relative += \"..\" + pathSeparator;\n }\n relative += targetPath.substring(common.length());\n }\n\n return relative;\n }\n\n public static String getRelativePath(String targetPath, String basePath) {\n return getRelativePath(targetPath, basePath, File.pathSeparator);\n }\n}\n public class RelativePathFinderTest extends TestCase {\n\n public void testGetRelativePath() {\n assertEquals(\"./stuff/xyz.dat\", RelativePathFinder.getRelativePath(\n \"/var/data/stuff/xyz.dat\", \"/var/data/\", \"/\"));\n assertEquals(\"../../b/c\", RelativePathFinder.getRelativePath(\"/a/b/c\",\n \"/a/x/y/\", \"/\"));\n }\n\n}\n"
},
{
"answer_id": 205655,
"author": "Adam Crume",
"author_id": 25498,
"author_profile": "https://Stackoverflow.com/users/25498",
"pm_score": 9,
"selected": true,
"text": "String path = \"/var/data/stuff/xyz.dat\";\nString base = \"/var/data\";\nString relative = new File(base).toURI().relativize(new File(path).toURI()).getPath();\n// relative == \"stuff/xyz.dat\"\n java.nio.file.Path#relativize"
},
{
"answer_id": 705963,
"author": "Christian K.",
"author_id": 61588,
"author_profile": "https://Stackoverflow.com/users/61588",
"pm_score": 5,
"selected": false,
"text": "relativize() URI java.net.URI.relativize"
},
{
"answer_id": 1269907,
"author": "Gili",
"author_id": 14731,
"author_profile": "https://Stackoverflow.com/users/14731",
"pm_score": 3,
"selected": false,
"text": "/**\n * Returns the path of one File relative to another.\n *\n * @param target the target directory\n * @param base the base directory\n * @return target's path relative to the base directory\n * @throws IOException if an error occurs while resolving the files' canonical names\n */\n public static File getRelativeFile(File target, File base) throws IOException\n {\n String[] baseComponents = base.getCanonicalPath().split(Pattern.quote(File.separator));\n String[] targetComponents = target.getCanonicalPath().split(Pattern.quote(File.separator));\n\n // skip common components\n int index = 0;\n for (; index < targetComponents.length && index < baseComponents.length; ++index)\n {\n if (!targetComponents[index].equals(baseComponents[index]))\n break;\n }\n\n StringBuilder result = new StringBuilder();\n if (index != baseComponents.length)\n {\n // backtrack to base directory\n for (int i = index; i < baseComponents.length; ++i)\n result.append(\"..\" + File.separator);\n }\n for (; index < targetComponents.length; ++index)\n result.append(targetComponents[index] + File.separator);\n if (!target.getPath().endsWith(\"/\") && !target.getPath().endsWith(\"\\\\\"))\n {\n // remove final path separator\n result.delete(result.length() - File.separator.length(), result.length());\n }\n return new File(result.toString());\n }\n"
},
{
"answer_id": 1288584,
"author": "Matuszek",
"author_id": 155876,
"author_profile": "https://Stackoverflow.com/users/155876",
"pm_score": 2,
"selected": false,
"text": "\"\" split /a/b/c/ /a/x/y/ /m/n/o/a/b/c/ /m/n/o/a/x/y/ else break /a/b/c/d/ /x/y/c/z c C:\\foo\\bar D:\\baz\\quux public static String getRelativePath(String targetPath, String basePath, \n String pathSeparator) {\n\n // We need the -1 argument to split to make sure we get a trailing \n // \"\" token if the base ends in the path separator and is therefore\n // a directory. We require directory paths to end in the path\n // separator -- otherwise they are indistinguishable from files.\n String[] base = basePath.split(Pattern.quote(pathSeparator), -1);\n String[] target = targetPath.split(Pattern.quote(pathSeparator), 0);\n\n // First get all the common elements. Store them as a string,\n // and also count how many of them there are. \n String common = \"\";\n int commonIndex = 0;\n for (int i = 0; i < target.length && i < base.length; i++) {\n if (target[i].equals(base[i])) {\n common += target[i] + pathSeparator;\n commonIndex++;\n }\n else break;\n }\n\n if (commonIndex == 0)\n {\n // Whoops -- not even a single common path element. This most\n // likely indicates differing drive letters, like C: and D:. \n // These paths cannot be relativized. Return the target path.\n return targetPath;\n // This should never happen when all absolute paths\n // begin with / as in *nix. \n }\n\n String relative = \"\";\n if (base.length == commonIndex) {\n // Comment this out if you prefer that a relative path not start with ./\n //relative = \".\" + pathSeparator;\n }\n else {\n int numDirsUp = base.length - commonIndex - 1;\n // The number of directories we have to backtrack is the length of \n // the base path MINUS the number of common path elements, minus\n // one because the last element in the path isn't a directory.\n for (int i = 1; i <= (numDirsUp); i++) {\n relative += \"..\" + pathSeparator;\n }\n }\n relative += targetPath.substring(common.length());\n\n return relative;\n}\n public void testGetRelativePathsUnixy() \n{ \n assertEquals(\"stuff/xyz.dat\", FileUtils.getRelativePath(\n \"/var/data/stuff/xyz.dat\", \"/var/data/\", \"/\"));\n assertEquals(\"../../b/c\", FileUtils.getRelativePath(\n \"/a/b/c\", \"/a/x/y/\", \"/\"));\n assertEquals(\"../../b/c\", FileUtils.getRelativePath(\n \"/m/n/o/a/b/c\", \"/m/n/o/a/x/y/\", \"/\"));\n}\n\npublic void testGetRelativePathFileToFile() \n{\n String target = \"C:\\\\Windows\\\\Boot\\\\Fonts\\\\chs_boot.ttf\";\n String base = \"C:\\\\Windows\\\\Speech\\\\Common\\\\sapisvr.exe\";\n\n String relPath = FileUtils.getRelativePath(target, base, \"\\\\\");\n assertEquals(\"..\\\\..\\\\..\\\\Boot\\\\Fonts\\\\chs_boot.ttf\", relPath);\n}\n\npublic void testGetRelativePathDirectoryToFile() \n{\n String target = \"C:\\\\Windows\\\\Boot\\\\Fonts\\\\chs_boot.ttf\";\n String base = \"C:\\\\Windows\\\\Speech\\\\Common\";\n\n String relPath = FileUtils.getRelativePath(target, base, \"\\\\\");\n assertEquals(\"..\\\\..\\\\Boot\\\\Fonts\\\\chs_boot.ttf\", relPath);\n}\n\npublic void testGetRelativePathDifferentDriveLetters() \n{\n String target = \"D:\\\\sources\\\\recovery\\\\RecEnv.exe\";\n String base = \"C:\\\\Java\\\\workspace\\\\AcceptanceTests\\\\Standard test data\\\\geo\\\\\";\n\n // Should just return the target path because of the incompatible roots.\n String relPath = FileUtils.getRelativePath(target, base, \"\\\\\");\n assertEquals(target, relPath);\n}\n"
},
{
"answer_id": 1290311,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 4,
"selected": false,
"text": "public static URI resolve(URI baseURI,\n String reference)\n"
},
{
"answer_id": 1915729,
"author": "Rachel",
"author_id": 233101,
"author_profile": "https://Stackoverflow.com/users/233101",
"pm_score": 2,
"selected": false,
"text": " public static String getRelativePath(String targetPath, String basePath, \n String pathSeparator) {\n\n boolean isDir = false;\n {\n File f = new File(targetPath);\n isDir = f.isDirectory();\n }\n // We need the -1 argument to split to make sure we get a trailing \n // \"\" token if the base ends in the path separator and is therefore\n // a directory. We require directory paths to end in the path\n // separator -- otherwise they are indistinguishable from files.\n String[] base = basePath.split(Pattern.quote(pathSeparator), -1);\n String[] target = targetPath.split(Pattern.quote(pathSeparator), 0);\n\n // First get all the common elements. Store them as a string,\n // and also count how many of them there are. \n String common = \"\";\n int commonIndex = 0;\n for (int i = 0; i < target.length && i < base.length; i++) {\n if (target[i].equals(base[i])) {\n common += target[i] + pathSeparator;\n commonIndex++;\n }\n else break;\n }\n\n if (commonIndex == 0)\n {\n // Whoops -- not even a single common path element. This most\n // likely indicates differing drive letters, like C: and D:. \n // These paths cannot be relativized. Return the target path.\n return targetPath;\n // This should never happen when all absolute paths\n // begin with / as in *nix. \n }\n\n String relative = \"\";\n if (base.length == commonIndex) {\n // Comment this out if you prefer that a relative path not start with ./\n relative = \".\" + pathSeparator;\n }\n else {\n int numDirsUp = base.length - commonIndex - (isDir?0:1); /* only subtract 1 if it is a file. */\n // The number of directories we have to backtrack is the length of \n // the base path MINUS the number of common path elements, minus\n // one because the last element in the path isn't a directory.\n for (int i = 1; i <= (numDirsUp); i++) {\n relative += \"..\" + pathSeparator;\n }\n }\n //if we are comparing directories then we \n if (targetPath.length() > common.length()) {\n //it's OK, it isn't a directory\n relative += targetPath.substring(common.length());\n }\n\n return relative;\n}\n"
},
{
"answer_id": 3054692,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 6,
"selected": false,
"text": "FilenameUtils StringBuffer StringBuilder import java.io.File;\nimport java.util.regex.Pattern;\n\nimport org.apache.commons.io.FilenameUtils;\n\npublic class ResourceUtils {\n\n /**\n * Get the relative path from one file to another, specifying the directory separator. \n * If one of the provided resources does not exist, it is assumed to be a file unless it ends with '/' or\n * '\\'.\n * \n * @param targetPath targetPath is calculated to this file\n * @param basePath basePath is calculated from this file\n * @param pathSeparator directory separator. The platform default is not assumed so that we can test Unix behaviour when running on Windows (for example)\n * @return\n */\n public static String getRelativePath(String targetPath, String basePath, String pathSeparator) {\n\n // Normalize the paths\n String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);\n String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);\n\n // Undo the changes to the separators made by normalization\n if (pathSeparator.equals(\"/\")) {\n normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);\n normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);\n\n } else if (pathSeparator.equals(\"\\\\\")) {\n normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);\n normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);\n\n } else {\n throw new IllegalArgumentException(\"Unrecognised dir separator '\" + pathSeparator + \"'\");\n }\n\n String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));\n String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));\n\n // First get all the common elements. Store them as a string,\n // and also count how many of them there are.\n StringBuffer common = new StringBuffer();\n\n int commonIndex = 0;\n while (commonIndex < target.length && commonIndex < base.length\n && target[commonIndex].equals(base[commonIndex])) {\n common.append(target[commonIndex] + pathSeparator);\n commonIndex++;\n }\n\n if (commonIndex == 0) {\n // No single common path element. This most\n // likely indicates differing drive letters, like C: and D:.\n // These paths cannot be relativized.\n throw new PathResolutionException(\"No common path element found for '\" + normalizedTargetPath + \"' and '\" + normalizedBasePath\n + \"'\");\n } \n\n // The number of directories we have to backtrack depends on whether the base is a file or a dir\n // For example, the relative path from\n //\n // /foo/bar/baz/gg/ff to /foo/bar/baz\n // \n // \"..\" if ff is a file\n // \"../..\" if ff is a directory\n //\n // The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because\n // the resource referred to by this path may not actually exist, but it's the best I can do\n boolean baseIsFile = true;\n\n File baseResource = new File(normalizedBasePath);\n\n if (baseResource.exists()) {\n baseIsFile = baseResource.isFile();\n\n } else if (basePath.endsWith(pathSeparator)) {\n baseIsFile = false;\n }\n\n StringBuffer relative = new StringBuffer();\n\n if (base.length != commonIndex) {\n int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;\n\n for (int i = 0; i < numDirsUp; i++) {\n relative.append(\"..\" + pathSeparator);\n }\n }\n relative.append(normalizedTargetPath.substring(common.length()));\n return relative.toString();\n }\n\n\n static class PathResolutionException extends RuntimeException {\n PathResolutionException(String msg) {\n super(msg);\n }\n } \n}\n public void testGetRelativePathsUnix() {\n assertEquals(\"stuff/xyz.dat\", ResourceUtils.getRelativePath(\"/var/data/stuff/xyz.dat\", \"/var/data/\", \"/\"));\n assertEquals(\"../../b/c\", ResourceUtils.getRelativePath(\"/a/b/c\", \"/a/x/y/\", \"/\"));\n assertEquals(\"../../b/c\", ResourceUtils.getRelativePath(\"/m/n/o/a/b/c\", \"/m/n/o/a/x/y/\", \"/\"));\n}\n\npublic void testGetRelativePathFileToFile() {\n String target = \"C:\\\\Windows\\\\Boot\\\\Fonts\\\\chs_boot.ttf\";\n String base = \"C:\\\\Windows\\\\Speech\\\\Common\\\\sapisvr.exe\";\n\n String relPath = ResourceUtils.getRelativePath(target, base, \"\\\\\");\n assertEquals(\"..\\\\..\\\\Boot\\\\Fonts\\\\chs_boot.ttf\", relPath);\n}\n\npublic void testGetRelativePathDirectoryToFile() {\n String target = \"C:\\\\Windows\\\\Boot\\\\Fonts\\\\chs_boot.ttf\";\n String base = \"C:\\\\Windows\\\\Speech\\\\Common\\\\\";\n\n String relPath = ResourceUtils.getRelativePath(target, base, \"\\\\\");\n assertEquals(\"..\\\\..\\\\Boot\\\\Fonts\\\\chs_boot.ttf\", relPath);\n}\n\npublic void testGetRelativePathFileToDirectory() {\n String target = \"C:\\\\Windows\\\\Boot\\\\Fonts\";\n String base = \"C:\\\\Windows\\\\Speech\\\\Common\\\\foo.txt\";\n\n String relPath = ResourceUtils.getRelativePath(target, base, \"\\\\\");\n assertEquals(\"..\\\\..\\\\Boot\\\\Fonts\", relPath);\n}\n\npublic void testGetRelativePathDirectoryToDirectory() {\n String target = \"C:\\\\Windows\\\\Boot\\\\\";\n String base = \"C:\\\\Windows\\\\Speech\\\\Common\\\\\";\n String expected = \"..\\\\..\\\\Boot\";\n\n String relPath = ResourceUtils.getRelativePath(target, base, \"\\\\\");\n assertEquals(expected, relPath);\n}\n\npublic void testGetRelativePathDifferentDriveLetters() {\n String target = \"D:\\\\sources\\\\recovery\\\\RecEnv.exe\";\n String base = \"C:\\\\Java\\\\workspace\\\\AcceptanceTests\\\\Standard test data\\\\geo\\\\\";\n\n try {\n ResourceUtils.getRelativePath(target, base, \"\\\\\");\n fail();\n\n } catch (PathResolutionException ex) {\n // expected exception\n }\n}\n"
},
{
"answer_id": 8555628,
"author": "Vitalii Fedorenko",
"author_id": 288671,
"author_profile": "https://Stackoverflow.com/users/288671",
"pm_score": 8,
"selected": false,
"text": "import java.nio.file.Path;\nimport java.nio.file.Paths;\n\npublic class Test {\n\n public static void main(String[] args) {\n Path pathAbsolute = Paths.get(\"/var/data/stuff/xyz.dat\");\n Path pathBase = Paths.get(\"/var/data\");\n Path pathRelative = pathBase.relativize(pathAbsolute);\n System.out.println(pathRelative);\n }\n\n}\n stuff/xyz.dat\n"
},
{
"answer_id": 11215226,
"author": "Burn L.",
"author_id": 1483867,
"author_profile": "https://Stackoverflow.com/users/1483867",
"pm_score": 3,
"selected": false,
"text": "/**\n * Computes the path for a file relative to a given base, or fails if the only shared \n * directory is the root and the absolute form is better.\n * \n * @param base File that is the base for the result\n * @param name File to be \"relativized\"\n * @return the relative name\n * @throws IOException if files have no common sub-directories, i.e. at best share the\n * root prefix \"/\" or \"C:\\\"\n */\n\npublic static String getRelativePath(File base, File name) throws IOException {\n File parent = base.getParentFile();\n\n if (parent == null) {\n throw new IOException(\"No common directory\");\n }\n\n String bpath = base.getCanonicalPath();\n String fpath = name.getCanonicalPath();\n\n if (fpath.startsWith(bpath)) {\n return fpath.substring(bpath.length() + 1);\n } else {\n return (\"..\" + File.separator + getRelativePath(parent, name));\n }\n}\n"
},
{
"answer_id": 19332145,
"author": "NateS",
"author_id": 187883,
"author_profile": "https://Stackoverflow.com/users/187883",
"pm_score": 1,
"selected": false,
"text": "public static String getRelativePath (String baseDir, String targetPath) {\n String[] base = baseDir.replace('\\\\', '/').split(\"\\\\/\");\n targetPath = targetPath.replace('\\\\', '/');\n String[] target = targetPath.split(\"\\\\/\");\n\n // Count common elements and their length.\n int commonCount = 0, commonLength = 0, maxCount = Math.min(target.length, base.length);\n while (commonCount < maxCount) {\n String targetElement = target[commonCount];\n if (!targetElement.equals(base[commonCount])) break;\n commonCount++;\n commonLength += targetElement.length() + 1; // Directory name length plus slash.\n }\n if (commonCount == 0) return targetPath; // No common path element.\n\n int targetLength = targetPath.length();\n int dirsUp = base.length - commonCount;\n StringBuffer relative = new StringBuffer(dirsUp * 3 + targetLength - commonLength + 1);\n for (int i = 0; i < dirsUp; i++)\n relative.append(\"../\");\n if (commonLength < targetLength) relative.append(targetPath.substring(commonLength));\n return relative.toString();\n}\n"
},
{
"answer_id": 23950069,
"author": "pedromateo",
"author_id": 260981,
"author_profile": "https://Stackoverflow.com/users/260981",
"pm_score": 0,
"selected": false,
"text": "public static String GetRelativePath(String path, String base){\n\n final String SEP = \"/\";\n\n // if base is not a directory -> return empty\n if (!base.endsWith(SEP)){\n return \"\";\n }\n\n // check if path is a file -> remove last \"/\" at the end of the method\n boolean isfile = !path.endsWith(SEP);\n\n // get URIs and split them by using the separator\n String a = \"\";\n String b = \"\";\n try {\n a = new File(base).getCanonicalFile().toURI().getPath();\n b = new File(path).getCanonicalFile().toURI().getPath();\n } catch (IOException e) {\n e.printStackTrace();\n }\n String[] basePaths = a.split(SEP);\n String[] otherPaths = b.split(SEP);\n\n // check common part\n int n = 0;\n for(; n < basePaths.length && n < otherPaths.length; n ++)\n {\n if( basePaths[n].equals(otherPaths[n]) == false )\n break;\n }\n\n // compose the new path\n StringBuffer tmp = new StringBuffer(\"\");\n for(int m = n; m < basePaths.length; m ++)\n tmp.append(\"..\"+SEP);\n for(int m = n; m < otherPaths.length; m ++)\n {\n tmp.append(otherPaths[m]);\n tmp.append(SEP);\n }\n\n // get path string\n String result = tmp.toString();\n\n // remove last \"/\" if path is a file\n if (isfile && result.endsWith(SEP)){\n result = result.substring(0,result.length()-1);\n }\n\n return result;\n}\n"
},
{
"answer_id": 25743823,
"author": "Jirka Meluzin",
"author_id": 1113396,
"author_profile": "https://Stackoverflow.com/users/1113396",
"pm_score": 3,
"selected": false,
"text": "Path sourceFile = Paths.get(\"some/common/path/example/a/b/c/f1.txt\");\nPath targetFile = Paths.get(\"some/common/path/example/d/e/f2.txt\"); \nPath relativePath = sourceFile.relativize(targetFile);\nSystem.out.println(relativePath);\n ..\\..\\..\\..\\d\\e\\f2.txt\n Path sourceFile = Paths.get(new File(\"some/common/path/example/a/b/c/f1.txt\").parent());\nPath targetFile = Paths.get(\"some/common/path/example/d/e/f2.txt\"); \nPath relativePath = sourceFile.relativize(targetFile);\nSystem.out.println(relativePath);\n"
},
{
"answer_id": 31742504,
"author": "terensu",
"author_id": 4429268,
"author_profile": "https://Stackoverflow.com/users/4429268",
"pm_score": -1,
"selected": false,
"text": "private String relative(String left, String right){\n String[] lefts = left.split(\"/\");\n String[] rights = right.split(\"/\");\n int min = Math.min(lefts.length, rights.length);\n int commonIdx = -1;\n for(int i = 0; i < min; i++){\n if(commonIdx < 0 && !lefts[i].equals(rights[i])){\n commonIdx = i - 1;\n break;\n }\n }\n if(commonIdx < 0){\n return null;\n }\n StringBuilder sb = new StringBuilder(Math.max(left.length(), right.length()));\n sb.append(left).append(\"/\");\n for(int i = commonIdx + 1; i < lefts.length;i++){\n sb.append(\"../\");\n }\n for(int i = commonIdx + 1; i < rights.length;i++){\n sb.append(rights[i]).append(\"/\");\n }\n\n return sb.deleteCharAt(sb.length() -1).toString();\n}\n"
},
{
"answer_id": 36477801,
"author": "rmuller",
"author_id": 868941,
"author_profile": "https://Stackoverflow.com/users/868941",
"pm_score": 4,
"selected": false,
"text": "URI Path#relativize(Path)\n"
},
{
"answer_id": 41411138,
"author": "Mike",
"author_id": 448078,
"author_profile": "https://Stackoverflow.com/users/448078",
"pm_score": 0,
"selected": false,
"text": "import static java.util.Arrays.asList;\nimport static java.util.Collections.nCopies;\nimport static org.apache.commons.io.FilenameUtils.normalizeNoEndSeparator;\nimport static org.apache.commons.io.FilenameUtils.separatorsToUnix;\nimport static org.apache.commons.lang3.StringUtils.getCommonPrefix;\nimport static org.apache.commons.lang3.StringUtils.isBlank;\nimport static org.apache.commons.lang3.StringUtils.isNotEmpty;\nimport static org.apache.commons.lang3.StringUtils.join;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ResourceUtils {\n\n public static String getRelativePath(String targetPath, String basePath, String pathSeparator) {\n File baseFile = new File(basePath);\n if (baseFile.isFile() || !baseFile.exists() && !basePath.endsWith(\"/\") && !basePath.endsWith(\"\\\\\"))\n basePath = baseFile.getParent();\n\n String target = separatorsToUnix(normalizeNoEndSeparator(targetPath));\n String base = separatorsToUnix(normalizeNoEndSeparator(basePath));\n\n String commonPrefix = getCommonPrefix(target, base);\n if (isBlank(commonPrefix))\n return targetPath.replaceAll(\"/\", pathSeparator);\n\n target = target.replaceFirst(commonPrefix, \"\");\n base = base.replaceFirst(commonPrefix, \"\");\n\n List<String> result = new ArrayList<>();\n if (isNotEmpty(base))\n result.addAll(nCopies(base.split(\"/\").length, \"..\"));\n result.addAll(asList(target.replaceFirst(\"^/\", \"\").split(\"/\")));\n\n return join(result, pathSeparator);\n }\n}\n"
},
{
"answer_id": 43308179,
"author": "Ben Hutchison",
"author_id": 979493,
"author_profile": "https://Stackoverflow.com/users/979493",
"pm_score": 0,
"selected": false,
"text": "PathTool import org.codehaus.plexus.util.PathTool;\n\nString relativeFilePath = PathTool.getRelativeFilePath(file1, file2);\n"
},
{
"answer_id": 47494646,
"author": "alftank",
"author_id": 8603796,
"author_profile": "https://Stackoverflow.com/users/8603796",
"pm_score": 0,
"selected": false,
"text": "package org.afc.util;\n\nimport java.io.File;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class FileUtil {\n\n public static String getRelativePath(String basePath, String filePath) {\n return getRelativePath(new File(basePath), new File(filePath));\n }\n\n public static String getRelativePath(File base, File file) {\n\n List<String> bases = new LinkedList<String>();\n bases.add(0, base.getName());\n for (File parent = base.getParentFile(); parent != null; parent = parent.getParentFile()) {\n bases.add(0, parent.getName());\n }\n\n List<String> files = new LinkedList<String>();\n files.add(0, file.getName());\n for (File parent = file.getParentFile(); parent != null; parent = parent.getParentFile()) {\n files.add(0, parent.getName());\n }\n\n int overlapIndex = 0;\n while (overlapIndex < bases.size() && overlapIndex < files.size() && bases.get(overlapIndex).equals(files.get(overlapIndex))) {\n overlapIndex++;\n }\n\n StringBuilder relativePath = new StringBuilder();\n for (int i = overlapIndex; i < bases.size(); i++) {\n relativePath.append(\"..\").append(File.separatorChar);\n }\n\n for (int i = overlapIndex; i < files.size(); i++) {\n relativePath.append(files.get(i)).append(File.separatorChar);\n }\n\n relativePath.deleteCharAt(relativePath.length() - 1);\n return relativePath.toString();\n }\n\n}\n"
},
{
"answer_id": 65433687,
"author": "nullsector76",
"author_id": 12715384,
"author_profile": "https://Stackoverflow.com/users/12715384",
"pm_score": 0,
"selected": false,
"text": " public static String getRealtivePath(File root, File file) \n {\n String path = file.getPath();\n String rootPath = root.getPath();\n boolean plus1 = path.contains(File.separator);\n return path.substring(path.indexOf(rootPath) + rootPath.length() + (plus1 ? 1 : 0));\n }\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23424/"
] |
204,801
|
<p>I believe the following VB.Net code is the equivalent of the proceeding C# code; however the VB.Net test fails - the event handling Lambda is never called.</p>
<p>What is going on?</p>
<p>VB.Net version - fails:</p>
<pre class="lang-vb prettyprint-override"><code><TestFixture()> _
Public Class TestClass
<Test()> _
Public Sub EventTest()
Dim eventClass As New EventClass
Dim eventRaised As Boolean = False
AddHandler eventClass.AnEvent, Function() (eventRaised = True)
eventClass.RaiseIt()
Assert.IsTrue(eventRaised)
End Sub
End Class
Public Class EventClass
Public Event AnEvent()
Public Sub RaiseIt()
RaiseEvent AnEvent()
End Sub
End Class
</code></pre>
<p>C# version - passes:</p>
<pre><code>[TestFixture]
public class TestClass
{
[Test]
public void EventTest()
{
var eventClass = new EventClass();
var eventRaised = false;
eventClass.AnEvent += () => { eventRaised = true; };
eventClass.RaiseIt();
Assert.IsTrue(eventRaised);
}
}
public class EventClass
{
public delegate void EventHandler();
public event EventHandler AnEvent;
public void RaiseIt()
{
AnEvent();
}
}
</code></pre>
|
[
{
"answer_id": 204992,
"author": "Gareth D",
"author_id": 3580,
"author_profile": "https://Stackoverflow.com/users/3580",
"pm_score": 5,
"selected": true,
"text": "eventRaised = true <TestFixture()> _\nPublic Class Test\n <Test()> _\n Public Sub EventTest()\n Dim eventClass As New EventClass\n Dim eventRaised As Boolean = False\n AddHandler eventClass.AnEvent, Function() (SetValueToTrue(eventRaised))\n eventClass.RaiseIt()\n Assert.IsTrue(eventRaised)\n End Sub\n\n Private Function SetValueToTrue(ByRef value As Boolean) As Boolean\n value = True\n Return True\n End Function\n\nEnd Class\n\nPublic Class EventClass\n Public Event AnEvent()\n Public Sub RaiseIt()\n RaiseEvent AnEvent()\n End Sub\nEnd Class\n"
},
{
"answer_id": 14182962,
"author": "svick",
"author_id": 41071,
"author_profile": "https://Stackoverflow.com/users/41071",
"pm_score": 5,
"selected": false,
"text": "Sub Sub() eventRaised = True\n"
},
{
"answer_id": 62450550,
"author": "Ahmed_mag",
"author_id": 11241728,
"author_profile": "https://Stackoverflow.com/users/11241728",
"pm_score": 0,
"selected": false,
"text": " Dim app As System.Windows.Application = New System.Windows.Application With {\n .ShutdownMode = Windows.ShutdownMode.OnExplicitShutdown\n }\n AddHandler Closed, Sub()\n app.Shutdown()\n End Sub\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3580/"
] |
204,806
|
<p>This concept is new to me, and a colleague suggested it. Sadly, I had no idea what he was talking about. Can someone enlighten me?</p>
|
[
{
"answer_id": 204923,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 2,
"selected": false,
"text": "object _comObject;\nType _comObjectType;\n_comObjectType = Type.GetTypeFromProgID(\"MyCompany.MyApplication.MyObject\", true);\n_comObject = Activator.CreateInstance(_comObjectType);\n\nstring name = (string)_comObjectType.InvokeMember(\"GetCustomerName\", BindingFlags.InvokeMethod, null, _comObject, , new object [] { _customerId });\n MyCompany.MyApplication.MyObject obj = new MyObject();\nstring name = obj.GetCustomerName(_customerId);\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
] |
204,807
|
<p>I am looking for a way to create or implement a collapsible side panel inside of a form. Similar in the way a ToolStripContainer works I would like the same general concept except using panels that I can fill with controls. Does anyone know of a simple way to do this with the provided .Net controls or is this a total custom job. Either way I would appreciate some suggestions.</p>
|
[
{
"answer_id": 11003847,
"author": "General Grey",
"author_id": 1034475,
"author_profile": "https://Stackoverflow.com/users/1034475",
"pm_score": 1,
"selected": false,
"text": " private void button1_Click(object sender, EventArgs e)\n {\n if (button1.Text == \">\")\n {\n panel1.Width = 200;\n button1.Text = \"<\";\n }\n else\n {\n panel1.Width = button1.Width;\n button1.Text = \">\";\n }\n }\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25511/"
] |
204,813
|
<p>In the past people used to wrap HTML comment tags around blocks of JavaScript in order to prevent "older" browsers from displaying the script. Even Lynx is smart enough to ignore JavaScript, so why do some people keep doing this? Are there any valid reasons these days?</p>
<pre><code><script type="text/javascript">
<!--
//some js code
//-->
</script>
</code></pre>
<p>Edit: There is ONE situation I did encounter. Some code editors, such as Dreamweaver, get confused by quoted HTML inside a JavaScript string when in "design view" and try to display it as part of your page.</p>
|
[
{
"answer_id": 207749,
"author": "Ionuț Staicu",
"author_id": 23810,
"author_profile": "https://Stackoverflow.com/users/23810",
"pm_score": 4,
"selected": false,
"text": "<script type=\"text/javascript\" charset=\"utf-8\">\n/* <![CDATA[ */\n\n/* ]]> */\n</script>\n"
},
{
"answer_id": 251722,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 1,
"selected": false,
"text": "<script charset=\"utf-8\">\n//<![CDATA[\n\n//]]>\n</script>\n"
},
{
"answer_id": 677725,
"author": "Tim Büthe",
"author_id": 60518,
"author_profile": "https://Stackoverflow.com/users/60518",
"pm_score": 4,
"selected": false,
"text": "-->\n //-->\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12579/"
] |
204,814
|
<p>Wow, I just got back a huge project in C# from outsourced developers and while going through my code review my analysis tool revealed bunches of what it considered bad stuff. One of the more discouraging messages was:</p>
<pre><code>Exceptions.DontSwallowErrorsCatchingNonspecificExceptionsRule : 2106 defects
</code></pre>
<p>The developers assure me they had good reason for all the empty catch blocks, that sometimes the try with empty catch blocks are just there to ignore useless exceptions and keep the application from crashing. I feel this is a cop out and complete BS. Some of the examples I actually looked up were database calls where the record was being saved to the database, and in this case, if an exception was ignored, the user would get back an okay prompt, think everything was okay, and continue on with their work. In reality, their work was never saved. I think this is absolutely the most horrible kind of error. In this case, they are completely wrong in throwing that code in a try with an empty catch block. But my question is, "Is this EVER acceptable in ANY situation?" I think not, but I've been known to be wrong. </p>
|
[
{
"answer_id": 204870,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 7,
"selected": true,
"text": "try {\n // Do something that might generate an exception\n} catch (System.InvalidCastException ex) {\n // This exception is safe to ignore due to...\n} catch (System.Exception ex) {\n // Exception handling\n}\n"
},
{
"answer_id": 205022,
"author": "belugabob",
"author_id": 13397,
"author_profile": "https://Stackoverflow.com/users/13397",
"pm_score": 3,
"selected": false,
"text": "public void testSomething(){\n try{\n fooThatThrowsAnException(parameterThatCausesTheException);\n fail(\"The method didn't throw the exception that we expected it to\");\n } catch(SomeException e){\n // do nothing, as we would expect this to happen, if the code works OK.\n }\n}\n @Test(expected = SomeException.class)\npublic void testSomething(){\n fooThatThrowsAnException(parameterThatCausesTheException);\n fail(\"The method didn't throw the exception that we expected it to\");\n}\n"
},
{
"answer_id": 205883,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "Connection con = DriverManager.getConnection(url, \"***\", \"***\");\n\ntry {\n PreparedStatement pStmt = con.prepareStatement(\"your query here\");\n\n ... // query the database and get the results\n}\ncatch(ClassNotFoundException cnfe) {\n // real exception handling goes here\n}\ncatch(SQLException sqle) {\n // real exception handling goes here\n}\nfinally {\n try {\n con.close();\n }\n catch {\n // What do you do here?\n }\n}\n"
},
{
"answer_id": 205888,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 3,
"selected": false,
"text": " public FileStream OpenFile(string path)\n {\n FileStream f = null;\n try\n {\n f = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);\n }\n catch (FileNotFoundException)\n {\n }\n return f;\n }\n public FileStream OpenFile(string path)\n {\n FileStream f = null;\n FileInfo fi = new FileInfo(path);\n if (fi.Exists)\n {\n f = new FileStream(path, FileMode.Open, FileAccess.ReadWrite); \n }\n return f;\n }\n catch\n{\n}\n try"
},
{
"answer_id": 207919,
"author": "Jon Bright",
"author_id": 1813,
"author_profile": "https://Stackoverflow.com/users/1813",
"pm_score": 2,
"selected": false,
"text": "String foo=\"foobar\";\nbyte[] foobytes;\n\ntry\n{\n foobytes=foo.getBytes(\"UTF-8\");\n}\ncatch (UnsupportedEncodingException uee)\n{\n // This is guaranteed by the Java Language Specification not to occur, \n // since every Java implementation is required to support UTF-8.\n}\n ...\ncatch (UnsupportedEncodingException uee)\n{\n // This is guaranteed by the Java Language Specification not to occur, \n // since every Java implementation is required to support UTF-8.\n uee.printStackTrace();\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18893/"
] |
204,823
|
<p>I'm required to write documentation for my current project that lists all .c files and for each one lists every .h file which is directly or indirectly included by that file.</p>
<p>This is a large project, and although we have Makefiles which theoretically have this information, those Makefiles are sometimes incorrect (we inherited this project from another company). We've often had to do a <code>make clean ; make</code> for our changes to actually be reflected in the recompilation, so I don't want to rely on these Makefiles.</p>
<p>So is there a tool which lets us give it the name of a .c file and an include path and have it tell us all of the .h files which are directly or indirectly included by the .c file? We don't have anything weird like</p>
<pre><code>#define my_include "some_file.h"
#include my_include
</code></pre>
<p>so the tool doesn't need to be perfect. Anything that searched .c and .h files in an include path for regular includes would be good enough.</p>
|
[
{
"answer_id": 204893,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "gcc -M file.c"
},
{
"answer_id": 204930,
"author": "Mark Baker",
"author_id": 11815,
"author_profile": "https://Stackoverflow.com/users/11815",
"pm_score": 5,
"selected": true,
"text": "SRCS=$(wildcard *.c)\n\ndepend: $(SRCS)\n gcc -M $(CFLAGS) $(SRCS) >depend\n\ninclude depend\n SRCS=$(wildcard *.c)\nDEPS=$(SRCS:.c=.dep)\n\n%.dep : %.c\n gcc -M $(CFLAGS) $< >$@\n\ninclude $(DEPS)\n"
},
{
"answer_id": 244341,
"author": "humble_guru",
"author_id": 23961,
"author_profile": "https://Stackoverflow.com/users/23961",
"pm_score": 2,
"selected": false,
"text": "$ scons --tree=all\nscons: Reading SConscript files ...\n\nscons: done reading SConscript files.\nscons: Building targets ...\nscons: `.' is up to date.\n+-.\n +-SConstruct\n +-app\n | +-test.o\n | | +-test.c\n | | +-/include/PCI_1149_1.h\n | | +-/include/Pci.h\n | | +-/usr/bin/gcc\n | +-/usr/bin/gcc\n | +-/lib/libpci1149_64.a\n ...\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
] |
204,829
|
<p>Situation:</p>
<ul>
<li>text: a string</li>
<li>R: a regex that matches part of the string. This might be expensive to calculate. </li>
</ul>
<p>I want to both delete the R-matches from the text, and see what they actually contain. Currently, I do this like:</p>
<pre><code>import re
ab_re = re.compile("[ab]")
text="abcdedfe falijbijie bbbb laifsjelifjl"
ab_re.findall(text)
# ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
ab_re.sub('',text)
# 'cdedfe flijijie lifsjelifjl'
</code></pre>
<p>This runs the regex twice, near as I can tell. Is there a technique to do it all on pass, perhaps using re.split? It seems like with split based solutions I'd need to do the regex at least twice as well. </p>
|
[
{
"answer_id": 204961,
"author": "Hamish Downer",
"author_id": 3189,
"author_profile": "https://Stackoverflow.com/users/3189",
"pm_score": 0,
"selected": false,
"text": "import re\nab_re = re.compile(\"([ab])\")\ntext=\"abcdedfe falijbijie bbbb laifsjelifjl\"\nmatches = ab_re.split(text)\n# matches = ['', 'a', '', 'b', 'cdedfe f', 'a', 'lij', 'b', 'ijie ', 'b', '', 'b', '', 'b', '', 'b', ' l', 'a', 'ifsjelifjl']\n\n# now extract the matches\nRmatches = []\nremaining = []\nfor i in range(1, len(matches), 2):\n Rmatches.append(matches[i])\n# Rmatches = ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']\n\nfor i in range(0, len(matches), 2):\n remaining.append(matches[i])\nremainingtext = ''.join(remaining)\n# remainingtext = 'cdedfe flijijie lifsjelifjl'\n"
},
{
"answer_id": 204981,
"author": "Deestan",
"author_id": 6848,
"author_profile": "https://Stackoverflow.com/users/6848",
"pm_score": 3,
"selected": true,
"text": "import re\n\nr = re.compile(\"[ab]\")\ntext = \"abcdedfe falijbijie bbbb laifsjelifjl\"\n\nmatches = []\nreplaced = []\npos = 0\nfor m in r.finditer(text):\n matches.append(m.group(0))\n replaced.append(text[pos:m.start()])\n pos = m.end()\nreplaced.append(text[pos:])\n\nprint matches\nprint ''.join(replaced)\n ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']\ncdedfe flijijie lifsjelifjl\n"
},
{
"answer_id": 205056,
"author": "Gregg Lind",
"author_id": 15842,
"author_profile": "https://Stackoverflow.com/users/15842",
"pm_score": 2,
"selected": false,
"text": "import re\ntext=\"abcdedfe falijbijie bbbb laifsjelifjl\"\nab_re = re.compile(\"([ab])\")\ntokens = ab_re.split(text)\nnon_matches = tokens[0::2]\nmatches = tokens[1::2]\n def split_matches(text,compiled_re):\n ''' given a compiled re, split a text \n into matching and nonmatching sections\n returns m, n_m, two lists\n '''\n tokens = compiled_re.split(text)\n matches = tokens[1::2]\n non_matches = tokens[0::2]\n return matches,non_matches\n\nm,nm = split_matches(text,ab_re)\n''.join(nm) # equivalent to ab_re.sub('',text)\n"
},
{
"answer_id": 205072,
"author": "Jon Cage",
"author_id": 15369,
"author_profile": "https://Stackoverflow.com/users/15369",
"pm_score": 2,
"selected": false,
"text": "import re\n\ntext = \"abcdedfe falijbijie bbbb laifsjelifjl\"\nmatches = []\n\nab_re = re.compile( \"[ab]\" )\n\ndef verboseTest( m ):\n matches.append( m.group(0) )\n return ''\n\ntextWithoutMatches = ab_re.sub( verboseTest, text )\n\nprint matches\n# ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']\nprint textWithoutMatches\n# cdedfe flijijie lifsjelifjl\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15842/"
] |
204,831
|
<p>With so many languages and frameworks that exist, and with new ones appearing all the time, I don't have the time to download, install, and configure each one to evaluate it. In the past I've run across webapps that allow one to write or paste code into a window, and see the results in realtime in the browser, usually in a tutorial setting. </p>
<p>What are your favorite sandbox sites for a given technology?</p>
<p><strong>Edit:</strong> @fretj provided the link to the excellent <a href="http://code.google.com/apis/ajax/playground/" rel="noreferrer">Google Code Playground</a> (+1 upvote), but I thought that it was just for experimenting with Google's own apps (Search, Maps, Earth, Language, etc). But it turns out that it contains a few hidden gems: In addition to their apps, you can try out the many Javascript libraries that they host including <a href="http://code.google.com/apis/ajax/playground/#jquery" rel="noreferrer">jQuery</a>, <a href="http://code.google.com/apis/ajax/playground/#jqueryui" rel="noreferrer">jQuery UI</a>, <a href="http://code.google.com/apis/ajax/playground/#mootools" rel="noreferrer">MooTools</a>, <a href="http://code.google.com/apis/ajax/playground/#dojo" rel="noreferrer">Dojo</a>, and <a href="http://code.google.com/apis/ajax/playground/#prototype_scriptaculous" rel="noreferrer">Prototype Scriptaculous</a>. </p>
<p>They're all hidden under the Libraries category in the "Pick an API" box. I overlooked the category because I thought it was for an app called Google Libraries. There's also a Javascript category for Javascript itself.</p>
|
[
{
"answer_id": 27371632,
"author": "DJMcMayhem",
"author_id": 3524982,
"author_profile": "https://Stackoverflow.com/users/3524982",
"pm_score": 0,
"selected": false,
"text": "from time import sleep\nprint \"We are going to sleep for 5 seconds.\"\nsleep(5)\nprint \"Now we will sleep for 3 seconds.\"\nsleep(3)\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8161/"
] |
204,852
|
<p>I have an xsd like this </p>
<pre><code><xsd:complexType name="A">
<xsd:complexContent>
<xsd:sequence>
<xsd:element name="options">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Day">
...
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexContent>
</xsd:complexType>
<xsd:complexType name="B">
<xsd:complexContent>
<xsd:extension base="A">
...What would go here...
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</code></pre>
<p>So basically I want class A to have a sequence of options (Day, Week for example) then I want B to inherit from A and have all of A's options and an additional 2 or 3 options like hours, seconds.</p>
|
[
{
"answer_id": 205247,
"author": "csgero",
"author_id": 21764,
"author_profile": "https://Stackoverflow.com/users/21764",
"pm_score": 3,
"selected": false,
"text": "<xsd:sequence> <xsd:complexType name=\"B\"> \n <xsd:complexContent>\n <xsd:extension base=\"A\">\n <xsd:sequence>\n <xsd:element name=\"Hours\">\n ...\n </xsd:element>\n </xsd:sequence>\n </xsd:extension>\n </xsd:complexContent>\n</xsd:complexType>\n"
},
{
"answer_id": 207487,
"author": "Richard Nienaber",
"author_id": 9539,
"author_profile": "https://Stackoverflow.com/users/9539",
"pm_score": 6,
"selected": true,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xs:schema id=\"inheritance\"\n targetNamespace=\"http://test.com\"\n elementFormDefault=\"qualified\"\n xmlns=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:test=\"http://test.com\"\n>\n <xs:element name=\"Time\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"First\" type=\"test:A\" />\n <xs:element name=\"Second\" type=\"test:B\" />\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n\n <xs:complexType name=\"shortOptions\">\n <xs:sequence>\n <xs:element name=\"Day\" />\n </xs:sequence>\n </xs:complexType>\n\n <xs:complexType name=\"longOptions\">\n <xs:complexContent>\n <xs:extension base=\"test:shortOptions\">\n <xs:sequence>\n <xs:element name=\"Week\" />\n </xs:sequence>\n </xs:extension>\n </xs:complexContent>\n </xs:complexType>\n\n <xs:complexType name=\"A\">\n <xs:sequence>\n <xs:element name=\"options\" type=\"test:shortOptions\" />\n </xs:sequence>\n </xs:complexType>\n\n <xs:complexType name=\"B\">\n <xs:sequence>\n <xs:element name=\"options\" type=\"test:longOptions\" />\n </xs:sequence>\n </xs:complexType>\n\n</xs:schema>\n <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<Time xmlns=\"http://test.com\">\n <First>\n <options>\n <Day>Today</Day>\n </options>\n </First>\n <Second>\n <options>\n <Day>Tomorrow</Day>\n <Week>This Week</Week>\n </options>\n </Second>\n</Time>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22763/"
] |
204,877
|
<p>What does the following mean?</p>
<pre><code>Class.Function(variable := 1 + 1)
</code></pre>
<p>What is this operator called, and what does it do? </p>
|
[
{
"answer_id": 204935,
"author": "Ikke",
"author_id": 20261,
"author_profile": "https://Stackoverflow.com/users/20261",
"pm_score": 5,
"selected": true,
"text": "sub test(optional a as string = \"\", optional b as string = \"\")\n msgbox(a & b)\nend sub\n test(b:= \"blaat\")\n'in stead of\ntest(\"\", \"blaat\")\n"
},
{
"answer_id": 204947,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 0,
"selected": false,
"text": "Class.Function variable"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40/"
] |
204,886
|
<p>you can request the http header to check if a web page has been edited by looking at its date but how about dynamic pages such as - php, aspx- which grabs its data from a database?</p>
|
[
{
"answer_id": 204971,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 0,
"selected": false,
"text": "Last-Modified Last-Modified Last-Modified Last-Modified"
},
{
"answer_id": 236380,
"author": "Leandro López",
"author_id": 22695,
"author_profile": "https://Stackoverflow.com/users/22695",
"pm_score": 2,
"selected": false,
"text": "function doConditionalGet($timestamp) {\n // A PHP implementation of conditional get, see \n // http://fishbowl.pastiche.org/archives/001132.html\n $last_modified = substr(date('r', $timestamp), 0, -5).'GMT';\n $etag = '\"'.md5($last_modified).'\"';\n\n // Send the headers\n header(\"Last-Modified: $last_modified\");\n header(\"ETag: $etag\");\n\n // See if the client has provided the required headers\n $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ?\n stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) :\n false;\n\n $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ?\n stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : \n false;\n\n if (!$if_modified_since && !$if_none_match) {\n return;\n }\n\n // At least one of the headers is there - check them\n if ($if_none_match && $if_none_match != $etag) {\n return; // etag is there but doesn't match\n }\n\n if ($if_modified_since && $if_modified_since != $last_modified) {\n return; // if-modified-since is there but doesn't match\n }\n\n // Nothing has changed since their last request - serve a 304 and exit\n header('HTTP/1.0 304 Not Modified');\n exit;\n}\n If-Modified-Since If-None-Match Last-Modified ETag ETag Last-Modified"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459737/"
] |
204,914
|
<p>I'm trying to simply use some of the examples and instructions regarding the YUI-Uploader, and I'm being frustrated by a number of issues.</p>
<ol>
<li>The "YUI Library: Uploader" cheat sheet's simple use case doesn't work for me because all the listed methods except <code>addListener()</code> do not exist on the myUploader object.</li>
<li>The <a href="http://developer.yahoo.com/yui/examples/uploader/uploader-simple.html" rel="nofollow noreferrer">example</a> is for version 2.5.1 and includes a method called <code>browse()</code>, which not only was removed in version 2.6.0 but I cannot find any documentation for how to use the 2.5.1 version if I so choose.</li>
<li>I can't find the source FLA to the <code>uploader.swf</code> file so that I could theoretically diagnose all these issues.</li>
</ol>
<p>Has anyone successfully used the 2.6.0 YUI Uploader, and if so is there some common interfering JavaScript I should avoid, or a better example to follow? Thank you.</p>
<p>Thanks for the replies.</p>
<p>I might note that I finished my "uploader" project before receiving any responses to this.
Part of my problems were due to some of the examples being for v2.5.1 and another part were due to not using an event listener to see when the component was ready. I got the most help from just dissecting what <a href="http://flickr.com" rel="nofollow noreferrer">Flickr</a> did.</p>
|
[
{
"answer_id": 689083,
"author": "Simon Lieschke",
"author_id": 2766,
"author_profile": "https://Stackoverflow.com/users/2766",
"pm_score": 3,
"selected": true,
"text": "uploader.swf Uploader.as"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459/"
] |
204,918
|
<p>Does SQLAlchemy support some kind of caching so if I repeatedly run the same query it returns the response from cache instead of querying the database? Is this cache automatically cleared when the DB is updated?</p>
<p>Or what's the best way to implement this on a CherryPy + SQLAlchemy setup?</p>
|
[
{
"answer_id": 232376,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 4,
"selected": false,
"text": "Does SQLAlchemy do any kind of internal caching?\n\nFor example, if you ask for the same data twice (or an obvious subset\nof the initially requested data) will the database be hit once or twice?\n\nI recently wrote a caching database abstraction layer for an\napplication and (while fun) it was a fair bit of work to get it to a\nminimally functional state. If SQLAlchemy did that I would seriously\nconsider jumping on the bandwagon.\n\nI've found things in the docs that imply something like this might be\ngoing on, but nothing explicit.\n4:36 PM\n No; the author of SA [rightly, IMO] considers caching a separate concern.\n\nWhat you saw in the docs is probably the SA identity map, which makes it so \nif you load an instance in two different places, they will refer\nto the same object. But the database will still be queried twice, so it is\nnot a cache in the sense you mean.\n"
},
{
"answer_id": 2152159,
"author": "zzzeek",
"author_id": 34549,
"author_profile": "https://Stackoverflow.com/users/34549",
"pm_score": 7,
"selected": true,
"text": "dogpile"
},
{
"answer_id": 33484529,
"author": "Jeff Widman",
"author_id": 770425,
"author_profile": "https://Stackoverflow.com/users/770425",
"pm_score": 4,
"selected": false,
"text": "dogpile memcached redis query baked queries baked sqlalchemy query"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9789/"
] |
204,924
|
<p>I know that you can apply CSS in order to style objects in Flex using the StyleManager:<br>
<a href="http://livedocs.adobe.com/flex/3/html/help.html?content=styles_07.html" rel="nofollow noreferrer">http://livedocs.adobe.com/flex/3/html/help.html?content=styles_07.html</a> </p>
<p>You can also load <strong>compiled</strong> CSS files (SWFs) dynamically:<br>
<a href="http://livedocs.adobe.com/flex/3/html/help.html?content=styles_10.html" rel="nofollow noreferrer">http://livedocs.adobe.com/flex/3/html/help.html?content=styles_10.html</a> </p>
<p>However, I'm dynamically creating my CSS files using a web GUI and a server-side script.
If the CSS is changed, then the script would also need to compile the CSS into an SWF (which is not a viable option). Is there any way around this?</p>
|
[
{
"answer_id": 7534609,
"author": "sixtyfootersdude",
"author_id": 251589,
"author_profile": "https://Stackoverflow.com/users/251589",
"pm_score": 2,
"selected": false,
"text": "public function extractFromStyleSheet(css:String):void {\n\n // Create a StyleSheet Object\n var styleSheet:StyleSheet = new StyleSheet();\n styleSheet.parseCSS(css);\n\n // Iterate through the selector objects\n var selectorNames:Array = styleSheet.styleNames;\n for(var i:int=0; i<selectorNames.length; i++){\n\n // Do something with each selector\n trace(\"Selector: \"+selelectorNames[i];\n\n var properties:Object = styleSheet.getStyle(selectorNames[i]);\n for (var property:String in properties){\n\n // Do something with each property in the selector\n trace(\"\\t\"+property+\" -> \"+properties[property]+\"\\n\");\n }\n }\n}\n cssStyle = new CSSStyleDeclaration();\ncssStyle.setStyle(\"color\", \"<valid color>);\nFlexGlobals.topLevelApplication.styleManager.setStyleDeclaration(\"Button\", cssStyle, true);\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18146/"
] |
204,926
|
<p>Are there any good code profilers/analyzers for Erlang? I need something that can build a call graph (eg gprof) for my code.</p>
|
[
{
"answer_id": 205002,
"author": "krakatoa",
"author_id": 12223,
"author_profile": "https://Stackoverflow.com/users/12223",
"pm_score": 3,
"selected": false,
"text": "fprof:apply(foo, create_file_slow, [junk, 1024]).\nfprof:profile().\nfprof:analyse().\n fprof:apply trace profile analyse"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2727/"
] |
204,933
|
<p>I read an excel sheet into a datagrid.From there , I have managed to read the grid's rows into a DataTable object.The DataTable object has data because when I make equal a grid's datasource to that table object , the grid is populated.</p>
<p>My Problem : I want to use the table object and manipulate its values using SQL server,(i.e. I want to store it as a temporary table and manipulate it using SQL queries from within C# code and , I want it to return a different result inte a grid.(I don't know how to work with temporary tables in C#)</p>
<p>Here's code to execute when clicking button....</p>
<pre><code> SqlConnection conn = new SqlConnection("server = localhost;integrated security = SSPI");
//is connection string incorrect?
SqlCommand cmd = new SqlCommand();
//!!The method ConvertFPSheetDataTable Returns a DataTable object//
cmd.Parameters.AddWithValue("#table",ConvertFPSheetDataTable(12,false,fpSpread2_Sheet1));
//I am trying to create temporary table
//Here , I do a query
cmd.CommandText = "Select col1,col2,SUM(col7) From #table group by col1,col2 Drop #table";
SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText,conn);
DataTable dt = new DataTable();
da.Fill(dt); ***// I get an error here 'Invalid object name '#table'.'***
fpDataSet_Sheet1.DataSource = dt;
//**NOTE:** fpDataSet_Sheet1 is the grid control
</code></pre>
|
[
{
"answer_id": 204964,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": " var query = from row in table.Rows.Cast<DataRow>()\n group row by new\n {\n Col1 = row.Field<int>(1),\n Col2 = row.Field<int>(2)\n } into grp\n select new\n {\n Col1 = grp.Key.Col1,\n Col2 = grp.Key.Col2,\n SumCol7 = grp.Sum(x => x.Field<int>(7))\n };\n foreach (var item in query)\n {\n Console.WriteLine(\"{0},{1}: {2}\",\n item.Col1, item.Col2, item.SumCol7);\n }\n"
},
{
"answer_id": 205312,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 0,
"selected": false,
"text": "dv = new DataView(dataTableName);\n dv.RowFilter = \"Country = 'USA'\";\ndv.RowFilter = \"EmployeeID >5 AND Birthdate < #1/31/82#\"\ndv.RowFilter = \"Description LIKE '*product*'\"\ndv.RowFilter = \"employeeID IN (2,4,5)\"\n dv.Sort = \"City\"\n vals(0)= \"John\"\n vals(1) = \"Smith\"\n i = dv.Find(vals)\n"
},
{
"answer_id": 205383,
"author": "Ryan Abbott",
"author_id": 27908,
"author_profile": "https://Stackoverflow.com/users/27908",
"pm_score": 2,
"selected": false,
"text": "// Load the reports in bulk\nSqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString);\n// Map the columns\nforeach(DataColumn col in dataTable.Columns)\n bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);\nbulkCopy.DestinationTableName = \"SQLTempTable\";\nbulkCopy.WriteToServer(dataTable);\n // For CSV\n connStr = string.Format(\"Provider=Microsoft.JET.OLEDB.4.0;Data Source={0};Extended Properties='Text;HDR=Yes;FMT=Delimited;IMEX=1'\", Folder);\n cmdStr = string.Format(\"SELECT * FROM [{0}]\", FileName);\n // For XLS\n connStr = string.Format(\"Provider=Microsoft.JET.OLEDB.4.0;Data Source={0}{1};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'\", Folder, FileName);\n cmdStr = \"select * from [Sheet1$]\";\nOleDbConnection oConn = new OleDbConnection(connStr);\n OleDbCommand cmd = new OleDbCommand(cmdStr, oConn);\n OleDbDataAdapter da = new OleDbDataAdapter(cmd);\n oConn.Open();\n da.Fill(dataTable);\n oConn.Close();\n connectionString=\"Data Source=localhost\\<instance>;database=<yourDataBase>;Integrated Security=SSPI\" providerName=\"System.Data.SqlClient\"\n"
},
{
"answer_id": 18109049,
"author": "Al Option",
"author_id": 2024420,
"author_profile": "https://Stackoverflow.com/users/2024420",
"pm_score": 0,
"selected": false,
"text": "Select col1,col2,SUM(col7) From #table group by col1,col2\n Select col1,col2,SUM(col7) From @#table group by col1,col2\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
204,936
|
<p>What is the best way to set the time on a remote machine remotely? The machine is running Windows XP and is receiving the new time through a web service call. The goal is to keep the remote machines in synch with the server. The system is locked down so that our web service is the only access, so I cannot use a time server on each remote machine.</p>
|
[
{
"answer_id": 204967,
"author": "Robert S.",
"author_id": 7565,
"author_profile": "https://Stackoverflow.com/users/7565",
"pm_score": 3,
"selected": false,
"text": "[StructLayout(LayoutKind.Sequential)] \npublic struct SYSTEMTIME { \n public short wYear; \n public short wMonth; \n public short wDayOfWeek; \n public short wDay; \n public short wHour; \n public short wMinute; \n public short wSecond; \n public short wMilliseconds; \n } \n [DllImport(\"kernel32.dll\", SetLastError=true)] \npublic static extern bool SetSystemTime(ref SYSTEMTIME theDateTime ); \n"
},
{
"answer_id": 205018,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "unit TimeHandler;\n\ninterface\n\ntype\n TTimeHandler = class\n private\n FServerName : widestring;\n public\n constructor Create(servername : widestring);\n function RemoteSystemTime : TDateTime;\n procedure SetLocalSystemTime(settotime : TDateTime);\n end;\n\nimplementation\n\nuses\n Windows, SysUtils, Messages;\n\nfunction NetRemoteTOD(ServerName :PWideChar; var buffer :pointer) : integer; stdcall; external 'netapi32.dll';\nfunction NetApiBufferFree(buffer : Pointer) : integer; stdcall; external 'netapi32.dll';\n\ntype\n //See MSDN documentation on the TIME_OF_DAY_INFO structure.\n PTime_Of_Day_Info = ^TTime_Of_Day_Info;\n TTime_Of_Day_Info = record\n ElapsedDate : integer;\n Milliseconds : integer;\n Hours : integer;\n Minutes : integer;\n Seconds : integer;\n HundredthsOfSeconds : integer;\n TimeZone : LongInt;\n TimeInterval : integer;\n Day : integer;\n Month : integer;\n Year : integer;\n DayOfWeek : integer;\n end;\n\nconstructor TTimeHandler.Create(servername: widestring);\nbegin\n inherited Create;\n FServerName := servername;\nend;\n\nfunction TTimeHandler.RemoteSystemTime: TDateTime;\nvar\n Buffer : pointer;\n Rek : PTime_Of_Day_Info;\n DateOnly, TimeOnly : TDateTime;\n timezone : integer;\nbegin\n //if the call is successful...\n if 0 = NetRemoteTOD(PWideChar(FServerName),Buffer) then begin\n //store the time of day info in our special buffer structure\n Rek := PTime_Of_Day_Info(Buffer);\n\n //windows time is in GMT, so we adjust for our current time zone\n if Rek.TimeZone <> -1 then\n timezone := Rek.TimeZone div 60\n else\n timezone := 0;\n\n //decode the date from integers into TDateTimes\n //assume zero milliseconds\n try\n DateOnly := EncodeDate(Rek.Year,Rek.Month,Rek.Day);\n TimeOnly := EncodeTime(Rek.Hours,Rek.Minutes,Rek.Seconds,0);\n except on e : exception do\n raise Exception.Create(\n 'Date retrieved from server, but it was invalid!' +\n #13#10 +\n e.Message\n );\n end;\n\n //translate the time into a TDateTime\n //apply any time zone adjustment and return the result\n Result := DateOnly + TimeOnly - (timezone / 24);\n end //if call was successful\n else begin\n raise Exception.Create('Time retrieval failed from \"'+FServerName+'\"');\n end;\n\n //free the data structure we created\n NetApiBufferFree(Buffer);\nend;\n\nprocedure TTimeHandler.SetLocalSystemTime(settotime: TDateTime);\nvar\n SystemTime : TSystemTime;\nbegin\n DateTimeToSystemTime(settotime,SystemTime);\n SetLocalTime(SystemTime);\n //tell windows that the time changed\n PostMessage(HWND_BROADCAST,WM_TIMECHANGE,0,0);\nend;\n procedure TfrmMain.SynchLocalTimeWithServer;\nvar\n tod : TTimeHandler;\nbegin\n tod := TTimeHandler.Create(cboServerName.Text);\n try\n tod.SetLocalSystemTime(tod.RemoteSystemTime);\n finally\n FreeAndNil(tod);\n end; //try-finally\nend;\n"
},
{
"answer_id": 205044,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 0,
"selected": false,
"text": "TIME\n net time \\\\server_name\n"
},
{
"answer_id": 11299586,
"author": "jp2code",
"author_id": 153923,
"author_profile": "https://Stackoverflow.com/users/153923",
"pm_score": 1,
"selected": false,
"text": "DateTime SYSTEMTIME public class TimeTool {\n\n private static readonly DateTime NODATE = new DateTime(1900, 1, 1);\n\n#if PocketPC\n [DllImport(\"coredll.dll\")]\n#else\n [DllImport(\"kernel32.dll\")]\n#endif\n static extern bool SetLocalTime([In] ref SYSTEMTIME lpLocalTime);\n\n public struct SYSTEMTIME {\n public short Year, Month, DayOfWeek, Day, Hour, Minute, Second, Millisecond;\n /// <summary>\n /// Convert form System.DateTime\n /// </summary>\n /// <param name=\"time\">Creates System Time from this variable</param>\n public void FromDateTime(DateTime time) {\n Year = (short)time.Year;\n Month = (short)time.Month;\n DayOfWeek = (short)time.DayOfWeek;\n Day = (short)time.Day;\n Hour = (short)time.Hour;\n Minute = (short)time.Minute;\n Second = (short)time.Second;\n Millisecond = (short)time.Millisecond;\n }\n\n public DateTime ToDateTime() {\n return new DateTime(Year, Month, Day, Hour, Minute, Second, Millisecond);\n }\n\n public static DateTime ToDateTime(SYSTEMTIME time) {\n return time.ToDateTime();\n }\n }\n\n // read SQL Time and set time on device\n public static int SyncWithSqlTime(System.Data.SqlClient.SqlConnection con) {\n SYSTEMTIME systemTime = new SYSTEMTIME();\n DateTime sqlTime = NODATE;\n string sql = \"SELECT GETDATE() AS [CurrentDateTime]\";\n using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, con)) {\n try {\n cmd.Connection.Open();\n System.Data.SqlClient.SqlDataReader r = cmd.ExecuteReader();\n while (r.Read()) {\n if (!r.IsDBNull(0)) {\n sqlTime = (DateTime)r[0];\n }\n }\n } catch (Exception) {\n return -1;\n }\n }\n if (sqlTime != NODATE) {\n systemTime.FromDateTime(sqlTime); // Convert to SYSTEMTIME\n if (SetLocalTime(ref systemTime)) { //Call Win32 API to set time\n return 1;\n }\n }\n return 0;\n }\n\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3457/"
] |
204,942
|
<p>We have an application that installs SQL Server Express from the command line and specifies the service account as the LocalSystem account via the parameter SQLACCOUNT="NT AUTHORITY\SYSTEM".</p>
<p>This doesn't work with different languages because the account name for LocalSystem is different. There's a table listing the differences here:</p>
<p><a href="http://forums.microsoft.com/MSR/ShowPost.aspx?PostID=685354&SiteID=37" rel="nofollow noreferrer">http://forums.microsoft.com/MSR/ShowPost.aspx?PostID=685354&SiteID=37</a></p>
<p>This doesn't seem to be complete (the Swedish version isn't listed). So I'd like to be able to determine the name programmatically, perhaps using the SID?</p>
<p>I've found some VB Script to do this:</p>
<pre><code>Set objWMI = GetObject("winmgmts:root\cimv2")
Set objSid = objWMI.Get("Win32_SID.SID='S-1-5-18'")
MsgBox objSid.ReferencedDomainName & "\" & objSid.AccountName
</code></pre>
<p>Does anyone know the equivalent code that can be used in C#?</p>
|
[
{
"answer_id": 204955,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 1,
"selected": false,
"text": "ManagementObject m = new ManagementObject(\"winmgmts:root\\cimv2\");\nm.Get();\nMessageBox.Show(m[\"Win32_SID.SID='S-1-5-18'\"].ToString());\n"
},
{
"answer_id": 205012,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 4,
"selected": true,
"text": "using System.Security.Principal;\n\n\nSecurityIdentifier sid = new SecurityIdentifier(\"S-1-5-18\");\nNTAccount acct = (NTAccount)sid.Translate(typeof(NTAccount));\nConsole.WriteLine(acct.Value);\n"
},
{
"answer_id": 1159563,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "/// <summary>\n/// Returns the Account name for the specified SID \n// using WMI against the specified remote machine\n/// </summary>\nprivate string RemoteSID2AccountName(String MachineName, String SIDString)\n{\n ManagementScope oScope = new ManagementScope(@\"\\\\\" + MachineName + \n @\"\\root\\cimv2\");\n ManagementPath oPath = new ManagementPath(\"Win32_SID.SID='\" + SIDString + \"'\");\n ManagementObject oObject = new ManagementObject(oScope, oPath, null);\n return oObject[\"AccountName\"].ToString();\n}\n"
},
{
"answer_id": 15926564,
"author": "Vinicius Ottoni",
"author_id": 1160608,
"author_profile": "https://Stackoverflow.com/users/1160608",
"pm_score": 2,
"selected": false,
"text": "string localSystem = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null).Translate(typeof(NTAccount)).Value;\n WellKnownSidType NetworkService"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5449/"
] |
204,950
|
<p>I have just installed the Krypton Toolkit 3.0.6 from component Factory.
I find that in the create new Project Dialog Box , Krypton Form does not show up as an option. I am sure it used to show up ( and I have actually used it in an earlier version of krypton toolkit).But after the new install it does not.</p>
|
[
{
"answer_id": 208226,
"author": "dezkev",
"author_id": 28291,
"author_profile": "https://Stackoverflow.com/users/28291",
"pm_score": 2,
"selected": false,
"text": "public partial class Form1 : ComponentFactory.Krypton.Toolkit.KryptonForm\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
204,963
|
<p>I'm quite confused by something. I've got 2 select lists, and if you choose an option in the first, I then load the 2nd with a certain set of options. I clear this out and repopulate it every time you change the selection in the first select element. Now, on postback, I need to know the value of the option that was selected in the 2nd select element, but it is always showing up as -1.</p>
<p>I'm sure I'm missing something fundamental and dumb on my part, but can anyone point me in the right direction?</p>
|
[
{
"answer_id": 208226,
"author": "dezkev",
"author_id": 28291,
"author_profile": "https://Stackoverflow.com/users/28291",
"pm_score": 2,
"selected": false,
"text": "public partial class Form1 : ComponentFactory.Krypton.Toolkit.KryptonForm\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232/"
] |
204,970
|
<p>Suppose I have following string:</p>
<pre><code>String asd = "this is test ass this is test"
</code></pre>
<p>and I want to split the string using "ass" character sequence.</p>
<p>I used:</p>
<pre><code>asd.split("ass");
</code></pre>
<p>It doesn't work. What do I need to do?</p>
|
[
{
"answer_id": 205004,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "public class Test\n{\n public static void main(String[] args) {\n String asd = \"this is test ass this is test\";\n String[] bits = asd.split(\"ass\");\n for (String bit : bits) {\n System.out.println(\"'\" + bit + \"'\");\n }\n }\n}\n 'this is test '\n' this is test'\n"
},
{
"answer_id": 205023,
"author": "johnstok",
"author_id": 27929,
"author_profile": "https://Stackoverflow.com/users/27929",
"pm_score": 1,
"selected": true,
"text": "public class Splitter {\n\n public static void main(final String[] args) {\n final String asd = \"this is test ass this is test\";\n final String[] parts = asd.split(\"ass\");\n for (final String part : parts) {\n System.out.println(part);\n }\n }\n}\n this is test \n this is test\n"
},
{
"answer_id": 38609312,
"author": "Bhimreddy",
"author_id": 6634977,
"author_profile": "https://Stackoverflow.com/users/6634977",
"pm_score": 1,
"selected": false,
"text": "String asd = \"this is test foo this is test\";\nString[] parts = asd.split(\"foo\");\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25778/"
] |
204,983
|
<p>If you want to associate some constant value with a class, here are two ways to accomplish the same goal:</p>
<pre><code>class Foo
{
public:
static const size_t Life = 42;
};
class Bar
{
public:
enum {Life = 42};
};
</code></pre>
<p>Syntactically and semantically they appear to be identical from the client's point of view:</p>
<pre><code>size_t fooLife = Foo::Life;
size_t barLife = Bar::Life;
</code></pre>
<p>Is there any reason other than just pure style concerns why one would be preferable to another?</p>
|
[
{
"answer_id": 204999,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "size_t *pLife1 = &Foo::Life;\nsize_t *pLife2 = &Bar::Life;\n"
},
{
"answer_id": 205000,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": true,
"text": "enum static const enum struct foo {\n static int const bar = 42; // Declaration, initialization.\n};\n\nint const foo::bar; // Definition.\n"
},
{
"answer_id": 206776,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 3,
"selected": false,
"text": "// MyPImpl.hpp\n\nclass MyImpl ;\n\nclass MyPimpl\n{\n public :\n enum { Life = 42 } ;\n private :\n MyImpl * myImpl ;\n}\n // MyPImpl.hpp\n\nclass MyImpl ;\n\nclass MyPimpl\n{\n public :\n static const int Life ;\n private :\n MyImpl * myImpl ;\n}\n // MyPImpl.cpp\nconst int MyPImpl::Life = 42 ;\n"
},
{
"answer_id": 211180,
"author": "deft_code",
"author_id": 28817,
"author_profile": "https://Stackoverflow.com/users/28817",
"pm_score": 3,
"selected": false,
"text": "static const enum enum static const Foo::Life &Foo::Life; int foo = rand()? Foo::Life: Foo::Everthing;\n Life Everything Foo::Life Foo::Everything class Foo {\n public:\n constexpr size_t Life = 42;\n};\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/241536/"
] |
204,991
|
<p>I'm not quite sure how this happened, but somehow a completely empty hierarchy of directories has ended up in my repository:</p>
<pre><code>com/
com/companyname/
com/companyname/blah/
com/sun/
com/sun/java/
com/sun/java/jax_rpc_ri/
</code></pre>
<p>I think what happened was that these directories did have files in them, but then a developer realized he/she shouldn't have checked them in in the first place since these are by-products of the build process, so he/she removed the files but somehow the empty directories are left in the repository as ancient relics.</p>
<p>How can I remove this from CVS? The only results I seem to be able to find on google say that there shouldn't be a need to remove empty directories as CVS won't keep them around in the first place, and that the <code>-P</code> (prune) options to <code>cvs update</code> should remove them from the working directory - which is zero help if you actually have empty directories in your repository.</p>
<p>A <code>cvs remove</code> and <code>cvs commit</code> doesn't seem to take care of this situation:</p>
<pre><code>$ cvs remove -Rf com
cvs remove: Removing com
cvs remove: Removing com/companyname
cvs remove: Removing com/companyname/blah
cvs remove: Removing com/sun
cvs remove: Removing com/sun/java
cvs remove: Removing com/sun/java/jax_rpc_ri
$ cvs commit com
cvs commit: Examining com
cvs commit: Examining com/companyname
cvs commit: Examining com/companyname/blah
cvs commit: Examining com/sun
cvs commit: Examining com/sun/java
cvs commit: Examining com/sun/java/jax_rpc_ri
$ ls -l com
total 24
drwxrwxr-x 2 matt matt 4096 Oct 15 14:38 CVS
drwxrwxr-x 9 matt matt 4096 Oct 15 14:38 companyname
drwxrwxr-x 4 matt matt 4096 Oct 15 14:38 sun
</code></pre>
<p>It's still there!</p>
<p>Does SVN have this weird behavior too?</p>
|
[
{
"answer_id": 205042,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 5,
"selected": false,
"text": "cvs update -dP\n"
},
{
"answer_id": 205081,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 1,
"selected": false,
"text": "~/Sandbox/my_project/some_stuff_i_want\n~/Sandbox/my_project/empty_dir_1\n~/Sandbox/my_project/other_stuff_i_want\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/204991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
] |
205,001
|
<p>What's the best way to remove a page frame automatically?</p>
<p>I've used this type of code before:</p>
<pre><code><script language="JavaScript">
setTimeout ("changePage()", 3000);
function changePage() {
if (self.parent.frames.length != 0)
self.parent.location="http://www.example.com";
}
</script>
</code></pre>
|
[
{
"answer_id": 205055,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 0,
"selected": false,
"text": "if ( self.location !== top.location )\n{\n top.location.replace( self.location );\n}\n"
},
{
"answer_id": 205057,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 1,
"selected": false,
"text": "// is the current page at the top of the browser window hierarchy?\nif (top.location != self.location) \n{\n // it isn't, so force this page to be at \n // the top of the hierarchy, in its own window\n top.location = self.location \n}\n"
},
{
"answer_id": 205065,
"author": "Remy Sharp",
"author_id": 22617,
"author_profile": "https://Stackoverflow.com/users/22617",
"pm_score": 4,
"selected": true,
"text": "<script type=\"text/javascript\">\nif (window.top.location != window.location) {\n window.top.location = window.location;\n}\n</script>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28260/"
] |
205,040
|
<p>In my SQL database, I have a one-to-many relationship, something like this:</p>
<pre>
Teacher Student
John Alex
John Mike
John Sean
Bob Jack
Gary George
Gary Paul
</pre>
<p>I'd like to display a table listing each teacher, with their students as a comma-delimited list, like this:</p>
<pre>
Teacher Students
John Alex, Mike, Sean
Bob Jack
Gary George, Paul
</pre>
<p><a href="https://stackoverflow.com/questions/180032/how-can-i-combine-multiple-rows-into-a-comma-delimited-list-in-sql-server-2005">This question</a> describes how to do this on the SQL Server end, but is there a way to do this on the SSRS side of things?</p>
|
[
{
"answer_id": 30518651,
"author": "Jerry",
"author_id": 53531,
"author_profile": "https://Stackoverflow.com/users/53531",
"pm_score": 4,
"selected": true,
"text": "=Join(LookUpSet(Fields!TeacherName.Value, \n Fields!TeacherName.Value, \n Fields!StudentName.Value, \n \"YourTeacherDataSet\"), \",\")\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16911/"
] |
205,064
|
<p>On Unix, is there any way that one process can change another's environment variables (assuming they're all being run by the same user)? A general solution would be best, but if not, what about the specific case where one is a child of the other?</p>
<p>Edit: How about via gdb?</p>
|
[
{
"answer_id": 205082,
"author": "Davide",
"author_id": 25891,
"author_profile": "https://Stackoverflow.com/users/25891",
"pm_score": 3,
"selected": false,
"text": "/proc/${pid}/environ"
},
{
"answer_id": 211064,
"author": "An̲̳̳drew",
"author_id": 17035,
"author_profile": "https://Stackoverflow.com/users/17035",
"pm_score": 8,
"selected": true,
"text": "(gdb) attach process_id\n\n(gdb) call putenv (\"env_var_name=env_var_value\")\n\n(gdb) detach\n"
},
{
"answer_id": 594140,
"author": "Ruben Bartelink",
"author_id": 11635,
"author_profile": "https://Stackoverflow.com/users/11635",
"pm_score": 1,
"selected": false,
"text": "CreateProcess GetCommandLine"
},
{
"answer_id": 61801422,
"author": "Kakash1hatake",
"author_id": 1822868,
"author_profile": "https://Stackoverflow.com/users/1822868",
"pm_score": 2,
"selected": false,
"text": "$] sudo gdb -p $$\n(gdb) call putenv(\"TEST=1234\")\n$1 = 0\n(gdb) call (char*) getenv(\"TEST\")\n$2 = 0x0\n(gdb) detach\n(gdb) quit\n$] echo \"TEST=$TEST\"\nTEST=\n $] sudo gdb -p $$\n(gdb) call (int) setenv(\"TEST\", \"1234\", 1)\n$1 = 0\n(gdb) call (char*) getenv(\"TEST\")\n$2 = 0x55f19ff5edc0 \"1234\"\n(gdb) detach\n(gdb) quit\n$] echo \"TEST=$TEST\"\nTEST=1234\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
] |
205,070
|
<p>Real UID, effective UID, and some systems even have a "saved UID". What's the purpose of all these, especially the last one?</p>
|
[
{
"answer_id": 24708775,
"author": "LGkash",
"author_id": 2922591,
"author_profile": "https://Stackoverflow.com/users/2922591",
"pm_score": 2,
"selected": false,
"text": "setuid"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
] |
205,073
|
<p>This is probably a simple answer but I can't find it. I have a table with a column of integers and I want to ensure that when a row is inserted that the value in this column is greater than zero. I could do this on the code side but thought it would be best to enforce it on the table.</p>
<p>Thanks!</p>
<p>I was in error with my last comment all is good now.</p>
|
[
{
"answer_id": 205093,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 3,
"selected": false,
"text": "ALTER TABLE Table1 ADD CONSTRAINT Constraint1 CHECK (YourCol > 0)\n ALTER TABLE Table1 ADD CONSTRAINT Constraint2 CHECK (StartDate<EndDate OR EndDate IS NULL)\n"
},
{
"answer_id": 205095,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 5,
"selected": true,
"text": "create table foo (\n [...]\n ,Foobar int not null check (Foobar > 0)\n [...]\n)\n alter table foo\n add constraint Foobar_NonNegative\n check (Foobar > 0)\n sys.check_constraints select name\n ,description\n from sys.check_constraints\n where name = 'Foobar_NonNegative'\n"
},
{
"answer_id": 205102,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 0,
"selected": false,
"text": "CHECK CREATE TABLE Test(\n [ID] [int] NOT NULL,\n [MyCol] [int] NOT NULL CHECK (MyCol > 1)\n)\n"
},
{
"answer_id": 205103,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 0,
"selected": false,
"text": "ALTER TABLE tableName WITH NOCHECK\nADD CONSTRAINT constraintName CHECK (columnName > 0)\n"
},
{
"answer_id": 65052922,
"author": "Hamid Jolany",
"author_id": 555078,
"author_profile": "https://Stackoverflow.com/users/555078",
"pm_score": 0,
"selected": false,
"text": "BEGIN TRANSACTION\n GO\n ALTER TABLE dbo.table1 ADD CONSTRAINT\n CK_table1_field1 CHECK (field1>0)\n GO\n ALTER TABLE dbo.table1 SET (LOCK_ESCALATION = TABLE)\n GO\nCOMMIT\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2357/"
] |
205,087
|
<p>We are using jQuery <a href="http://jquery.com/demo/thickbox/" rel="noreferrer">thickbox</a> to dynamically display an iframe when someone clicks on a picture. In this iframe, we are using <a href="http://devkick.com/lab/galleria/demo_01.htm" rel="noreferrer">galleria</a> a javascript library to display multiple pictures.</p>
<p>The problem seems to be that <code>$(document).ready</code> in the iframe seems to be fired too soon and the iframe content isn't even loaded yet, so galleria code is not applied properly on the DOM elements. <code>$(document).ready</code> seems to use the iframe parent ready state to decide if the iframe is ready.</p>
<p>If we extract the function called by document ready in a separate function and call it after a timeout of 100 ms. It works, but we can't take the chance in production with a slow computer.</p>
<pre><code>$(document).ready(function() { setTimeout(ApplyGalleria, 100); });
</code></pre>
<p>My question: which jQuery event should we bind to to be able to execute our code when the dynamic iframe is ready and not just it's a parent?</p>
|
[
{
"answer_id": 205221,
"author": "Pier Luigi",
"author_id": 27789,
"author_profile": "https://Stackoverflow.com/users/27789",
"pm_score": 9,
"selected": true,
"text": "function callIframe(url, callback) {\n $(document.body).append('<IFRAME id=\"myId\" ...>');\n $('iframe#myId').attr('src', url);\n\n $('iframe#myId').load(function() {\n callback(this);\n });\n}\n"
},
{
"answer_id": 205280,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 4,
"selected": false,
"text": "<body>\nThe content of your IFrame\n<script type=\"text/javascript\">\n//<![CDATA[\n fireOnReadyEvent();\n parent.IFrameLoaded();\n//]]>\n</script>\n</body>\n"
},
{
"answer_id": 205539,
"author": "EtienneT",
"author_id": 9140,
"author_profile": "https://Stackoverflow.com/users/9140",
"pm_score": 2,
"selected": false,
"text": "$(document).ready $('#TB_iframeContent', top.document).load(ApplyGalleria);\n"
},
{
"answer_id": 735199,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "$('iframe').ready(function() {\n $('body', $('iframe').contents()).html('Hello World!');\n});\n $(function() {\n function manipIframe() {\n el = $('body', $('iframe').contents());\n if (el.length != 1) {\n setTimeout(manipIframe, 100);\n return;\n }\n el.html('Hello World!');\n }\n manipIframe();\n});\n"
},
{
"answer_id": 1555751,
"author": "Danny G",
"author_id": 76302,
"author_profile": "https://Stackoverflow.com/users/76302",
"pm_score": 1,
"selected": false,
"text": "<iframe id=\"testframe\" src=\"about:blank\" onload=\"if (testframe.location.href != 'about:blank') testframe_loaded()\"></iframe>\n"
},
{
"answer_id": 11989472,
"author": "Pavel Savara",
"author_id": 129124,
"author_profile": "https://Stackoverflow.com/users/129124",
"pm_score": 1,
"selected": false,
"text": "\nvar url = \"http://example.com/my.pdf\";\n// show spinner\n$.mobile.showPageLoadingMsg('b', note, false);\n$.ajax({\n url: url,\n cache: true,\n mimeType: 'application/pdf',\n success: function () {\n // display cached data\n $(scroller).append('<embed type=\"application/pdf\" src=\"' + url + '\" />');\n // hide spinner\n $.mobile.hidePageLoadingMsg();\n }\n});\n \nHttpContext.Response.Expires = 1;\nHttpContext.Response.Cache.SetNoServerCaching();\nHttpContext.Response.Cache.SetAllowResponseInBrowserHistory(false);\nHttpContext.Response.CacheControl = \"Private\";\n"
},
{
"answer_id": 16290979,
"author": "Ricardo Freitas",
"author_id": 689223,
"author_profile": "https://Stackoverflow.com/users/689223",
"pm_score": 3,
"selected": false,
"text": "var iframe = window.frameElement;\n\nif (iframe){\n iframe.contentDocument = document;//normalization: some browsers don't set the contentDocument, only the contentWindow\n\n var parent = window.parent;\n $(parent.document).ready(function(){//wait for parent to make sure it has jQuery ready\n var parent$ = parent.jQuery;\n\n parent$(iframe).trigger(\"iframeloading\");\n\n $(function(){\n parent$(iframe).trigger(\"iframeready\");\n });\n\n $(window).load(function(){//kind of unnecessary, but here for completion\n parent$(iframe).trigger(\"iframeloaded\");\n });\n\n $(window).unload(function(e){//not possible to prevent default\n parent$(iframe).trigger(\"iframeunloaded\");\n });\n\n $(window).on(\"beforeunload\",function(){\n parent$(iframe).trigger(\"iframebeforeunload\");\n });\n });\n}\n $(function(){\n $(\"iframe\").on(\"iframeloading iframeready iframeloaded iframebeforeunload iframeunloaded\", function(e){\n console.log(e.type);\n });\n});\n"
},
{
"answer_id": 35317607,
"author": "Jon Freynik",
"author_id": 2109714,
"author_profile": "https://Stackoverflow.com/users/2109714",
"pm_score": 1,
"selected": false,
"text": "<script>\n (function($, document, undefined) {\n $.fn[\"iready\"] = function(callback) {\n var ifr = this.filter(\"iframe\"),\n arg = arguments,\n src = this,\n clc = null, // collection\n lng = 50, // length of time to wait between intervals\n ivl = -1, // interval id\n chk = function(ifr) {\n try {\n var cnt = ifr.contents(),\n doc = cnt[0],\n src = ifr.attr(\"src\"),\n url = doc.URL;\n switch (doc.readyState) {\n case \"complete\":\n if (!src || src === \"about:blank\") {\n // we don't care about empty iframes\n ifr.data(\"ready\", \"true\");\n } else if (!url || url === \"about:blank\") {\n // empty document still needs loaded\n ifr.data(\"ready\", undefined);\n } else {\n // not an empty iframe and not an empty src\n // should be loaded\n ifr.data(\"ready\", true);\n }\n\n break;\n case \"interactive\":\n ifr.data(\"ready\", \"true\");\n break;\n case \"loading\":\n default:\n // still loading\n break; \n }\n } catch (ignore) {\n // as far as we're concerned the iframe is ready\n // since we won't be able to access it cross domain\n ifr.data(\"ready\", \"true\");\n }\n\n return ifr.data(\"ready\") === \"true\";\n };\n\n if (ifr.length) {\n ifr.each(function() {\n if (!$(this).data(\"ready\")) {\n // add to collection\n clc = (clc) ? clc.add($(this)) : $(this);\n }\n });\n if (clc) {\n ivl = setInterval(function() {\n var rd = true;\n clc.each(function() {\n if (!$(this).data(\"ready\")) {\n if (!chk($(this))) {\n rd = false;\n }\n }\n });\n\n if (rd) {\n clearInterval(ivl);\n clc = null;\n callback.apply(src, arg);\n }\n }, lng);\n } else {\n clc = null;\n callback.apply(src, arg);\n }\n } else {\n clc = null;\n callback.apply(this, arguments);\n }\n return this;\n };\n }(jQuery, document));\n</script>\n"
},
{
"answer_id": 45440415,
"author": "udondan",
"author_id": 2753241,
"author_profile": "https://Stackoverflow.com/users/2753241",
"pm_score": 2,
"selected": false,
"text": "$('<iframe/>', {\n src: 'https://example.com/',\n load: function() {\n alert(\"loaded\")\n }\n}).appendTo('body');\n"
},
{
"answer_id": 61968548,
"author": "Crashalot",
"author_id": 144088,
"author_profile": "https://Stackoverflow.com/users/144088",
"pm_score": 2,
"selected": false,
"text": "$.ready load function onIframeReady($i, successFn, errorFn) {\n try {\n const iCon = $i.first()[0].contentWindow,\n bl = \"about:blank\",\n compl = \"complete\";\n const callCallback = () => {\n try {\n const $con = $i.contents();\n if($con.length === 0) { // https://git.io/vV8yU\n throw new Error(\"iframe inaccessible\");\n }\n\n\n successFn($con);\n } catch(e) { // accessing contents failed\n errorFn();\n }\n };\n const observeOnload = () => {\n $i.on(\"load.jqueryMark\", () => {\n try {\n const src = $i.attr(\"src\").trim(),\n href = iCon.location.href;\n if(href !== bl || src === bl || src === \"\") {\n $i.off(\"load.jqueryMark\");\n callCallback();\n }\n } catch(e) {\n errorFn();\n }\n });\n };\n if(iCon.document.readyState === compl) {\n const src = $i.attr(\"src\").trim(),\n href = iCon.location.href;\n if(href === bl && src !== bl && src !== \"\") {\n observeOnload();\n } else {\n callCallback();\n }\n } else {\n observeOnload();\n }\n} catch(e) {\n errorFn();\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9140/"
] |
205,112
|
<p>Is there any way to print in memory collection or variable size in WPF? </p>
<p>I am using the following code in which I print the ListView control. But when the content is larger than the vertical scroll bar takes over and cuts the content. </p>
<pre><code> PrintDialog printDialog = new PrintDialog();
printDialog.ShowDialog();
printDialog.PrintVisual(lvDocumentSummary, "testing printing!");
</code></pre>
|
[
{
"answer_id": 380522,
"author": "Ifeanyi Echeruo",
"author_id": 47702,
"author_profile": "https://Stackoverflow.com/users/47702",
"pm_score": 4,
"selected": true,
"text": "FlowDocument fd = new FlowDocument();\n\nforeach(object item in items)\n{\n fd.Blocks.Add(new Paragraph(new Run(item.ToString())));\n}\n\nfd.Print();\n PrintDialog pd = new PrintDialog();\npd.PrintDocument(fd);\n"
},
{
"answer_id": 56609431,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Print private void Button_Click(object sender, RoutedEventArgs e)\n {\n FlowDocument fd = new FlowDocument();\n foreach (var item in COLLECTION) //<- put your collection here\n {\n fd.Blocks.Add(new Paragraph(new Run(item.ToString())));\n }\n\n PrintDialog pd = new PrintDialog();\n if (pd.ShowDialog() != true) return;\n\n fd.PageHeight = pd.PrintableAreaHeight;\n fd.PageWidth = pd.PrintableAreaWidth;\n\n IDocumentPaginatorSource idocument = fd as IDocumentPaginatorSource;\n\n pd.PrintDocument(idocument.DocumentPaginator, \"Printing Flow Document...\");\n }\n }\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3797/"
] |
205,114
|
<p>I have an asp.net 2.0 page that contains 2 <code>UpdatePanels</code>.</p>
<p>The first panel contains a <code>TreeView</code> control, when I select a node in the three view control it triggers an update of the second <code>UpdatePanel</code> only. This much is behaving correctly.</p>
<p>There are two buttons on the page outside of an update panel (previous/next). These buttons trigger an update of both panels. The behaviour of the buttons is to select the adjacent node in the tree. The first time I click on one of these buttons I get the expected behaviour, and adjacent node is selected and the both panels are updated to reflect this change.</p>
<p>The problem happens when I click any of these buttons again. The selected node of the treeview seems to remember the previously selected node and the buttons act on this node. So the behaviour of the previous/next buttons is to do nothing or jump back two.</p>
<p><strong>Edit</strong> - Sample code that demonstrates my problem</p>
<p>The markup</p>
<pre><code> <asp:UpdatePanel ID="myTreeViewPanel" runat="server">
<ContentTemplate>
<asp:TreeView runat="server" ID="myTreeView" OnSelectedNodeChanged="myTreeView_SelectedNodeChanged">
<SelectedNodeStyle BackColor="#FF8000" />
</asp:TreeView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="myButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdatePanel ID="myLabelPanel" runat="server">
<ContentTemplate>
<asp:Label runat="server" ID="myLabel" Text="myLabel"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="myTreeView" EventName="SelectedNodeChanged" />
<asp:AsyncPostBackTrigger ControlID="myButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button runat="server" ID="myButton" Text="myButton" OnClick="myButton_Click" />
</code></pre>
<p>The code behind</p>
<pre><code> protected void Page_Load ( object sender, EventArgs e )
{
if ( !IsPostBack )
{
myTreeView.Nodes.Add( new TreeNode( "Test 1", "Test One" ) );
myTreeView.Nodes.Add( new TreeNode( "Test 2", "Test two" ) );
myTreeView.Nodes.Add( new TreeNode( "Test 3", "Test three" ) );
myTreeView.Nodes.Add( new TreeNode( "Test 4", "Test four" ) );
myTreeView.Nodes.Add( new TreeNode( "Test 5", "Test five" ) );
myTreeView.Nodes.Add( new TreeNode( "Test 6", "Test size" ) );
}
}
protected void myTreeView_SelectedNodeChanged ( object sender, EventArgs e )
{
UpdateLabel( );
}
protected void myButton_Click ( object sender, EventArgs e )
{
// here we just select the next node in the three
int index = myTreeView.Nodes.IndexOf( myTreeView.SelectedNode );
myTreeView.Nodes[ index + 1 ].Select( );
UpdateLabel( );
}
private void UpdateLabel ( )
{
myLabel.Text = myTreeView.SelectedNode.Value;
}
</code></pre>
<p>It is like the viewstate of the tree is not being saved?</p>
|
[
{
"answer_id": 206077,
"author": "tpower",
"author_id": 18107,
"author_profile": "https://Stackoverflow.com/users/18107",
"pm_score": 0,
"selected": false,
"text": "protected override object SaveViewState()\n{\n ViewState[\"SelectedNodePath\"] = myTreeView.SelectedNode.ValuePath;\n return base.SaveViewState();\n}\n\nprotected void Page_PreLoad(object sender, EventArgs e)\n{\n if (ViewState[\"SelectedNodePath\"] != null)\n {\n TreeNode node = myTreeView.FindNode(ViewState[\"SelectedNodePath\"].ToString());\n if (node != null)\n node.Select();\n }\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18107/"
] |
205,154
|
<p>I'm exploring git to see how it might work for my company. I've got git installed and I need to know a couple things:</p>
<ul>
<li>How can I set up a git server on my computer to act as my central repo?</li>
<li>I'm trying to figure out how to manage my workflow with just the GUI on Windows (using the GUI is a requirement). How do I take a bunch of files in a folder and get them into my GIT repo?</li>
</ul>
<p>If there's a good tutorial for each item I'm plenty happy looking there instead if you can point me in the right direction. Thanks!</p>
|
[
{
"answer_id": 205295,
"author": "Grant Limberg",
"author_id": 27314,
"author_profile": "https://Stackoverflow.com/users/27314",
"pm_score": 2,
"selected": false,
"text": "git init\n git add .\ngit commit -m \"Initial Import\"\n git clone projectFolder/ ProjectName.git\n git clone [user@]host.xz:/path/to/repo.git/\n git clone D:/path/to/repo.git/\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9401/"
] |
205,158
|
<p>Sorry, that title just hurts. I'm wondering if there is a Linq to collections extension method that collapses the following code segment into a single line:</p>
<pre><code>public IEnumerable<Child> GetAllChildren(IEnumerable<Parent> parents){
var result = new List<Child>();
foreach(Parent parent in parents)
foreach(Child child in parent.Children)
result.Add(child);
return result;
}
</code></pre>
<p>If you can collapse that into a single statement, try it on insane difficulty:</p>
<pre><code>public IEnumerable<Child> GetAllChildren(IEnumerable<Grandparent> nanas){
var result = new List<Child>();
foreach(Grandparent papa in nanas)
foreach(Parent parent in papa.Children)
foreach(Child child in parent.Children)
result.Add(child);
return result;
}
</code></pre>
|
[
{
"answer_id": 205169,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": false,
"text": "public IEnumerable<Child> GetAllChildren(IEnumerable<Parent> parents)\n{\n return from parent in parents\n from child in parent.Children\n select child;\n}\n public IEnumerable<Child> GetAllChildren(IEnumerable<Grandparent> nanas)\n{\n return from papa in nanas\n from parent in papa.Children\n from child in parent.Children\n select child;\n}\n return (from .....\n ...\n select child).ToList();\n"
},
{
"answer_id": 205309,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 4,
"selected": true,
"text": "return parents\n .SelectMany(p => p.Children);\n return oldies\n .SelectMany(grand => grand.Children)\n .SelectMany(parent => parent.Children);\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
205,159
|
<p>I would like to execute <code>ls</code> in a Perl program as part of a CGI script. For this I used <code>exec(ls)</code>, but this does not return from the <code>exec</code> call.</p>
<p>Is there a better way to get a listing of a directory in Perl?</p>
|
[
{
"answer_id": 205168,
"author": "holli",
"author_id": 18606,
"author_profile": "https://Stackoverflow.com/users/18606",
"pm_score": 3,
"selected": false,
"text": "$listing = `ls`;\n"
},
{
"answer_id": 205172,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 7,
"selected": true,
"text": "opendir my($dh), $dirname or die \"Couldn't open dir '$dirname': $!\";\nmy @files = readdir $dh;\nclosedir $dh;\n#print files...\n"
},
{
"answer_id": 206646,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 4,
"selected": false,
"text": "glob opendir"
},
{
"answer_id": 210841,
"author": "JDrago",
"author_id": 28758,
"author_profile": "https://Stackoverflow.com/users/28758",
"pm_score": 0,
"selected": false,
"text": "my @files = map { chomp; $_ } `find`;\n"
},
{
"answer_id": 3361544,
"author": "dynax60",
"author_id": 368067,
"author_profile": "https://Stackoverflow.com/users/368067",
"pm_score": 3,
"selected": false,
"text": "chdir $dir or die \"Cannot chroot to $dir: $!\\n\";\nmy @files = glob(\"*.txt\");\n"
},
{
"answer_id": 3458794,
"author": "Octoberdan",
"author_id": 189491,
"author_profile": "https://Stackoverflow.com/users/189491",
"pm_score": 3,
"selected": false,
"text": "File::Find::Rule->maxdepth(1)->directory->in($base_dir);\n #!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\n# See http://search.cpan.org/~rclamp/File-Find-Rule-0.32/README\nuse File::Find::Rule;\n\n# If a base directory was not past to the script, assume current working director\nmy $base_dir = shift // '.';\nmy $find_rule = File::Find::Rule->new;\n\n# Do not descend past the first level\n$find_rule->maxdepth(1);\n\n# Only return directories\n$find_rule->directory;\n\n# Apply the rule and retrieve the subdirectories\nmy @sub_dirs = $find_rule->in($base_dir);\n\n# Print out the name of each directory on its own line\nprint join(\"\\n\", @sub_dirs);\n"
},
{
"answer_id": 6587372,
"author": "Greg",
"author_id": 830252,
"author_profile": "https://Stackoverflow.com/users/830252",
"pm_score": 3,
"selected": false,
"text": "my $dir = </dir/path/*> \n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28280/"
] |
205,160
|
<p>We are running our Junit 4 test suite against Weblogic 9 in front of an Oracle 10 database (using Hudson as a continuous integration server) and occasionally we will get an ORA-12519 crash during script teardown. However, the error is very intermittent: </p>
<ul>
<li>It usually happens for the same Test class </li>
<li>It doesn't always happen for the same test cases (sometimes they pass) </li>
<li>It doesn't happen for the same number of test cases (anywhere from 3-9) </li>
<li>Sometimes it doesn't happen at all, everything passes </li>
</ul>
<p>While I can't guarantee this doesn't happen locally (when running against the same database, of course), I have run the same suite of class multiple times with no issues.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 9561838,
"author": "edwardsmatt",
"author_id": 91362,
"author_profile": "https://Stackoverflow.com/users/91362",
"pm_score": 5,
"selected": false,
"text": "SQL*Plus SYSTEM alter system set processes=150 scope=spfile;"
},
{
"answer_id": 36326337,
"author": "Rahul Vishwakarma",
"author_id": 5312512,
"author_profile": "https://Stackoverflow.com/users/5312512",
"pm_score": 2,
"selected": false,
"text": "Thread.sleep() connection.close();"
},
{
"answer_id": 41226131,
"author": "Shendor",
"author_id": 871542,
"author_profile": "https://Stackoverflow.com/users/871542",
"pm_score": 1,
"selected": false,
"text": "SpringJUnit4ClassRunner @DirtiesContext"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/410/"
] |
205,165
|
<p>As you may already know, the .NET Framework's <a href="http://msdn.microsoft.com/en-us/library/ms173121.aspx" rel="noreferrer"><em>protected internal</em></a> access modifier works in a strange way: It doesn't mean the class is <em>protected</em> <strong>AND</strong> <em>internal</em>, it says the class is <em>protected</em> <strong>OR</strong> <em>internal</em>; that is, the modified class or member can be accessed from whitin the same assembly <strong>as well as</strong> from the same hierarchy.</p>
<p>So, knowing this: When would you use it? Can you give an example? Is there a good, <em>illuminating</em> usage example inside .NET Base Class Library?</p>
|
[
{
"answer_id": 205191,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 4,
"selected": true,
"text": "ToString() ToPersistableString() internal protected AccessibilityNotifyClients Control protected internal CheckedItemCollection CheckListBox"
},
{
"answer_id": 9251173,
"author": "stackoverflowuser",
"author_id": 237121,
"author_profile": "https://Stackoverflow.com/users/237121",
"pm_score": 2,
"selected": false,
"text": "public abstract class Controller : ControllerBase, <Omitted Interfaces>\n{\n protected internal ViewResult View() {\n return View(null /* viewName */, null /* masterName */, null /* model */);\n }\n\n protected internal ContentResult Content(string content) {\n return Content(content, null /* contentType */);\n }\n\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18552/"
] |
205,179
|
<p>What is a <code>DOCVARIABLE</code> in Microsoft Word 2003? How do I set it? How do I make it display in my Word document?</p>
|
[
{
"answer_id": 205210,
"author": "Chris Serra",
"author_id": 13435,
"author_profile": "https://Stackoverflow.com/users/13435",
"pm_score": 3,
"selected": false,
"text": "Sub GetSetDocVars()\n\nDim fName As String\nfName = \"Jeff Smith\"\n' Set contents of variable \"fName\" in a document using a document\n' variable called \"FullName\".\nActiveDocument.Variables.Add Name:=\"FullName\", Value:=fName\n' Retrieve the contents of the document variable.\nMsgBox ActiveDocument.Variables(\"FullName\").Value\n\nEnd Sub\n"
},
{
"answer_id": 57160389,
"author": "wojtekc",
"author_id": 1631574,
"author_profile": "https://Stackoverflow.com/users/1631574",
"pm_score": 0,
"selected": false,
"text": "Sub GetVariables()\n ' Declaration of output variavle, which is a string\n Dim output As String\n output = \"\"\n\n For Each Variable In ActiveDocument.Variables\n ' & is used for string concatenation.\n output = output & Variable.Name & \" = \" & Variable & vbNewLine\n Next\n\n MsgBox output\nEnd Sub\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5653/"
] |
205,180
|
<p>In a Web application, is it possible to force a PDF file to be printed on the client? If the browser is configured to open the PDF inside the window, I guess that calling window.print() will work, but some browsers (like mine) are configured to open the PDF externally.</p>
|
[
{
"answer_id": 4655430,
"author": "taeyoung",
"author_id": 570957,
"author_profile": "https://Stackoverflow.com/users/570957",
"pm_score": 3,
"selected": false,
"text": "<html>\n<script language=\"javascript\">\ntimerID = setTimeout(\"exPDF.print();\", 1000);\n</script>\n<body>\n<object id=\"exPDF\" type=\"application/pdf\" data=\"111.pdf\" width=\"100%\" height=\"500\"/>\n</body>\n</html>\n"
},
{
"answer_id": 21181994,
"author": "Simone",
"author_id": 3203075,
"author_profile": "https://Stackoverflow.com/users/3203075",
"pm_score": 0,
"selected": false,
"text": "<?php\n\n// 1. GET the jnlp file with curl\n\n$ch = curl_init();\ncurl_setopt($ch, CURLOPT_URL, \"http://www.pdfprint.it/printPdf?auth=XXXX\"); \ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //return the transfer as a string \n$jnlp = curl_exec($ch);\ncurl_close($ch); \n\n$pdfDoc =\"example.pdf\";\n\n\n//2. put in the jnlp your PDF document base64 encoded\n\n$jnlp = str_replace(\"####\", base64_encode(file_get_contents($pdfDoc)),$jnlp);\n\n\n//3. echo the jnlp file \n\nheader('Content-type: application/x-java-jnlp-file');\n\necho $jnlp;\n"
},
{
"answer_id": 47855359,
"author": "Ali",
"author_id": 6741585,
"author_profile": "https://Stackoverflow.com/users/6741585",
"pm_score": 1,
"selected": false,
"text": " <button type=\"button\" onclick=\"printJS('docs/printjs.pdf')\">\n Print PDF\n </button>"
},
{
"answer_id": 67877878,
"author": "konnic",
"author_id": 16146239,
"author_profile": "https://Stackoverflow.com/users/16146239",
"pm_score": 0,
"selected": false,
"text": "print() // create iframe element\nconst iframe = document.createElement('iframe');\n\n// create object URL for your blob or file and set it as the iframe's src\niframe.src = window.URL.createObjectURL(fileOrBlob);\niframe.name = 'pdf';\n\n// call the print method in the iframe onload handler\niframe.onload = () => {\n const pdfFrame = window.frames[\"pdf\"];\n pdfFrame.focus();\n pdfFrame.print();\n}\ndocument.body.appendChild(iframe);\n iframe.hidden = true;"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2680/"
] |
205,182
|
<p>Is there a way of reusing the same resultMap multiple times in a single query.</p>
<p>For example, suppose I have a "foo" resultMap:</p>
<pre><code><resultMap id="foo" class="Foo">
<result property="Bar" column="bar" />
</resultMap>
</code></pre>
<p>Is there a way to define another resultMap that reuses the above for different columns? Something like...</p>
<pre><code><resultMap id="fizz"class="Fizz">
<result property="Foo1" column="bar=bar1" resultMapping="foo" />
<result property="Foo2" column="bar=bar2" resultMapping="foo" />
<result property="Foo3" column="bar=bar3" resultMapping="foo" />
</resultMap>
</code></pre>
|
[
{
"answer_id": 205257,
"author": "James Rose",
"author_id": 9703,
"author_profile": "https://Stackoverflow.com/users/9703",
"pm_score": 3,
"selected": true,
"text": "<result property=\"Foo1\" column=\"bar1Id\" select=\"selectFoo\"/> selectFoo fooMap Foo <result property=\"Foo1\" resultMap=\"fooMap\"/> Foos <result property=\"foo1.bar\" column=\"foo1bar\"/> <result property=\"foo2.bar\" column=\"foo2bar\"/>"
},
{
"answer_id": 11127823,
"author": "duffy356",
"author_id": 1358430,
"author_profile": "https://Stackoverflow.com/users/1358430",
"pm_score": 1,
"selected": false,
"text": "<resultMap id=\"document\" class=\"Document\"> \n <result property=\"Id\" column=\"Document_ID\"/>\n <result property=\"Title\" column=\"Document_Title\"/>\n <discriminator column=\"Document_Type\" type=\"string\"/>\n <subMap value=\"Book\" resultMapping=\"book\"/>\n <subMap value=\"Newspaper\" resultMapping=\"newspaper\"/>\n</resultMap>\n\n<resultMap id=\"book\" class=\"Book\" extends=\"document\"> \n <property=\"PageNumber\" column=\"Document_PageNumber\"/>\n</resultMap>\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4094/"
] |
205,188
|
<p>There seems to be lots of different ways to register assemblies with the GAC, as in, they 'work'. However, what's the "proper" way of doing it?</p>
<p>In response to Lou Franco (and gacutil):</p>
<p>I'm using Gacutil for development, but it seems to me to be not the proper way to install it, since gacutil isn't included in the basic .NET utilities past .NET 1.1 - it's only a developer tool.</p>
<p>Additional: Gacutil (as seen in responses below) is not redistributable, and therefore should not be used in any app that you intend to give to people who are not developers. AKA, customers. See <a href="http://blogs.msdn.com/astebner/archive/2006/11/04/why-to-not-use-gacutil-exe-in-an-application-setup.aspx" rel="noreferrer">This blog post (and comments) by Aaron Stebner</a>.</p>
<p>In response to using WIX:</p>
<p>WIX might be great and all, but how does it work under the hood? What details makes the way WIX installs the assembly the right way to install it? How does it look it up? Is it a system/.NET call? Is there some call in a dll buried somewhere in System32 that needs to be made? </p>
<p>(Edit: it looks like WIX uses MSI under the hood. See my comments in the accepted answer.)</p>
<p>Final edit: It looks like the correct way to install an assembly to the GAC is using windows installer, and nothing else. I'm going to give Wix a try. Thanks all!</p>
|
[
{
"answer_id": 205212,
"author": "Robert P",
"author_id": 18097,
"author_profile": "https://Stackoverflow.com/users/18097",
"pm_score": 2,
"selected": false,
"text": "System.EnterpriseServices.Internal.Publish GacInstall"
},
{
"answer_id": 205223,
"author": "Mathieu Garstecki",
"author_id": 22078,
"author_profile": "https://Stackoverflow.com/users/22078",
"pm_score": -1,
"selected": false,
"text": "gacutil -i Library.dll %SystemRoot%\\Microsoft.Net\\Framework\\v1.1.4322\\gacutil -i\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18097/"
] |
205,190
|
<p>Clearly the following is incorrect.</p>
<pre><code>INSERT INTO `aTable` (`A`,`B`) VALUES((SELECT MAX(`A`) FROM `aTable`)*2),'name');
</code></pre>
<p>I get the value:</p>
<p>SQL query: </p>
<pre><code>INSERT INTO `aTable` (`A`, `B` )
VALUES
(
(
SELECT MAX(`A`)
FROM `aTable`
) *2
, 'name'
)
</code></pre>
<p>MySQL said:</p>
<p>1093 - You can't specify target table 'aTable' for update in FROM clause </p>
<p>So, I'm trying to make a bitmap table, each row corresponds to one Bit, and has a 'map' value.</p>
<p>To insert in the table, I don't want to do two queries, I want to do one.
How should I do this?</p>
<p>No one commented on this, but since I am trying to make a bitmap, it should be * 2 not ^ 2, my mistake, please note that is why the comments often say ^ 2, it was an error in the version that the commenters read.</p>
|
[
{
"answer_id": 205844,
"author": "Leonel Martins",
"author_id": 26673,
"author_profile": "https://Stackoverflow.com/users/26673",
"pm_score": 5,
"selected": true,
"text": "insert into aTable select max(a)^2, 'name' from aTable;\n insert into aTable select max(a)^2, 'name' from aTable group by B;\n insert into aTable select max(a)^2, 'name' from aTable, bTable;\n"
},
{
"answer_id": 7960671,
"author": "Hoser",
"author_id": 1022818,
"author_profile": "https://Stackoverflow.com/users/1022818",
"pm_score": 4,
"selected": false,
"text": "INSERT INTO tableA SET fieldA = (SELECT max(x.fieldA) FROM tableA x)+1;\n INSERT INTO tableA SET secondaryKey = 123, fieldA = COALESCE((SELECT max(x.fieldA) FROM tableA x WHERE x.secondaryKey = 123)+1,1);\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/144/"
] |
205,239
|
<p>Consider the following interface in Java:</p>
<pre><code>public interface I {
public final String KEY = "a";
}
</code></pre>
<p>And the following class:</p>
<pre><code>public class A implements I {
public String KEY = "b";
public String getKey() {
return KEY;
}
}
</code></pre>
<p>Why is it possible for class A to come along and override interface I's final constant?</p>
<p>Try for yourself:</p>
<pre><code>A a = new A();
String s = a.getKey(); // returns "b"!!!
</code></pre>
|
[
{
"answer_id": 205249,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 5,
"selected": false,
"text": "public class A implements I {\n public String KEY = \"b\";\n\n public String getKey() {\n String KEY = \"c\";\n return KEY;\n }\n}\n"
},
{
"answer_id": 205268,
"author": "Steve B.",
"author_id": 19479,
"author_profile": "https://Stackoverflow.com/users/19479",
"pm_score": 2,
"selected": false,
"text": "public class A implements I {\n public String KEY = \"B\";\n\n public static void main(String args[])\n {\n A t = new A();\n System.out.println(t.KEY);\n System.out.println(((I) t).KEY);\n }\n}\n A.KEY=\"C\" <-- this compiles.\n public class C implements I{\n\n public static void main (String args[])\n {\n C t = new C();\n c.KEY=\"V\"; <--- compiler error ! can't assign to final\n\n }\n}\n"
},
{
"answer_id": 205358,
"author": "Jorn",
"author_id": 8681,
"author_profile": "https://Stackoverflow.com/users/8681",
"pm_score": 2,
"selected": false,
"text": "I.KEY //returns \"a\"\nB.KEY //returns \"b\"\n"
},
{
"answer_id": 205427,
"author": "André",
"author_id": 9683,
"author_profile": "https://Stackoverflow.com/users/9683",
"pm_score": 5,
"selected": true,
"text": "public class Person {\n private final String name;\n private final int age;\n private final int iq = 110;\n private final Object country = \"South Africa\";\n\n public Person(String name, int age) {\n this.name = name;\n this.age = age;\n }\n\n public String toString() {\n return name + \", \" + age + \" of IQ=\" + iq + \" from \" + country;\n }\n}\n import java.lang.reflect.Field;\n\npublic class FinalFieldChange {\n private static void change(Person p, String name, Object value)\n throws NoSuchFieldException, IllegalAccessException {\n Field firstNameField = Person.class.getDeclaredField(name);\n firstNameField.setAccessible(true);\n firstNameField.set(p, value);\n }\n public static void main(String[] args) throws Exception {\n Person heinz = new Person(\"Heinz Kabutz\", 32);\n change(heinz, \"name\", \"Ng Keng Yap\");\n change(heinz, \"age\", new Integer(27));\n change(heinz, \"iq\", new Integer(150));\n change(heinz, \"country\", \"Malaysia\");\n System.out.println(heinz);\n }\n}\n Ng Keng Yap, 27 of IQ=110 from Malaysia Note, no exceptions, no complaints, and an incorrect IQ result. It seems that if we set a\n Ng Keng Yap, 27 of IQ=110 from Malaysia When Narve Saetre mailed me that he managed to change a final field in JDK 5 using\n import java.lang.reflect.Field;\n\npublic class FinalStaticFieldChange {\n /** Static fields of type String or primitive would get inlined */\n private static final String stringValue = \"original value\";\n private static final Object objValue = stringValue;\n\n private static void changeStaticField(String name)\n throws NoSuchFieldException, IllegalAccessException {\n Field statFinField = FinalStaticFieldChange.class.getDeclaredField(name);\n statFinField.setAccessible(true);\n statFinField.set(null, \"new Value\");\n }\n\n public static void main(String[] args) throws Exception {\n changeStaticField(\"stringValue\");\n changeStaticField(\"objValue\");\n System.out.println(\"stringValue = \" + stringValue);\n System.out.println(\"objValue = \" + objValue);\n System.out.println();\n }\n}\n"
},
{
"answer_id": 14690836,
"author": "Arnaldo Ignacio Gaspar Véjar",
"author_id": 1843385,
"author_profile": "https://Stackoverflow.com/users/1843385",
"pm_score": 2,
"selected": false,
"text": "public interface I {\n public final String KEY = \"a\";\n}\n public class A implements I {\n public String KEY = \"b\";\n\n public String getKey() {\n return KEY; // returns \"b\"\n }\n\n public static String getParentKey(){\n return KEY; // returns \"a\"\n }\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24545/"
] |
205,240
|
<p>Is it possible with Axis2 and Eclipse to generate a Web Service client and have it use java types that you already have in packages instead of creating it's own types. Reason being of course if I have type A already created and it creates it's own Type A I can't just assign variable of type A to variable of type B.</p>
<p>The wsdl is being generated from a Web Service deployed to an application server.
If it's not possible to generate it from that would it be possible to generate a client from the already existing java files.</p>
|
[
{
"answer_id": 206188,
"author": "Michael Sharek",
"author_id": 1958,
"author_profile": "https://Stackoverflow.com/users/1958",
"pm_score": 3,
"selected": true,
"text": "serviceClient = new RPCServiceClient();\nOptions options = serviceClient.getOptions();\n\nEndpointReference targetEPR = new EndpointReference(\"http://myservice\");\n\noptions.setTo(targetEPR);\n\nQName methodName = new QName(\"ns\",\"methodName\");\n\nClass<?>[] returnTypes = new Class[] { String.class };\n\nObject[] args = new Object[] { \"parameter\" };\n\nObject[] response = serviceClient.invokeBlocking(methodName, args,\n returnTypes);\n"
},
{
"answer_id": 2872633,
"author": "Parth",
"author_id": 344993,
"author_profile": "https://Stackoverflow.com/users/344993",
"pm_score": 0,
"selected": false,
"text": "//common interface for response handlers...\n//implement this for diff. web service/methods\npublic interface WSRespHandler{\n public Object getMeResp(Object respData);\n}\n\n\n//pass particular handler to client when you call some WS\npublic class WebServiceClient {\n public Object getResp(WSRespHandler respHandler) {\n ..\n\n return repHandler.getMeResp(xmlData);\n }\n}\n"
},
{
"answer_id": 14460708,
"author": "davidfm",
"author_id": 1732156,
"author_profile": "https://Stackoverflow.com/users/1732156",
"pm_score": 0,
"selected": false,
"text": " %AXIS2_HOME%\\bin\\WSDL2Java -uri <wsdl file path> -p <package name> -u\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28288/"
] |
205,270
|
<p>My MFC application using the "ESRI MapObjects LT2" ActiveX plugin throws an ASSERT at me when closing it.
The error occurs in <code>cmdtarg.cpp</code>:</p>
<pre><code>CCmdTarget::~CCmdTarget()
{
#ifndef _AFX_NO_OLE_SUPPORT
if (m_xDispatch.m_vtbl != 0)
((COleDispatchImpl*)&m_xDispatch)->Disconnect();
ASSERT(m_dwRef <= 1); //<--- Fails because m_dwRef is 3
#endif
m_pModuleState = NULL;
}
</code></pre>
<p>I built the (native C++) application with VC9.
When I compile the application with VC6, it behaves nicely.</p>
<p>What could be the reason for this?</p>
|
[
{
"answer_id": 205639,
"author": "Alessandro Jacopson",
"author_id": 15485,
"author_profile": "https://Stackoverflow.com/users/15485",
"pm_score": 2,
"selected": false,
"text": "_ATL_DEBUG_INTERFACES _ATL_DEBUG_INTERFACES\n"
},
{
"answer_id": 205890,
"author": "foraidt",
"author_id": 27596,
"author_profile": "https://Stackoverflow.com/users/27596",
"pm_score": 1,
"selected": false,
"text": "_ATL_DEBUG_INTERFACES stdafx. #pragma once AddRef() Release() CMap1 CWnd CMyWnd::OnCreate() CMap1::Create()"
},
{
"answer_id": 785307,
"author": "foraidt",
"author_id": 27596,
"author_profile": "https://Stackoverflow.com/users/27596",
"pm_score": 2,
"selected": true,
"text": "void CMyWnd::OnDestroy()\n{\n // Apparently we have to disconnect the (ActiveX) Map control manually\n // with this undocumented method.\n COleControlSite* pSite = GetOleControlSite(MY_DIALOG_CONTROL_ID);\n if(NULL != pSite)\n {\n pSite->ExternalDisconnect();\n }\n\n CWnd::OnDestroy();\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27596/"
] |
205,271
|
<p>I've recently begun evaluating a few project management projects for the company I work for. It's the classic case - growing company looking for the right solution (meaning, free or really cheap). It's a combination shop - Windows, Macs, and Linux on the desktop. The tech savviness, of course, ranges from newbie to unix guru. </p>
<p>I have yet to find anything really close to a total solution. I don't expect to find one, but I am looking for suggestions/guidance/any sort of feedback based on people's experience.</p>
<p>What I'm looking for:</p>
<ul>
<li>web based</li>
<li>methodology independent (not looking for an agile solution, etc.)</li>
<li>free or really cheap</li>
<li>document management</li>
<li>timelines and milestones</li>
<li>task tracking and assigning </li>
<li>reporting</li>
<li>source control</li>
<li>development wiki</li>
</ul>
<p>I've looked at Trac, Projectivity, Basecamp, JIRA, RT, XPlanner, and SharedPlan. I've stayed away from Bugzilla due to previous unhappy experiences with it. None of these things really does everything - some are extendable, but I'd check here before going down that path.</p>
<p>Thanks,</p>
|
[
{
"answer_id": 1051092,
"author": "Kasper",
"author_id": 23499,
"author_profile": "https://Stackoverflow.com/users/23499",
"pm_score": 1,
"selected": false,
"text": "* web based\n* methodology independent \n* free or really cheap\n* document management\n* timelines and milestones\n* task tracking and assigning\n* reporting\n* source control\n* development wiki\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13483/"
] |
205,296
|
<p>I have a local svn repository in my PC, I have been using it for a hobby project and it wasn't meant to be accessible to anyone, so I commited files with passwords in them.</p>
<p>Now, I'm thinking of making the repository available for other people and I don't want to have that data there.</p>
<p>Is there a way to crawl the repository and replace all the passwords and account data with a text like "xxxxxxxxxx"?</p>
|
[
{
"answer_id": 205329,
"author": "Matt",
"author_id": 17803,
"author_profile": "https://Stackoverflow.com/users/17803",
"pm_score": 3,
"selected": false,
"text": "svnadmin dump > mysvn\n svnadmin load /path/to/new/repo < mysvn\n"
},
{
"answer_id": 6236215,
"author": "dr jerry",
"author_id": 288190,
"author_profile": "https://Stackoverflow.com/users/288190",
"pm_score": 3,
"selected": false,
"text": "svnadmin create /tmp/your_local_repo\n #!/bin/bash\nexit 0\n chmod +x /tmp/isd_gc/hooks/pre-revprop-change\n svnsync init --username yourname@youremail file:///tmp/your_local_repo https://yourproject.googlecode.com/svn \n svnsync sync --username yourname@youremail file:///tmp/your_local_repo\n svnadmin dump . > /tmp/tst_dump_gc.dmp\n svndumpfilter exclude /trunk/unwanted file_1.jsvg < /tmp/tst_dump_gc.dmp > /tmp/tst_dump_clean1.dmp\n svndumpfilter exclude /trunk/unwanted file_2.jsvg < /tmp/tst_dump_clean1.dmp > /tmp/tst_dump_clean2.dmp\n rm -rf /tmp/your_local_repo\n\nsvnadmin create /tmp/your_local_repo\n [/tmp]$svnadmin load --ignore-uuid your_local_repo < /tmp/tst_dump_clean2.dmp\n svnsync sync --username yourname@youremail https://yourproject.googlecode.com/svn\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
205,299
|
<p>I tried the following code in LINQPad and got the results given below:</p>
<pre><code>List<string> listFromSplit = new List<string>("a, b".Split(",".ToCharArray())).Dump();
listFromSplit.ForEach(delegate(string s)
{
s.Trim();
});
listFromSplit.Dump();
</code></pre>
<blockquote>
<p>"a" and " b"</p>
</blockquote>
<p>so the letter b didn't get the white-space removed as I was expecting...?</p>
<p>Anyone have any ideas</p>
<p>[NOTE: the .Dump() method is an extension menthod in LINQPad that prints out the contents of any object in a nice intelligently formatted way]</p>
|
[
{
"answer_id": 205306,
"author": "Sciolist",
"author_id": 16045,
"author_profile": "https://Stackoverflow.com/users/16045",
"pm_score": 4,
"selected": false,
"text": "var s = \" asd \";\ns.Trim();\n var s = \" asd \";\ns = s.Trim();\n var listFromSplit = \"a, b\".Split(',').Select(s=>s.Trim());\n"
},
{
"answer_id": 205339,
"author": "akmad",
"author_id": 1314,
"author_profile": "https://Stackoverflow.com/users/1314",
"pm_score": 4,
"selected": true,
"text": "s = s.Trim();\n List<string> temp = new List<string>(\"a, b\".Split(\",\".ToCharArray()));\nList<string> listFromSplit = new List<string>();\n\ntemp.ForEach(delegate(string s) \n{ \n listFromSplit.Add(s.Trim()); \n});\n\nlistFromSplit.Dump();\n string[] temp = \"a, b\".Split(\",\".ToCharArray());\nList<string> listFromSplit = new List<string>();\n\nforeach (string s in temp)\n{\n listFromSplit.Add(s.Trim()); \n};\n\nlistFromSplit.Dump();\n"
},
{
"answer_id": 205342,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "List<string> listFromSplit =\n new List<string>( \"a , b \".Split( new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries ));\n"
},
{
"answer_id": 205509,
"author": "akuhn",
"author_id": 24468,
"author_profile": "https://Stackoverflow.com/users/24468",
"pm_score": 1,
"selected": false,
"text": "var result = from each in listFromSplit select each.Trim();\n"
},
{
"answer_id": 584385,
"author": "mezoid",
"author_id": 39532,
"author_profile": "https://Stackoverflow.com/users/39532",
"pm_score": 2,
"selected": false,
"text": "var result = listFromSplit.Select(s => s.Trim());\n"
},
{
"answer_id": 11904279,
"author": "frax",
"author_id": 1552658,
"author_profile": "https://Stackoverflow.com/users/1552658",
"pm_score": 0,
"selected": false,
"text": " public static void TrimCollection(this IList<string> stringCollection) {\n\n for (int i = 0; i <= stringCollection.Count() - 1; i++)\n stringCollection[i] = stringCollection[i].Trim();\n\n }\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5351/"
] |
205,340
|
<p>I'm getting odd results from a <code>MySQL SELECT</code> query involving a <code>LEFT JOIN</code>, and I can't understand whether my understanding of <code>LEFT JOIN</code> is wrong or whether I'm seeing a genuinely odd behavior.</p>
<p>I have a two tables with a many-to-one relationship: For every record in <code>table 1</code> there are 0 or more records in <code>table 2</code>. I want to select all the records in table 1 with a column that counts the number of related records in table 2. As I understand it, <code>LEFT JOIN</code> should always return all records on the <code>LEFT</code> side of the statement.</p>
<p>Here's a test database that exhibits the problem:</p>
<pre><code>CREATE DATABASE Test;
USE Test;
CREATE TABLE Dates (
dateID INT UNSIGNED NOT NULL AUTO_INCREMENT,
date DATE NOT NULL,
UNIQUE KEY (dateID)
) TYPE=MyISAM;
CREATE TABLE Slots (
slotID INT UNSIGNED NOT NULL AUTO_INCREMENT,
dateID INT UNSIGNED NOT NULL,
UNIQUE KEY (slotID)
) TYPE=MyISAM;
INSERT INTO Dates (date) VALUES ('2008-10-12'),('2008-10-13'),('2008-10-14');
INSERT INTO Slots (dateID) VALUES (3);
</code></pre>
<p>The Dates table has three records, and the Slots 1 - and that record points to the third record in Dates.</p>
<p>If I do the following query..</p>
<pre><code>SELECT d.date, count(s.slotID) FROM Dates AS d LEFT JOIN Slots AS s ON s.dateID=d.dateID GROUP BY s.dateID;
</code></pre>
<p>..I expect to see a table with 3 rows in - two with a count of 0, and one with a count of 1. But what I actually see is this:</p>
<pre><code>+------------+-----------------+
| date | count(s.slotID) |
+------------+-----------------+
| 2008-10-12 | 0 |
| 2008-10-14 | 1 |
+------------+-----------------+
</code></pre>
<p>The first record with a zero count appears, but the later record with a zero count is ignored. </p>
<p>Am I doing something wrong, or do I just not understand what LEFT JOIN is supposed to do?</p>
|
[
{
"answer_id": 205372,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 4,
"selected": true,
"text": "GROUP BY d.dateID s.DateID NULL LEFT JOIN GROUP BY SELECT"
},
{
"answer_id": 205578,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 1,
"selected": false,
"text": "SELECT date, count(slotID) as slotCount\nFROM Dates LEFT OUTER JOIN Slots USING (dateID)\nGROUP BY (date)\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28299/"
] |
205,359
|
<p>This is similar to my previous posting. But this time I want to call a function that exists on the main mxml page.</p>
<p>This is my main mxml page:</p>
<p>main.mxml</p>
<pre><code><mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:ns1="*">
<mx:Script>
<![CDATA[
public function changeText(currentText:String):void{
switch (currentText){
case "changeText":
lblOne.text = "More Text";
}
}
]]>
</mx:Script>
<mx:HBox x="137.5" y="10" width="100%" height="100%">
<ns1:menu id="buttons"> </ns1:menu>
</mx:HBox>
<mx:Canvas x="137" y="88" width="408.5" height="200">
<mx:HBox x="0" y="10" width="388.5" height="190">
<mx:Panel width="388" height="179" layout="absolute">
<mx:Label x="10" y="10" text="Some Text" visible="{buttons.showLabel}" id="lblOne"/>
</mx:Panel>
</mx:HBox>
</mx:Canvas>
</mx:Application>
</code></pre>
<p>Here is my included page:</p>
<p>menu.mxml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300">
<mx:Script>
<![CDATA[
[Bindable] public var showLabel:Boolean = true;
]]>
</mx:Script>
<mx:MenuBar width="380" height="58"></mx:MenuBar>
<mx:Button x="10" y="10" width="80" label="Show" id="btnOne" click="this.showLabel=true;" />
<mx:Button x="94" y="10" width="80" label="Hide" id="btnTwo" click="this.showLabel=false;"/>
<mx:Button x="181" y="10" width="80" label="Run Function" id="btnThree" click="{changeText('changeText')}"/>
</mx:Canvas>
</code></pre>
<p>How do I call the changeText function from the button on menu.mxml?</p>
|
[
{
"answer_id": 205462,
"author": "Brandon",
"author_id": 23133,
"author_profile": "https://Stackoverflow.com/users/23133",
"pm_score": 3,
"selected": true,
"text": " <mx:Metadata>\n [Event(name=\"buttonClicked\", type=\"flash.events.Event\")]\n </mx:Metadata>\n\n <mx:Button x=\"10\" y=\"10\" width=\"80\" label=\"Show\" id=\"btnOne\" click=\"this.showLabel=true;dispatchEvent(new Event(\"buttonClicked\"));\"/>\n <ns1:menu id=\"buttons\" buttonClicked=\"changeText(\"Your Text\");\">\n buttons.addEventListener(\"buttonClicked\",changeText(\"Your Text\"));\n"
},
{
"answer_id": 1350709,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<mx:Button x=\"181\" y=\"10\" width=\"80\" label=\"Run Function\" id=\"btnThree\" click=\"{changeText('changeText')}\"/>\n <mx:Button x=\"181\" y=\"10\" width=\"80\" label=\"Run Function\" id=\"btnThree\" click=\"{parentDocument*.changeText('changeText')}\"/>**\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24563/"
] |
205,375
|
<p>I have a String such as: </p>
<pre><code>Cerepedia, una apliación web
</code></pre>
<p>I would like to transform it into something URL valid such as: </p>
<pre><code>Cerepedia,unaaplicacionweb
</code></pre>
<p><strong>Note:</strong> the special character transformation and spaces removal. </p>
<p>By the way, are commas allowed in URLs?</p>
|
[
{
"answer_id": 205423,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 2,
"selected": false,
"text": "public class AsciiUtils {\n\n /**\n * Contains a list of all the characters that map one to one for UNICODE.\n */\n private static final String PLAIN_ASCII = \n \"AaEeIiOoUu\" // grave\n + \"AaEeIiOoUuYy\" // acute\n + \"AaEeIiOoUuYy\" // circumflex\n + \"AaEeIiOoUuYy\" // tilde\n + \"AaEeIiOoUuYy\" // umlaut\n + \"Aa\" // ring\n + \"Cc\" // cedilla\n + \"Nn\" // n tilde (spanish)\n ;\n\n /**\n * Actual accented values, corresponds one to one with ASCII\n */\n private static final String UNICODE =\n \"\\u00C0\\u00E0\\u00C8\\u00E8\\u00CC\\u00EC\\u00D2\\u00F2\\u00D9\\u00F9\" \n +\"\\u00C1\\u00E1\\u00C9\\u00E9\\u00CD\\u00ED\\u00D3\\u00F3\\u00DA\\u00FA\\u00DD\\u00FD\" \n +\"\\u00C2\\u00E2\\u00CA\\u00EA\\u00CE\\u00EE\\u00D4\\u00F4\\u00DB\\u00FB\\u0176\\u0177\" \n +\"\\u00C2\\u00E2\\u00CA\\u00EA\\u00CE\\u00EE\\u00D4\\u00F4\\u00DB\\u00FB\\u0176\\u0177\" \n +\"\\u00C4\\u00E4\\u00CB\\u00EB\\u00CF\\u00EF\\u00D6\\u00F6\\u00DC\\u00FC\\u0178\\u00FF\" \n +\"\\u00C5\\u00E5\" \n +\"\\u00C7\\u00E7\" \n +\"\\u00D1\\u00F1\"\n ;\n\n // private constructor, can't be instanciated!\n private AsciiUtils() { \n }\n\n\n /**\n * Removes accentued from a string and replace with ascii equivalent\n * @param s The string to englishify\n * @return The string without the french and spanish stuff.\n */\n public static String convertNonAscii(String s) {\n\n StringBuilder b = new StringBuilder();\n\n int n = s.length();\n for (int i = 0; i < n; i++) {\n char c = s.charAt(i);\n int pos = UNICODE.indexOf(c);\n if (pos > -1) {\n b.append(PLAIN_ASCII.charAt(pos));\n } else {\n b.append(c);\n }\n }\n\n return b.toString();\n\n }\n\n}\n"
},
{
"answer_id": 221627,
"author": "Sergio del Amo",
"author_id": 2138,
"author_profile": "https://Stackoverflow.com/users/2138",
"pm_score": 0,
"selected": false,
"text": "public static String removeSpaces(String s) {\n StringTokenizer st = new StringTokenizer(s,\" \",false);\n String t=\"\";\n while (st.hasMoreElements()) t += st.nextElement();\n return t;\n}\n"
},
{
"answer_id": 222361,
"author": "Sergio del Amo",
"author_id": 2138,
"author_profile": "https://Stackoverflow.com/users/2138",
"pm_score": 0,
"selected": false,
"text": "String s = \"Cerepedia, una apliación web\";\nString ENCODING= \"uft-8\";\nString encoded_s = URLEncoder.encode(s,ENCODING); // Cerepedia+una+aplicaci%C3%83%C2%B3n+web\nString s_hexa_free = EncodingTableUtils.replaceHexa(,ENCODING)); // Cerepedia+una+aplicacion+web\n import java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Set;\n\npublic class EncodingTableUtils {\n public final static HashMap iso88591 = new HashMap();\n static {\n iso88591.put(\"%C3%A1\", \"a\"); // á\n iso88591.put(\"%C3%81\", \"A\"); // Á\n iso88591.put(\"%C3%A9\", \"e\"); // é\n iso88591.put(\"%C3%89\", \"E\"); // É\n iso88591.put(\"%C3%AD\", \"i\"); // í\n iso88591.put(\"%C3%8D\", \"I\"); // Í\n iso88591.put(\"%C3%93\", \"O\"); // Ó\n iso88591.put(\"%C3%B3\", \"o\"); // ó\n iso88591.put(\"%C3%BA\", \"u\"); // ú\n iso88591.put(\"%C3%9A\", \"U\"); // Ú\n iso88591.put(\"%C3%91\", \"N\"); // Ñ\n iso88591.put(\"%C3%B1\", \"n\"); // ñ\n }\n public final static HashMap utf8 = new HashMap();\n static {\n utf8.put(\"%C3%83%C2%A1\", \"a\"); // á\n utf8.put(\"%C3%83%EF%BF\", \"A\"); // Á\n utf8.put(\"%BD%C3%83%C2\", \"e\"); // é\n utf8.put(\"%A9%C3%83%E2\", \"E\"); // É\n utf8.put(\"%80%B0%C3%83\", \"i\"); // í\n utf8.put(\"%C2%AD%C3%83\", \"I\"); // Í\n utf8.put(\"%EF%BF%BD%C3\", \"O\"); // Ó\n utf8.put(\"%C3%83%C2%B3\", \"o\"); // ó\n utf8.put(\"%83%E2%80%9C\", \"u\"); // ú \n utf8.put(\"%C3%83%C2%BA\", \"U\"); // Ú\n utf8.put(\"%C3%83%C5%A1\", \"N\"); // Ñ\n utf8.put(\"%C3%83%E2%80\", \"n\"); // ñ\n }\n\n public final static HashMap enc_table = new HashMap();\n static {\n enc_table.put(\"iso-8859-1\", iso88591);\n enc_table.put(\"utf-8\", utf8);\n }\n\n\n /**\n * Replace Hexadecimal characters with equivalent english not special ones\n * <p>Example: á Hexa: %C3%A1 gets replaced with a</p>\n * @param s Usually a string coming from URLEncode.encode\n * @param enc Encoding UTF-8 or ISO-8850-1\n */\n public static String convertHexaDecimal(String s, String enc) {\n HashMap characters = (HashMap) enc_table.get(enc.toLowerCase());\n if(characters==null) return \"\";\n Set keys = characters.keySet();\n Iterator it = keys.iterator();\n while(it.hasNext()) {\n String key = (String) it.next();\n String regex = EscapeChars.forRegex(key);\n String replacement = (String) characters.get(key); \n s = s.replaceAll(regex, replacement); \n }\n return s;\n }\n}\n public final class EscapeChars {\n/**\n * Replace characters having special meaning in regular expressions\n * with their escaped equivalents, preceded by a '\\' character.\n *\n * <P>The escaped characters include :\n *<ul>\n *<li>.\n *<li>\\\n *<li>?, * , and +\n *<li>&\n *<li>:\n *<li>{ and }\n *<li>[ and ]\n *<li>( and )\n *<li>^ and $\n *</ul>\n */\n public static String forRegex(String aRegexFragment){\n final StringBuilder result = new StringBuilder();\n\n final StringCharacterIterator iterator = new StringCharacterIterator(aRegexFragment);\n char character = iterator.current();\n while (character != CharacterIterator.DONE ){\n /*\n * All literals need to have backslashes doubled.\n */\n if (character == '.') {\n result.append(\"\\\\.\");\n }\n else if (character == '\\\\') {\n result.append(\"\\\\\\\\\");\n }\n else if (character == '?') {\n result.append(\"\\\\?\");\n }\n else if (character == '*') {\n result.append(\"\\\\*\");\n }\n else if (character == '+') {\n result.append(\"\\\\+\");\n }\n else if (character == '&') {\n result.append(\"\\\\&\");\n }\n else if (character == ':') {\n result.append(\"\\\\:\");\n }\n else if (character == '{') {\n result.append(\"\\\\{\");\n }\n else if (character == '}') {\n result.append(\"\\\\}\");\n }\n else if (character == '[') {\n result.append(\"\\\\[\");\n }\n else if (character == ']') {\n result.append(\"\\\\]\");\n }\n else if (character == '(') {\n result.append(\"\\\\(\");\n }\n else if (character == ')') {\n result.append(\"\\\\)\");\n }\n else if (character == '^') {\n result.append(\"\\\\^\");\n }\n else if (character == '$') {\n result.append(\"\\\\$\");\n }\n else {\n //the char is not a special one\n //add it to the result as is\n result.append(character);\n }\n character = iterator.next();\n }\n return result.toString();\n }\n}\n"
},
{
"answer_id": 38610011,
"author": "Bhimreddy",
"author_id": 6634977,
"author_profile": "https://Stackoverflow.com/users/6634977",
"pm_score": -1,
"selected": false,
"text": " public class Test {\n\n public static void main(final String[] args) {\n String str = \"Cerepedia, una apliación web\";\n String[] parts = str.split(\" \");\n int sum=0;\n for (int i=0;i<=parts.length-1;i++) {\n sum = sum+parts[i].length();\n }\n\n int k=0;\n char[] url = new char[25];\n for (int i=0;i<=parts.length-1;i++) {\n char[] temp = parts[i].toCharArray();\n\n\n for(int j=0;j<temp.length;j++){\n\n url[k]=temp[j];\n k++;\n }\n\n }\n System.out.println(url);\n\n }\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
205,382
|
<p>I have the following C# which simply replaces parts of the input string that look like EQUIP:19d005 into URLs, like this:</p>
<pre><code>input = Regex.Replace(input, @"(EQUIP:)(\S+)", @"<a title=""View equipment item $2"" href=""/EquipmentDisplay.asp?eqnum=$2"">$1$2</a>", RegexOptions.IgnoreCase);
</code></pre>
<p>The HTML ends up looking like this.</p>
<pre><code><a title="View equipment item 19d005" href="/EquipmentDisplay.asp?eqnum=19d005">EQUIP:19d005</a>
</code></pre>
<p>The only trouble is that the destination page expects the eqnum querystring to be all UPPERCASE so it returns the correct equipment when eqnum=19D005 but fails if it receives eqnum=19d005.</p>
<p>I guess I can modify and correct EquipmentDisplay.asp's errant requirement of uppercase values however, if possible I'd like to make the C# code comply with the existing classic ASP page by uppercasing the $2 in the Regex.Replace statement above.</p>
<p>Ideally, I'd like the HTML returned to look like this:</p>
<pre><code><a title="View equipment item 19d005" href="/EquipmentDisplay.asp?eqnum=19D005">EQUIP:19d005</a>
</code></pre>
<p><em>Notice although the original string was EQUIP:19d005 (lowercase), only the eqnum= value is uppercased.</em></p>
<p>Can it be done and if so, what's the tidiest way to do it?</p>
|
[
{
"answer_id": 205413,
"author": "John Fiala",
"author_id": 9143,
"author_profile": "https://Stackoverflow.com/users/9143",
"pm_score": 0,
"selected": false,
"text": "input = Regex.Replace(input.ToUpper, @\"(EQUIP:)(\\S+)\", @\"<a title=\"\"View equipment item $2\"\" href=\"\"/EquipmentDisplay.asp?eqnum=$2\"\">$1$2</a>\", RegexOptions.IgnoreCase);"
},
{
"answer_id": 205422,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 2,
"selected": false,
"text": "var match = Regex.Match(input, @\"(EQUIP:)(\\S+)\", RegexOptions.IgnoreCase);\nvar input = String.Format( @\"<a title=\"\"View equipment item {1}\"\" href=\"\"/EquipmentDisplay.asp?eqnum={2}\"\">{0}{1}</a>\", \nmatch.Groups[1].Value,\nmatch.Groups[2].Value,\nmatch.Groups[2].Value.ToUpper());\n"
},
{
"answer_id": 205445,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": " static void Main(string[] args)\n {\n string input = \"EQUIP:12312dd23\";\n string output = Regex.Replace(input, @\"(EQUIP:)(\\S+)\", \n new MatchEvaluator(genURL), RegexOptions.IgnoreCase);\n Console.WriteLine(output);\n Console.ReadKey();\n }\n static string genURL(Match m)\n {\n return string.Format(@\"<a title=\"\"View item {0}\"\" \n href=\"\"/EqDisp.asp?eq={2}\"\">{1}{0}</a>\",\n m.Groups[2].Value,m.Groups[1].Value,m.Groups[2].Value.ToUpper());\n }\n"
},
{
"answer_id": 205448,
"author": "Duncan",
"author_id": 25035,
"author_profile": "https://Stackoverflow.com/users/25035",
"pm_score": 5,
"selected": true,
"text": "input = Regex.Replace(input, @\"(EQUIP:)(\\S+)\", m => string.Format(@\"<a title=\"\"View equipment item {1}\"\" href=\"\"/EquipmentDisplay.asp?eqnum={2}\"\">{0}{1}</a>\", m.Groups[1].Value, m.Groups[2].Value, m.Groups[2].Value.ToUpper()), RegexOptions.IgnoreCase);\n var input = Regex.Replace(input, @\"(EQUIP:)(\\S+)\", Evaluator, RegexOptions.IgnoreCase);\n\nprivate static string Evaluator(Match match)\n{\n return string.Format(@\"<a title=\"\"View equipment item {1}\"\" href=\"\"/EquipmentDisplay.asp?eqnum={2}\"\">{0}{1}</a>\", match.Groups[1].Value, match.Groups[2].Value, match.Groups[2].Value.ToUpper());\n}\n"
},
{
"answer_id": 205469,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 0,
"selected": false,
"text": "string input = \"EQUIP:19d005\";\nRegex regex = new Regex (@\"(EQUIP:)(\\S+)\", RegexOptions.IgnoreCase);\nstring eqlabel = regex.Replace(input, \"$1\");\nstring eqnum = regex.Replace(input, \"$2\");\nstring eqnumu = eqnum.ToUpperInvariant();\ninput = string.Format(@\"<a title=\"\"View equipment item {1}\"\" href=\"\"/EquipmentDisplay.asp?eqnum={2}\"\">{0}{1}</a>\", eqlabel, eqnum, eqnumu);\n"
},
{
"answer_id": 205586,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 0,
"selected": false,
"text": "public static string FormatToCustomAnchorTag(this string value)\n{\n\n return Regex.Replace(value.ToLower() + value.ToUpper(),\n @\"(?<equiplo>equip:)(?<equipnolo>\\S+)(?<equipup>EQUIP:)(?<equipnoup>\\S+)\",\n @\"<a title=\"\"View equipment item ${equipnolo}\"\" href=\"\"/EquipmentDisplay.asp?eqnum=${equipnoup}\"\">${equipup}${equipnolo}</a>\");\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7508/"
] |
205,386
|
<p>What are those bad habits you've developed since you've started coding in Cocoa?</p>
<p>I think making a list of bad habits and actively adding to it and, more importantly, breaking those habits is a good technique to produce your code quality. So start now, get your bad habits off your chest. Maybe other people share your bad habits. </p>
|
[
{
"answer_id": 205618,
"author": "Jablair",
"author_id": 24168,
"author_profile": "https://Stackoverflow.com/users/24168",
"pm_score": 3,
"selected": false,
"text": "self.displayName = name\n displayName = name\n"
},
{
"answer_id": 206002,
"author": "lfalin",
"author_id": 28106,
"author_profile": "https://Stackoverflow.com/users/28106",
"pm_score": 4,
"selected": false,
"text": "nil NSError**"
},
{
"answer_id": 217217,
"author": "mmalc",
"author_id": 23233,
"author_profile": "https://Stackoverflow.com/users/23233",
"pm_score": 4,
"selected": false,
"text": "NSError"
},
{
"answer_id": 225934,
"author": "Colin Barrett",
"author_id": 23106,
"author_profile": "https://Stackoverflow.com/users/23106",
"pm_score": 1,
"selected": false,
"text": "return self;"
},
{
"answer_id": 18596871,
"author": "Travis M.",
"author_id": 1446573,
"author_profile": "https://Stackoverflow.com/users/1446573",
"pm_score": 2,
"selected": false,
"text": "@interface MyViewController (){\n NSArray *_tableData;\n NSNumberFormatter *_numberFormat;\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23113/"
] |
205,393
|
<p>Is it possible to reload a page that was loaded thru link_to_remote? I'm doing this in my controller: <br></p>
<pre><code>def create
if captchas_verified
do_something
else
render :action=>'new'
end
</code></pre>
<p>But when the captchas is wrong, it do not render a form that is inside of the new template. By the way, in the webserver log, it shows that the templades was rendered.</p>
<p>Thanks!</p>
<p>UPDATED: Today i changed the render to:</p>
<pre><code>render(:update) { |page| page.call 'location.reload' }
</code></pre>
<p>But it makes me update the page that called the link_to_remote not the page that was opened thru the link_to_remote</p>
<p>UPDATED 2: I fixed using
page.replace_html "mydiv", :partial => "new"
instead of
page.call 'location.reload'</p>
|
[
{
"answer_id": 206115,
"author": "jdl",
"author_id": 9465,
"author_profile": "https://Stackoverflow.com/users/9465",
"pm_score": 1,
"selected": false,
"text": "render :update do |page| page << 'window.location.reload()' end\n"
},
{
"answer_id": 206144,
"author": "salt.racer",
"author_id": 757,
"author_profile": "https://Stackoverflow.com/users/757",
"pm_score": 3,
"selected": true,
"text": "render :update render :action render(:update) do |page|\n page.replace_html(\"div_to_update\", :partial => \"name_of_template\", :object => @object)\n page << \"alert('javascript can be inserted here as well')\"\nend\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18642/"
] |
205,411
|
<p>How would you go about creating a random alpha-numeric string that matches a certain regular expression?</p>
<p>This is specifically for creating initial passwords that fulfill regular password requirements.</p>
|
[
{
"answer_id": 648840,
"author": "Chas. Owens",
"author_id": 78259,
"author_profile": "https://Stackoverflow.com/users/78259",
"pm_score": 4,
"selected": false,
"text": "#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nuse String::Random qw/random_regex/;\n\nprint random_regex('[A-Za-z]{3}[0-9][A-Z]{2}[!@#$%^&*]'), \"\\n\";\n"
},
{
"answer_id": 15969145,
"author": "Tamlyn",
"author_id": 132208,
"author_profile": "https://Stackoverflow.com/users/132208",
"pm_score": 2,
"selected": false,
"text": "([A-PR-UWYZ]([0-9]([0-9]|[A-HJKSTUW])?|[A-HK-Y][0-9]([0-9]|[ABEHMNPRVWXY])?) ?[0-9][ABD-HJLNP-UW-Z]{2}|GIR0AA)\n D43WF\nB6 6SB\nMP445FR\nP9 7EX\nN9 2DH\nGQ28 4UL\nNH1 2SL\nKY2 9LS\nTE4Y 0AP\n"
},
{
"answer_id": 23230477,
"author": "Gajus",
"author_id": 368691,
"author_profile": "https://Stackoverflow.com/users/368691",
"pm_score": 2,
"selected": false,
"text": "$generator = new \\Gajus\\Parsley\\Generator();\n\n/**\n * Generate a set of random codes based on Parsley pattern.\n * Codes are guaranteed to be unique within the set.\n *\n * @param string $pattern Parsley pattern.\n * @param int $amount Number of codes to generate.\n * @param int $safeguard Number of additional codes generated in case there are duplicates that need to be replaced.\n * @return array\n */\n$codes = $generator->generateFromPattern('FOO[A-Z]{10}[0-9]{2}', 100);\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1550/"
] |
205,431
|
<p>I'm trying to draw images on the iPhone using with rounded corners, a la the contact images in the Contacts app. I've got code that generally work, but it occasionally crashes inside of the UIImage drawing routines with an <code>EXEC_BAD_ACCESS</code> - <code>KERN_INVALID_ADDRESS</code>. I thought this might be related to the <a href="https://stackoverflow.com/questions/158914/cropping-a-uiimage">cropping question</a> I asked a few weeks back, but I believe I'm setting up the clipping path correctly.</p>
<p>Here's the code I'm using - when it doesn't crash, the result looks fine and anybody looking to get a similar look is free to borrow the code.</p>
<pre><code>- (UIImage *)borderedImageWithRect: (CGRect)dstRect radius:(CGFloat)radius {
UIImage *maskedImage = nil;
radius = MIN(radius, .5 * MIN(CGRectGetWidth(dstRect), CGRectGetHeight(dstRect)));
CGRect interiorRect = CGRectInset(dstRect, radius, radius);
UIGraphicsBeginImageContext(dstRect.size);
CGContextRef maskedContextRef = UIGraphicsGetCurrentContext();
CGContextSaveGState(maskedContextRef);
CGMutablePathRef borderPath = CGPathCreateMutable();
CGPathAddArc(borderPath, NULL, CGRectGetMinX(interiorRect), CGRectGetMinY(interiorRect), radius, PNDegreeToRadian(180), PNDegreeToRadian(270), NO);
CGPathAddArc(borderPath, NULL, CGRectGetMaxX(interiorRect), CGRectGetMinY(interiorRect), radius, PNDegreeToRadian(270.0), PNDegreeToRadian(360.0), NO);
CGPathAddArc(borderPath, NULL, CGRectGetMaxX(interiorRect), CGRectGetMaxY(interiorRect), radius, PNDegreeToRadian(0.0), PNDegreeToRadian(90.0), NO);
CGPathAddArc(borderPath, NULL, CGRectGetMinX(interiorRect), CGRectGetMaxY(interiorRect), radius, PNDegreeToRadian(90.0), PNDegreeToRadian(180.0), NO);
CGContextBeginPath(maskedContextRef);
CGContextAddPath(maskedContextRef, borderPath);
CGContextClosePath(maskedContextRef);
CGContextClip(maskedContextRef);
[self drawInRect: dstRect];
maskedImage = UIGraphicsGetImageFromCurrentImageContext();
CGContextRestoreGState(maskedContextRef);
UIGraphicsEndImageContext();
return maskedImage;
}
</code></pre>
<p>and here's the crash log. It looks the same whenever I get one of these crashes</p>
<pre>
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x6e2e6181
Crashed Thread: 0
Thread 0 Crashed:
0 com.apple.CoreGraphics 0x30fe56d8 CGGStateGetRenderingIntent + 4
1 libRIP.A.dylib 0x33c4a7d8 ripc_RenderImage + 104
2 libRIP.A.dylib 0x33c51868 ripc_DrawImage + 3860
3 com.apple.CoreGraphics 0x30fecad4 CGContextDelegateDrawImage + 80
4 com.apple.CoreGraphics 0x30feca40 CGContextDrawImage + 368
5 UIKit 0x30a6a708 -[UIImage drawInRect:blendMode:alpha:] + 1460
6 UIKit 0x30a66904 -[UIImage drawInRect:] + 72
7 MyApp 0x0003f8a8 -[UIImage(PNAdditions) borderedImageWithRect:radius:] (UIImage+PNAdditions.m:187)
</pre>
|
[
{
"answer_id": 206005,
"author": "benzado",
"author_id": 10947,
"author_profile": "https://Stackoverflow.com/users/10947",
"pm_score": 1,
"selected": false,
"text": "CGPathRelease(borderPath)"
},
{
"answer_id": 510228,
"author": "PCheese",
"author_id": 61274,
"author_profile": "https://Stackoverflow.com/users/61274",
"pm_score": 2,
"selected": false,
"text": "EXC_BAD_ACCESS UIImage *originalImage = [UIImage imageNamed:@\"OriginalImage.png\"] \n[self performSelectorOnMainThread:@selector(displayImageWithRoundedCorners:) withObject:originalImage waitUntilDone:YES];\n"
},
{
"answer_id": 510760,
"author": "Jablair",
"author_id": 24168,
"author_profile": "https://Stackoverflow.com/users/24168",
"pm_score": 2,
"selected": false,
"text": "UIGraphicsBeginImageContext UIGraphicsBeginImageContext CGBitmapContextCreate"
},
{
"answer_id": 1307717,
"author": "MagicSeth",
"author_id": 131876,
"author_profile": "https://Stackoverflow.com/users/131876",
"pm_score": 8,
"selected": true,
"text": "UIImageView * roundedView = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@\"wood.jpg\"]];\n// Get the Layer of any view\nCALayer * l = [roundedView layer];\n[l setMasksToBounds:YES];\n[l setCornerRadius:10.0];\n\n// You can even add a border\n[l setBorderWidth:4.0];\n[l setBorderColor:[[UIColor blueColor] CGColor]];\n"
},
{
"answer_id": 1462318,
"author": "cuasiJoe",
"author_id": 138745,
"author_profile": "https://Stackoverflow.com/users/138745",
"pm_score": 5,
"selected": false,
"text": "appIconImage.image = [UIImage imageWithContentsOfFile:@\"image.png\"]; \nappIconImage.layer.masksToBounds = YES;\nappIconImage.layer.cornerRadius = 10.0;\nappIconImage.layer.borderWidth = 1.0;\nappIconImage.layer.borderColor = [[UIColor grayColor] CGColor];\n #import <QuartzCore/QuartzCore.h>\n"
},
{
"answer_id": 18585960,
"author": "Jonny",
"author_id": 129202,
"author_profile": "https://Stackoverflow.com/users/129202",
"pm_score": 5,
"selected": false,
"text": "#import <UIKit/UIKit.h>\n\n@interface UIImage (additions)\n-(UIImage*)makeRoundCornersWithRadius:(const CGFloat)RADIUS;\n@end\n #import \"UIImage+additions.h\"\n\n@implementation UIImage (additions)\n-(UIImage*)makeRoundCornersWithRadius:(const CGFloat)RADIUS {\n UIImage *image = self;\n\n // Begin a new image that will be the new image with the rounded corners\n // (here with the size of an UIImageView)\n UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);\n\n const CGRect RECT = CGRectMake(0, 0, image.size.width, image.size.height);\n // Add a clip before drawing anything, in the shape of an rounded rect\n [[UIBezierPath bezierPathWithRoundedRect:RECT cornerRadius:RADIUS] addClip];\n // Draw your image\n [image drawInRect:RECT];\n\n // Get the image, here setting the UIImageView image\n //imageView.image\n UIImage* imageNew = UIGraphicsGetImageFromCurrentImageContext();\n\n // Lets forget about that we were drawing\n UIGraphicsEndImageContext();\n\n return imageNew;\n}\n@end\n"
},
{
"answer_id": 24404939,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "@interface....\n\nIBOutlet UIImageView *testImg;\n\n@end\n -(void)viewDidLoad{\n testImg.layer.backgroundColor=[[UIColor clearColor] CGColor];\n testImg.layer.cornerRadius=20;\n testImg.layer.masksToBounds = YES;\n }\n"
},
{
"answer_id": 28317655,
"author": "user3536010",
"author_id": 3536010,
"author_profile": "https://Stackoverflow.com/users/3536010",
"pm_score": 0,
"selected": false,
"text": "UIImage *originalImage = [UIImage imageNamed:@\"OriginalImage.png\"] \n[self performSelectorOnMainThread:@selector(displayImageWithRoundedCorners:) withObject:originalImage waitUntilDone:YES];\n"
},
{
"answer_id": 54476845,
"author": "Naresh",
"author_id": 8090893,
"author_profile": "https://Stackoverflow.com/users/8090893",
"pm_score": 0,
"selected": false,
"text": "let imgView = UIImageView()\nimgView.frame = CGRect(x: 200, y: 200, width: 200, height: 200)\nimgView.image = UIImage(named: \"yourimagename\")\nimgView.imgViewCorners()\n//If you want complete round shape\n//imgView.imgViewCorners(width: imgView.frame.width)//Pass ImageView width\nview.addSubview(imgView)\n\nextension UIImageView {\n//If you want only round corners\nfunc imgViewCorners() {\n layer.cornerRadius = 10\n layer.borderWidth = 1.0\n layer.borderColor = UIColor.red.cgColor\n layer.masksToBounds = true\n}\n//If you want complete round shape\nfunc imgViewCorners(width:CGFloat) {\n layer.cornerRadius = width/2\n layer.borderWidth = 1.0\n layer.borderColor = UIColor.red.cgColor\n layer.masksToBounds = true\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24168/"
] |
205,435
|
<p>I keep getting an NHibernate.PersistentObjectException when calling session.Save() which is due to an uninitialized proxy passed to save(). If I fiddle with my cascade settings I can make it go away, but then child objects aren't being saved.</p>
<p>The only other fix I have found is by adding the following to my DefaultSaveEventListener.</p>
<pre><code> protected override bool ReassociateIfUninitializedProxy(object obj, global::NHibernate.Engine.ISessionImplementor source)
{
if (!NHibernateUtil.IsInitialized(obj))
NHibernateUtil.Initialize(obj);
return base.ReassociateIfUninitializedProxy(obj, source);
}
</code></pre>
<p>This is obviously not an ideal solution.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 2936444,
"author": "mathieu",
"author_id": 971,
"author_profile": "https://Stackoverflow.com/users/971",
"pm_score": 2,
"selected": false,
"text": "use ISession.Get() ISession.Load()"
},
{
"answer_id": 3309406,
"author": "Rabid",
"author_id": 123883,
"author_profile": "https://Stackoverflow.com/users/123883",
"pm_score": 2,
"selected": false,
"text": "DefaultSaveEventListener <event type=\"save-update\">\n <listener class=\"MyNamespace.MyCustomSaveEventListener, MyAssembly\" />\n</event>\n DefaultSaveEventListener DefaultSaveOrUpdateEventListener"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4590/"
] |
205,440
|
<p>I like to know if there is a way to read the user input inside a batch file, because i have a file named: "fif.bat" that recives two parameters (just call them <strong><em>paramA</em></strong> and <strong><em>paramB</em></strong>) so i execute the file like this:</p>
<pre><code>fif paramA paramB
</code></pre>
<p>I have to change paramA every month, but i call this file lot of times so i like to open a console and have printed this:</p>
<pre><code>fif paramA
</code></pre>
<p>So i only have to write paramB and change paramA when i want it.</p>
<p>PD: paramA is very large so it's very helpful if i can have it there instead of writing every time. And i don't want to make another batch file to call fif whit paramA.</p>
|
[
{
"answer_id": 205461,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 0,
"selected": false,
"text": "SET /P SET /P paramB=\"Prompt String: \"\n"
},
{
"answer_id": 205471,
"author": "Jeremy",
"author_id": 9266,
"author_profile": "https://Stackoverflow.com/users/9266",
"pm_score": 4,
"selected": true,
"text": "@ECHO OFF\nSET /p paramA=Parameter A:\nECHO you typed %paramA%\nPAUSE\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601/"
] |
205,444
|
<p>We are implementing an IP based geolocation service, and we need to find some IP's from various markets (LA, NY etc) to fully test the service.</p>
<p>Does anybody know of a directory where we could find what IP ranges are used where?</p>
<p>EDIT: We have already implemented the system, it uses a 3rd party DB and a webservice. We just want some IP's from known markets to verify its working properly.</p>
<p>I'm going to see if I can get what I need from the free maxmind database.</p>
|
[
{
"answer_id": 10543947,
"author": "Jay Prall",
"author_id": 56083,
"author_profile": "https://Stackoverflow.com/users/56083",
"pm_score": 0,
"selected": false,
"text": "ExitNodes server1, server2, server3\nStrictExitNodes 1\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
205,447
|
<p>I've got a model in CakePHP that doesn't have a table, called Upload. I've got a validation in this Model for a field called source_id.</p>
<p>I've got a form that builds a nice looking $this-data, giving me a well formated set, including:</p>
<pre><code>$this->data['Upload']['source_id']
</code></pre>
<p>However, the validation rule I have set doesn't seem to run at all. I copied this validation rule from another model where it does work, so I'm confident that it works:</p>
<pre><code>var $validate = array(
'source_id' => array(
rule' => 'numeric',
'required' => true,
'allowEmpty' => false,
'message' => 'Error!.'
)
);
</code></pre>
<p>Can you not validate fields for a model that lacks a database table?</p>
<p>The form uses the Upload model, and submits to another controller action method.</p>
<p>CakePHP 1.2, PHP/MySQL 5, XAMPP.</p>
|
[
{
"answer_id": 205459,
"author": "Justin",
"author_id": 43,
"author_profile": "https://Stackoverflow.com/users/43",
"pm_score": 4,
"selected": true,
"text": "$this->Upload->set($this->data);\n$this->Upload->validates();\n"
},
{
"answer_id": 298222,
"author": "Chris Hawes",
"author_id": 22776,
"author_profile": "https://Stackoverflow.com/users/22776",
"pm_score": 2,
"selected": false,
"text": "var $useTable = false;\n\nvar $_schema = array(\n 'name' =>array('type'=>'string', 'length'=>100), \n 'email' =>array('type'=>'string', 'length'=>255), \n 'phone' =>array('type'=>'string', 'length'=>20),\n 'subject' =>array('type'=>'string', 'length'=>255),\n 'message' =>array('type'=>'text')\n);\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43/"
] |
205,458
|
<p>For years, I've been using named blocks to limit the scope of temporary variables. I've never seen this done anywhere else, which makes me wonder if this is a bad idea. Especially since the Eclipse IDE flags these as warnings by default.</p>
<p>I've used this to good effect, I think, in my own code. But since it is un-idiomatic to the point where good programmers will distrust it when they see it, I really have two ways to go from here: </p>
<ol>
<li>avoid doing it, or </li>
<li>promote it, with the hope that it will become an idiom.</li>
</ol>
<p>Example (within a larger method):</p>
<pre><code>final Date nextTuesday;
initNextTuesday: {
GregorianCalendar cal = new GregorianCalendar();
... // About 5-10 lines of setting the calendar fields
nextTuesday = cal.getTime();
}
</code></pre>
<p>Here I'm using a GregorianCalendar just to initialize a date, and I want to make sure that I don't accidentally reuse it.</p>
<p>Some people have commented that you don't actually need to name the block. While that's true, a raw block looks even more like a bug, as the intent is unclear. Furthermore, naming something encourages you to think about the intention of the block. The goal here is to identify distinct sections of code, not to give every temporary variable its own scope.</p>
<p>Many people have commented that it's best to go straight to small methods. I agree that this should be your first instinct. However, there may be several mitigating factors:</p>
<ul>
<li>To even consider a named block, the code should be short, one-off code that will never be called elsewhere.</li>
<li>A named block is a quick way to organize an oversized method without creating a one-off method with a dozen parameters. This is especially true when a class is in flux, and the inputs are likely to change from version to version.</li>
<li>Creating a new method encourages its reuse, which may be ill-advised if the use cases aren't well-established. A named block is easier (psychologically, at least) to throw away.</li>
<li>Especially for unit tests, you may need to define a dozen different objects for one-off assertions, and they are just different enough that you can't (yet) find a way to consolidate them into a small number of methods, nor can you think of a way to distinguish them with names that aren't a mile long.</li>
</ul>
<p>Advantages of using the named scope:</p>
<ol>
<li>Can't accidentally reuse temporary variables</li>
<li>Limited scope gives garbage collector and JIT compiler more information about programmer intent</li>
<li>Block name provides a comment on a block of code, which I find more readable than open-ended comments</li>
<li>Makes it easier to refactor code out of a big method into little methods, or vice versa, since the named block is easier to separate than unstructured code.</li>
</ol>
<p>Disadvantages:</p>
<p>Not idiomatic: programmers who haven't seen this use of named blocks (i.e. everyone but me) assume it's buggy, since they can't find references to the block name. (Just like Eclipse does.) And getting something to become idiomatic is an uphill battle.</p>
<p>It can be used as an excuse for bad programming habits, such as:</p>
<ul>
<li>Making huge, monolithic methods where several small methods would be more legible.</li>
<li>Layers of indentation too deep to read easily.</li>
</ul>
<p>Note: I've edited this question extensively, based on some thoughtful responses. Thanks!</p>
|
[
{
"answer_id": 205548,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 3,
"selected": false,
"text": "final String example;\n{\n final StringBuilder sb = new StringBuilder();\n for(int i = 0; i < 100; i++)\n sb.append(i);\n example = sb.toString();\n\n}\n"
},
{
"answer_id": 26636059,
"author": "Floegipoky",
"author_id": 2517719,
"author_profile": "https://Stackoverflow.com/users/2517719",
"pm_score": 1,
"selected": false,
"text": "final Date nextTuesday;\ninitNextTuesday: {\n GregorianCalendar cal = new GregorianCalendar();\n ... // About 5-10 lines of setting the calendar fields\n nextTuesday = cal.getTime();\n}\n nextTuesday Date final Date nextTuesday;\ninitNextTuesday: {\n GregorianCalendar cal = new GregorianCalendar();\n //1\n //2\n //3\n //4\n //5\n nextTuesday = cal.getTime();\n}\n final Date nextTuesday = getNextTuesday();\n"
},
{
"answer_id": 29760231,
"author": "jin",
"author_id": 1371719,
"author_profile": "https://Stackoverflow.com/users/1371719",
"pm_score": 0,
"selected": false,
"text": "Type foo(args..){\n declare ret\n ...\n make temp vars to add information on ret\n ...\n\n make some more temp vars to add info on ret. not much related to above code. but previously declared vars are still alive\n ...\n\n\n return ret\n}\n"
},
{
"answer_id": 29770223,
"author": "Premraj",
"author_id": 1697099,
"author_profile": "https://Stackoverflow.com/users/1697099",
"pm_score": 1,
"selected": false,
"text": "class Break {\n public static void main(String args[]) {\n boolean t = true;\n first: {\n second: {\n third: {\n System.out.println(\"Before the break.\");\n if (t)\n break second; // break out of second block\n System.out.println(\"This won't execute\");\n }\n System.out.println(\"This won't execute\");\n }\n System.out.println(\"This is after second block.\");\n }\n }\n}\n class BreakLoop4 {\n public static void main(String args[]) {\n outer: for (int i = 0; i < 3; i++) {\n System.out.print(\"Pass \" + i + \": \");\n for (int j = 0; j < 100; j++) {\n if (j == 10)\n break outer; // exit both loops\n System.out.print(j + \" \");\n }\n System.out.println(\"This will not print\");\n }\n System.out.println(\"Loops complete.\");\n }\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18078/"
] |
205,468
|
<p>Hey everyone, I am researching a project where we would need to keep a value encrypted from the client all the way to a black box system without decrypting it at any point in between. We are using SSL between the browser and web server, but the values are automatically decrypted at the web server, which is what we need to keep from happening. We need to be able to pass it through the web server (still encrypted) and through other back end systems until it hits its final destination where it would be decrypted. </p>
<p>So my question is what options are available to us for maintaining an encrypted state for a value from the browser back, without decrypting it anywhere along the way?</p>
<p>Thanks
Mark</p>
|
[
{
"answer_id": 205484,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 2,
"selected": false,
"text": " client browser web server random server blackbox\nroute ---- SSL -------------><------------- not encrypted ------->\ndata *-------- PGP/GPG encrypted --------->\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15815/"
] |
205,521
|
<p>I'm trying to write a regex to replace all spaces that are not included in quotes so something like this:</p>
<pre><code>a = 4, b = 2, c = "space here"
</code></pre>
<p>would return this:</p>
<pre><code>a=4,b=2,c="space here"
</code></pre>
<p>I spent some time searching this site and I found a similar q/a ( <a href="https://stackoverflow.com/questions/79968/split-a-string-by-spaces-in-python#80449">Split a string by spaces -- preserving quoted substrings -- in Python</a> ) that would replace all the spaces inside quotes with a token that could be re-substituted in after wiping all the other spaces...but I was hoping there was a cleaner way of doing it.</p>
|
[
{
"answer_id": 205581,
"author": "Rômulo Ceccon",
"author_id": 23193,
"author_profile": "https://Stackoverflow.com/users/23193",
"pm_score": 2,
"selected": false,
"text": "mystring.scan(/((\".*?\")|([^ ]))/).map { |x| x[0] }.join\n"
},
{
"answer_id": 205862,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 3,
"selected": false,
"text": "result = string.gsub(/( |(\".*?\"))/, \"\\\\2\")\n"
},
{
"answer_id": 211024,
"author": "Senmiao Liu",
"author_id": 28809,
"author_profile": "https://Stackoverflow.com/users/28809",
"pm_score": 0,
"selected": false,
"text": "/( |(\"([^\"\\\\]|\\\\.)*\")|('([^'\\\\]|\\\\.)*'))/\n"
},
{
"answer_id": 211063,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 3,
"selected": false,
"text": "a = 4, b = 2, c = \"space\" here\"\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
205,522
|
<p>I have image data and i want to get a sub image of that to use as an opengl texture. </p>
<pre><code>glGenTextures(1, &m_name);
glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldName);
glBindTexture(GL_TEXTURE_2D, m_name);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_data);
</code></pre>
<p>How can i get a sub image of that image loaded as a texture. I think it has something to do with using glTexSubImage2D, but i have no clue how to use it to create a new texture that i can load. Calling: </p>
<pre><code>glTexSubImage2D(GL_TEXTURE_2D, 0, xOffset, yOffset, xWidth, yHeight, GL_RGBA, GL_UNSIGNED_BYTE, m_data);
</code></pre>
<p>does nothing that i can see, and calling glCopyTexSubImage2D just takes part of my framebuffer.
Thanks</p>
|
[
{
"answer_id": 205569,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "GL_UNPACK_ROW_LENGTH GL_UNPACK_ROW_LENGTH glPixelStorei( GL_UNPACK_ROW_LENGTH, img_width );\nchar *subimg = (char*)m_data + (sub_x + sub_y*img_width)*4;\nglTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, sub_width, sub_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, subimg );\nglPixelStorei( GL_UNPACK_ROW_LENGTH, 0 );\n glPixelStorei( GL_UNPACK_ROW_LENGTH, img_width );\nglPixelStorei( GL_UNPACK_SKIP_PIXELS, sub_x );\nglPixelStorei( GL_UNPACK_SKIP_ROWS, sub_y );\n\nglTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, sub_width, sub_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_data );\n\nglPixelStorei( GL_UNPACK_ROW_LENGTH, 0 );\nglPixelStorei( GL_UNPACK_SKIP_PIXELS, 0 );\nglPixelStorei( GL_UNPACK_SKIP_ROWS, 0 );\n GL_UNPACK_ROW_LENGTH glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, sub_width, sub_height, 0, GL_RGBA, GL_UNSIGNED_BYTES, NULL );\n\nfor( int y = 0; y < sub_height; y++ )\n{\n char *row = m_data + ((y + sub_y)*img_width + sub_x) * 4;\n glTexSubImage2D( GL_TEXTURE_2D, 0, 0, y, sub_width, 1, GL_RGBA, GL_UNSIGNED_BYTE, row );\n}\n"
},
{
"answer_id": 48332955,
"author": "vedranm",
"author_id": 1111634,
"author_profile": "https://Stackoverflow.com/users/1111634",
"pm_score": 2,
"selected": false,
"text": "glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_Pixels );\n glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, mWidth, mHeight, GL_RGBA, GL_UNSIGNED_BYTE, m_Pixels );\n auto *ptr = m_Pixels + (x + y * mWidth) * 4;\nfor( int i = 0; i < h; i++, ptr += mWidth * 4 ) {\n glTexSubImage2D( GL_TEXTURE_2D, 0, x, y+i, w, 1, GL_RGBA, GL_UNSIGNED_BYTE, ptr );\n}\n auto *ptr = m_Pixels + (y * mWidth) * 4;\nglTexSubImage2D( GL_TEXTURE_2D, 0, 0, y, mWidth, h, GL_RGBA, GL_UNSIGNED_BYTE, ptr );\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25893/"
] |
205,526
|
<p>I'm working on an application for work that is going to query our employee database. The end users want the ability to search based on the standard name/department criteria, but they also want the flexibility to query for all people with the first name of "James" that works in the Health Department. The one thing I want to avoid is to simply have the stored procedure take a list of parameters and generate a SQL statement to execute, since that would open doors to SQL injection at an internal level.</p>
<p>Can this be done?</p>
|
[
{
"answer_id": 205537,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": -1,
"selected": false,
"text": "SELECT EmpId, NameLast, NameMiddle, NameFirst, DepartmentName\n FROM dbo.Employee\n INNER JOIN dbo.Department ON dbo.Employee.DeptId = dbo.Department.Id\n WHERE IdCrq IS NOT NULL\n AND\n (\n @bitSearchFirstName = 0\n OR\n Employee.NameFirst = @vchFirstName\n )\n AND\n (\n @bitSearchMiddleName = 0\n OR\n Employee.NameMiddle = @vchMiddleName\n )\n AND\n (\n @bitSearchFirstName = 0\n OR\n Employee.NameLast = @vchLastName\n )\n AND\n (\n @bitSearchDepartment = 0\n OR\n Department.Id = @intDeptID\n )\n"
},
{
"answer_id": 205541,
"author": "BoltBait",
"author_id": 20848,
"author_profile": "https://Stackoverflow.com/users/20848",
"pm_score": 3,
"selected": false,
"text": "CREATE PROCEDURE ps_Customers_SELECT_NameCityCountry\n@Cus_Name varchar(30) = NULL,\n@Cus_City varchar(30) = NULL,\n@Cus_Country varchar(30) =NULL\nAS\nSELECT Cus_Name,\n Cus_City,\n Cus_Country\nFROM Customers\nWHERE Cus_Name = COALESCE(@Cus_Name,Cus_Name) AND\n Cus_City = COALESCE(@Cus_City,Cus_City) AND\n Cus_Country = COALESCE(@Cus_Country,Cus_Country)\n"
},
{
"answer_id": 205554,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 2,
"selected": false,
"text": "SELECT\n E.EmployeeID,\n E.LastName,\n E.FirstName\nWHERE\n E.FirstName = COALESCE(@FirstName, E.FirstName) AND\n E.LastName = COALESCE(@LastName, E.LastName) AND\n E.DepartmentID = COALESCE(@DepartmentID, E.DepartmentID)\n"
},
{
"answer_id": 205605,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 5,
"selected": true,
"text": "COALESCE CREATE PROCEDURE ps_Customers_SELECT_NameCityCountry\n @Cus_Name varchar(30) = NULL\n ,@Cus_City varchar(30) = NULL\n ,@Cus_Country varchar(30) = NULL\n ,@Dept_ID int = NULL\n ,@Dept_ID_partial varchar(10) = NULL\nAS\nSELECT Cus_Name\n ,Cus_City\n ,Cus_Country\n ,Dept_ID\nFROM Customers\nWHERE (@Cus_Name IS NULL OR Cus_Name LIKE '%' + @Cus_Name + '%')\n AND (@Cus_City IS NULL OR Cus_City LIKE '%' + @Cus_City + '%')\n AND (@Cus_Country IS NULL OR Cus_Country LIKE '%' + @Cus_Country + '%')\n AND (@Dept_ID IS NULL OR Dept_ID = @DeptID)\n AND (@Dept_ID_partial IS NULL OR CONVERT(varchar, Dept_ID) LIKE '%' + @Dept_ID_partial + '%')\n"
},
{
"answer_id": 205820,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE dbo.Test_Coalesce (\n my_id INT NOT NULL IDENTITY,\n my_string VARCHAR(20) NULL )\nGO\nINSERT INTO dbo.Test_Coalesce (my_string) VALUES (NULL)\nINSERT INTO dbo.Test_Coalesce (my_string) VALUES ('t')\nINSERT INTO dbo.Test_Coalesce (my_string) VALUES ('x')\nINSERT INTO dbo.Test_Coalesce (my_string) VALUES (NULL)\nGO\nDECLARE @my_string VARCHAR(20)\nSET @my_string = NULL\nSELECT * FROM dbo.Test_Coalesce WHERE my_string = COALESCE(@my_string, my_string)\nGO\n my_string = COALESCE(@my_string, my_string) =>\nmy_string = COALESCE(NULL, my_string) =>\nmy_string = my_string =>\nNULL = NULL\n SELECT\n my_id,\n my_string\nFROM\n dbo.Test_Coalesce\nWHERE\n (@my_string IS NULL OR my_string = @my_string)\n"
},
{
"answer_id": 28470325,
"author": "Manoj Pandey",
"author_id": 2443887,
"author_profile": "https://Stackoverflow.com/users/2443887",
"pm_score": 0,
"selected": false,
"text": "USE [AdventureWorks]\nGO\n\nCREATE PROCEDURE USP_GET_Contacts_DynSearch\n(\n -- Optional Filters for Dynamic Search\n @ContactID INT = NULL, \n @FirstName NVARCHAR(50) = NULL, \n @LastName NVARCHAR(50) = NULL, \n @EmailAddress NVARCHAR(50) = NULL, \n @EmailPromotion INT = NULL, \n @Phone NVARCHAR(25) = NULL\n)\nAS\nBEGIN\n SET NOCOUNT ON\n\n DECLARE\n @lContactID INT, \n @lFirstName NVARCHAR(50), \n @lLastName NVARCHAR(50), \n @lEmailAddress NVARCHAR(50), \n @lEmailPromotion INT, \n @lPhone NVARCHAR(25)\n\n SET @lContactID = @ContactID\n SET @lFirstName = LTRIM(RTRIM(@FirstName))\n SET @lLastName = LTRIM(RTRIM(@LastName))\n SET @lEmailAddress = LTRIM(RTRIM(@EmailAddress))\n SET @lEmailPromotion = @EmailPromotion\n SET @lPhone = LTRIM(RTRIM(@Phone))\n\n SELECT\n ContactID, \n Title, \n FirstName, \n MiddleName, \n LastName, \n Suffix, \n EmailAddress, \n EmailPromotion, \n Phone\n FROM [Person].[Contact]\n WHERE\n (@lContactID IS NULL OR ContactID = @lContactID)\n AND (@lFirstName IS NULL OR FirstName LIKE '%' + @lFirstName + '%')\n AND (@lLastName IS NULL OR LastName LIKE '%' + @lLastName + '%')\n AND (@lEmailAddress IS NULL OR EmailAddress LIKE '%' + @lEmailAddress + '%')\n AND (@lEmailPromotion IS NULL OR EmailPromotion = @lEmailPromotion)\n AND (@lPhone IS NULL OR Phone = @lPhone)\n ORDER BY ContactID\n\nEND\nGO\n"
},
{
"answer_id": 48301647,
"author": "Ravindra Vairagi",
"author_id": 6656918,
"author_profile": "https://Stackoverflow.com/users/6656918",
"pm_score": 0,
"selected": false,
"text": "GO\nSET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\n-- =============================================\n-- Author: --\n-- Create date:\n-- Description: --\n-- =============================================\nCREATE PROCEDURE [dbo].[usp_StudentList]\n @PageNumber INT = 1, -- Paging parameter\n @PageSize INT = 10,-- Paging parameter\n @Search VARCHAR(MAX) = NULL, --Generic Search Parameter\n @OrderBy VARCHAR(MAX) = 'FirstName', --Default Column Name 'FirstName' for records ordering\n @SortDir VARCHAR(MAX) = 'asc' --Default ordering 'asc' for records ordering\nAS\nBEGIN\n SET NOCOUNT ON;\n\n --Query required for paging, this query used to show total records\n SELECT COUNT(StudentId) AS RecordsTotal FROM Student\n\n SELECT Student.*, \n --Query required for paging, this query used to show total records filtered\n COUNT(StudentId) OVER (PARTITION BY 1) AS RecordsFiltered \n FROM Student\n WHERE \n --Generic Search \n -- Below is the column list to add in Generic Serach\n (@Search IS NULL OR Student.FirstName LIKE '%'+ @Search +'%')\n OR (@Search IS NULL OR Student.LastName LIKE '%'+ @Search +'%')\n --Order BY\n -- Below is the column list to allow sorting\n ORDER BY \n CASE WHEN @SortDir = 'asc' AND @OrderBy = 'FirstName' THEN Student.FirstName END,\n CASE WHEN @SortDir = 'desc' AND @OrderBy = 'FirstName' THEN Student.FirstName END DESC,\n CASE WHEN @SortDir = 'asc' AND @OrderBy = 'LastName' THEN Student.LastName END,\n CASE WHEN @SortDir = 'desc' AND @OrderBy = 'LastName' THEN Student.LastName END DESC,\n OFFSET @PageSize * (@PageNumber - 1) ROWS FETCH NEXT @PageSize ROWS ONLY;\nEND\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71/"
] |
205,529
|
<p>Say I have a C function which takes a variable number of arguments: How can I call another function which expects a variable number of arguments from inside of it, passing all the arguments that got into the first function?</p>
<p>Example:</p>
<pre><code>void format_string(char *fmt, ...);
void debug_print(int dbg_lvl, char *fmt, ...) {
format_string(fmt, /* how do I pass all the arguments from '...'? */);
fprintf(stdout, fmt);
}
</code></pre>
|
[
{
"answer_id": 205584,
"author": "SmacL",
"author_id": 22564,
"author_profile": "https://Stackoverflow.com/users/22564",
"pm_score": 9,
"selected": true,
"text": "va_list va_arg() void format_string(char *fmt,va_list argptr, char *formatted_string);\n\n\nvoid debug_print(int dbg_lvl, char *fmt, ...) \n{ \n char formatted_string[MAX_FMT_SIZE];\n\n va_list argptr;\n va_start(argptr,fmt);\n format_string(fmt, argptr, formatted_string);\n va_end(argptr);\n fprintf(stdout, \"%s\",formatted_string);\n}\n"
},
{
"answer_id": 205589,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "printf vprintf va_list ... ... va_list"
},
{
"answer_id": 5426238,
"author": "user2023370",
"author_id": 2023370,
"author_profile": "https://Stackoverflow.com/users/2023370",
"pm_score": 5,
"selected": false,
"text": "template <typename... Ts>\nvoid format_string(char *fmt, Ts ... ts) {}\n\ntemplate <typename... Ts>\nvoid debug_print(int dbg_lvl, char *fmt, Ts... ts)\n{\n format_string(fmt, ts...);\n}\n"
},
{
"answer_id": 6835569,
"author": "Yoda",
"author_id": 864185,
"author_profile": "https://Stackoverflow.com/users/864185",
"pm_score": 3,
"selected": false,
"text": "void format_string(char *fmt, ...);\nvoid debug_print(int dbg_level, int numOfArgs, char *fmt, ...)\n {\n va_list argumentsToPass;\n va_start(argumentsToPass, fmt);\n char *list = new char[numOfArgs];\n for(int n = 0; n < numOfArgs; n++)\n list[n] = va_arg(argumentsToPass, char);\n va_end(argumentsToPass);\n for(int n = numOfArgs - 1; n >= 0; n--)\n {\n char next;\n next = list[n];\n __asm push next;\n }\n __asm push fmt;\n __asm call format_string;\n fprintf(stdout, fmt);\n }\n"
},
{
"answer_id": 8283720,
"author": "Rose Perrone",
"author_id": 365298,
"author_profile": "https://Stackoverflow.com/users/365298",
"pm_score": 6,
"selected": false,
"text": " void func(type* values) {\n while(*values) {\n x = *values++;\n /* do whatever with x */\n }\n }\n\nfunc((type[]){val1,val2,val3,val4,0});\n"
},
{
"answer_id": 12755437,
"author": "BSalita",
"author_id": 317797,
"author_profile": "https://Stackoverflow.com/users/317797",
"pm_score": 2,
"selected": false,
"text": "__VA_ARGS__ // pass number of arguments version\n #define callVardicMethodSafely(...) {value_t *args[] = {NULL, __VA_ARGS__}; _actualFunction(args+1,sizeof(args) / sizeof(*args) - 1);}\n\n\n// NULL terminated array version\n #define callVardicMethodSafely(...) {value_t *args[] = {NULL, __VA_ARGS__, NULL}; _actualFunction(args+1);}\n"
},
{
"answer_id": 16450540,
"author": "Jim",
"author_id": 2364065,
"author_profile": "https://Stackoverflow.com/users/2364065",
"pm_score": -1,
"selected": false,
"text": "void inner_func(int &i)\n{\n va_list vars;\n va_start(vars, i);\n int j = va_arg(vars);\n va_end(vars); // Generally useless, but should be included.\n}\n\nvoid func(int i, ...)\n{\n inner_func(i);\n}\n"
},
{
"answer_id": 29731121,
"author": "Jagdish",
"author_id": 2335246,
"author_profile": "https://Stackoverflow.com/users/2335246",
"pm_score": 3,
"selected": false,
"text": "#define NONE 0x00\n#define DBG 0x1F\n#define INFO 0x0F\n#define ERR 0x07\n#define EMR 0x03\n#define CRIT 0x01\n\n#define DEBUG_LEVEL ERR\n\n#define WHERESTR \"[FILE : %s, FUNC : %s, LINE : %d]: \"\n#define WHEREARG __FILE__,__func__,__LINE__\n#define DEBUG(...) fprintf(stderr, __VA_ARGS__)\n#define DEBUG_PRINT(X, _fmt, ...) if((DEBUG_LEVEL & X) == X) \\\n DEBUG(WHERESTR _fmt, WHEREARG,__VA_ARGS__)\n\nint main()\n{\n int x=10;\n DEBUG_PRINT(DBG, \"i am x %d\\n\", x);\n return 0;\n}\n"
},
{
"answer_id": 31675300,
"author": "Engineer",
"author_id": 279738,
"author_profile": "https://Stackoverflow.com/users/279738",
"pm_score": 0,
"selected": false,
"text": "... #define LOGI(...)\n ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))\n"
},
{
"answer_id": 51167684,
"author": "VarunG",
"author_id": 6165026,
"author_profile": "https://Stackoverflow.com/users/6165026",
"pm_score": 3,
"selected": false,
"text": "#include <stdarg.h>\n#include <stdio.h>\n\nvoid print(char const* fmt, ...)\n{\n va_list arg;\n va_start(arg, fmt);\n vprintf(fmt, arg);\n va_end(arg);\n}\n\nvoid printFormatted(char const* fmt, va_list arg)\n{\n vprintf(fmt, arg);\n}\n\nvoid showLog(int mdl, char const* type, ...)\n{\n print(\"\\nMDL: %d, TYPE: %s\", mdl, type);\n\n va_list arg;\n va_start(arg, type);\n char const* fmt = va_arg(arg, char const*);\n printFormatted(fmt, arg);\n va_end(arg);\n}\n\nint main() \n{\n int x = 3, y = 6;\n showLog(1, \"INF, \", \"Value = %d, %d Looks Good! %s\", x, y, \"Infact Awesome!!\");\n showLog(1, \"ERR\");\n}\n"
},
{
"answer_id": 64944830,
"author": "Ali80",
"author_id": 1896554,
"author_profile": "https://Stackoverflow.com/users/1896554",
"pm_score": 2,
"selected": false,
"text": "/// logs all messages below this level, level 0 turns off LOG \n#ifndef LOG_LEVEL\n#define LOG_LEVEL 5 // 0:off, 1:error, 2:warning, 3: info, 4: debug, 5:verbose\n#endif\n#define _LOG_FORMAT_SHORT(letter, format) \"[\" #letter \"]: \" format \"\\n\"\n\n/// short log\n#define log_s(level, format, ...) \\ \n if (level <= LOG_LEVEL) \\ \n printf(_LOG_FORMAT_SHORT(level, format), ##__VA_ARGS__)\n\n log_s(1, \"fatal error occurred\");\nlog_s(3, \"x=%d and name=%s\",2, \"ali\");\n [1]: fatal error occurred\n[3]: x=2 and name=ali\n const char* _getFileName(const char* path)\n{\n size_t i = 0;\n size_t pos = 0;\n char* p = (char*)path;\n while (*p) {\n i++;\n if (*p == '/' || *p == '\\\\') {\n pos = i;\n }\n p++;\n }\n return path + pos;\n}\n\n#define _LOG_FORMAT(letter, format) \\ \n \"[\" #letter \"][%s:%u] %s(): \" format \"\\n\", _getFileName(__FILE__), __LINE__, __FUNCTION__\n\n#ifndef LOG_LEVEL\n#define LOG_LEVEL 5 // 0:off, 1:error, 2:warning, 3: info, 4: debug, 5:verbose\n#endif\n\n/// long log\n#define log_l(level, format, ...) \\ \n if (level <= LOG_LEVEL) \\ \n printf(_LOG_FORMAT(level, format), ##__VA_ARGS__)\n log_s(1, \"fatal error occurred\");\nlog_s(3, \"x=%d and name=%s\",2, \"ali\");\n [1][test.cpp:97] main(): fatal error occurred\n[3][test.cpp:98] main(): x=2 and name=ali\n ... int print_custom(const char* format, ...)\n{\n static char loc_buf[64];\n char* temp = loc_buf;\n int len;\n va_list arg;\n va_list copy;\n va_start(arg, format);\n va_copy(copy, arg);\n len = vsnprintf(NULL, 0, format, arg);\n va_end(copy);\n if (len >= sizeof(loc_buf)) {\n temp = (char*)malloc(len + 1);\n if (temp == NULL) {\n return 0;\n }\n }\n vsnprintf(temp, len + 1, format, arg);\n printf(temp); // replace with any print function you want\n va_end(arg);\n if (len >= sizeof(loc_buf)) {\n free(temp);\n }\n return len;\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4381/"
] |
205,546
|
<p>Visual Studio makes calling a web service easy, trying to figure out what is going on under the covers is difficult.</p>
<p>How can I see the actual XML generated from my .Net app when making a call to a web service?</p>
|
[
{
"answer_id": 205572,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 1,
"selected": false,
"text": "myDataSet.WriteXml(filename);\n"
},
{
"answer_id": 205828,
"author": "quickcel",
"author_id": 9129,
"author_profile": "https://Stackoverflow.com/users/9129",
"pm_score": 1,
"selected": false,
"text": "Dim url As String = \"http://web.service.com/\"\nDim request As WebRequest = WebRequest.Create(url)\nDim response As WebResponse = request.GetResponse()\nDim stream As Stream = response.GetResponseStream()\n\nDim xmlDoc As XmlDocument = New XmlDocument\nxmlDoc.Load(stream)\nxmlDoc.Save(\"C:\\Temp\\foo.xml\")\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25121/"
] |
205,555
|
<p>During my work with databases I noticed that I write query strings and in this strings I have to put several restrictions in the where-clause from a list/array/collection. Should look like this:</p>
<pre><code>select * from customer
where customer.id in (34, 26, ..., 2);
</code></pre>
<p>You can simplify this by reducing this to the question that you have collection of strings and want to create a comma-separated list of this strings in just one string.</p>
<p>My approach I have used so far is something like that:</p>
<pre><code>String result = "";
boolean first = true;
for(String string : collectionOfStrings) {
if(first) {
result+=string;
first=false;
} else {
result+=","+string;
}
}
</code></pre>
<p>But this is as you can see very ugly. You cannot see what happens there on the first look, especially when the constructed strings (like every SQL query) is getting complicated.</p>
<p>What is your (more) elegant way?</p>
|
[
{
"answer_id": 205596,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 1,
"selected": false,
"text": "public static final String toSqlList(Collection<?> values) {\n\n String collectionString = values.toString();\n\n // Convert the square brackets produced by Collection.toString() to round brackets used by SQL\n return \"(\" + collectionString.substring(1, collectionString.length() - 1) + \")\";\n}\n"
},
{
"answer_id": 205657,
"author": "Denis Fradlin",
"author_id": 28316,
"author_profile": "https://Stackoverflow.com/users/28316",
"pm_score": 2,
"selected": false,
"text": "public static <T> String join(Collection<T> values)\n{\n StringBuffer ret = new StringBuffer();\n for (T value : values)\n {\n if (ret.length() > 0) ret.append(\",\");\n ret.append(value);\n }\n return ret.toString();\n}\n"
},
{
"answer_id": 205712,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 7,
"selected": true,
"text": " StringBuilder result = new StringBuilder();\n for(String string : collectionOfStrings) {\n result.append(string);\n result.append(\",\");\n }\n return result.length() > 0 ? result.substring(0, result.length() - 1): \"\";\n"
},
{
"answer_id": 205813,
"author": "Telcontar",
"author_id": 518,
"author_profile": "https://Stackoverflow.com/users/518",
"pm_score": 2,
"selected": false,
"text": "SELECT.... FROM.... WHERE ID IN( value1, value2,....valueN)\n valueX SELECT.... FROM.... WHERE ID IN( ?, ?,....?)\n Statement.setString(nParameter,parameterValue)"
},
{
"answer_id": 205817,
"author": "Ogre Psalm33",
"author_id": 13140,
"author_profile": "https://Stackoverflow.com/users/13140",
"pm_score": 6,
"selected": false,
"text": "collectionOfStrings = /* source string collection */;\nString csList = StringUtils.join(collectionOfStrings.toArray(), \",\");\n"
},
{
"answer_id": 205976,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 6,
"selected": false,
"text": "StringBuilder buff = new StringBuilder();\nString sep = \"\";\nfor (String str : strs) {\n buff.append(sep);\n buff.append(str);\n sep = \",\";\n}\nreturn buff.toString();\n"
},
{
"answer_id": 205996,
"author": "Julie",
"author_id": 8217,
"author_profile": "https://Stackoverflow.com/users/8217",
"pm_score": 7,
"selected": false,
"text": "join Joiner.on(\",\").join(collectionOfStrings);\n"
},
{
"answer_id": 206067,
"author": "silverminken",
"author_id": 24777,
"author_profile": "https://Stackoverflow.com/users/24777",
"pm_score": 2,
"selected": false,
"text": "/**\n * Creates a comma-separated list of values from given collection.\n * \n * @param <T> Value type.\n * @param values Value collection.\n * @return Comma-separated String of values.\n */\npublic <T> String toParameterList(Collection<T> values) {\n if (values == null || values.isEmpty()) {\n return \"\"; // Depending on how you want to deal with this case...\n }\n StringBuilder result = new StringBuilder();\n Iterator<T> i = values.iterator();\n result.append(i.next().toString());\n while (i.hasNext()) {\n result.append(\",\").append(i.next().toString());\n }\n return result.toString();\n}\n"
},
{
"answer_id": 208476,
"author": "Miguel Ping",
"author_id": 22992,
"author_profile": "https://Stackoverflow.com/users/22992",
"pm_score": 4,
"selected": false,
"text": "public static String convert(List<String> list) {\n String res = \"\";\n for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {\n res += iterator.next() + (iterator.hasNext() ? \",\" : \"\");\n }\n return res;\n}\n"
},
{
"answer_id": 936813,
"author": "Peter Lawrey",
"author_id": 57695,
"author_profile": "https://Stackoverflow.com/users/57695",
"pm_score": 3,
"selected": false,
"text": "List collections = Arrays.asList(34, 26, \"...\", 2);\nString asString = collection.toString();\n// justValues = \"34, 26, ..., 2\"\nString justValues = asString.substring(1, asString.length()-1);\n"
},
{
"answer_id": 1173979,
"author": "case nelson",
"author_id": 111716,
"author_profile": "https://Stackoverflow.com/users/111716",
"pm_score": 3,
"selected": false,
"text": "Joiner.on(\", \").join(34, 26, ..., 2)\n"
},
{
"answer_id": 2132934,
"author": "xss",
"author_id": 258496,
"author_profile": "https://Stackoverflow.com/users/258496",
"pm_score": 1,
"selected": false,
"text": "AbstractCollections toString() java.util String s= java.util.Arrays.toString(collectionOfStrings.toArray());\ns = s.substing(1, s.length()-1);// [] are guaranteed to be there\n"
},
{
"answer_id": 2133160,
"author": "dfa",
"author_id": 89266,
"author_profile": "https://Stackoverflow.com/users/89266",
"pm_score": 1,
"selected": false,
"text": "@Test\npublic void join() {\n List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);\n String string = $(list).join(\",\");\n}\n $ $(1, 5).join(\",\")"
},
{
"answer_id": 7005680,
"author": "VIM",
"author_id": 887135,
"author_profile": "https://Stackoverflow.com/users/887135",
"pm_score": 1,
"selected": false,
"text": "StringBuffer inString = new StringBuffer(listOfIDs.get(0).toString());\nfor (Long currentID : listOfIDs) {\n inString.append(\",\").append(currentID);\n}\n"
},
{
"answer_id": 7688450,
"author": "Jeff",
"author_id": 984148,
"author_profile": "https://Stackoverflow.com/users/984148",
"pm_score": 3,
"selected": false,
"text": "public static <T> String buildCommaSeparatedString(Collection<T> values) {\n if (values==null || values.isEmpty()) return \"\";\n StringBuilder result = new StringBuilder();\n for (T val : values) {\n result.append(val);\n result.append(\",\");\n }\n return result.substring(0, result.length() - 1);\n}\n"
},
{
"answer_id": 7935427,
"author": "Julio César",
"author_id": 1019183,
"author_profile": "https://Stackoverflow.com/users/1019183",
"pm_score": 0,
"selected": false,
"text": "java.util.List<String> lista = new java.util.ArrayList<String>();\nlista.add(\"Hola\");\nlista.add(\"Julio\");\nSystem.out.println(lista.toString().replace('[','(').replace(']',')'));\n\n$~(Hola, Julio)\n"
},
{
"answer_id": 9015846,
"author": "weekens",
"author_id": 362738,
"author_profile": "https://Stackoverflow.com/users/362738",
"pm_score": 2,
"selected": false,
"text": "StringUtils.arrayToCommaDelimitedString(\n collectionOfStrings.toArray()\n)\n"
},
{
"answer_id": 12981729,
"author": "Victor",
"author_id": 3419,
"author_profile": "https://Stackoverflow.com/users/3419",
"pm_score": 1,
"selected": false,
"text": "private String commas(Iterable<String> strings) {\n StringBuilder buffer = new StringBuilder();\n Iterator<String> it = strings.iterator();\n if (it.hasNext()) {\n buffer.append(it.next());\n while (it.hasNext()) {\n buffer.append(',');\n buffer.append(it.next());\n }\n }\n\n return buffer.toString();\n}\n"
},
{
"answer_id": 15254328,
"author": "iTake",
"author_id": 898776,
"author_profile": "https://Stackoverflow.com/users/898776",
"pm_score": 2,
"selected": false,
"text": "String res = \"\";\nfor (String i : values) {\n res += res.isEmpty() ? i : \",\"+i;\n}\n"
},
{
"answer_id": 18399511,
"author": "cloudy_weather",
"author_id": 2028803,
"author_profile": "https://Stackoverflow.com/users/2028803",
"pm_score": 1,
"selected": false,
"text": "Arrays.asList(parameters).toString()\n"
},
{
"answer_id": 19963805,
"author": "Todd Gatts",
"author_id": 2989479,
"author_profile": "https://Stackoverflow.com/users/2989479",
"pm_score": 0,
"selected": false,
"text": "String commaSeparatedNames = namesList.toString().replaceAll( \"[\\\\[|\\\\]| ]\", \"\" ); // replace [ or ] or blank\n"
},
{
"answer_id": 27243582,
"author": "Ups",
"author_id": 2493314,
"author_profile": "https://Stackoverflow.com/users/2493314",
"pm_score": 0,
"selected": false,
"text": " for (int i =0; i < tokens.size(); i++){\n builder.append(tokens.get(i));\n if(i != tokens.size()-1){\n builder.append(TOKEN_DELIMITER);\n }\n }\n"
},
{
"answer_id": 27510575,
"author": "robjwilkins",
"author_id": 4315049,
"author_profile": "https://Stackoverflow.com/users/4315049",
"pm_score": 3,
"selected": false,
"text": "String.join(\", \", collectionOfStrings)\n Joiner.on(\",\").join(collectionOfStrings);\n"
},
{
"answer_id": 27782188,
"author": "elcuco",
"author_id": 78712,
"author_profile": "https://Stackoverflow.com/users/78712",
"pm_score": 1,
"selected": false,
"text": "public static String toString(int[] numbers) {\n StringBuilder res = new StringBuilder();\n for (int number : numbers) {\n if (res.length() != 0) {\n res.append(',');\n }\n res.append(number);\n }\n return res.toString();\n}\n"
},
{
"answer_id": 29234107,
"author": "Christof",
"author_id": 640539,
"author_profile": "https://Stackoverflow.com/users/640539",
"pm_score": 2,
"selected": false,
"text": "reduce() import java.util.Arrays;\nimport java.util.List;\n\nimport org.apache.commons.lang.StringUtils; \n\nimport com.google.common.base.Joiner;\n\npublic class Dummy {\n public static void main(String[] args) {\n\n List<String> strings = Arrays.asList(\"abc\", \"de\", \"fg\");\n String commaSeparated = strings\n .stream()\n .reduce((s1, s2) -> {return s1 + \",\" + s2; })\n .get();\n\n System.out.println(commaSeparated);\n\n System.out.println(Joiner.on(',').join(strings));\n\n System.out.println(StringUtils.join(strings, \",\"));\n\n }\n}\n"
},
{
"answer_id": 29758572,
"author": "Pascalius",
"author_id": 505248,
"author_profile": "https://Stackoverflow.com/users/505248",
"pm_score": 2,
"selected": false,
"text": "TextUtils.join(\",\",collectionOfStrings.toArray());\n"
},
{
"answer_id": 30954872,
"author": "Abdull",
"author_id": 923560,
"author_profile": "https://Stackoverflow.com/users/923560",
"pm_score": 6,
"selected": false,
"text": "String String.join(CharSequence delimiter, CharSequence... elements) String String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements) String String Collectors.joining(CharSequence delimiter) String joined = anyCollection.stream().map(Object::toString).collect(Collectors.joining(\",\"));"
},
{
"answer_id": 33164417,
"author": "Fathah Rehman P",
"author_id": 991065,
"author_profile": "https://Stackoverflow.com/users/991065",
"pm_score": 0,
"selected": false,
"text": "String memberIdsModifiedForQuery = memberIds.toString().replace(\"[\", \"(\").replace(\"]\", \")\");\n public static void main(String[] args) { \n List<Integer>memberIds=new ArrayList<Integer>(); //This contain member ids we want to process\n //adding some sample values for example\n memberIds.add(3); \n memberIds.add(4);\n memberIds.add(2);\n String memberIdsModifiedForQuery = memberIds.toString().replace(\"[\", \"(\").replace(\"]\", \")\"); //here you will get (3,4,5) That you can directly use in query\n System.out.println(memberIdsModifiedForQuery);\n String exampleQuery=\"select * from customer where customer.id in \"+memberIdsModifiedForQuery+\" \";\n }\n"
},
{
"answer_id": 38301017,
"author": "Jayman Jani",
"author_id": 4993880,
"author_profile": "https://Stackoverflow.com/users/4993880",
"pm_score": 0,
"selected": false,
"text": "android.text.TextUtils ArrayList<String>Myli = new ArrayList<String>();\n String ArayCommase=android.text.TextUtils.join(\",\", Myli);\n"
},
{
"answer_id": 57900835,
"author": "Sridhar",
"author_id": 8036307,
"author_profile": "https://Stackoverflow.com/users/8036307",
"pm_score": 2,
"selected": false,
"text": "List<String> collectionOfStrings = // List of string to concat\nString csvStrings = StringUtils.collectionToDelimitedString(collectionOfStrings, \",\");\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1038/"
] |
205,557
|
<p>If you develop for ATG Dynamo, how do you structure your modules and dependencies?</p>
<p>How do you structure the projects? source directories, JARs configs etc.</p>
<p>How do you build and deploy? What tools do you use?</p>
|
[
{
"answer_id": 271071,
"author": "talanb",
"author_id": 20103,
"author_profile": "https://Stackoverflow.com/users/20103",
"pm_score": 3,
"selected": false,
"text": "root\n deploy\n class (compile java to here)\n config (primary configpath)\n docroot (JHTML docroot)\n dev (configpath for dev environment)\n test (configpath for QA environment)\n prod (configpath for prod environment)\n j2ee (j2ee web-app)\n WEB-INF\n dir-a (application JSPs)\n dir-b (application JSPs)\n src\n java (java src)\n sql (sql src)\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15452/"
] |
205,568
|
<p>There's a lot of advice out there that you shouldn't expose your fields publically, and instead use trivial properties. I see it over & over.</p>
<p>I understand the arguments, but <a href="https://stackoverflow.com/questions/174198/c35-automatic-properties-why-not-access-the-field-directly#205567">I don't think it's good advice in most cases</a>.</p>
<p>Does anyone have an example of a time when it really mattered? When writing a trivial property made something important possible in the future (or when failing to use one got them in to real trouble)?</p>
<p>EDIT: The DataBinding argument is correct, but not very interesting. It's a bug in the DataBinding code that it won't accept public fields. So, we have to write properties to work around that bug, not because properties are a wise class design choice.</p>
<p>EDIT: To be clear, I'm looking for real-world examples, not theory. A time when it really mattered.</p>
<p>EDIT: The ability to set a breakpoint on the setter seems valuable. Designing my code for the debugger is unfortunate: I'd rather the debugger get smarter, but given the debugger we have, I'll take this ability. Good stuff.</p>
|
[
{
"answer_id": 207146,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 6,
"selected": true,
"text": "get set public string Name { get; set; }\n public string name;\n"
},
{
"answer_id": 13385502,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 0,
"selected": false,
"text": "Thing.Boz Point X Thing.Boz.X += 5; Thing.Boz var tmp = Thing.Boz; tmp.X += 5; Thing.Boz = tmp; Boz Boz Interlocked ActOnXXX delegate void ActionByRef<T1>(ref T1 p1);\ndelegate void ActionByRef<T1,T2>(ref T1 p1, ref T2 p2);\ndelegate void ActionByRef<T1,T2,T3>(ref T1 p1, ref T2 p2, ref T3 p3);\n// Method within the type that defines property `Boz`\nvoid ActOnBoz<T1>(ActionByRef<Point, T1> proc, ref T1 p1)\n{\n proc(ref _Boz, ref p1); // _Boz is the private backing field\n}\n q Thing.Boz.X Thing.ActOnBoz((ref Point pt, ref int x) => {pt.X += x;}, ref q); Thing._Boz"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5314/"
] |
205,573
|
<p>I want to do something like this:</p>
<pre><code>List<Animal> animals = new ArrayList<Animal>();
for( Class c: list_of_all_classes_available_to_my_app() )
if (c is Animal)
animals.add( new c() );
</code></pre>
<p>So, I want to look at all of the classes in my application's universe, and when I find one that descends from Animal, I want to create a new object of that type and add it to the list. This allows me to add functionality without having to update a list of things. I can avoid the following:</p>
<pre><code>List<Animal> animals = new ArrayList<Animal>();
animals.add( new Dog() );
animals.add( new Cat() );
animals.add( new Donkey() );
...
</code></pre>
<p>With the above approach, I can simply create a new class that extends Animal and it'll get picked up automatically.</p>
<p>UPDATE: 10/16/2008 9:00 a.m. Pacific Standard Time:</p>
<p>This question has generated a lot of great responses -- thank you. <s>From the responses and my research, I've found that what I really want to do is just not possible under Java. There are approaches, such as ddimitrov's ServiceLoader mechanism that can work -- but they are very heavy for what I want, and I believe I simply move the problem from Java code to an external configuration file.</s> <strong>Update 5/10/19</strong> (11 years later!) There are now several libraries that can help with this according to @IvanNik's <a href="https://stackoverflow.com/a/9240969/9648">answer</a> <a href="https://github.com/ronmamo/reflections" rel="noreferrer">org.reflections</a> looks good. Also <a href="https://github.com/classgraph/classgraph" rel="noreferrer">ClassGraph</a> from @Luke Hutchison's <a href="https://stackoverflow.com/a/51625104/9648">answer</a> looks interesting. There are several more possibilities in the answers as well.</p>
<p>Another way to state what I want: a static function in my Animal class finds and instantiates all classes that inherit from Animal -- without any further configuration/coding. If I have to configure, I might as well just instantiate them in the Animal class anyway. I understand that because a Java program is just a loose federation of .class files that that's just the way it is.</p>
<p>Interestingly, it seems this is <a href="http://my.safaribooksonline.com/0596003390/csharpckbk-CHP-12-SECT-8" rel="noreferrer">fairly trivial</a> in C#.</p>
|
[
{
"answer_id": 205903,
"author": "jonathan-stafford",
"author_id": 27587,
"author_profile": "https://Stackoverflow.com/users/27587",
"pm_score": 3,
"selected": false,
"text": "for (String classpathEntry : System.getProperty(\"java.class.path\").split(System.getProperty(\"path.separator\"))) {\n if (classpathEntry.endsWith(\".jar\")) {\n File jar = new File(classpathEntry);\n\n JarInputStream is = new JarInputStream(new FileInputStream(jar));\n\n JarEntry entry;\n while( (entry = is.getNextJarEntry()) != null) {\n if(entry.getName().endsWith(\".class\")) {\n // Class.forName(entry.getName()) and check\n // for implementation of the interface\n }\n }\n }\n}\n"
},
{
"answer_id": 205989,
"author": "JohnnyLambada",
"author_id": 9648,
"author_profile": "https://Stackoverflow.com/users/9648",
"pm_score": 1,
"selected": false,
"text": "public abstract class Animal{\n private static Animal[] animals= null;\n public static Animal[] getAnimals(){\n if (animals==null){\n animals = new Animal[]{\n new Dog(),\n new Cat(),\n new Lion()\n };\n }\n return animals;\n }\n}\n"
},
{
"answer_id": 206083,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public class Dog extends Animal{\n\nstatic\n{\n Animal a = new Dog();\n //add a to the List\n}\n"
},
{
"answer_id": 206488,
"author": "Paul Sonier",
"author_id": 28053,
"author_profile": "https://Stackoverflow.com/users/28053",
"pm_score": 3,
"selected": false,
"text": "public abstract class Animal\n {\n private static ArrayList<Class> instantiatedDerivedTypes;\n public Animal() {\n Class derivedClass = this.getClass();\n if (!instantiatedDerivedClass.contains(derivedClass)) {\n instantiatedDerivedClass.Add(derivedClass);\n }\n }\n"
},
{
"answer_id": 9240969,
"author": "IvanNik",
"author_id": 1118996,
"author_profile": "https://Stackoverflow.com/users/1118996",
"pm_score": 8,
"selected": true,
"text": "Reflections reflections = new Reflections(\"com.mycompany\"); \nSet<Class<? extends MyInterface>> classes = reflections.getSubTypesOf(MyInterface.class);\n public static void main(String[] args) throws IllegalAccessException, InstantiationException {\n Reflections reflections = new Reflections(\"java.util\");\n Set<Class<? extends List>> classes = reflections.getSubTypesOf(java.util.List.class);\n for (Class<? extends List> aClass : classes) {\n System.out.println(aClass.getName());\n if(aClass == ArrayList.class) {\n List list = aClass.newInstance();\n list.add(\"test\");\n System.out.println(list.getClass().getName() + \": \" + list.size());\n }\n }\n}\n"
},
{
"answer_id": 20120607,
"author": "DJDaveMark",
"author_id": 344029,
"author_profile": "https://Stackoverflow.com/users/344029",
"pm_score": 2,
"selected": false,
"text": "package test;\n\nimport java.util.Set;\nimport net.sourceforge.stripes.util.ResolverUtil;\n\npublic class BaseClassTest {\n public static void main(String[] args) throws Exception {\n ResolverUtil<Animal> resolver = new ResolverUtil<Animal>();\n resolver.findImplementations(Animal.class, \"test\");\n Set<Class<? extends Animal>> classes = resolver.getClasses();\n\n for (Class<? extends Animal> clazz : classes) {\n System.out.println(clazz);\n }\n }\n}\n\nclass Animal {}\nclass Dog extends Animal {}\nclass Cat extends Animal {}\nclass Donkey extends Animal {}\n ClassLoader#loadClass(String fullyQualifiedName) Animal.class.isAssignableFrom(loadedClass);"
},
{
"answer_id": 28424686,
"author": "Osman Shoukry",
"author_id": 634553,
"author_profile": "https://Stackoverflow.com/users/634553",
"pm_score": 1,
"selected": false,
"text": "String package = \"com.mycompany\";\nList<Animal> animals = new ArrayList<Animal>();\n\nfor(PojoClass pojoClass : PojoClassFactory.enumerateClassesByExtendingType(package, Animal.class, null) {\n animals.add((Animal) InstanceFactory.getInstance(pojoClass));\n}\n"
},
{
"answer_id": 49711316,
"author": "Ali Bagheri",
"author_id": 6893709,
"author_profile": "https://Stackoverflow.com/users/6893709",
"pm_score": 2,
"selected": false,
"text": "public static Set<Class> getExtendedClasses(Class superClass)\n{\n try\n {\n ResolverUtil resolver = new ResolverUtil();\n resolver.findImplementations(superClass, superClass.getPackage().getName());\n return resolver.getClasses(); \n }\n catch(Exception e)\n {Log.d(\"Log:\", \" Err: getExtendedClasses() \");}\n\n return null;\n}\n\ngetExtendedClasses(Animals.class);\n"
},
{
"answer_id": 51625104,
"author": "Luke Hutchison",
"author_id": 3950982,
"author_profile": "https://Stackoverflow.com/users/3950982",
"pm_score": 3,
"selected": false,
"text": "List<Class<Animal>> animals;\ntry (ScanResult scanResult = new ClassGraph().whitelistPackages(\"com.zoo.animals\")\n .enableClassInfo().scan()) {\n animals = scanResult\n .getSubclasses(Animal.class.getName())\n .loadClasses(Animal.class);\n}\n"
},
{
"answer_id": 67374201,
"author": "AlexIsOK",
"author_id": 13945652,
"author_profile": "https://Stackoverflow.com/users/13945652",
"pm_score": 0,
"selected": false,
"text": "newInstance() Reflections r = new Reflections(\"com.example.location.of.sub.classes\")\nSet<Class<? extends Animal>> classes = r.getSubTypesOf(Animal.class);\n\nclasses.forEach(c -> {\n Animal a = c.getDeclaredConstructor().newInstance();\n //a is your instance of Animal.\n});\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9648/"
] |
205,582
|
<p>The new ASP.NET routing is great for simple path style URL's but if you want to use a url such as:</p>
<p><a href="http://example.com/items/search.xhtml?term=Text+to+find&page=2" rel="nofollow noreferrer">http://example.com/items/search.xhtml?term=Text+to+find&page=2</a></p>
<p>Do you have to use a catch all parameter with a validation?</p>
|
[
{
"answer_id": 207748,
"author": "Richard Szalay",
"author_id": 3603,
"author_profile": "https://Stackoverflow.com/users/3603",
"pm_score": 3,
"selected": true,
"text": "Search(string term, int page)\n"
},
{
"answer_id": 7725561,
"author": "George Filippakos",
"author_id": 961333,
"author_profile": "https://Stackoverflow.com/users/961333",
"pm_score": 0,
"selected": false,
"text": "MapPageRoute(\"myroute\", \"myroute/{x}\", \"~/routehander.aspx\")\n http://mywebsite.com/myroute/{x}?url=myurl\n Dim x as integer = 12\nDim rvd As New Routing.RouteValueDictionary\nrvd.Add(\"x\", x)\nrvd.Add(\"url\", Server.UrlEncode(\"/default.aspx\"))\nHttpContext.Current.ApplicationInstance.Response.RedirectToRoutePermanent(\"myroute\", rvd)\n http://mywebsite.com/myroute/12?url=%252fdefault.aspx\n"
},
{
"answer_id": 9673676,
"author": "naspinski",
"author_id": 14777,
"author_profile": "https://Stackoverflow.com/users/14777",
"pm_score": 0,
"selected": false,
"text": "Request.QueryString[\"some_value\"];"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16340/"
] |
205,583
|
<p>I need to reproduce a bug, and a guy from the other team has sent me a .mdf and .ldf files from his sql server 2005 instance. When I attach the database, all I get is empty tables, even though file is 2 mb large. The db contains 2 tables that have, among other thing, a varbinary(max) field. At the same time another database, which has no varbinaries in tables, is attached ok and data are in place. What could be possible reason why data became inaccessible?</p>
|
[
{
"answer_id": 207748,
"author": "Richard Szalay",
"author_id": 3603,
"author_profile": "https://Stackoverflow.com/users/3603",
"pm_score": 3,
"selected": true,
"text": "Search(string term, int page)\n"
},
{
"answer_id": 7725561,
"author": "George Filippakos",
"author_id": 961333,
"author_profile": "https://Stackoverflow.com/users/961333",
"pm_score": 0,
"selected": false,
"text": "MapPageRoute(\"myroute\", \"myroute/{x}\", \"~/routehander.aspx\")\n http://mywebsite.com/myroute/{x}?url=myurl\n Dim x as integer = 12\nDim rvd As New Routing.RouteValueDictionary\nrvd.Add(\"x\", x)\nrvd.Add(\"url\", Server.UrlEncode(\"/default.aspx\"))\nHttpContext.Current.ApplicationInstance.Response.RedirectToRoutePermanent(\"myroute\", rvd)\n http://mywebsite.com/myroute/12?url=%252fdefault.aspx\n"
},
{
"answer_id": 9673676,
"author": "naspinski",
"author_id": 14777,
"author_profile": "https://Stackoverflow.com/users/14777",
"pm_score": 0,
"selected": false,
"text": "Request.QueryString[\"some_value\"];"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17481/"
] |
205,614
|
<p>My initial installation for the <strong>MySQL</strong> had no password for root. I assigned a password for root and everything worked fine. Due to some reason (don't ask why) I had to revert back to the original settings where root didn't have any password.</p>
<p>I changed the root password to <code>'' (empty string)</code>. The problem now is that MySQL doesn't run with <code>'mysql -uroot'</code>, it expects a password. On running <code>'mysql -uroot -p'</code> and hitting enter on the password prompt gets me into the db, but is not same as the default setting.</p>
<p>Is there any other flag/setting that I am missing to set/unset which tells mysql to not expect a password?</p>
<p>Thanks</p>
|
[
{
"answer_id": 205661,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 4,
"selected": false,
"text": "[client]\nhost=localhost\nuser = root\npassword = mypassword\ndatabase = mydatabase\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13492/"
] |
205,631
|
<p>i got a client side javascript function which is triggered on a button click (basically, its a calculator!!). Sometimes, due to enormous data on the page, the javascript calculator function take to long & makes the page appear inactive to the user. I was planning to display a transparent div over entire page, maybe with a busy indicator (in the center) till the calculator function ends, so that user waits till process ends. </p>
<pre>
function CalculateAmountOnClick() {
// Display transparent div
// MY time consuming loop!
{
}
// Remove transparent div
}
</pre>
<p>Any ideas on how to go about this? Should i assign a css class to a div (which surrounds my entire page's content) using javascript when my calculator function starts? I tried that but didnt get desired results. Was facing issues with transparency in IE 6. Also how will i show a loading message + image in such a transparent div?</p>
<p>TIA</p>
|
[
{
"answer_id": 205648,
"author": "kemiller2002",
"author_id": 1942,
"author_profile": "https://Stackoverflow.com/users/1942",
"pm_score": 2,
"selected": false,
"text": "display:inline position:absolute z-index:99 100% display:none"
},
{
"answer_id": 205707,
"author": "Joel Anair",
"author_id": 7441,
"author_profile": "https://Stackoverflow.com/users/7441",
"pm_score": 0,
"selected": false,
"text": "<div> position:absolute left top none div function showLoadingIndicator()\n{\n // Display div by setting display to 'inline'\n setTimeout(CalculateAmountOnClick,0);\n}\n\nfunction CalculateAmountOnClick()\n{\n // MY time consuming loop!\n {\n }\n // Remove transparent div \n}\n"
},
{
"answer_id": 205758,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 5,
"selected": true,
"text": "function CalculateAmountOnClick () {\n var curtain = document.body.appendChild( document.createElement('div') );\n curtain.id = \"curtain\";\n curtain.onkeypress = curtain.onclick = function(){ return false; }\n try {\n // your operations\n }\n finally {\n curtain.parentNode.removeChild( curtain );\n }\n}\n #curtain {\n position: fixed;\n _position: absolute;\n z-index: 99;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n _height: expression(document.body.offsetHeight + \"px\");\n background: url(curtain.png);\n _background: url(curtain.gif);\n}\n function modalProcess( callback ) {\n var ret;\n var curtain = document.body.appendChild( document.createElement('div') );\n curtain.id = \"curtain\";\n curtain.onkeypress = curtain.onclick = function(){ return false; }\n try {\n ret = callback();\n }\n finally {\n curtain.parentNode.removeChild( curtain );\n }\n return ret;\n}\n var result = modalProcess(function(){\n // your operations here\n});\n"
},
{
"answer_id": 210931,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 3,
"selected": false,
"text": "function processLoop( actionFunc, numTimes, doneFunc ) {\n var i = 0;\n var f = function () {\n if (i < numTimes) {\n actionFunc( i++ ); // closure on i\n setTimeout( f, 10 )\n } \n else if (doneFunc) { \n doneFunc();\n }\n };\n f();\n}\n\n// add a curtain here\nprocessLoop(function (i){\n // loop code goes in here\n console.log('number: ', i);\n}, \n10, // how many times to run loop\nfunction (){\n // things that happen after the processing is done go here\n console.log('done!');\n // remove curtain here\n});\n // add a curtain\nvar curtain = document.body.appendChild( document.createElement('div') );\ncurtain.id = \"curtain\";\ncurtain.onkeypress = curtain.onclick = function(){ return false; }\n// delay running processing\nsetTimeout(function(){\n try {\n // here we go...\n myHeavyProcessingFunction();\n }\n finally {\n // remove the curtain\n curtain.parentNode.removeChild( curtain );\n }\n}, 40);\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28321/"
] |
205,644
|
<p>I came across an issue that makes me think there is bug in the 3.0 framework. When I try to use extension methods I get the following error: </p>
<pre><code>Missing compiler required member
'System.Runtime.CompilerServices.ExtensionAttribute..ctor'
</code></pre>
<p>When using this simple code:</p>
<pre><code>public static class StringUtils {
static void TestExtension(this String targetString) {
}
}
</code></pre>
<p>The only way to make this compile error go away is to add the following code:</p>
<pre><code>namespace System.Runtime.CompilerServices {
public class ExtensionAttribute : Attribute { }
}
</code></pre>
<p>It's been a few months since I have used extensions methods, but I'm pretty sure I didn't have to do this. Has anyone else come across this issue?</p>
|
[
{
"answer_id": 577527,
"author": "lexx",
"author_id": 67014,
"author_profile": "https://Stackoverflow.com/users/67014",
"pm_score": 1,
"selected": false,
"text": "<assemblies>\n <add assembly=\"System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/>\n</assemblies>\n <configuration>\n <!--Some other config-->\n <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n <dependentAssembly>\n <assemblyIdentity name=\"System.Core\" publicKeyToken=\"B77A5C561934E089\"/>\n <bindingRedirect oldVersion=\"2.0.0.0-2.1.0.0\" newVersion=\"3.5.0.0\"/>\n </dependentAssembly>\n </assemblyBinding>\n</configuration>\n"
},
{
"answer_id": 2078904,
"author": "Andrew Myhre",
"author_id": 5152,
"author_profile": "https://Stackoverflow.com/users/5152",
"pm_score": 4,
"selected": false,
"text": "namespace System.Runtime.CompilerServices\n{\n public class ExtensionAttribute : Attribute { }\n}\n"
},
{
"answer_id": 2179515,
"author": "7wp",
"author_id": 66803,
"author_profile": "https://Stackoverflow.com/users/66803",
"pm_score": 6,
"selected": false,
"text": "System.Runtime.CompilerServices.ExtensionAttribute..ctor Newtonsoft.Json.Net Newtonsoft.Json.Net20.dll"
},
{
"answer_id": 25815602,
"author": "DJGray",
"author_id": 1243040,
"author_profile": "https://Stackoverflow.com/users/1243040",
"pm_score": 2,
"selected": false,
"text": "C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.0\\Microsoft.CSharp.dll\n"
},
{
"answer_id": 36422244,
"author": "Elya Livshitz",
"author_id": 802848,
"author_profile": "https://Stackoverflow.com/users/802848",
"pm_score": 0,
"selected": false,
"text": "<Reference Include=\"System\" />\n<Reference Include=\"System.Core\" />\n<Reference Include=\"System.Xml.Linq\" />\n<Reference Include=\"System.Data.DataSetExtensions\" />\n<Reference Include=\"Microsoft.CSharp\" />\n<Reference Include=\"System.Data\" />\n<Reference Include=\"System.Net.Http\" />\n<Reference Include=\"System.Xml\" />\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/205644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17902/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.