qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
47,066 |
<p>I am writing a C program in Linux. Commands like execv() require a path in the form of a C string. Is there a command that will return the current path in the form of a C-style string?</p>
|
[
{
"answer_id": 47071,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": true,
"text": "#include <unistd.h>\n\nchar *getcwd(char *buf, size_t size);\n"
},
{
"answer_id": 47074,
"author": "Andreas Kraft",
"author_id": 4799,
"author_profile": "https://Stackoverflow.com/users/4799",
"pm_score": 2,
"selected": false,
"text": "#include <unistd.h>\n\nchar path[MAXPATHLEN];\ngetcwd(path, MAXPATHLEN);\nprintf(\"pwd -> %s\\n\", path);\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/47066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/159/"
] |
47,078 |
<p>We are currently using the ExtJS tree view in an application - a requirement has arisen requiring a user to select multiple nodes (which the tree view supports currently through a pluggable selection model) - but you can not then drag the multiple selections to another part of the tree.</p>
<p>Does anyone know of an ajax control (commercial or non-commercial) that supports multiple-selection drag / drop - or a example of enabling this functionality in ExtJS?</p>
|
[
{
"answer_id": 3988952,
"author": "Benoit",
"author_id": 483194,
"author_profile": "https://Stackoverflow.com/users/483194",
"pm_score": 2,
"selected": true,
"text": "..new Ext.tree.TreePanel({\n ...\n selModel : new Ext.tree.MultiSelectionModel()\n ...\n})\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/47078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4843/"
] |
47,087 |
<p>Here are a few possibilities to get the conversation started:</p>
<ol>
<li>Escape all input upon initialization.</li>
<li>Escape each value, preferably when generating the SQL.</li>
</ol>
<p>The first solution is suboptimal, because you then need to unescape each value if you want to use it in anything other than SQL, like outputting it on a web page.</p>
<p>The second solution makes much more sense, but manually escaping each value is a pain.</p>
<p>I'm aware of <a href="http://en.wikipedia.org/wiki/SQL_injection#Using_Parameterized_Statements" rel="noreferrer">prepared statements</a>, however I find <a href="http://www.php.net/manual/en/book.mysqli.php" rel="noreferrer">MySQLi</a> cumbersome. Also, separating the query from the inputs concerns me, because although it's crucial to get the order correct it's easy to make a mistake, and thus write the wrong data to the wrong fields.</p>
|
[
{
"answer_id": 47108,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": -1,
"selected": false,
"text": "$_GET $_POST $_COOKIE"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/47087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
47,089 |
<p>About 6 months ago I rolled out a site where every request needed to be over https. The only way at the time I could find to ensure that every request to a page was over https was to check it in the page load event. If the request was not over http I would response.redirect("<a href="https://example.com" rel="noreferrer">https://example.com</a>")</p>
<p>Is there a better way -- ideally some setting in the web.config?</p>
|
[
{
"answer_id": 47095,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 9,
"selected": true,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration>\n <system.webServer>\n <rewrite>\n <rules>\n <rule name=\"HTTP to HTTPS redirect\" stopProcessing=\"true\">\n <match url=\"(.*)\" />\n <conditions>\n <add input=\"{HTTPS}\" pattern=\"off\" ignoreCase=\"true\" />\n </conditions>\n <action type=\"Redirect\" url=\"https://{HTTP_HOST}/{R:1}\"\n redirectType=\"Permanent\" />\n </rule>\n </rules>\n <outboundRules>\n <rule name=\"Add Strict-Transport-Security when HTTPS\" enabled=\"true\">\n <match serverVariable=\"RESPONSE_Strict_Transport_Security\"\n pattern=\".*\" />\n <conditions>\n <add input=\"{HTTPS}\" pattern=\"on\" ignoreCase=\"true\" />\n </conditions>\n <action type=\"Rewrite\" value=\"max-age=31536000\" />\n </rule>\n </outboundRules>\n </rewrite>\n </system.webServer>\n</configuration>\n protected void Application_BeginRequest(Object sender, EventArgs e)\n{\n if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false))\n {\n Response.Redirect(\"https://\" + Request.ServerVariables[\"HTTP_HOST\"]\n+ HttpContext.Current.Request.RawUrl);\n }\n}\n"
},
{
"answer_id": 47110,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": false,
"text": "using System;\nusing System.Web;\n\nnamespace HttpsOnly\n{\n /// <summary>\n /// Redirects the Request to HTTPS if it comes in on an insecure channel.\n /// </summary>\n public class HttpsOnlyModule : IHttpModule\n {\n public void Init(HttpApplication app)\n {\n // Note we cannot trust IsSecureConnection when \n // in a webfarm, because usually only the load balancer \n // will come in on a secure port the request will be then \n // internally redirected to local machine on a specified port.\n\n // Move this to a config file, if your behind a farm, \n // set this to the local port used internally.\n int specialPort = 443;\n\n if (!app.Context.Request.IsSecureConnection \n || app.Context.Request.Url.Port != specialPort)\n {\n app.Context.Response.Redirect(\"https://\" \n + app.Context.Request.ServerVariables[\"HTTP_HOST\"] \n + app.Context.Request.RawUrl); \n }\n }\n\n public void Dispose()\n {\n // Needed for IHttpModule\n }\n }\n}\n <httpModules>\n <add name=\"HttpsOnlyModule\" type=\"HttpsOnly.HttpsOnlyModule, HttpsOnly\" />\n </httpModules>\n"
},
{
"answer_id": 2269476,
"author": "Mark",
"author_id": 18264,
"author_profile": "https://Stackoverflow.com/users/18264",
"pm_score": 7,
"selected": false,
"text": " <rewrite>\n <rules>\n <rule name=\"Redirect HTTP to HTTPS\" stopProcessing=\"true\">\n <match url=\"(.*)\"/>\n <conditions>\n <add input=\"{HTTPS}\" pattern=\"^OFF$\"/>\n </conditions>\n <action type=\"Redirect\" url=\"https://{HTTP_HOST}/{R:1}\" redirectType=\"SeeOther\"/>\n </rule>\n </rules>\n </rewrite>\n"
},
{
"answer_id": 4190691,
"author": "Alexander",
"author_id": 509015,
"author_profile": "https://Stackoverflow.com/users/509015",
"pm_score": 2,
"selected": false,
"text": "X-WebMux-SSL-termination: true"
},
{
"answer_id": 8234498,
"author": "Troy Hunt",
"author_id": 73948,
"author_profile": "https://Stackoverflow.com/users/73948",
"pm_score": 7,
"selected": false,
"text": "protected void Application_BeginRequest(Object sender, EventArgs e)\n{\n switch (Request.Url.Scheme)\n {\n case \"https\":\n Response.AddHeader(\"Strict-Transport-Security\", \"max-age=300\");\n break;\n case \"http\":\n var path = \"https://\" + Request.Url.Host + Request.Url.PathAndQuery;\n Response.Status = \"301 Moved Permanently\";\n Response.AddHeader(\"Location\", path);\n break;\n }\n}\n"
},
{
"answer_id": 13847410,
"author": "Paul Schroeder",
"author_id": 1392711,
"author_profile": "https://Stackoverflow.com/users/1392711",
"pm_score": 2,
"selected": false,
"text": " public bool JustRedirected\n {\n get\n {\n if (Session[RosadaConst.JUSTREDIRECTED] == null)\n return false;\n\n return (bool)Session[RosadaConst.JUSTREDIRECTED];\n }\n set\n {\n Session[RosadaConst.JUSTREDIRECTED] = value;\n }\n }\n"
},
{
"answer_id": 26232427,
"author": "Chandan Kumar",
"author_id": 707137,
"author_profile": "https://Stackoverflow.com/users/707137",
"pm_score": 3,
"selected": false,
"text": "<add key=\"HttpsServer\" value=\"stage\"/>\n or\n<add key=\"HttpsServer\" value=\"prod\"/>\n void Application_BeginRequest(Object sender, EventArgs e)\n{\n //if (ConfigurationManager.AppSettings[\"HttpsServer\"].ToString() == \"prod\")\n if (ConfigurationManager.AppSettings[\"HttpsServer\"].ToString() == \"stage\")\n {\n if (!HttpContext.Current.Request.IsSecureConnection)\n {\n if (!Request.Url.GetLeftPart(UriPartial.Authority).Contains(\"www\"))\n {\n HttpContext.Current.Response.Redirect(\n Request.Url.GetLeftPart(UriPartial.Authority).Replace(\"http://\", \"https://www.\"), true);\n }\n else\n {\n HttpContext.Current.Response.Redirect(\n Request.Url.GetLeftPart(UriPartial.Authority).Replace(\"http://\", \"https://\"), true);\n }\n }\n }\n}\n"
},
{
"answer_id": 29126120,
"author": "Muhammad Rehan Saeed",
"author_id": 1212017,
"author_profile": "https://Stackoverflow.com/users/1212017",
"pm_score": 5,
"selected": false,
"text": "GlobalFilters.Filters.Add(new RequireHttpsAttribute());\n AntiForgeryConfig.RequireSsl = true;\n <system.web>\n <httpCookies httpOnlyCookies=\"true\" requireSSL=\"true\" />\n</system.web>\n // app is your OWIN IAppBuilder app in Startup.cs\napp.UseHsts(options => options.MaxAge(days: 30).Preload());\n // app is your OWIN IAppBuilder app in Startup.cs\napp.UseHpkp(options => options\n .Sha256Pins(\n \"Base64 encoded SHA-256 hash of your first certificate e.g. cUPcTAZWKaASuYWhhneDttWpY3oBAkE3h2+soZS7sWs=\",\n \"Base64 encoded SHA-256 hash of your second backup certificate e.g. M8HztCzM3elUxkcjR2S5P4hhyBNf6lHkmjAHKhpGPWE=\")\n .MaxAge(days: 30));\n <script src=\"https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.4/bootstrap.min.js\"></script>\n"
},
{
"answer_id": 33682196,
"author": "Gup3rSuR4c",
"author_id": 188081,
"author_profile": "https://Stackoverflow.com/users/188081",
"pm_score": 2,
"selected": false,
"text": "HTTPS FTP HTTP https://blah.com HSTS"
},
{
"answer_id": 39425833,
"author": "noelicus",
"author_id": 865643,
"author_profile": "https://Stackoverflow.com/users/865643",
"pm_score": 2,
"selected": false,
"text": "WebApplication Global.asax.cs protected void Application_BeginRequest(Object sender, EventArgs e)\n {\n // Allow https pages in debugging\n if (Request.IsLocal)\n {\n if (Request.Url.Scheme == \"http\")\n {\n int localSslPort = 44362; // Your local IIS port for HTTPS\n\n var path = \"https://\" + Request.Url.Host + \":\" + localSslPort + Request.Url.PathAndQuery;\n\n Response.Status = \"301 Moved Permanently\";\n Response.AddHeader(\"Location\", path);\n }\n }\n else\n {\n switch (Request.Url.Scheme)\n {\n case \"https\":\n Response.AddHeader(\"Strict-Transport-Security\", \"max-age=31536000\");\n break;\n case \"http\":\n var path = \"https://\" + Request.Url.Host + Request.Url.PathAndQuery;\n Response.Status = \"301 Moved Permanently\";\n Response.AddHeader(\"Location\", path);\n break;\n }\n }\n }\n"
},
{
"answer_id": 42969197,
"author": "user7755300",
"author_id": 7755300,
"author_profile": "https://Stackoverflow.com/users/7755300",
"pm_score": 1,
"selected": false,
"text": "app.UseHttpsWithHsts(HttpsMode.AllowedRedirectForGet, configureRoutes: routeAction);\n"
},
{
"answer_id": 52229827,
"author": "Nour Lababidi",
"author_id": 1461144,
"author_profile": "https://Stackoverflow.com/users/1461144",
"pm_score": 2,
"selected": false,
"text": "<system.webServer> \n <rewrite>\n <rules>\n <rule name=\"HTTP/S to HTTPS Redirect\" enabled=\"true\" \n stopProcessing=\"true\">\n <match url=\"(.*)\" />\n <conditions logicalGrouping=\"MatchAny\">\n <add input=\"{SERVER_PORT_SECURE}\" pattern=\"^0$\" />\n </conditions>\n <action type=\"Redirect\" url=\"https://{HTTP_HOST}{REQUEST_URI}\" \n redirectType=\"Permanent\" />\n </rule>\n </rules>\n </rewrite>\n"
},
{
"answer_id": 53457767,
"author": "Mike",
"author_id": 914490,
"author_profile": "https://Stackoverflow.com/users/914490",
"pm_score": 3,
"selected": false,
"text": "<site> <hsts enabled=\"true\" max-age=\"31536000\" includeSubDomains=\"true\" redirectHttpToHttps=\"true\" />\n c:\ncd C:\\WINDOWS\\system32\\inetsrv\\\nappcmd.exe set config -section:system.applicationHost/sites \"/[name='Contoso'].hsts.enabled:True\" /commit:apphost\nappcmd.exe set config -section:system.applicationHost/sites \"/[name='Contoso'].hsts.max-age:31536000\" /commit:apphost\nappcmd.exe set config -section:system.applicationHost/sites \"/[name='Contoso'].hsts.includeSubDomains:True\" /commit:apphost\nappcmd.exe set config -section:system.applicationHost/sites \"/[name='Contoso'].hsts.redirectHttpToHttps:True\" /commit:apphost\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/47089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4846/"
] |
47,104 |
<p>Can anyone explain this behavior or how to get around it?</p>
<p>If you execute this query:</p>
<pre><code>select *
from TblA
left join freetexttable ( TblB, *, 'query' ) on TblA.ID = [Key]
inner join DifferentDbCatalog.dbo.TblC on TblA.ID = TblC.TblAID
</code></pre>
<p>It will be very very very slow.</p>
<p>If you change that query to use two inner joins instead of a left join, it will be very fast. If you change it to use two left joins instead of an inner join, it will be very fast.</p>
<p>You can observe this same behavior if you use a sql table variable instead of the freetexttable as well. </p>
<p>The performance problem arises any time you have a table variable (or freetexttable) and a table in a different database catalog where one is in an inner join and the other is in a left join.</p>
<p>Does anyone know why this is slow, or how to speed it up?</p>
|
[
{
"answer_id": 47128,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "SELECT * \nFROM TblA\nINNER JOIN DifferentDbCatalog.dbo.TblC on TblA.ID = TblC.TblAID\nLEFT JOIN freetexttable ( TblB, *, 'query' ) on TblA.ID = [Key]\n"
},
{
"answer_id": 47131,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 1,
"selected": false,
"text": "freetexttable(TblB, *, 'query')"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/47104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4407/"
] |
47,107 |
<p>Is there a way to disallow publishing of debug builds with ClickOnce?</p>
<p>I only want to allow release builds through, but right now human error causes a debug build to slip through once in a while. </p>
<p>We're publishing the build from within Visual Studio.</p>
|
[
{
"answer_id": 865822,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 3,
"selected": false,
"text": "<Choose>\n <When Condition=\" '$(Configuration)'=='Debug' \">\n <Exec Command=\"C:\\foo.bat\" ContinueOnError=\"false\" />\n </When>\n </Choose>\n"
},
{
"answer_id": 15080048,
"author": "Sam Storie",
"author_id": 571237,
"author_profile": "https://Stackoverflow.com/users/571237",
"pm_score": 7,
"selected": true,
"text": "<!-- The following makes sure we don’t try to publish a configuration that defines the DEBUG constant -->\n<Target Name=\"BeforePublish\">\n <Error Condition=\"'$(DebugSymbols)' == 'true'\" Text=\"You attempted to publish a configuration that defines the DEBUG constant!\" />\n</Target>\n </Project>"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/47107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3641/"
] |
47,144 |
<p>In my C# program, I have a thread that represents a running test, which can be aborted by a click on a button labeled "Interrupt execution". In order for the thread (and therefore the test) to terminate in an elegant manner (and do some vital work beforehand), this button is enabled only in some well-defined moments, in which I catch <code>ThreadAbortedException</code>, do <code>Thread.ResetAbort()</code> and die beautifully (that is, the thread).</p>
<p>The problem is that, in the time window in which aborting is possible, there are some tasks that need to be done from start to finish once initiated, and, so, I fear TAE. Locks don't provide a solution for this, and, although finally blocks do, I don't find it elegant to wrap important code in the following manner:</p>
<pre><code>try {
} finally {
// vital code
}
</code></pre>
<p>However, I didn't find any other solution.</p>
<p>Is this another way to delay the interference of <code>ThreadAbortException</code> until the end of the block?</p>
|
[
{
"answer_id": 47150,
"author": "Corey",
"author_id": 1595,
"author_profile": "https://Stackoverflow.com/users/1595",
"pm_score": 2,
"selected": false,
"text": "Thread.BeginCriticalRegion()\n\n//do important stuff here\n\nThread.EndCriticalRegion()\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4850/"
] |
47,169 |
<p>I'd like to enable/disable some other controls based on how many items are in my <code>ListView</code> control. I can't find any event that would do this, either on the <code>ListView</code> itself or on the <code>ListViewItemCollection</code>. Maybe there's a way to generically watch any collection in C# for changes?</p>
<p>I'd be happy with other events too, even ones that sometimes fire when the items don't change, but for example the <code>ControlAdded</code> and <code>Layout</code> events didn't work :(.</p>
|
[
{
"answer_id": 47178,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "Public Class MyListViewItemCollection\n Inherits ListView.ListViewItemCollection\n\n Public Event ItemAdded(ByVal Item As ListViewItem)\n\n Sub New(ByVal owner As ListView)\n MyBase.New(owner)\n End Sub\n\n Public Overrides Function Add(ByVal value As System.Windows.Forms.ListViewItem) As System.Windows.Forms.ListViewItem\n Dim Item As ListViewItem\n\n Item = MyBase.Add(value)\n\n RaiseEvent ItemAdded(Item)\n\n Return Item\n End Function\nEnd Class\n"
},
{
"answer_id": 47200,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 3,
"selected": true,
"text": "Public Class MonitoredListView\n Inherits ListView\n\n Public Event ItemAdded()\n Public Event ItemRemoved()\n\n Public Sub New()\n MyBase.New()\n End Sub\n\n Public Function AddItem(ByVal Text As String) As ListViewItem\n RaiseEvent ItemAdded()\n\n MyBase.Items.Add(Text)\n End Function\n\n Public Sub RemoveItem(ByVal Item As ListViewItem)\n RaiseEvent ItemRemoved()\n\n MyBase.Items.Remove(Item)\n End Sub\n\nEnd Class\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3191/"
] |
47,177 |
<p>I would like to monitor the following system information in Java:</p>
<ul>
<li>Current CPU usage** (percent)</li>
<li>Available memory* (free/total)</li>
<li><p>Available disk space (free/total)</p>
<p>*Note that I mean overall memory available to the whole system, not just the JVM.</p></li>
</ul>
<p>I'm looking for a cross-platform solution (Linux, Mac, and Windows) that doesn't rely on my own code calling external programs or using JNI. Although these are viable options, I would prefer not to maintain OS-specific code myself if someone already has a better solution.</p>
<p>If there's a free library out there that does this in a reliable, cross-platform manner, that would be great (even if it makes external calls or uses native code itself).</p>
<p>Any suggestions are much appreciated.</p>
<p>To clarify, I would like to get the current CPU usage for the whole system, not just the Java process(es).</p>
<p>The SIGAR API provides all the functionality I'm looking for in one package, so it's the best answer to my question so far. However, due it being licensed under the GPL, I cannot use it for my original purpose (a closed source, commercial product). It's possible that Hyperic may license SIGAR for commercial use, but I haven't looked into it. For my GPL projects, I will definitely consider SIGAR in the future.</p>
<p>For my current needs, I'm leaning towards the following:</p>
<ul>
<li>For CPU usage, <code>OperatingSystemMXBean.getSystemLoadAverage() / OperatingSystemMXBean.getAvailableProcessors()</code> (load average per cpu)</li>
<li>For memory, <code>OperatingSystemMXBean.getTotalPhysicalMemorySize()</code> and <code>OperatingSystemMXBean.getFreePhysicalMemorySize()</code></li>
<li>For disk space, <code>File.getTotalSpace()</code> and <code>File.getUsableSpace()</code></li>
</ul>
<p>Limitations:</p>
<p>The <code>getSystemLoadAverage()</code> and disk space querying methods are only available under Java 6. Also, some JMX functionality may not be available to all platforms (i.e. it's been reported that <code>getSystemLoadAverage()</code> returns -1 on Windows).</p>
<p>Although originally licensed under GPL, it <a href="http://forums.hyperic.com/jiveforums/thread.jspa?threadID=11426&tstart=0" rel="noreferrer">has been changed</a> to <a href="http://support.hyperic.com/display/SIGAR/Home#Home-license" rel="noreferrer">Apache 2.0</a>, which can generally be used for closed source, commercial products.</p>
|
[
{
"answer_id": 47199,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 6,
"selected": false,
"text": "import java.lang.management.ManagementFactory;\nimport java.lang.management.OperatingSystemMXBean;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\n\nprivate static void printUsage() {\n OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();\n for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {\n method.setAccessible(true);\n if (method.getName().startsWith(\"get\")\n && Modifier.isPublic(method.getModifiers())) {\n Object value;\n try {\n value = method.invoke(operatingSystemMXBean);\n } catch (Exception e) {\n value = e;\n } // try\n System.out.println(method.getName() + \" = \" + value);\n } // if\n } // for\n}\n"
},
{
"answer_id": 835213,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " private double getAverageValueByLinux() throws InterruptedException {\n try {\n\n long delay = 50;\n List<Double> listValues = new ArrayList<Double>();\n for (int i = 0; i < 100; i++) {\n long cput1 = getCpuT();\n Thread.sleep(delay);\n long cput2 = getCpuT();\n double cpuproc = (1000d * (cput2 - cput1)) / (double) delay;\n listValues.add(cpuproc);\n }\n listValues.remove(0);\n listValues.remove(listValues.size() - 1);\n double sum = 0.0;\n for (Double double1 : listValues) {\n sum += double1;\n }\n return sum / listValues.size();\n } catch (Exception e) {\n e.printStackTrace();\n return 0;\n }\n\n}\n\nprivate long getCpuT throws FileNotFoundException, IOException {\n BufferedReader reader = new BufferedReader(new FileReader(\"/proc/stat\"));\n String line = reader.readLine();\n Pattern pattern = Pattern.compile(\"\\\\D+(\\\\d+)\\\\D+(\\\\d+)\\\\D+(\\\\d+)\\\\D+(\\\\d+)\")\n Matcher m = pattern.matcher(line);\n\n long cpuUser = 0;\n long cpuSystem = 0;\n if (m.find()) {\n cpuUser = Long.parseLong(m.group(1));\n cpuSystem = Long.parseLong(m.group(3));\n }\n return cpuUser + cpuSystem;\n}\n"
},
{
"answer_id": 2841055,
"author": "Md. Mukit Hasan",
"author_id": 342030,
"author_profile": "https://Stackoverflow.com/users/342030",
"pm_score": 2,
"selected": false,
"text": "public MProcessor() {\n String s;\n try {\n Process ps = Runtime.getRuntime().exec(\"Pc.bat\");\n BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));\n while((s = br.readLine()) != null) {\n System.out.println(s);\n }\n }\n catch( Exception ex ) {\n System.out.println(ex.toString());\n }\n}\n"
},
{
"answer_id": 3095779,
"author": "ludovicc",
"author_id": 373467,
"author_profile": "https://Stackoverflow.com/users/373467",
"pm_score": 4,
"selected": false,
"text": "MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer();\n\nOperatingSystemMXBean osMBean = ManagementFactory.newPlatformMXBeanProxy(\nmbsc, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);\n\nlong nanoBefore = System.nanoTime();\nlong cpuBefore = osMBean.getProcessCpuTime();\n\n// Call an expensive task, or sleep if you are monitoring a remote process\n\nlong cpuAfter = osMBean.getProcessCpuTime();\nlong nanoAfter = System.nanoTime();\n\nlong percent;\nif (nanoAfter > nanoBefore)\n percent = ((cpuAfter-cpuBefore)*100L)/\n (nanoAfter-nanoBefore);\nelse percent = 0;\n\nSystem.out.println(\"Cpu usage: \"+percent+\"%\");\n com.sun.management.OperatingSystemMXBean java.lang.management.OperatingSystemMXBean"
},
{
"answer_id": 13034111,
"author": "Gp2you",
"author_id": 1659061,
"author_profile": "https://Stackoverflow.com/users/1659061",
"pm_score": 6,
"selected": false,
"text": "com.sun.management.OperatingSystemMXBean java.lang.management.OperatingSystemMXBean long getCommittedVirtualMemorySize()\n// Returns the amount of virtual memory that is guaranteed to be available to the running process in bytes, or -1 if this operation is not supported.\n\nlong getFreePhysicalMemorySize()\n// Returns the amount of free physical memory in bytes.\n\nlong getFreeSwapSpaceSize()\n// Returns the amount of free swap space in bytes.\n\ndouble getProcessCpuLoad()\n// Returns the \"recent cpu usage\" for the Java Virtual Machine process.\n\nlong getProcessCpuTime()\n// Returns the CPU time used by the process on which the Java virtual machine is running in nanoseconds.\n\ndouble getSystemCpuLoad()\n// Returns the \"recent cpu usage\" for the whole system.\n\nlong getTotalPhysicalMemorySize()\n// Returns the total amount of physical memory in bytes.\n\nlong getTotalSwapSpaceSize()\n// Returns the total amount of swap space in bytes.\n"
},
{
"answer_id": 21772609,
"author": "pragati",
"author_id": 3309149,
"author_profile": "https://Stackoverflow.com/users/3309149",
"pm_score": 3,
"selected": false,
"text": "/* YOU CAN TRY THIS TOO */\n\nimport java.io.File;\n import java.lang.management.ManagementFactory;\n// import java.lang.management.OperatingSystemMXBean;\n import java.lang.reflect.Method;\n import java.lang.reflect.Modifier;\n import java.lang.management.RuntimeMXBean;\n import java.io.*;\n import java.net.*;\n import java.util.*;\n import java.io.LineNumberReader;\n import java.lang.management.ManagementFactory;\nimport com.sun.management.OperatingSystemMXBean;\nimport java.lang.management.ManagementFactory;\nimport java.util.Random;\n\n\n\n public class Pragati\n {\n\n public static void printUsage(Runtime runtime)\n {\n long total, free, used;\n int mb = 1024*1024;\n\n total = runtime.totalMemory();\n free = runtime.freeMemory();\n used = total - free;\n System.out.println(\"\\nTotal Memory: \" + total / mb + \"MB\");\n System.out.println(\" Memory Used: \" + used / mb + \"MB\");\n System.out.println(\" Memory Free: \" + free / mb + \"MB\");\n System.out.println(\"Percent Used: \" + ((double)used/(double)total)*100 + \"%\");\n System.out.println(\"Percent Free: \" + ((double)free/(double)total)*100 + \"%\");\n }\n public static void log(Object message)\n {\n System.out.println(message);\n }\n\n public static int calcCPU(long cpuStartTime, long elapsedStartTime, int cpuCount)\n {\n long end = System.nanoTime();\n long totalAvailCPUTime = cpuCount * (end-elapsedStartTime);\n long totalUsedCPUTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime()-cpuStartTime;\n //log(\"Total CPU Time:\" + totalUsedCPUTime + \" ns.\");\n //log(\"Total Avail CPU Time:\" + totalAvailCPUTime + \" ns.\");\n float per = ((float)totalUsedCPUTime*100)/(float)totalAvailCPUTime;\n log( per);\n return (int)per;\n }\n\n static boolean isPrime(int n)\n {\n // 2 is the smallest prime\n if (n <= 2)\n {\n return n == 2;\n }\n // even numbers other than 2 are not prime\n if (n % 2 == 0)\n {\n return false;\n }\n // check odd divisors from 3\n // to the square root of n\n for (int i = 3, end = (int)Math.sqrt(n); i <= end; i += 2)\n {\n if (n % i == 0)\n {\n return false;\n }\n }\n return true;\n}\n public static void main(String [] args)\n {\n int mb = 1024*1024;\n int gb = 1024*1024*1024;\n /* PHYSICAL MEMORY USAGE */\n System.out.println(\"\\n**** Sizes in Mega Bytes ****\\n\");\n com.sun.management.OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean();\n //RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();\n //operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();\n com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean)\n java.lang.management.ManagementFactory.getOperatingSystemMXBean();\n long physicalMemorySize = os.getTotalPhysicalMemorySize();\n System.out.println(\"PHYSICAL MEMORY DETAILS \\n\");\n System.out.println(\"total physical memory : \" + physicalMemorySize / mb + \"MB \");\n long physicalfreeMemorySize = os.getFreePhysicalMemorySize();\n System.out.println(\"total free physical memory : \" + physicalfreeMemorySize / mb + \"MB\");\n /* DISC SPACE DETAILS */\n File diskPartition = new File(\"C:\");\n File diskPartition1 = new File(\"D:\");\n File diskPartition2 = new File(\"E:\");\n long totalCapacity = diskPartition.getTotalSpace() / gb;\n long totalCapacity1 = diskPartition1.getTotalSpace() / gb;\n double freePartitionSpace = diskPartition.getFreeSpace() / gb;\n double freePartitionSpace1 = diskPartition1.getFreeSpace() / gb;\n double freePartitionSpace2 = diskPartition2.getFreeSpace() / gb;\n double usablePatitionSpace = diskPartition.getUsableSpace() / gb;\n System.out.println(\"\\n**** Sizes in Giga Bytes ****\\n\");\n System.out.println(\"DISC SPACE DETAILS \\n\");\n //System.out.println(\"Total C partition size : \" + totalCapacity + \"GB\");\n //System.out.println(\"Usable Space : \" + usablePatitionSpace + \"GB\");\n System.out.println(\"Free Space in drive C: : \" + freePartitionSpace + \"GB\");\n System.out.println(\"Free Space in drive D: : \" + freePartitionSpace1 + \"GB\");\n System.out.println(\"Free Space in drive E: \" + freePartitionSpace2 + \"GB\");\n if(freePartitionSpace <= totalCapacity%10 || freePartitionSpace1 <= totalCapacity1%10)\n {\n System.out.println(\" !!!alert!!!!\");\n }\n else\n System.out.println(\"no alert\");\n\n Runtime runtime;\n byte[] bytes;\n System.out.println(\"\\n \\n**MEMORY DETAILS ** \\n\");\n // Print initial memory usage.\n runtime = Runtime.getRuntime();\n printUsage(runtime);\n\n // Allocate a 1 Megabyte and print memory usage\n bytes = new byte[1024*1024];\n printUsage(runtime);\n\n bytes = null;\n // Invoke garbage collector to reclaim the allocated memory.\n runtime.gc();\n\n // Wait 5 seconds to give garbage collector a chance to run\n try {\n Thread.sleep(5000);\n } catch(InterruptedException e) {\n e.printStackTrace();\n return;\n }\n\n // Total memory will probably be the same as the second printUsage call,\n // but the free memory should be about 1 Megabyte larger if garbage\n // collection kicked in.\n printUsage(runtime);\n for(int i = 0; i < 30; i++)\n {\n long start = System.nanoTime();\n // log(start);\n //number of available processors;\n int cpuCount = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();\n Random random = new Random(start);\n int seed = Math.abs(random.nextInt());\n log(\"\\n \\n CPU USAGE DETAILS \\n\\n\");\n log(\"Starting Test with \" + cpuCount + \" CPUs and random number:\" + seed);\n int primes = 10000;\n //\n long startCPUTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();\n start = System.nanoTime();\n while(primes != 0)\n {\n if(isPrime(seed))\n {\n primes--;\n }\n seed++;\n\n }\n float cpuPercent = calcCPU(startCPUTime, start, cpuCount);\n log(\"CPU USAGE : \" + cpuPercent + \" % \");\n\n\n try\n {\n Thread.sleep(1000);\n }\n catch (InterruptedException e) {}\n }\n\n try\n {\n Thread.sleep(500);\n }`enter code here`\n catch (Exception ignored) { }\n }\n }\n"
},
{
"answer_id": 27282046,
"author": "bizzr3",
"author_id": 1020474,
"author_profile": "https://Stackoverflow.com/users/1020474",
"pm_score": 5,
"selected": false,
"text": "import com.sun.management.OperatingSystemMXBean;\n...\nOperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(\n OperatingSystemMXBean.class);\n// What % CPU load this current JVM is taking, from 0.0-1.0\nSystem.out.println(osBean.getProcessCpuLoad());\n\n// What % load the overall system is at, from 0.0-1.0\nSystem.out.println(osBean.getSystemCpuLoad());\n"
},
{
"answer_id": 68758496,
"author": "Coderman69",
"author_id": 14999071,
"author_profile": "https://Stackoverflow.com/users/14999071",
"pm_score": 0,
"selected": false,
"text": " OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);\n System.out.println((osBean.getCpuLoad() * 100) + \"%\");\n com.sun.management.OperatingSystemMXBean"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2783/"
] |
47,198 |
<p>If I was going to start an open source project using Python what version should I use to ensure that the vast majority of users can use it on their system?</p>
<p>I'm the kind of person who quickly jumps to the next version (which I'll do when Python 3 comes out) but many people may be more conservative if their current version seems to be working fine. What version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements?</p>
|
[
{
"answer_id": 47201,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 2,
"selected": false,
"text": "from __future__ import *\n"
},
{
"answer_id": 47264,
"author": "Christopher Mahan",
"author_id": 479,
"author_profile": "https://Stackoverflow.com/users/479",
"pm_score": 1,
"selected": false,
"text": "apt-get install python2.5"
},
{
"answer_id": 7695227,
"author": "Mechanical snail",
"author_id": 319931,
"author_profile": "https://Stackoverflow.com/users/319931",
"pm_score": 0,
"selected": false,
"text": "2to3"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
] |
47,203 |
<p>When should I choose one or the other? What are the implications regarding space and (full-text) indexing?</p>
<p>BTW: I'm currently using SQL Server 2005 planing to upgrade to 2008 in the following months.</p>
<p>Thanks</p>
|
[
{
"answer_id": 47214,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 5,
"selected": true,
"text": "varbinary(max) SqlParameter varbinary(max) varchar(max)"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148/"
] |
47,207 |
<p>Can i print out a url <code>/admin/manage/products/add</code> of a certain view in a template?</p>
<p>Here is the rule i want to create a link for</p>
<pre><code>(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),
</code></pre>
<p>I would like to have /manage/products/add in a template without hardcoding it. How can i do this?</p>
<p><strong>Edit:</strong> I am not using the default admin (well, i am but it is at another url), this is my own</p>
|
[
{
"answer_id": 47212,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 2,
"selected": false,
"text": "{% url create_object %}\n"
},
{
"answer_id": 47213,
"author": "Cristian",
"author_id": 680,
"author_profile": "https://Stackoverflow.com/users/680",
"pm_score": 0,
"selected": false,
"text": "get_absolute_url permalink"
},
{
"answer_id": 47304,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 5,
"selected": true,
"text": "get_absolute_url (r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}, \"create-product\"),\n {% url create-product %}\n {% url 'create-product' %}\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
] |
47,217 |
<p>I've got a DataSet in VisualStudio 2005. I need to change the datatype of a column in one of the datatables from <code>System.Int32</code> to <code>System.Decimal</code>. When I try to change the datatype in the <code>DataSet Designer</code> I receive the following error:</p>
<blockquote>
<p>Property value is not valid. Cannot change DataType of a column once
it has data.</p>
</blockquote>
<p>From my understanding, this should be changing the datatype in the schema for the DataSet. I don't see how there can be any data to cause this error.</p>
<p>Does any one have any ideas?</p>
|
[
{
"answer_id": 1905709,
"author": "Are",
"author_id": 231880,
"author_profile": "https://Stackoverflow.com/users/231880",
"pm_score": 6,
"selected": true,
"text": "DefaultValue <DBNull> <DBNull>"
},
{
"answer_id": 34353698,
"author": "ldam",
"author_id": 1492861,
"author_profile": "https://Stackoverflow.com/users/1492861",
"pm_score": 2,
"selected": false,
"text": "var column = myTable.Columns.Add(\"Column1\");\ncolumn.DataType = typeof(int); //nope, exception!\n var column = myTable.Columns.Add(\"Column1\", typeof(int));\n"
},
{
"answer_id": 58379030,
"author": "Caius Jard",
"author_id": 1410664,
"author_profile": "https://Stackoverflow.com/users/1410664",
"pm_score": 0,
"selected": false,
"text": "Open With... XML (Text) Editor <xs:element name=\"DataColumn1\"\n msprop:Generator_ColumnVarNameInTable=\"columnDataColumn1\"\n msprop:Generator_ColumnPropNameInRow=\"DataColumn1\"\n msprop:Generator_ColumnPropNameInTable=\"DataColumn1Column\"\n msprop:Generator_UserColumnName=\"DataColumn1\" \n type=\"xs:int\" \n minOccurs=\"0\" />\n type=\"xs:int\" type=\"xs:decimal\" Run Custom Tool"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3123/"
] |
47,239 |
<p>Does anyone know a way to auto-generate database tables for a given class? I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand. For example, given the following class:</p>
<pre><code>class Foo
{
private string property1;
public string Property1
{
get { return property1; }
set { property1 = value; }
}
private int property2;
public int Property2
{
get { return property2; }
set { property2 = value; }
}
}
</code></pre>
<p>I'd expect the following SQL:</p>
<pre><code>CREATE TABLE Foo
(
Property1 VARCHAR(500),
Property2 INT
)
</code></pre>
<p>I'm also wondering how you could handle complex types. For example, in the previously cited class, if we changed that to be :</p>
<pre><code>class Foo
{
private string property1;
public string Property1
{
get { return property1; }
set { property1 = value; }
}
private System.Management.ManagementObject property2;
public System.Management.ManagementObject Property2
{
get { return property2; }
set { property2 = value; }
}
}
</code></pre>
<p></p>
<p>How could I handle this?</p>
<p>I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped.</p>
|
[
{
"answer_id": 47251,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE MiscTypes /* may have to include standard types as well */\n ( TypeID INT,\n TypeName VARCHAR(...)\n )\n\nCREATE TABLE MiscProperties\n ( PropertyID INT,\n DeclaringTypeID INT, /* FK to MiscTypes */\n PropertyName VARCHAR(...),\n ValueTypeID INT /* FK to MiscTypes */\n )\n\nCREATE TABLE MiscData\n ( ObjectID INT,\n TypeID INT\n )\n\nCREATE TABLE MiscValues\n ( ObjectID INT, /* FK to MiscData*/\n PropertyID INT,\n Value VARCHAR(...)\n )\n"
},
{
"answer_id": 47273,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 8,
"selected": true,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Reflection;\n\nnamespace TableGenerator\n{\n class Program\n {\n static void Main(string[] args)\n {\n List<TableClass> tables = new List<TableClass>();\n\n // Pass assembly name via argument\n Assembly a = Assembly.LoadFile(args[0]);\n\n Type[] types = a.GetTypes();\n\n // Get Types in the assembly.\n foreach (Type t in types)\n {\n TableClass tc = new TableClass(t); \n tables.Add(tc);\n }\n\n // Create SQL for each table\n foreach (TableClass table in tables)\n {\n Console.WriteLine(table.CreateTableScript());\n Console.WriteLine();\n }\n\n // Total Hacked way to find FK relationships! Too lazy to fix right now\n foreach (TableClass table in tables)\n {\n foreach (KeyValuePair<String, Type> field in table.Fields)\n {\n foreach (TableClass t2 in tables)\n {\n if (field.Value.Name == t2.ClassName)\n {\n // We have a FK Relationship!\n Console.WriteLine(\"GO\");\n Console.WriteLine(\"ALTER TABLE \" + table.ClassName + \" WITH NOCHECK\");\n Console.WriteLine(\"ADD CONSTRAINT FK_\" + field.Key + \" FOREIGN KEY (\" + field.Key + \") REFERENCES \" + t2.ClassName + \"(ID)\");\n Console.WriteLine(\"GO\");\n\n }\n }\n }\n }\n }\n }\n\n public class TableClass\n {\n private List<KeyValuePair<String, Type>> _fieldInfo = new List<KeyValuePair<String, Type>>();\n private string _className = String.Empty;\n\n private Dictionary<Type, String> dataMapper\n {\n get\n {\n // Add the rest of your CLR Types to SQL Types mapping here\n Dictionary<Type, String> dataMapper = new Dictionary<Type, string>();\n dataMapper.Add(typeof(int), \"BIGINT\");\n dataMapper.Add(typeof(string), \"NVARCHAR(500)\");\n dataMapper.Add(typeof(bool), \"BIT\");\n dataMapper.Add(typeof(DateTime), \"DATETIME\");\n dataMapper.Add(typeof(float), \"FLOAT\");\n dataMapper.Add(typeof(decimal), \"DECIMAL(18,0)\");\n dataMapper.Add(typeof(Guid), \"UNIQUEIDENTIFIER\");\n\n return dataMapper;\n }\n }\n\n public List<KeyValuePair<String, Type>> Fields\n {\n get { return this._fieldInfo; }\n set { this._fieldInfo = value; }\n }\n\n public string ClassName\n {\n get { return this._className; }\n set { this._className = value; }\n }\n\n public TableClass(Type t)\n {\n this._className = t.Name;\n\n foreach (PropertyInfo p in t.GetProperties())\n {\n KeyValuePair<String, Type> field = new KeyValuePair<String, Type>(p.Name, p.PropertyType);\n\n this.Fields.Add(field);\n }\n }\n\n public string CreateTableScript()\n {\n System.Text.StringBuilder script = new StringBuilder();\n\n script.AppendLine(\"CREATE TABLE \" + this.ClassName);\n script.AppendLine(\"(\");\n script.AppendLine(\"\\t ID BIGINT,\");\n for (int i = 0; i < this.Fields.Count; i++)\n {\n KeyValuePair<String, Type> field = this.Fields[i];\n\n if (dataMapper.ContainsKey(field.Value))\n {\n script.Append(\"\\t \" + field.Key + \" \" + dataMapper[field.Value]);\n }\n else\n {\n // Complex Type? \n script.Append(\"\\t \" + field.Key + \" BIGINT\");\n }\n\n if (i != this.Fields.Count - 1)\n {\n script.Append(\",\");\n }\n\n script.Append(Environment.NewLine);\n }\n\n script.AppendLine(\")\");\n\n return script.ToString();\n }\n }\n}\n public class FakeDataClass\n{\n public int AnInt\n {\n get;\n set;\n }\n\n public string AString\n {\n get;\n set;\n }\n\n public float AFloat\n {\n get;\n set;\n }\n\n public FKClass AFKReference\n {\n get;\n set;\n }\n}\n\npublic class FKClass\n {\n public int AFKInt\n {\n get;\n set;\n }\n }\n CREATE TABLE FakeDataClass\n(\n ID BIGINT,\n AnInt BIGINT,\n AString NVARCHAR(255),\n AFloat FLOAT,\n AFKReference BIGINT\n)\n\n\nCREATE TABLE FKClass\n(\n ID BIGINT,\n AFKInt BIGINT\n)\n\n\nGO\nALTER TABLE FakeDataClass WITH NOCHECK\nADD CONSTRAINT FK_AFKReference FOREIGN KEY (AFKReference) REFERENCES FKClass(ID)\nGO\n"
},
{
"answer_id": 47389,
"author": "Portman",
"author_id": 1690,
"author_profile": "https://Stackoverflow.com/users/1690",
"pm_score": 4,
"selected": false,
"text": "// Create new table, called TestTable\nTable newTable = new Table(db, \"TestTable\");\n // Create a PK Index for the table\nIndex index = new Index(newTable, \"PK_TestTable\");\nindex.IndexKeyType = IndexKeyType.DriPrimaryKey;\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4550/"
] |
47,309 |
<p>I'm trying to install <a href="http://godi.camlcity.org/godi/index.html" rel="noreferrer">GODI</a> on linux (Ubuntu). It's a library management tool for the ocaml language. I've actually installed this before --twice, but awhile ago-- with no issues --that I can remember-- but this time I just can't figure out what I'm missing.</p>
<pre><code>$ ./bootstrap --prefix /home/nlucaroni/godi
$ ./bootstrap_stage2
.: 1: godi_confdir: not found
Error: Command fails with code 2: /bin/sh
Failure!
</code></pre>
<p>I had added the proper directories to the path, and they show up with a quick <code>echo $path</code>, and <code>godi_confdir</code> reported as being:</p>
<pre><code> /home/nlucaroni/godi/etc
</code></pre>
<p>(...and the directory exists, with the godi.conf file present). So, I can't figure out why <code>./bootstrap_stage2</code> isn't working.</p>
|
[
{
"answer_id": 47655,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 2,
"selected": false,
"text": "which godi_confdir"
},
{
"answer_id": 47678,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 2,
"selected": true,
"text": "/tmp/ GODI_BASEPKG_PCRE godi.conf conf-opengl-6 GL/gl.h Checking the suggestion > ===> Configuring for conf-opengl-6\n> Checking the suggestion\n> Include=/usr/include/GL/gl.h Library=/<GLU+GL>\n> Checking /usr:\n> Include=/usr/include/GL/gl.h Library=/usr/lib/<GLU+GL>\n> Checking /usr:\n> Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/<GLU+GL>\n> Checking /usr/local:\n> Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/<GLU+GL>\n> Exception: Failure \"Cannot find library\".\n> Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1022: Command returned with non-zero exit code\n> Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1375: Command returned with non-zero exit code\n\n### Error: Command fails with code 1: godi_console\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157/"
] |
47,329 |
<p>I'm implementing a custom control and in this control I need to write a bunch of links to the current page, each one with a different query parameter. I need to keep existing query string intact, and add (or modify the value of ) an extra query item (eg. "page"):</p>
<pre><code>"Default.aspx?page=1"
"Default.aspx?page=2"
"Default.aspx?someother=true&page=2"
</code></pre>
<p>etc.</p>
<p>Is there a simple helper method that I can use in the Render method ... uhmm ... like:</p>
<pre><code>Page.ClientScript.SomeURLBuilderMethodHere(this,"page","1");
Page.ClientScript.SomeURLBuilderMethodHere(this,"page","2");
</code></pre>
<p>That will take care of generating a correct URL, maintain existing query string items and not create duplicates eg. page=1&page=2&page=3?</p>
<p>Rolling up my own seems like such an unappealing task.</p>
|
[
{
"answer_id": 47344,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 2,
"selected": true,
"text": " /// <summary>\n /// Set a parameter value in a query string. If the parameter is not found in the passed in query string,\n /// it is added to the end of the query string\n /// </summary>\n /// <param name=\"queryString\">The query string that is to be manipulated</param>\n /// <param name=\"paramName\">The name of the parameter</param>\n /// <param name=\"paramValue\">The value that the parameter is to be set to</param>\n /// <returns>The query string with the parameter set to the new value.</returns>\n public static string SetParameter(string queryString, string paramName, object paramValue)\n {\n //create the regex\n //match paramname=*\n //string regex = String.Format(@\"{0}=[^&]*\", paramName);\n string regex = @\"([&?]{0,1})\" + String.Format(@\"({0}=[^&]*)\", paramName);\n\n RegexOptions options = RegexOptions.RightToLeft;\n // Querystring has parameters...\n if (Regex.IsMatch(queryString, regex, options))\n {\n queryString = Regex.Replace(queryString, regex, String.Format(\"$1{0}={1}\", paramName, paramValue));\n }\n else\n {\n // If no querystring just return the Parameter Key/Value\n if (queryString == String.Empty)\n {\n return String.Format(\"{0}={1}\", paramName, paramValue);\n }\n else\n {\n // Append the new parameter key/value to the end of querystring\n queryString = String.Format(\"{0}&{1}={2}\", queryString, paramName, paramValue);\n }\n }\n return queryString;\n }\n NameValueCollection"
},
{
"answer_id": 47346,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 0,
"selected": false,
"text": "public static string SetParameterInUrl(string url, string paramName, object paramValue)\n{\n int queryStringIndex = url.IndexOf(\"?\");\n string path;\n string queryString;\n if (queryStringIndex >= 0 && !url.EndsWith(\"?\"))\n {\n path = url.Substring(0, queryStringIndex);\n queryString = url.Substring(queryStringIndex + 1);\n }\n else\n {\n path = url;\n queryString = string.Empty;\n }\n return path + \"?\" + SetParameter(queryString, paramName, paramValue);\n}\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3263/"
] |
47,338 |
<p>I have a problem with a sample routing with the preview 5 of asp.net mvc.</p>
<p>In the AccountController I have 2 actions: </p>
<pre><code>public ActionResult Delete()
public ActionResult Delete(string username)
</code></pre>
<p>While trying to look for Account/Delete or Account/Delete?username=davide the ControllerActionInvoker throws a exception saying that Delete request is ambiguous between my tow actions methods.</p>
<p>The default route in the global.asax hasn't been changed.</p>
<p>Shouldn't the action invoker understand what's the method to call looking in the parameters list?</p>
<p>Using the preview 4 I hadn't these kind of problem performing the same operation.</p>
<p>Any idea?</p>
|
[
{
"answer_id": 49187,
"author": "crucible",
"author_id": 3717,
"author_profile": "https://Stackoverflow.com/users/3717",
"pm_score": 0,
"selected": false,
"text": "public ActionResult Delete(string id)\n{\n if(string.IsNullOrEmpty(id)) return EmptyID();\n\n // Continue normal Delete method\n}\n\npublic ActionResult EmptyID()\n{\n // The method you were going to have on a blank delete.\n}\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1812/"
] |
47,363 |
<p>What is the command to list all triggers in a MySQL database?</p>
|
[
{
"answer_id": 47364,
"author": "Harry",
"author_id": 4704,
"author_profile": "https://Stackoverflow.com/users/4704",
"pm_score": 9,
"selected": true,
"text": "show triggers;\n INFORMATION_SCHEMA select trigger_schema, trigger_name, action_statement\nfrom information_schema.triggers\n TRIGGERS"
},
{
"answer_id": 7257460,
"author": "sunil",
"author_id": 921665,
"author_profile": "https://Stackoverflow.com/users/921665",
"pm_score": 4,
"selected": false,
"text": "select * from information_schema.triggers where \ninformation_schema.triggers.trigger_name like '%trigger_name%' and \ninformation_schema.triggers.trigger_schema like '%data_base_name%'\n"
},
{
"answer_id": 7710970,
"author": "Kainda",
"author_id": 987431,
"author_profile": "https://Stackoverflow.com/users/987431",
"pm_score": 4,
"selected": false,
"text": "SHOW TRIGGERS LIKE '%trigger_name%'\\G\n SHOW TRIGGERS\\G\n"
},
{
"answer_id": 18782762,
"author": "Pragnesh Karia",
"author_id": 1027670,
"author_profile": "https://Stackoverflow.com/users/1027670",
"pm_score": 4,
"selected": false,
"text": "select * from information_schema.triggers where \ninformation_schema.triggers.trigger_schema like '%your_db_name%'\n TRIGGER_CATALOG \nTRIGGER_SCHEMA\nTRIGGER_NAME\nEVENT_MANIPULATION\nEVENT_OBJECT_CATALOG\nEVENT_OBJECT_SCHEMA \nEVENT_OBJECT_TABLE\nACTION_ORDER\nACTION_CONDITION\nACTION_STATEMENT\nACTION_ORIENTATION\nACTION_TIMING\nACTION_REFERENCE_OLD_TABLE\nACTION_REFERENCE_NEW_TABLE\nACTION_REFERENCE_OLD_ROW\nACTION_REFERENCE_NEW_ROW\nCREATED \nSQL_MODE\nDEFINER \nCHARACTER_SET_CLIENT\nCOLLATION_CONNECTION\nDATABASE_COLLATION\n"
},
{
"answer_id": 69413373,
"author": "Leon Gomez",
"author_id": 17055440,
"author_profile": "https://Stackoverflow.com/users/17055440",
"pm_score": 0,
"selected": false,
"text": "select LOWER(concat('delimiter |', '\\n', 'create trigger %data_base_name%.', TRIGGER_NAME, '\\n', \n' ', ACTION_TIMING, ' ', EVENT_MANIPULATION, ' on %data_base_name%.', EVENT_OBJECT_TABLE, ' for each row', '\\n',\nACTION_STATEMENT, '\\n',\n'|')) AS TablaTriggers from information_schema.triggers where \ninformation_schema.triggers.trigger_schema like '%data_base_name%'\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4704/"
] |
47,387 |
<p>I've been hearing about triggers, and I have a few questions.<br />
What are triggers?<br />
How do I set them up?<br />
Are there any precautions, aside from typical SQL stuff, that should be taken?</p>
|
[
{
"answer_id": 47391,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": "CREATE TRIGGER triggerName [BEFORE|AFTER] [INSERT|UPDATE|DELETE|REPLACE] ON tableName FOR EACH ROW SET stuffToDoHERE;\n"
},
{
"answer_id": 47392,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 1,
"selected": false,
"text": "CREATE\n [DEFINER = { user | CURRENT_USER }]\n TRIGGER trigger_name trigger_time trigger_event\n ON tbl_name FOR EACH ROW trigger_stmt\n CREATE TABLE account (acct_num INT, amount DECIMAL(10,2));\nCREATE TRIGGER ins_sum BEFORE INSERT ON account FOR EACH ROW SET @sum = @sum + NEW.amount;\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
47,400 |
<p>With the code, forms and data inside the same database I am wondering what are the best practices to design a suite of tests for a Microsoft Access application (say for Access 2007).</p>
<p>One of the main issues with testing forms is that only a few controls have a <code>hwnd</code> handle and other controls only get one they have focus, which makes automation quite opaque since you cant get a list of controls on a form to act on.</p>
<p>Any experience to share?</p>
|
[
{
"answer_id": 70572,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 4,
"selected": false,
"text": "AfterUpdate Private Sub myControl_AfterUpdate() \n CTLAfterUpdate myControl\n On Error Resume Next\n Eval (\"CTLAfterUpdate_MyForm()\")\n On Error GoTo 0 \nEnd sub\n CTLAfterUpdate CTLAfterUpdateMyForm utilityFormEvents MyAppFormEvents"
},
{
"answer_id": 6959038,
"author": "mwolfe02",
"author_id": 154439,
"author_profile": "https://Stackoverflow.com/users/154439",
"pm_score": 3,
"selected": false,
"text": "'>>> 1 + 1\n'2\n'>>> 3 - 1\n'0\nSub DocTests()\nDim Comp As Object, i As Long, CM As Object\nDim Expr As String, ExpectedResult As Variant, TestsPassed As Long, TestsFailed As Long\nDim Evaluation As Variant\n For Each Comp In Application.VBE.ActiveVBProject.VBComponents\n Set CM = Comp.CodeModule\n For i = 1 To CM.CountOfLines\n If Left(Trim(CM.Lines(i, 1)), 4) = \"'>>>\" Then\n Expr = Trim(Mid(CM.Lines(i, 1), 5))\n On Error Resume Next\n Evaluation = Eval(Expr)\n If Err.Number = 2425 And Comp.Type <> 1 Then\n 'The expression you entered has a function name that '' can't find.\n 'This is not surprising because we are not in a standard code module (Comp.Type <> 1).\n 'So we will just ignore it.\n GoTo NextLine\n ElseIf Err.Number <> 0 Then\n Debug.Print Err.Number, Err.Description, Expr\n GoTo NextLine\n End If\n On Error GoTo 0\n ExpectedResult = Trim(Mid(CM.Lines(i + 1, 1), InStr(CM.Lines(i + 1, 1), \"'\") + 1))\n Select Case ExpectedResult\n Case \"True\": ExpectedResult = True\n Case \"False\": ExpectedResult = False\n Case \"Null\": ExpectedResult = Null\n End Select\n Select Case TypeName(Evaluation)\n Case \"Long\", \"Integer\", \"Short\", \"Byte\", \"Single\", \"Double\", \"Decimal\", \"Currency\"\n ExpectedResult = Eval(ExpectedResult)\n Case \"Date\"\n If IsDate(ExpectedResult) Then ExpectedResult = CDate(ExpectedResult)\n End Select\n If (Evaluation = ExpectedResult) Then\n TestsPassed = TestsPassed + 1\n ElseIf (IsNull(Evaluation) And IsNull(ExpectedResult)) Then\n TestsPassed = TestsPassed + 1\n Else\n Debug.Print Comp.Name; \": \"; Expr; \" evaluates to: \"; Evaluation; \" Expected: \"; ExpectedResult\n TestsFailed = TestsFailed + 1\n End If\n End If\nNextLine:\n Next i\n Next Comp\n Debug.Print \"Tests passed: \"; TestsPassed; \" of \"; TestsPassed + TestsFailed\nEnd Sub\n Module: 3 - 1 evaluates to: 2 Expected: 0 \nTests passed: 1 of 2\n Eval Eval Eval Public Function AddTwoValues(ByVal p1 As Variant, _\n ByVal p2 As Variant) As Variant\n'>>> AddTwoValues(1,1)\n'2\n'>>> AddTwoValues(1,1) = 1\n'False\n'>>> AddTwoValues(1,Null)\n'Null\n'>>> IsError(AddTwoValues(1,\"foo\"))\n'True\n\nOn Error GoTo ErrorHandler\n\n AddTwoValues = p1 + p2\n\nExitHere:\n On Error GoTo 0\n Exit Function\n\nErrorHandler:\n AddTwoValues = CVErr(Err.Number)\n GoTo ExitHere\nEnd Function\n"
},
{
"answer_id": 28347000,
"author": "RubberDuck",
"author_id": 3198973,
"author_profile": "https://Stackoverflow.com/users/3198973",
"pm_score": 6,
"selected": true,
"text": "Public Event OnSayHello()\nPublic Event AfterTextUpdate()\n\nPublic Property Let Text(value As String)\n Me.TextBox1.value = value\nEnd Property\n\nPublic Property Get Text() As String\n Text = Me.TextBox1.value\nEnd Property\n\nPrivate Sub SayHello_Click()\n RaiseEvent OnSayHello\nEnd Sub\n\nPrivate Sub TextBox1_AfterUpdate()\n RaiseEvent AfterTextUpdate\nEnd Sub\n MyModel Private mText As String\nPublic Property Let Text(value As String)\n mText = value\nEnd Property\n\nPublic Property Get Text() As String\n Text = mText\nEnd Property\n\nPublic Function Reversed() As String\n Dim result As String\n Dim length As Long\n\n length = Len(mText)\n\n Dim i As Long\n For i = 0 To length - 1\n result = result + Mid(mText, (length - i), 1)\n Next i\n\n Reversed = result\nEnd Function\n\nPublic Sub SayHello()\n MsgBox Reversed()\nEnd Sub\n Private WithEvents view As Form_Form1\nPrivate model As MyModel\n\nPublic Sub Run()\n Set model = New MyModel\n Set view = New Form_Form1\n view.Visible = True\nEnd Sub\n\nPrivate Sub view_AfterTextUpdate()\n model.Text = view.Text\nEnd Sub\n\nPrivate Sub view_OnSayHello()\n model.SayHello\n view.Text = model.Reversed()\nEnd Sub\n Private controller As FormController\n\nPublic Sub Run()\n Set controller = New FormController\n controller.Run\nEnd Sub\n model MyModel.Reversed() '@TestModule\nPrivate Assert As New Rubberduck.AssertClass\n\n'@TestMethod\nPublic Sub ReversedReversesCorrectly()\n\nArrange:\n Dim model As New MyModel\n Const original As String = \"Hello\"\n Const expected As String = \"olleH\"\n Dim actual As String\n\n model.Text = original\n\nAct:\n actual = model.Reversed\n\nAssert:\n Assert.AreEqual expected, actual\n\nEnd Sub\n"
},
{
"answer_id": 32775460,
"author": "AndrewM",
"author_id": 3133514,
"author_profile": "https://Stackoverflow.com/users/3133514",
"pm_score": 2,
"selected": false,
"text": "Public Function GetOutputFolder(OutputFolder As eOutputFolder) As FunctRet\n\n '///Returns a full path when provided with a target folder alias. e.g. 'temp' folder\n\n Dim fr As FunctRet\n\n Select Case OutputFolder\n Case 1\n fr.Rtn = \"C:\\Temp\\\"\n fr.Success = True\n Case 2\n fr.Rtn = TrailingSlash(Application.CurrentProject.path)\n fr.Success = True\n Case 3\n fr.EM = \"Can't set custom paths – not yet implemented\"\n Case Else\n fr.EM = \"Unrecognised output destination requested\"\n End Select\n\n exitproc:\n GetOutputFolder = fr\n\n End Function\n Public Enum eOutputFolder\n eDefaultDirectory = 1\n eAppPath = 2\n eCustomPath = 3\nEnd Enum\n 'Type FunctRet is used as a generic means of reporting function returns\nPublic Type FunctRet\n Success As Long 'Boolean flag for success, boolean not used to avoid nulls\n Rtn As Variant 'Return Value\n EM As String 'Error message\n Cmt As String 'Comments\n Origin As String 'Originating procedure/function\nEnd Type\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3811/"
] |
47,402 |
<p>Given an array of characters which forms a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.</p>
<p>Example input and output:</p>
<pre><code>>>> reverse_words("this is a string")
'string a is this'
</code></pre>
<p>It should be O(N) time and O(1) space (<code>split()</code> and pushing on / popping off the stack are not allowed).</p>
<p>The puzzle is taken from <a href="http://halcyon.usc.edu/~kiran/msqs.html#programming" rel="noreferrer" title="Microsoft Interview Questions">here</a>.</p>
|
[
{
"answer_id": 47416,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "reverse input string\nreverse each word (you will need to find word boundaries)\n"
},
{
"answer_id": 47423,
"author": "smh",
"author_id": 1077,
"author_profile": "https://Stackoverflow.com/users/1077",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n#include <string.h>\n\nvoid reverseString(char* string, int length)\n{\n char swap;\n for (int i = 0; i < length/2; i++)\n {\n swap = string[length - 1 - i];\n string[length - 1 - i] = string[i];\n string[i] = swap;\n } \n}\n\nint main (int argc, const char * argv[]) {\n char teststring[] = \"Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.\";\n printf(\"%s\\n\", teststring);\n int length = strlen(teststring);\n reverseString(teststring, length);\n int i = 0;\n while (i < length)\n {\n int wordlength = strspn(teststring + i, \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\");\n reverseString(teststring + i, wordlength);\n i += wordlength + 1;\n }\n printf(\"%s\\n\", teststring);\n return 0;\n}\n"
},
{
"answer_id": 47424,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 1,
"selected": false,
"text": "def reverse_words_nosplit(str_):\n \"\"\"\n >>> f = reverse_words_nosplit\n >>> f(\"this is a string\")\n 'string a is this'\n \"\"\"\n iend = len(str_)\n s = \"\"\n while True:\n ispace = str_.rfind(\" \", 0, iend)\n if ispace == -1:\n s += str_[:iend]\n break\n s += str_[ispace+1:iend]\n s += \" \"\n iend = ispace\n return s\n"
},
{
"answer_id": 47426,
"author": "Thomas Watnedal",
"author_id": 4059,
"author_profile": "https://Stackoverflow.com/users/4059",
"pm_score": 6,
"selected": true,
"text": "void swap(char* str, int i, int j){\n char t = str[i];\n str[i] = str[j];\n str[j] = t;\n}\n\nvoid reverse_string(char* str, int length){\n for(int i=0; i<length/2; i++){\n swap(str, i, length-i-1);\n }\n}\nvoid reverse_words(char* str){\n int l = strlen(str);\n //Reverse string\n reverse_string(str,strlen(str));\n int p=0;\n //Find word boundaries and reverse word by word\n for(int i=0; i<l; i++){\n if(str[i] == ' '){\n reverse_string(&str[p], i-p);\n p=i+1;\n }\n }\n //Finally reverse the last word.\n reverse_string(&str[p], l-p);\n}\n"
},
{
"answer_id": 47434,
"author": "Xian",
"author_id": 4642,
"author_profile": "https://Stackoverflow.com/users/4642",
"pm_score": 1,
"selected": false,
"text": "(define (reverse sentence-to-reverse)\n (reverse-iter (sentence-to-reverse \"\"))\n\n(define (reverse-iter(sentence, reverse-sentence)\n (if (= 0 string-length sentence)\n reverse-sentence\n ( reverse-iter( remove-first-word(sentence), add-first-word(sentence, reverse-sentence)))\n"
},
{
"answer_id": 47435,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 0,
"selected": false,
"text": "#include <string>\n#include <iostream>\nusing namespace std;\n\nstring revwords(string in) {\n string rev;\n int wordlen = 0;\n for (int i = in.length(); i >= 0; --i) {\n if (i == 0 || iswspace(in[i-1])) {\n if (wordlen) {\n for (int j = i; wordlen--; )\n rev.push_back(in[j++]);\n wordlen = 0;\n }\n if (i > 0)\n rev.push_back(in[i-1]);\n }\n else\n ++wordlen;\n }\n return rev;\n}\n\nint main() {\n cout << revwords(\"this is a sentence\") << \".\" << endl;\n cout << revwords(\" a sentence with extra spaces \") << \".\" << endl;\n return 0;\n}\n"
},
{
"answer_id": 47455,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 0,
"selected": false,
"text": "using System;\n\nnamespace q47407\n{\n class MainClass\n {\n public static void Main(string[] args)\n {\n string s = Console.ReadLine();\n string[] r = s.Split(' ');\n for(int i = r.Length-1 ; i >= 0; i--)\n Console.Write(r[i] + \" \");\n Console.WriteLine();\n\n }\n }\n}\n"
},
{
"answer_id": 47509,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 2,
"selected": false,
"text": "#include <string>\n#include <boost/next_prior.hpp>\n\nvoid reverse(std::string& foo) {\n using namespace std;\n std::reverse(foo.begin(), foo.end());\n string::iterator begin = foo.begin();\n while (1) {\n string::iterator space = find(begin, foo.end(), ' ');\n std::reverse(begin, space);\n begin = boost::next(space);\n if (space == foo.end())\n break;\n }\n}\n"
},
{
"answer_id": 47565,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/dmd -run\n/**\n * to compile & run:\n * $ dmd -run reverse_words.d\n * to optimize:\n * $ dmd -O -inline -release reverse_words.d\n */\nimport std.algorithm: reverse;\nimport std.stdio: writeln;\nimport std.string: find;\n\nvoid reverse_words(char[] str) {\n // reverse whole string\n reverse(str);\n\n // reverse each word\n for (auto i = 0; (i = find(str, \" \")) != -1; str = str[i + 1..length])\n reverse(str[0..i]);\n\n // reverse last word\n reverse(str);\n}\n\nvoid main() {\n char[] str = cast(char[])(\"this is a string\");\n writeln(str);\n reverse_words(str);\n writeln(str);\n}\n"
},
{
"answer_id": 1010975,
"author": "Demi",
"author_id": 67985,
"author_profile": "https://Stackoverflow.com/users/67985",
"pm_score": 0,
"selected": false,
"text": "static char[] ReverseAllWords(char[] in_text)\n{\n int lindex = 0;\n int rindex = in_text.Length - 1;\n if (rindex > 1)\n {\n //reverse complete phrase\n in_text = ReverseString(in_text, 0, rindex);\n\n //reverse each word in resultant reversed phrase\n for (rindex = 0; rindex <= in_text.Length; rindex++)\n {\n if (rindex == in_text.Length || in_text[rindex] == ' ')\n {\n in_text = ReverseString(in_text, lindex, rindex - 1);\n lindex = rindex + 1;\n }\n }\n }\n return in_text;\n}\n\nstatic char[] ReverseString(char[] intext, int lindex, int rindex)\n{\n char tempc;\n while (lindex < rindex)\n {\n tempc = intext[lindex];\n intext[lindex++] = intext[rindex];\n intext[rindex--] = tempc;\n }\n return intext;\n}\n"
},
{
"answer_id": 1011107,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "reverse_words: func [s [string!]] [form reverse parse s none]\n"
},
{
"answer_id": 3337552,
"author": "Anurag",
"author_id": 165737,
"author_profile": "https://Stackoverflow.com/users/165737",
"pm_score": 0,
"selected": false,
"text": "# Reverse all words in string\ndef reverse_words(string)\n return string if string == ''\n\n reverse(string, 0, string.size - 1)\n\n bounds = next_word_bounds(string, 0)\n\n while bounds.all? { |b| b < string.size }\n reverse(string, bounds[:from], bounds[:to])\n bounds = next_word_bounds(string, bounds[:to] + 1)\n end\n\n string\nend\n\n# Reverse a single word between indices \"from\" and \"to\" in \"string\"\ndef reverse(s, from, to)\n half = (from - to) / 2 + 1\n\n half.times do |i|\n s[from], s[to] = s[to], s[from]\n from, to = from.next, to.next\n end\n\n s\nend\n\n# Find the boundaries of the next word starting at index \"from\"\ndef next_word_bounds(s, from)\n from = s.index(/\\S/, from) || s.size\n to = s.index(/\\s/, from + 1) || s.size\n\n return { from: from, to: to - 1 }\nend\n"
},
{
"answer_id": 3711850,
"author": "Shivkrish22",
"author_id": 401275,
"author_profile": "https://Stackoverflow.com/users/401275",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n\nvoid reverse(char* string, int length){\n int i;\n for (i = 0; i < length/2; i++){\n string[length - 1 - i] ^= string[i] ;\n string[i] ^= string[length - 1 - i];\n string[length - 1 - i] ^= string[i];\n } \n}\n\nint main () {\nchar string[] = \"This is a test string\";\nchar *ptr;\nint i = 0;\nint word = 0;\nptr = (char *)&string;\nprintf(\"%s\\n\", string);\nint length=0;\nwhile (*ptr++){\n ++length;\n}\nreverse(string, length);\nprintf(\"%s\\n\", string);\n\nfor (i=0;i<length;i++){\n if(string[i] == ' '){\n reverse(&string[word], i-word);\n word = i+1;\n }\n} \nreverse(&string[word], i-word); //for last word \nprintf(\"\\n%s\\n\", string);\nreturn 0;\n}\n"
},
{
"answer_id": 23667400,
"author": "vran freelancer",
"author_id": 1092823,
"author_profile": "https://Stackoverflow.com/users/1092823",
"pm_score": 0,
"selected": false,
"text": " public static string reverseWords(String s)\n {\n\n char[] stringChar = s.ToCharArray();\n int length = stringChar.Length, tempIndex = 0;\n\n Swap(stringChar, 0, length - 1);\n\n for (int i = 0; i < length; i++)\n {\n if (i == length-1)\n {\n Swap(stringChar, tempIndex, i);\n tempIndex = i + 1;\n }\n else if (stringChar[i] == ' ')\n {\n Swap(stringChar, tempIndex, i-1);\n tempIndex = i + 1;\n }\n }\n\n return new String(stringChar);\n }\n\n private static void Swap(char[] p, int startIndex, int endIndex)\n {\n while (startIndex < endIndex)\n {\n p[startIndex] ^= p[endIndex];\n p[endIndex] ^= p[startIndex];\n p[startIndex] ^= p[endIndex];\n startIndex++;\n endIndex--;\n }\n }\n"
},
{
"answer_id": 27279070,
"author": "aady",
"author_id": 2047752,
"author_profile": "https://Stackoverflow.com/users/2047752",
"pm_score": 0,
"selected": false,
"text": "l=\"Is this as expected ??\"\n\" \".join(each[::-1] for each in l[::-1].split())\n '?? expected as this Is'\n"
},
{
"answer_id": 27602891,
"author": "zoha khan",
"author_id": 3209871,
"author_profile": "https://Stackoverflow.com/users/3209871",
"pm_score": 0,
"selected": false,
"text": "public class Solution {\npublic String reverseWords(String p) {\n String reg=\" \";\n if(p==null||p.length()==0||p.equals(\"\"))\n{\n return \"\";\n}\nString[] a=p.split(\"\\\\s+\");\nStringBuilder res=new StringBuilder();;\nfor(int i=0;i<a.length;i++)\n{\n\n String temp=doReverseString(a[i]);\n res.append(temp);\n res.append(\" \");\n}\nString resultant=doReverseString(res.toString());\nSystem.out.println(res);\nreturn resultant.toString().replaceAll(\"^\\\\s+|\\\\s+$\", \"\"); \n}\n\n\npublic String doReverseString(String s)`{`\n\n\nchar str[]=s.toCharArray();\nint start=0,end=s.length()-1;\nwhile(start<end)\n{\nchar temp=str[start];\nstr[start]=str[end];\nstr[end]=temp;\nstart++;\nend--;\n}\nString a=new String(str);\nreturn a;\n\n}\n\npublic static void main(String[] args)\n{\nSolution r=new Solution();\nString main=r.reverseWords(\"kya hua\");\n//System.out.println(re);\nSystem.out.println(main);\n}\n}\n"
},
{
"answer_id": 37529508,
"author": "Himanshu Mahajan",
"author_id": 1624283,
"author_profile": "https://Stackoverflow.com/users/1624283",
"pm_score": 0,
"selected": false,
"text": " #include <stdio.h>\n #include <string.h>\n\n void reverseStr(char* s, int start, int end);\n\n int main()\n {\n char s[] = \"This is test string\";\n\n int start = 0;\n int end = 0;\n int i = 0;\n\n while (1) {\n\n if (s[i] == ' ' || s[i] == '\\0')\n {\n reverseStr(s, start, end-1);\n start = i + 1;\n end = start;\n }\n else{\n end++;\n }\n\n if(s[i] == '\\0'){\n break;\n }\n i++;\n }\n\n reverseStr(s, 0, strlen(s)-1);\n printf(\"\\n\\noutput= %s\\n\\n\", s);\n\n return 0;\n }\n\n void reverseStr(char* s, int start, int end)\n {\n char temp;\n int j = end;\n int i = start;\n\n for (i = start; i < j ; i++, j--) {\n temp = s[i];\n s[i] = s[j];\n s[j] = temp;\n }\n }\n"
},
{
"answer_id": 37877392,
"author": "Sundara Moorthy Anandh",
"author_id": 6477821,
"author_profile": "https://Stackoverflow.com/users/6477821",
"pm_score": 1,
"selected": false,
"text": " #include<stdio.h>\n #include<string.h>\n\nint main()\n{\nchar *p,*s=\"this is good.\",*t;\nint i,j,a,l,count=0;\n\nl=strlen(s);\n\np=&s[l-1];\n\nt=&s[-1];\nwhile(*t)\n {\n if(*t==' ')\n count++;\n t++;\n }\n a=count;\n while(l!=0)\n {\nfor(i=0;*p!=' '&&t!=p;p--,i++);\n p++;\n\n for(;((*p)!='.')&&(*p!=' ');p++)\n printf(\"%c\",*p);\n printf(\" \");\n if(a==count)\n {\n p=p-i-1;\n l=l-i;\n }\n else\n {\n p=p-i-2;\n l=l-i-1;\n }\n\ncount--;\n }\n\nreturn 0; \n}\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4279/"
] |
47,413 |
<p>It's common to have a table where for example the the fields are account, value, and time. What's the best design pattern for retrieving the last value for each account? Unfortunately the last keyword in a grouping gives you the last physical record in the database, not the last record by any sorting. Which means IMHO it should never be used. The two clumsy approaches I use are either a subquery approach or a secondary query to determine the last record, and then joining to the table to find the value. Isn't there a more elegant approach?</p>
|
[
{
"answer_id": 47431,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 2,
"selected": true,
"text": "select * \nfrom table \nwhere account+time in (select account+max(time) \n from table \n group by account \n order by time) \n"
},
{
"answer_id": 47443,
"author": "shsteimer",
"author_id": 292,
"author_profile": "https://Stackoverflow.com/users/292",
"pm_score": 2,
"selected": false,
"text": "select account,last(value),max(time)\nfrom table\ngroup by account\n"
},
{
"answer_id": 47456,
"author": "Dhaust",
"author_id": 242,
"author_profile": "https://Stackoverflow.com/users/242",
"pm_score": 1,
"selected": false,
"text": "SELECT TOP 1 * FROM TableName ORDER BY Time DESC \n"
},
{
"answer_id": 47511,
"author": "Knox",
"author_id": 4873,
"author_profile": "https://Stackoverflow.com/users/4873",
"pm_score": 1,
"selected": false,
"text": "select T1.account, T1.value\nfrom table T as T1\nwhere T1 = (select max(T2.time) from table T as T2 where T1.account = T2.Account) \n"
},
{
"answer_id": 86354,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "SELECT\n a.account,\n a.time,\n a.value\nFROM\n tablename AS a INNER JOIN [\n SELECT\n account,\n Max(time) AS MaxOftime\n FROM\n tablename\n GROUP BY\n account\n ]. AS b\n ON\n (a.time = b.MaxOftime)\n AND (a.account = b.account)\n;\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4873/"
] |
47,420 |
<p>I'm using the d programing language to write a program, and I'm trying to use ddbg to debug it. When there is an exception, I want to have the program break whenever there is an exception thrown so that I can inspect the stack.</p>
<p>Alternatively, is there another debugger that works with d? Is there another way to get a stack trace when there is an exception?</p>
|
[
{
"answer_id": 47974,
"author": "user4891",
"author_id": 4891,
"author_profile": "https://Stackoverflow.com/users/4891",
"pm_score": 0,
"selected": false,
"text": "onex break\nonex b\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4891/"
] |
47,427 |
<p>Many websites, including this one, add what are apparently called <em>slugs</em> - descriptive but as far as I can tell useless bits of text - to the end of URLs.</p>
<p>For example, the URL the site gives for this question is:</p>
<p><a href="https://stackoverflow.com/questions/47427/why-do-some-websites-add-slugs-to-the-end-of-urls"><code>https://stackoverflow.com/questions/47427/why-do-some-websites-add-slugs-to-the-end-of-urls</code></a></p>
<p>But the following URL works just as well:</p>
<p><a href="https://stackoverflow.com/questions/47427/"><code>https://stackoverflow.com/questions/47427/</code></a></p>
<p>Is the point of this text just to somehow make the URL more user friendly or are there some other benefits? </p>
|
[
{
"answer_id": 47451,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 3,
"selected": false,
"text": "https://stackoverflow.com/questions/47427/ https://stackoverflow.com/questions/47427/why-do-some-websites-add-slugs-to-the-end-of-urls"
},
{
"answer_id": 47585,
"author": "billpg",
"author_id": 3568,
"author_profile": "https://Stackoverflow.com/users/3568",
"pm_score": 3,
"selected": false,
"text": "https://stackoverflow.com/questions/47427/why-is-billpg-so-very-awesome"
},
{
"answer_id": 136457,
"author": "Andrew Ingram",
"author_id": 15687,
"author_profile": "https://Stackoverflow.com/users/15687",
"pm_score": 4,
"selected": false,
"text": "/2008/sept/06/why-some-websites-add-slugs-end-of-urls/\n /2008/sept/06/why-some-websites-add-slugs-end-of-urls/\n/2008/sept/06/why-some-websites-add-slugs-end-of-urls-1/\n/2008/sept/06/why-some-websites-add-slugs-end-of-urls-2/\n"
},
{
"answer_id": 495292,
"author": "Alan Doherty",
"author_id": 59995,
"author_profile": "https://Stackoverflow.com/users/59995",
"pm_score": 2,
"selected": false,
"text": "https://stackoverflow.com/questions/47427/why-do-some-websites-add-slugs-to-the-end-of-urls https://stackoverflow.com/questions/47427/ https://stackoverflow.com/questions/47427/any-other-bollix https://stackoverflow.com/questions/47427/why-do-some-websites-add-slugs-to-the-end-of-urls"
},
{
"answer_id": 752718,
"author": "Cory R. King",
"author_id": 16742,
"author_profile": "https://Stackoverflow.com/users/16742",
"pm_score": 5,
"selected": false,
"text": "https://stackoverflow.com/questions/47427/wh https://stackoverflow.com/questions/47427/why-do-some-websites-add-slugs-to-the-end-of-urls https://stackoverflow.com/questions/47427/why-do-some- https://stackoverflow.com/questions/47427"
},
{
"answer_id": 2838248,
"author": "Robs",
"author_id": 78077,
"author_profile": "https://Stackoverflow.com/users/78077",
"pm_score": 3,
"selected": false,
"text": "<link rel=\"canonical\" href=\"http://stackoverflow.com/questions/47427/why-do-some-websites-add-slugs-to-the-end-of-urls\">\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3171/"
] |
47,432 |
<p>This free collection library comes from IT University of Copenhagen.</p>
<p><a href="http://www.itu.dk/research/c5/" rel="noreferrer">http://www.itu.dk/research/c5/</a></p>
<p>There is a video with one of the authors on Channel 9. I am trying to learn how to use these collections and I was wondering whether anyone has more experiences or what are your thoughts on this specific collection library for .NET. Do you like the way they are designed, do you like their performance and what were your major problems with them ?</p>
|
[
{
"answer_id": 209387,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 3,
"selected": false,
"text": "System.Collections.Generic IList ArrayList LinkedList ArrayList LinkedList C5.IList"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4694/"
] |
47,433 |
<p>Consider the following 2 queries:</p>
<pre><code>select tblA.a,tblA.b,tblA.c,tblA.d
from tblA
where tblA.a not in (select tblB.a from tblB)
select tblA.a,tblA.b,tblA.c,tblA.d
from tblA left outer join tblB
on tblA.a = tblB.a where tblB.a is null
</code></pre>
<p>Which will perform better? My assumption is that in general the join will be better except in cases where the subselect returns a very small result set.</p>
|
[
{
"answer_id": 57744,
"author": "Martynnw",
"author_id": 5466,
"author_profile": "https://Stackoverflow.com/users/5466",
"pm_score": 1,
"selected": false,
"text": "exists in"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292/"
] |
47,436 |
<p>What is the shortcut key for <em>Run to cursor</em> in Visual Studio 2008?</p>
|
[
{
"answer_id": 70101220,
"author": "Teoman shipahi",
"author_id": 929902,
"author_profile": "https://Stackoverflow.com/users/929902",
"pm_score": 0,
"selected": false,
"text": "Ctrl + Shift + P\n > Run to Cursor @command:editor.debug.action.runToCursor"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3854/"
] |
47,447 |
<p>I am trying to create a horizontal menu with the elements represented by <code><span></code>'s. The menu itself (parent <code><div></code>) has a fixed width, but the elements number is always different.</p>
<p>I would like to have child <code><span></code>'s of the same width, independently of how many of them are there.</p>
<p>What I've done so far: added a <code>float: left;</code> style for every span and specified its percentage width (percents are more or less fine, as the server knows at the time of the page generation, how many menu items are there and could divide 100% by this number). This works, except for the case when we have a division remainder (like for 3 elements), in this case I have a one-pixel hole to the right of the parent <code><div></code>, and if I rounding the percents up, the last menu element is wrapped. I also don't really like style generation on the fly, but if there's no other solution, it's fine.</p>
<p>What else could I try?</p>
<p>It seems like this is a very common problem, however googling for "child elements of the same width" didn't help.</p>
|
[
{
"answer_id": 47465,
"author": "Xian",
"author_id": 4642,
"author_profile": "https://Stackoverflow.com/users/4642",
"pm_score": 2,
"selected": false,
"text": "<div>\n<span class=\"first-in-row\">/<span><span></span><span></span><span class=\"first-in-row\"><span></span><span></span>...\n</div>\n .first-in-row { width:auto; /* or */ width:XXX px; }\n"
},
{
"answer_id": 47466,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 3,
"selected": true,
"text": "table.ClassName {\n table-layout: fixed\n}\n"
},
{
"answer_id": 47492,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "span:first-child {\n width: auto;\n}\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3894/"
] |
47,475 |
<p>If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names?</p>
<p>ie </p>
<pre><code>[Test]
public void ShouldValidateUserNameIsLessThan100Characters() {}
</code></pre>
<p>verse </p>
<pre><code>[Test]
public void UserNameTestValidation1() {}
</code></pre>
|
[
{
"answer_id": 47477,
"author": "zappan",
"author_id": 4723,
"author_profile": "https://Stackoverflow.com/users/4723",
"pm_score": 1,
"selected": false,
"text": "UserNameLengthValidate()\n UserNameLengthTest()\n"
},
{
"answer_id": 47478,
"author": "Adrian Mouat",
"author_id": 4332,
"author_profile": "https://Stackoverflow.com/users/4332",
"pm_score": 5,
"selected": true,
"text": "public void validateUserNameLength()\n"
},
{
"answer_id": 47507,
"author": "flipdoubt",
"author_id": 470,
"author_profile": "https://Stackoverflow.com/users/470",
"pm_score": 1,
"selected": false,
"text": "[TestFixture]\npublic class IndexableFileTest\n{\n [Test]\n public void Connect_InitializesReadOnlyProperties()\n {\n // ...\n }\n\n [Test,ExpectedException(typeof(NotInitializedException))]\n public void IsIndexable_ErrorWhenNotConnected()\n {\n // ...\n }\n\n [Test]\n public void IsIndexable_True()\n {\n // ...\n }\n\n [Test]\n public void IsIndexable_False()\n {\n // ...\n }\n}\n"
},
{
"answer_id": 47550,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 3,
"selected": false,
"text": " [Test]\n public void UsernameValidator_LessThanLengthLimit_ShouldValidate() {}\n"
},
{
"answer_id": 47627,
"author": "JC.",
"author_id": 3615,
"author_profile": "https://Stackoverflow.com/users/3615",
"pm_score": 0,
"selected": false,
"text": "[RowTest]\n[Row(\"GoodName\")]\n[Row(\"GoodName2\")]\npublic void Should_validate_username()\n{\n}\n\n[RowTest]\n[Row(\"BadUserName\")]\n[Row(\"Bad%!Name\")]\npublic void Should_invalidate_username()\n{\n}\n"
},
{
"answer_id": 47825,
"author": "Johan",
"author_id": 4804,
"author_profile": "https://Stackoverflow.com/users/4804",
"pm_score": 1,
"selected": false,
"text": "[Test]\nvoid TestThatExceptionIsRaisedWhenStringLengthLargerThen100()\n\n[Test]\nvoid TestThatStringLengthOf99IsAccepted()\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4642/"
] |
47,483 |
<p>I have a user script that would be much more useful if it could dynamically change some of its execution dependent on what the user wanted. Passing simple switches would easily solve this problem but I don't see any way to do it.</p>
<p>I also tried embedding a keyword in the script name, but <em>Xcode</em> copies the script to a guid-looking filename before execution, so that won't work either.</p>
<p>So does anyone know of a way to call a user script with some sort of argument? (other that the normal <code>%%%var%%%</code> variables)</p>
<hr />
<h3>EDIT:</h3>
<p>User scripts are accessible via the script menu in Xcode's menubar (between the Window and Help menus). My question is not about "run script" build phase scripts. My apologies for leaving that somewhat ambiguous.</p>
|
[
{
"answer_id": 47619,
"author": "vt.",
"author_id": 3905,
"author_profile": "https://Stackoverflow.com/users/3905",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\nresult=$( osascript << END\ntell app \"System Events\"\n set a to display dialog \"What shall be the result?\" default answer \"\"\nend tell\nreturn text returned of a\nEND\n)\n# do stuff with $result\n"
},
{
"answer_id": 2581443,
"author": "jkyle",
"author_id": 263199,
"author_profile": "https://Stackoverflow.com/users/263199",
"pm_score": 0,
"selected": false,
"text": "STRING = `%%%{PBXUtilityScriptsPath}%%%/AskUserForStringDialog \"DefaultString\" \"DefaultWindowName\"`\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4233/"
] |
47,487 |
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/30170/avoiding-repeated-constants-in-css">Avoiding repeated constants in CSS</a> </p>
</blockquote>
<p>We have some "theme colors" that are reused in our CSS sheet.</p>
<p>Is there a way to set a variable and then reuse it?</p>
<p>E.g.</p>
<pre><code>.css
OurColor: Blue
H1 {
color:OurColor;
}
</code></pre>
|
[
{
"answer_id": 47505,
"author": "Tim Sullivan",
"author_id": 722,
"author_profile": "https://Stackoverflow.com/users/722",
"pm_score": 3,
"selected": false,
"text": "$blue: #3bbfce;\n$margin: 16px;\n\n.content-navigation {\n border-color: $blue;\n color:\n darken($blue, 9%);\n}\n\n.border {\n padding: $margin / 2;\n margin: $margin / 2;\n border-color: $blue;\n}\n table.hl {\n margin: 2em 0;\n td.ln {\n text-align: right;\n }\n}\n\nli {\n font: {\n family: serif;\n weight: bold;\n size: 1.2em;\n }\n}\n"
},
{
"answer_id": 47508,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 8,
"selected": true,
"text": "/* Theme color: text */\nH1, P, TABLE, UL\n{ color: blue; }\n\n/* Theme color: emphasis */\nB, I, STRONG, EM\n{ color: #00006F; }\n\n/* ... */\n\n/* Theme font: header */\nH1, H2, H3, H4, H5, H6\n{ font-family: Comic Sans MS; }\n\n/* ... */\n\n/* H1-specific styles */\nH1\n{ \n font-size: 2em; \n margin-bottom: 1em;\n}\n"
},
{
"answer_id": 47513,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "h1 {\n color: #000;\n}\n.a-theme-color {\n color: #333;\n}\n <h1>This is my heading.</h1>\n<h1 class=\"a-theme-color\">This is my theme heading.</h1>\n"
},
{
"answer_id": 47785,
"author": "Simon Forrest",
"author_id": 4733,
"author_profile": "https://Stackoverflow.com/users/4733",
"pm_score": 1,
"selected": false,
"text": ".ourColor { color: blue; }\n.ourBorder { border: 1px solid blue; }\n.bigText { font-size: 1.5em; }\n <h1 class=\"ourColor\">Blue Header</h1>\n<div class=\"ourColor bigText\">Some big blue text.</div>\n<div class=\"ourColor ourBorder\">Some blue text with blue border.</div>\n"
},
{
"answer_id": 47816,
"author": "Matt",
"author_id": 2338,
"author_profile": "https://Stackoverflow.com/users/2338",
"pm_score": 1,
"selected": false,
"text": "a {\n color: ${colors.blue};\n}\n\n a:hover {\n color: ${colors.blue.light};\n }\n\np {\n padding: ${padding.normal};\n}\n <property name=\"colors.blue\" value=\"#0066FF\" />\n<property name=\"colors.blue.light\" value=\"#0099FF\" />\n<property name=\"padding.normal\" value=\"0.5em\" />\n\n<copy file=\"styles.css.template\" tofile=\"styles.css\" overwrite=\"true\">\n <filterchain>\n <expandproperties/>\n </filterchain>\n</copy>\n"
},
{
"answer_id": 69558,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<style> .myclass{color:<?php echo $color; ?>;} </style> $('.myclass').css('color', 'blue'); //The jsvarColor could be set with the original page response javascript\n // in the DOM or retrieved on demand (AJAX) based on user action.\n $('.myclass').css('color', jsvarColor);"
},
{
"answer_id": 112781,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 2,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<cssconstants>\n <colors>\n <color name=\"Red\" value=\"BE1E2D\" />\n <color name=\"Orange\" value=\"E36F1E\" />\n ...\n </colors>\n <fonts>\n <font name=\"Text\" value=\"'Segoe UI',Verdana,Arial,Helvetica,Geneva,sans-serif\" />\n <font name=\"Serif\" value=\"Georgia,'Times New Roman',Times,serif\" />\n ...\n </fonts>\n</cssconstants>\n font-family:[[f:Text]];\n background:[[c:Background]]; \n border-top:1px solid [[c:Red+.5]]; /* 50% white tint of red */\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4906/"
] |
47,519 |
<p>I have a fairly standards compliant XHTML+CSS site that looks great on all browsers on PC and Mac. The other day I saw it on FF3 on Linux and the letter spacing was slightly larger, throwing everything out of whack and causing unwanted wrapping and clipping of text. The CSS in question has</p>
<pre><code>font-size: 11px;
font-family: Arial, Helvetica, sans-serif;
</code></pre>
<p>I know it's going with the generic sans-serif, whatever that maps to. If I add the following, the text scrunches up enough to be close to what I get on the other platforms:</p>
<pre><code>letter-spacing: -1.5px;
</code></pre>
<p>but this would involve some nasty server-side OS sniffing. If there's a pure CSS solution to this I'd love to hear it.</p>
<p>The system in question is Ubuntu 7.04 but that is irrelevant as I'm looking to fix it for at least the majority of, if not all, Linux users. Of course asking the user to install a font is not an option!</p>
|
[
{
"answer_id": 47531,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 3,
"selected": false,
"text": "ems"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3206/"
] |
47,521 |
<p>Here is a sample code to retrieve data from a database using the yield keyword that I found in a few place while googling around :</p>
<pre><code>public IEnumerable<object> ExecuteSelect(string commandText)
{
using (IDbConnection connection = CreateConnection())
{
using (IDbCommand cmd = CreateCommand(commandText, connection))
{
connection.Open();
using (IDbDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
yield return reader["SomeField"];
}
}
connection.Close();
}
}
}
</code></pre>
<p>Am I correct in thinking that in this sample code, the connection would not be closed if we do not iterate over the whole datareader ? </p>
<p>Here is an example that would not close the connection, if I understand yield correctly..</p>
<pre><code>foreach(object obj in ExecuteSelect(commandText))
{
break;
}
</code></pre>
<p>For a db connection that might not be catastrophic, I suppose the GC would clean it up eventually, but what if instead of a connection it was a more critical resource?</p>
|
[
{
"answer_id": 47746,
"author": "Joel Gauvreau",
"author_id": 4789,
"author_profile": "https://Stackoverflow.com/users/4789",
"pm_score": 2,
"selected": false,
"text": "class Program\n{\n static void Main(string[] args)\n {\n foreach (int v in getValues())\n {\n Console.WriteLine(v);\n }\n Console.ReadKey();\n\n foreach (int v in getValues())\n {\n Console.WriteLine(v);\n break;\n }\n Console.ReadKey();\n }\n\n public static IEnumerable<int> getValues()\n {\n using (TestDisposable t = new TestDisposable())\n {\n for(int i = 0; i<10; i++)\n yield return t.GetValue();\n }\n }\n}\n\npublic class TestDisposable : IDisposable\n{\n private int value;\n\n public void Dispose()\n {\n Console.WriteLine(\"Disposed\");\n }\n\n public int GetValue()\n {\n value += 1;\n return value;\n }\n}\n"
},
{
"answer_id": 47799,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 5,
"selected": true,
"text": "IDisposable foreach foreach Dispose() using foreach using() Dispose()"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4789/"
] |
47,535 |
<p>Updating an old ASP/Access site for a client - I need SQL to add a column to an existing table and set a default value. Doesn't work - any ideas?</p>
<p>This works fine</p>
<pre><code>ALTER TABLE documents ADD COLUMN membersOnly NUMBER
</code></pre>
<p>I want this to work:</p>
<pre><code>ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0
</code></pre>
<p>Have googled and seen instructions for default values work for other field types but I want to add number. Thanks!</p>
|
[
{
"answer_id": 47552,
"author": "zappan",
"author_id": 4723,
"author_profile": "https://Stackoverflow.com/users/4723",
"pm_score": 4,
"selected": true,
"text": "ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0\n"
},
{
"answer_id": 6066172,
"author": "HansUp",
"author_id": 77335,
"author_profile": "https://Stackoverflow.com/users/77335",
"pm_score": 3,
"selected": false,
"text": "CurrentProject.Connection.Execute _\n \"ALTER TABLE discardme ADD COLUMN membersOnly SHORT DEFAULT 0\"\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137/"
] |
47,537 |
<p>Does anyone know if there is a c# Console app, similar to the Python or Ruby console? I know the whole "Compiled versus Interpreted" difference, but with C#'s reflection power I think it could be done.</p>
<p><strong>UPDATE</strong>
Well, it only took about 200 lines, but I wrote a simple one...It works a lot like osql. You enter commands and then run them with go.</p>
<p><a href="http://www.gfilter.net/junk/sharpconsole.jpg">SharpConsole http://www.gfilter.net/junk/sharpconsole.jpg</a></p>
<p>If anyone wants it, let me know.</p>
|
[
{
"answer_id": 47548,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 5,
"selected": true,
"text": "irb"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
47,589 |
<p>I'm dealing with a MySQL table that defines the JobName column as UNIQUE. If somebody tries to save a new Job to the database using a JobName that is already in the database, MySQL throws a warning.</p>
<p>I would like to be able to detect this warning, just like an error, in my PHP script and deal with it appropriately. Ideally I would like to know what kind of warning MySQL has thrown so that I can branch the code to handle it.</p>
<p>Is this possible? If not, is it because MySQL doesn't have this ability, PHP doesn't have this ability, or both?</p>
|
[
{
"answer_id": 47597,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 2,
"selected": false,
"text": "mysql_query() mysql_errno()"
},
{
"answer_id": 47606,
"author": "yukondude",
"author_id": 726,
"author_profile": "https://Stackoverflow.com/users/726",
"pm_score": 0,
"selected": false,
"text": "UPDATE mysqli_affected_rows() WHERE SET mysqli_affected_rows() update_time"
},
{
"answer_id": 47662,
"author": "Ian",
"author_id": 4396,
"author_profile": "https://Stackoverflow.com/users/4396",
"pm_score": 5,
"selected": true,
"text": "$warningCountResult = mysql_query(\"SELECT @@warning_count\");\nif ($warningCountResult) {\n $warningCount = mysql_fetch_row($warningCountResult );\n if ($warningCount[0] > 0) {\n //Have warnings\n $warningDetailResult = mysql_query(\"SHOW WARNINGS\");\n if ($warningDetailResult ) {\n while ($warning = mysql_fetch_assoc($warningDetailResult) {\n //Process it\n }\n }\n }//Else no warnings\n}\n SELECT @@warning_count"
},
{
"answer_id": 2029953,
"author": "tomsv",
"author_id": 246622,
"author_profile": "https://Stackoverflow.com/users/246622",
"pm_score": 0,
"selected": false,
"text": "$mysqli->query($query);\n\nif ($mysqli->warning_count) {\n if ($result = $mysqli->query(\"SHOW WARNINGS\")) {\n $row = $result->fetch_row();\n printf(\"%s (%d): %s\\n\", $row[0], $row[1], $row[2]);\n $result->close();\n }\n}\n"
},
{
"answer_id": 5058649,
"author": "AG3",
"author_id": 593260,
"author_profile": "https://Stackoverflow.com/users/593260",
"pm_score": 0,
"selected": false,
"text": "@ // this suppresses warnings that might result if there is no field titled \"field\" in the result\n $field_value = @mysql_result($result, 0, \"field\");\n"
},
{
"answer_id": 8032033,
"author": "Gigi",
"author_id": 1033016,
"author_profile": "https://Stackoverflow.com/users/1033016",
"pm_score": 2,
"selected": false,
"text": "ini_set('mysql.trace_mode', 1)\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2056/"
] |
47,591 |
<p>Specifically, I am looking to use CA on properties of types other than </p>
<ul>
<li>integers and doubles</li>
<li>CGRect, CGPoint, CGSize, and CGAffineTransform structures</li>
<li>CATransform3D data structures</li>
<li>CGColor and CGImage references</li>
</ul>
<p>and in objects other than CALayers or NSViews</p>
|
[
{
"answer_id": 59168,
"author": "millenomi",
"author_id": 6061,
"author_profile": "https://Stackoverflow.com/users/6061",
"pm_score": 1,
"selected": false,
"text": "[[someObject animator] setValue:[NSNumber numberWithFloat:1.0] forKeyPath:@\"someCustomProperty.progress\"];\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
47,605 |
<p>Assuming String a and b:</p>
<pre><code>a += b
a = a.concat(b)
</code></pre>
<p>Under the hood, are they the same thing?</p>
<p>Here is concat decompiled as reference. I'd like to be able to decompile the <code>+</code> operator as well to see what that does.</p>
<pre><code>public String concat(String s) {
int i = s.length();
if (i == 0) {
return this;
}
else {
char ac[] = new char[count + i];
getChars(0, count, ac, 0);
s.getChars(0, i, ac, count);
return new String(0, count + i, ac);
}
}
</code></pre>
|
[
{
"answer_id": 47624,
"author": "Bartosz Bierkowski",
"author_id": 3666,
"author_profile": "https://Stackoverflow.com/users/3666",
"pm_score": 2,
"selected": false,
"text": "a.concat(b) + + StringBuffer + += +"
},
{
"answer_id": 47626,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 7,
"selected": false,
"text": "String a = b + c + d;\n String a = new StringBuilder(b).append(c).append(d).toString();\n"
},
{
"answer_id": 47628,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 10,
"selected": true,
"text": "a null a.concat(b) NullPointerException a+=b a null concat() String + toString() concat() a += b; public class Concat {\n String cat(String a, String b) {\n a += b;\n return a;\n }\n}\n javap -c java.lang.String cat(java.lang.String, java.lang.String);\n Code:\n 0: new #2; //class java/lang/StringBuilder\n 3: dup\n 4: invokespecial #3; //Method java/lang/StringBuilder.\"<init>\":()V\n 7: aload_1\n 8: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 11: aload_2\n 12: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 15: invokevirtual #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/ String;\n 18: astore_1\n 19: aload_1\n 20: areturn\n a += b a = new StringBuilder()\n .append(a)\n .append(b)\n .toString();\n concat StringBuilder String StringBuilder String javac System.identityHashCode String.hashCode StringBuffer"
},
{
"answer_id": 47694,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 4,
"selected": false,
"text": "long start = System.currentTimeMillis();\n\nString a = \"a\";\n\nString b = \"b\";\n\nfor (int i = 0; i < 10000000; i++) { //ten million times\n String c = a.concat(b);\n}\n\nlong end = System.currentTimeMillis();\n\nSystem.out.println(end - start);\n \"a + b\" a.concat(b) concat() concat() new String(result) String a = new String(\"a\") // more than 20 times slower than String a = \"a\"\n"
},
{
"answer_id": 47716,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 5,
"selected": false,
"text": "StringBuilder toString()"
},
{
"answer_id": 47758,
"author": "ckpwong",
"author_id": 2551,
"author_profile": "https://Stackoverflow.com/users/2551",
"pm_score": 6,
"selected": false,
"text": "String c = a;\nfor (long i = 0; i < 100000L; i++) {\n c = c.concat(b); // make sure javac cannot skip the loop\n // using c += b for the alternative\n}\n StringBuilder.append() StringBuilder a += b concat a += b StringBuilder String"
},
{
"answer_id": 25378169,
"author": "Deepak Sharma",
"author_id": 1047565,
"author_profile": "https://Stackoverflow.com/users/1047565",
"pm_score": 3,
"selected": false,
"text": "concat String s = 10 + \"Hello\";\n String s = \"I\";\nString s1 = s.concat(\"am\").concat(\"good\").concat(\"boy\");\nSystem.out.println(s1);\n String s=\"I\";\nString s1=s.concat(\"am\").concat(\"good\").concat(\"boy\");\nSystem.out.println(s1);\n I\nam\ngood\nboy\nIam\nIamgood\nIamgoodboy\n String s=\"I\"+\"am\"+\"good\"+\"boy\";\nSystem.out.println(s);\n StringBuffer sb = new StringBuffer(\"I\");\nsb.append(\"am\");\nsb.append(\"good\");\nsb.append(\"boy\");\nSystem.out.println(sb);\n"
},
{
"answer_id": 46485284,
"author": "Paweł Adamski",
"author_id": 1268294,
"author_profile": "https://Stackoverflow.com/users/1268294",
"pm_score": 5,
"selected": false,
"text": "+ concat @Warmup(iterations = 5, time = 200, timeUnit = TimeUnit.MILLISECONDS)\n@Measurement(iterations = 5, time = 200, timeUnit = TimeUnit.MILLISECONDS)\npublic class StringConcatenation {\n\n @org.openjdk.jmh.annotations.State(Scope.Thread)\n public static class State2 {\n public String a = \"abc\";\n public String b = \"xyz\";\n }\n\n @org.openjdk.jmh.annotations.State(Scope.Thread)\n public static class State3 {\n public String a = \"abc\";\n public String b = \"xyz\";\n public String c = \"123\";\n }\n\n\n @org.openjdk.jmh.annotations.State(Scope.Thread)\n public static class State4 {\n public String a = \"abc\";\n public String b = \"xyz\";\n public String c = \"123\";\n public String d = \"!@#\";\n }\n\n @Benchmark\n public void plus_2(State2 state, Blackhole blackhole) {\n blackhole.consume(state.a+state.b);\n }\n\n @Benchmark\n public void plus_3(State3 state, Blackhole blackhole) {\n blackhole.consume(state.a+state.b+state.c);\n }\n\n @Benchmark\n public void plus_4(State4 state, Blackhole blackhole) {\n blackhole.consume(state.a+state.b+state.c+state.d);\n }\n\n @Benchmark\n public void stringbuilder_2(State2 state, Blackhole blackhole) {\n blackhole.consume(new StringBuilder().append(state.a).append(state.b).toString());\n }\n\n @Benchmark\n public void stringbuilder_3(State3 state, Blackhole blackhole) {\n blackhole.consume(new StringBuilder().append(state.a).append(state.b).append(state.c).toString());\n }\n\n @Benchmark\n public void stringbuilder_4(State4 state, Blackhole blackhole) {\n blackhole.consume(new StringBuilder().append(state.a).append(state.b).append(state.c).append(state.d).toString());\n }\n\n @Benchmark\n public void concat_2(State2 state, Blackhole blackhole) {\n blackhole.consume(state.a.concat(state.b));\n }\n\n @Benchmark\n public void concat_3(State3 state, Blackhole blackhole) {\n blackhole.consume(state.a.concat(state.b.concat(state.c)));\n }\n\n\n @Benchmark\n public void concat_4(State4 state, Blackhole blackhole) {\n blackhole.consume(state.a.concat(state.b.concat(state.c.concat(state.d))));\n }\n}\n Benchmark Mode Cnt Score Error Units\nStringConcatenation.concat_2 thrpt 50 24908871.258 ± 1011269.986 ops/s\nStringConcatenation.concat_3 thrpt 50 14228193.918 ± 466892.616 ops/s\nStringConcatenation.concat_4 thrpt 50 9845069.776 ± 350532.591 ops/s\nStringConcatenation.plus_2 thrpt 50 38999662.292 ± 8107397.316 ops/s\nStringConcatenation.plus_3 thrpt 50 34985722.222 ± 5442660.250 ops/s\nStringConcatenation.plus_4 thrpt 50 31910376.337 ± 2861001.162 ops/s\nStringConcatenation.stringbuilder_2 thrpt 50 40472888.230 ± 9011210.632 ops/s\nStringConcatenation.stringbuilder_3 thrpt 50 33902151.616 ± 5449026.680 ops/s\nStringConcatenation.stringbuilder_4 thrpt 50 29220479.267 ± 3435315.681 ops/s\n"
},
{
"answer_id": 70535824,
"author": "Christian Meyer",
"author_id": 5759656,
"author_profile": "https://Stackoverflow.com/users/5759656",
"pm_score": 0,
"selected": false,
"text": "s.concat(\"hello\"); NullPointereException System.out.println(3 + 'a'); //100 RuntimeException"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292/"
] |
47,612 |
<p>I've got a C# class with a <code>Dispose</code> function via <code>IDisposable</code>. It's intended to be used inside a <code>using</code> block so the expensive resource it handles can be released right away.</p>
<p>The problem is that a bug occurred when an exception was thrown before <code>Dispose</code> was called, and the programmer neglected to use <code>using</code> or <code>finally</code>.</p>
<p>In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use <code>using</code>.</p>
<p>Is there any way to for a <code>using</code> block to be automatically used in C#?</p>
<p>Many thanks.</p>
<p>UPDATE:</p>
<p>I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors.</p>
<p>Here's the bug I found, reduced to the essentials...</p>
<pre><code>try
{
PleaseDisposeMe a = new PleaseDisposeMe();
throw new Exception();
a.Dispose();
}
catch (Exception ex)
{
Log(ex);
}
// This next call will throw a time-out exception unless the GC
// runs a.Dispose in time.
PleaseDisposeMe b = new PleaseDisposeMe();
</code></pre>
<p>Using <code>FXCop</code> is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone?</p>
|
[
{
"answer_id": 47617,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 2,
"selected": false,
"text": "~ClassName()\n{\n}\n public class DisposableFinalisableClass : IDisposable\n {\n ~DisposableFinalisableClass()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if (disposing)\n {\n // tidy managed resources\n }\n\n // tidy unmanaged resources\n }\n }\n"
},
{
"answer_id": 47665,
"author": "Hershi",
"author_id": 1596,
"author_profile": "https://Stackoverflow.com/users/1596",
"pm_score": 3,
"selected": false,
"text": "class MyDisposable: IDisposable {\n public void Dispose() {\n lock(this) {\n if (disposed) {\n return;\n }\n\n disposed = true;\n }\n\n GC.SuppressFinalize(this);\n\n // Do actual disposing here ...\n }\n\n private bool disposed = false;\n}\n"
},
{
"answer_id": 48557,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "using using using (SqlConnection con = new SqlConnection(\"DB con str\") )\nusing (SqlCommand com = new SqlCommand( con, \"sql query\") )\n{\n //now code is indented one level\n //technically we're nested twice\n}\n using PleaseDisposeMe a;\ntry\n{\n a = new PleaseDisposeMe();\n throw new Exception();\n}\ncatch (Exception ex) { Log(ex); } \nfinally { \n //this always executes, even with the exception\n a.Dispose(); \n}\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3568/"
] |
47,639 |
<p>I just noticed that Chromium was installed in AppData in both Vista and XP. If Google does that and if other applications does this, than is that becuase there is some form of protection? Should we write installers that does the same thing as Google?</p>
|
[
{
"answer_id": 47649,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 5,
"selected": true,
"text": "%PROGRAMFILES% %USERPROFILE%\\Local Settings\\Apps %USERPROFILE%\\AppData\\Roaming ~/Applications"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/370899/"
] |
47,656 |
<p>I would like to do full-text searching of data in my Ruby on Rails application. What options exist?</p>
|
[
{
"answer_id": 47680,
"author": "sock",
"author_id": 4028,
"author_profile": "https://Stackoverflow.com/users/4028",
"pm_score": 5,
"selected": true,
"text": "acts_as_tsearch acts_as_solr acts_as_ferret acts_as_xapian"
},
{
"answer_id": 59523303,
"author": "Joshua Pinter",
"author_id": 293280,
"author_profile": "https://Stackoverflow.com/users/293280",
"pm_score": 2,
"selected": false,
"text": "MATCH() AGAINST() MATCH() AGAINST() add_index :table, :column, type: :fulltext\n where( \"MATCH( column ) AGAINST( ? )\", term )\n brew install elasticsearch\n brew services start elasticsearch\n searchkick bundle add searchkick --strict\n --strict searchkick class MyModel < ApplicationRecord\n searchkick\n end\n MyModel.reindex\n matching_records = MyModel.search( \"term\" )\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4028/"
] |
47,658 |
<p>I am writing a coding standards document for a team of about 15 developers with a project load of between 10 and 15 projects a year. Amongst other sections (which I may post here as I get to them) I am writing a section on code formatting. So to start with, I think it is wise that, for whatever reason, we establish some basic, consistent code formatting/naming standards.</p>
<p>I've looked at roughly 10 projects written over the last 3 years from this team and I'm, obviously, finding a pretty wide range of styles. Contractors come in and out and at times, and sometimes even double the team size.</p>
<p>I am looking for a few suggestions for code formatting and naming standards that have really paid off ... but that can also really be justified. I think consistency and shared-patterns go a long way to making the code more maintainable ... but, are there other things I ought to consider when defining said standards?</p>
<ul>
<li><p>How do you lineup parenthesis? Do you follow the same parenthesis guidelines when dealing with classes, methods, try catch blocks, switch statements, if else blocks, etc.</p></li>
<li><p>Do you line up fields on a column? Do you notate/prefix private variables with an underscore? Do you follow any naming conventions to make it easier to find particulars in a file? How do you order the members of your class?</p></li>
</ul>
<p>What about suggestions for namespaces, packaging or source code folder/organization standards? I tend to start with something like:</p>
<pre><code><com|org|...>.<company>.<app>.<layer>.<function>.ClassName
</code></pre>
<p>I'm curious to see if there are other, more accepted, practices than what I am accustomed to -- before I venture off dictating these standards. Links to standards already published online would be great too -- even though I've done a bit of that already.</p>
|
[
{
"answer_id": 48121,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 2,
"selected": false,
"text": "if(...)\n{\n\n}\n while(stillwaiting())\n{\n ;\n}\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4910/"
] |
47,676 |
<p>The Weblogic servers we are using have been configured to allow JNDI datasource names like "appds".</p>
<p>For development (localhost), we might be running Tomcat and when declared in the <context> section of server.xml, Tomcat will hang JNDI datasources on "java:comp/env/jdbc/*" in the JNDI tree.</p>
<p><strong>Problem:</strong> in Weblogic, the JNDI lookup is "appds" whilst in Tomcat, it seems that that I must provide the formal "java:comp/env/jdbc/appds". I'm afraid the Tomcat version is an implicit standard but unfortunately, I can't change Weblogic's config ... so that means we end up with two different spring config files (we're using spring 2.5) to facilitate the different environments.</p>
<p>Is there an elegant way to address this. Can I look JNDI names up directly in Tomcat? Can Spring take a name and look in both places? Google searches or suggestions would be great.</p>
|
[
{
"answer_id": 50552,
"author": "Binil Thomas",
"author_id": 3973,
"author_profile": "https://Stackoverflow.com/users/3973",
"pm_score": 0,
"selected": false,
"text": "WEB-INF/classes/application.properties /etc/sysenv ${ds.jndi} PropertyPlaceholderConfigurer classpath:application.properties file:/etc/sysenv ignoreResourceNotFound true /etc/sysenv BasicDataSource defaultObject JndiObjectFactoryBean"
},
{
"answer_id": 444367,
"author": "martsraits",
"author_id": 55036,
"author_profile": "https://Stackoverflow.com/users/55036",
"pm_score": 5,
"selected": true,
"text": "JndiLocatorSupport resourceRef"
},
{
"answer_id": 444553,
"author": "harmanjd",
"author_id": 54321,
"author_profile": "https://Stackoverflow.com/users/54321",
"pm_score": 1,
"selected": false,
"text": "<Resource name=\"jms/ConnectionFactory\" auth=\"Container\" type=\"org.apache.activemq.ActiveMQConnectionFactory\" description=\"\nJMS Connection Factory\"\n factory=\"org.apache.activemq.jndi.JNDIReferenceFactory\" brokerURL=\"tcp://localhost:61615\" brokerName=\"StandaloneAc\ntiveMQBroker\"/>\n <beans xmlns=\"http://www.springframework.org/schema/beans\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:util=\"http://www.springframework.org/schema/util\"\n xmlns:aop=\"http://www.springframework.org/schema/aop\"\n xmlns:jee=\"http://www.springframework.org/schema/jee\"\n xsi:schemaLocation=\"\nhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd\nhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd\nhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd\nhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd\">\n\n<jee:jndi-lookup jndi-name=\"jms/ConnectionFactory\" id=\"connectionFactory\" resource-ref=\"true\"\n expected-type=\"javax.jms.ConnectionFactory\" lookup-on-startup=\"false\"/>\n"
},
{
"answer_id": 4270169,
"author": "Leonel",
"author_id": 15649,
"author_profile": "https://Stackoverflow.com/users/15649",
"pm_score": 4,
"selected": false,
"text": "web.xml spring-beans.xml <resource-ref /> WEB-INF/weblogic.xml META-INF/context.xml jdbc/MyDataSource jms/ConnFactory java:comp/env/ <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:jee=\"http://www.springframework.org/schema/jee\"\n xsi:schemaLocation=\"\nhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\nhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd\">\n\n<jee:jndi-lookup jndi-name=\"jdbc/appds\"\n id=\"dataSource\" />\n</beans>\n <resource-ref>\n <description>My data source</description>\n <res-ref-name>jdbc/appds</res-ref-name>\n <res-type>javax.sql.DataSource</res-type>\n <res-auth>Container</res-auth>\n</resource-ref>\n <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<weblogic-web-app\n xmlns=\"http://xmlns.oracle.com/weblogic/weblogic-web-app\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"\n http://xmlns.oracle.com/weblogic/weblogic-web-app http://http://www.oracle.com/technology/weblogic/weblogic-web-app/1.1/weblogic-web-app.xsd\">\n\n<resource-description>\n <jndi-name>appds</jndi-name>\n <res-ref-name>jdbc/appds</res-ref-name>\n</resource-description>\n</weblogic-web-app>\n <Context>\n <ResourceLink global=\"jdbc/appds\" name=\"jdbc/appds\" type=\"javax.sql.DataSource\"/>\n</Context>\n"
},
{
"answer_id": 7001749,
"author": "Val Blant",
"author_id": 652634,
"author_profile": "https://Stackoverflow.com/users/652634",
"pm_score": 2,
"selected": false,
"text": "<bean id=\"dataSource\" class=\"org.springframework.jndi.JndiObjectFactoryBean\">\n <!-- This will prepend 'java:comp/env/' for Tomcat, but still fall back to the short name for Weblogic -->\n <property name=\"resourceRef\" value=\"true\" /> \n <property name=\"jndiName\" value=\"jdbc/AgriShare\" />\n</bean>\n jdbc/AgriShare"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4910/"
] |
47,683 |
<p>We have a Java listener that reads text messages off of a queue in JBossMQ. If we have to reboot JBoss, the listener will not reconnect and start reading messages again. We just get messages in the listener's log file every 2 minutes saying it can't connect. Is there something we're not setting in our code or in JBossMQ? I'm new to JMS so any help will be greatly appreciated. Thanks.</p>
|
[
{
"answer_id": 47963,
"author": "Todd",
"author_id": 3803,
"author_profile": "https://Stackoverflow.com/users/3803",
"pm_score": 4,
"selected": true,
"text": " public void onException (JMSException jsme)\n {\n if (!closeRequested)\n {\n this.disconnect();\n this.establishConnection(connectionProps, queueName, uname, pword, clientID, messageSelector);\n } \n else\n {\n //Client requested close so do not try to reconnect\n }\n }\n while(!initialized)"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3098/"
] |
47,701 |
<p>I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? </p>
<p>Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :)</p>
|
[
{
"answer_id": 56510,
"author": "asksol",
"author_id": 5577,
"author_profile": "https://Stackoverflow.com/users/5577",
"pm_score": 5,
"selected": true,
"text": "(gdb) thr 2\n[Switching to thread 2 (process 6159 thread 0x3f1b)]\n(gdb) backtrace\n....\n"
},
{
"answer_id": 550795,
"author": "Peter S Magnusson",
"author_id": 31024,
"author_profile": "https://Stackoverflow.com/users/31024",
"pm_score": 3,
"selected": false,
"text": "./configure --prefix=/usr/local/pydbg\nmake OPT=-g\nsudo make install\nsudo ln -s /usr/local/pydbg/bin/python /usr/local/bin/dbgpy\n while $pc < Py_Main || $pc > Py_GetArgcArgv\n while ($pc < Py_Main || $pc > Py_GetArgcArgv) && ($pc < t_bootstrap || $pc > thread_PyThread_start_new_thread)\n pystack gdb> attach <PID>\ngdb> info threads\ngdb> thread <N>\ngdb> bt\ngdb> pystack\ngdb> detach\n"
},
{
"answer_id": 59023050,
"author": "Błażej Michalik",
"author_id": 2146491,
"author_profile": "https://Stackoverflow.com/users/2146491",
"pm_score": 0,
"selected": false,
"text": "import sys\nimport socket\nimport pdb\n\ndef remote_trace():\n server = socket.socket()\n server.bind(('0.0.0.0', 12345))\n server.listen()\n client, _= server.accept()\n stream = client.makefile('rw')\n sys.stdin = sys.stdout = sys.stderr = stream\n pdb.set_trace()\n\nremote_trace()\n\n# Execute in the shell: `telnet 127.0.0.1 12345`\n"
},
{
"answer_id": 71794451,
"author": "gobenji",
"author_id": 1327601,
"author_profile": "https://Stackoverflow.com/users/1327601",
"pm_score": 1,
"selected": false,
"text": "python3.10-dbg /usr/share/gdb/auto-load/usr/bin/python3.10-gdb.py #!/usr/bin/env python3\n\nimport signal\nimport threading\n\ndef a():\n while True:\n pass\n\ndef b():\n while True:\n signal.pause()\n\nthreading.Thread(target=a).start()\nthreading.Thread(target=b).start()\n user@vsid:~$ ps -C python3 -L\n PID LWP TTY TIME CMD\n 1215 1215 pts/0 00:00:00 python3\n 1215 1216 pts/0 00:00:19 python3\n 1215 1217 pts/0 00:00:00 python3\nuser@vsid:~$ gdb -p 1215\nGNU gdb (Debian 10.1-2+b1) 10.1.90.20210103-git\nCopyright (C) 2021 Free Software Foundation, Inc.\nLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n[...]\n(gdb) info auto-load python-scripts\nLoaded Script\nYes /usr/share/gdb/auto-load/usr/bin/python3.10-gdb.py\n(gdb) info threads\n Id Target Id Frame\n* 1 Thread 0x7f2f034b4740 (LWP 1215) \"python3\" 0x00007f2f036a60fa in __futex_abstimed_wait_common64 (futex_word=futex_word@entry=0x7f2ef4000b60, expected=expected@entry=0,\n clockid=clockid@entry=0, abstime=abstime@entry=0x0, private=<optimized out>,\n cancel=cancel@entry=true) at ../sysdeps/nptl/futex-internal.c:74\n 2 Thread 0x7f2f02ea7640 (LWP 1216) \"python3\" 0x000000000051b858 in _PyEval_EvalFrameDefault\n (tstate=<optimized out>, f=<optimized out>, throwflag=<optimized out>)\n at ../Python/ceval.c:3850\n 3 Thread 0x7f2f026a6640 (LWP 1217) \"python3\" 0x00007f2f036a3932 in __libc_pause ()\n at ../sysdeps/unix/sysv/linux/pause.c:29\n(gdb) thread 2\n(gdb) py-bt\nTraceback (most recent call first):\n File \"/root/./threaded.py\", line 7, in a\n while True:\n File \"/usr/lib/python3.10/threading.py\", line 946, in run\n self._target(*self._args, **self._kwargs)\n File \"/usr/lib/python3.10/threading.py\", line 1009, in _bootstrap_inner\n self.run()\n File \"/usr/lib/python3.10/threading.py\", line 966, in _bootstrap\n self._bootstrap_inner()\n(gdb)\n 1216 ps a()"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
47,709 |
<p>When you print from Google Docs (using the "print" link, not File/Print) you end up printing a nicely formated PDF file instead of relying on the print engine of the browser. Same is true for some of the reports in Google Analytics . . . the printed reports as PDF's are beautiful. How do they do that? I can't imagine they use something like Adobe Acrobat to facilitate it but maybe they do. I've seen some expensive HTML to PDF converters online from time to time but have never tired it. Any thoughts?</p>
|
[
{
"answer_id": 88919,
"author": "Brian",
"author_id": 700,
"author_profile": "https://Stackoverflow.com/users/700",
"pm_score": 1,
"selected": false,
"text": "<pd4ml:transform>\n<!-- Your HTML is here -->\n\n<c:import url=\"/page.html\" />\n</pd4ml:transform>\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4835/"
] |
47,749 |
<p>A while ago I read the <a href="http://www.martinfowler.com/articles/mocksArentStubs.html" rel="nofollow noreferrer">Mocks Aren't Stubs</a> article by Martin Fowler and I must admit I'm a bit scared of external dependencies with regards to added complexity so I would like to ask:</p>
<p>What is the best method to use when unit testing?</p>
<p>Is it better to always use a mock framework to automatically mock the dependencies of the method being tested, or would you prefer to use simpler mechanisms like for instance test stubs?</p>
|
[
{
"answer_id": 47787,
"author": "Toran Billups",
"author_id": 2701,
"author_profile": "https://Stackoverflow.com/users/2701",
"pm_score": 2,
"selected": false,
"text": "<TestMethod()> _\nPublic Sub Should_Populate_Products_List_OnViewLoad_When_PostBack_Is_False()\n mMockery = New MockRepository()\n mView = DirectCast(mMockery.Stub(Of IProductView)(), IProductView)\n mProductService = DirectCast(mMockery.DynamicMock(Of IProductService)(), IProductService)\n mPresenter = New ProductPresenter(mView, mProductService)\n Dim ProductList As New List(Of Product)()\n ProductList.Add(New Product())\n Using mMockery.Record()\n SetupResult.For(mView.PageIsPostBack).Return(False)\n Expect.Call(mProductService.GetProducts()).Return(ProductList).Repeat.Once()\n End Using\n Using mMockery.Playback()\n mPresenter.OnViewLoad()\n End Using\n 'Verify that we hit the service dependency during the method when postback is false\n Assert.AreEqual(1, mView.Products.Count)\n mMockery.VerifyAll()\nEnd Sub\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1324220/"
] |
47,752 |
<p>Anyone have a quick method for de-duplicating a generic List in C#?</p>
|
[
{
"answer_id": 47755,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 6,
"selected": false,
"text": "list.Sort();\nInt32 index = list.Count - 1;\nwhile (index > 0)\n{\n if (list[index] == list[index - 1])\n {\n if (index < list.Count - 1)\n (list[index], list[list.Count - 1]) = (list[list.Count - 1], list[index]);\n list.RemoveAt(list.Count - 1);\n index--;\n }\n else\n index--;\n}\n"
},
{
"answer_id": 47757,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 9,
"selected": true,
"text": "using System;\nusing System.Collections.Generic;\n\nclass Program\n{\n static void Main()\n {\n HashSet<int> evenNumbers = new HashSet<int>();\n HashSet<int> oddNumbers = new HashSet<int>();\n\n for (int i = 0; i < 5; i++)\n {\n // Populate numbers with just even numbers.\n evenNumbers.Add(i * 2);\n\n // Populate oddNumbers with just odd numbers.\n oddNumbers.Add((i * 2) + 1);\n }\n\n Console.Write(\"evenNumbers contains {0} elements: \", evenNumbers.Count);\n DisplaySet(evenNumbers);\n\n Console.Write(\"oddNumbers contains {0} elements: \", oddNumbers.Count);\n DisplaySet(oddNumbers);\n\n // Create a new HashSet populated with even numbers.\n HashSet<int> numbers = new HashSet<int>(evenNumbers);\n Console.WriteLine(\"numbers UnionWith oddNumbers...\");\n numbers.UnionWith(oddNumbers);\n\n Console.Write(\"numbers contains {0} elements: \", numbers.Count);\n DisplaySet(numbers);\n }\n\n private static void DisplaySet(HashSet<int> set)\n {\n Console.Write(\"{\");\n foreach (int i in set)\n {\n Console.Write(\" {0}\", i);\n }\n Console.WriteLine(\" }\");\n }\n}\n\n/* This example produces output similar to the following:\n * evenNumbers contains 5 elements: { 0 2 4 6 8 }\n * oddNumbers contains 5 elements: { 1 3 5 7 9 }\n * numbers UnionWith oddNumbers...\n * numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 }\n */\n"
},
{
"answer_id": 47761,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 4,
"selected": false,
"text": "list = new ArrayList<T>(new HashSet<T>(list))\n List<T> noDupes = new ArrayList<T>(new HashSet<T>(list));\nlist.clear();\nlist.addAll(noDupes);\n"
},
{
"answer_id": 47763,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 3,
"selected": false,
"text": "HashSet var unique = new List<T>();\nvar hs = new HashSet<T>();\nforeach (T t in list)\n if (hs.Add(t))\n unique.Add(t);\n var hs = new HashSet<T>();\nlist.All( x => hs.Add(x) );\n HashSet O(N) O(N) O(N*lgN) O(1)"
},
{
"answer_id": 47776,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 8,
"selected": false,
"text": "var noDupes = list.Distinct().ToList();\n"
},
{
"answer_id": 47777,
"author": "Factor Mystic",
"author_id": 1569,
"author_profile": "https://Stackoverflow.com/users/1569",
"pm_score": 10,
"selected": false,
"text": "List<T> withDupes = LoadSomeData();\nList<T> noDupes = withDupes.Distinct().ToList();\n"
},
{
"answer_id": 48275,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 5,
"selected": false,
"text": "Distinct() public IEnumerable<T> DedupCollection<T> (IEnumerable<T> input) \n{\n var passedValues = new HashSet<T>();\n\n // Relatively simple dupe check alg used as example\n foreach(T item in input)\n if(passedValues.Add(item)) // True if item is new\n yield return item;\n}\n Distinct()"
},
{
"answer_id": 1792582,
"author": "Even Mien",
"author_id": 73794,
"author_profile": "https://Stackoverflow.com/users/73794",
"pm_score": 7,
"selected": false,
"text": "var noDupes = new HashSet<T>(withDupes);\n var noDupsList = new HashSet<T>(withDupes).ToList();\n"
},
{
"answer_id": 2571314,
"author": "Geoff Taylor",
"author_id": 308300,
"author_profile": "https://Stackoverflow.com/users/308300",
"pm_score": 4,
"selected": false,
"text": "public static List<T> Deduplicate<T>(this List<T> listToDeduplicate)\n{\n return listToDeduplicate.Distinct().ToList();\n}\n List<int> myFilteredList = unfilteredList.Deduplicate();\n"
},
{
"answer_id": 4954239,
"author": "Bhasin",
"author_id": 610952,
"author_profile": "https://Stackoverflow.com/users/610952",
"pm_score": 2,
"selected": false,
"text": " static void Main(string[] args)\n {\n List<string> alpha = new List<string>();\n\n for(char a = 'a'; a <= 'd'; a++)\n {\n alpha.Add(a.ToString());\n alpha.Add(a.ToString());\n }\n\n Console.WriteLine(\"Data :\");\n alpha.ForEach(delegate(string t) { Console.WriteLine(t); });\n\n alpha.ForEach(delegate (string v)\n {\n if (alpha.FindAll(delegate(string t) { return t == v; }).Count > 1)\n alpha.Remove(v);\n });\n\n Console.WriteLine(\"Unique Result :\");\n alpha.ForEach(delegate(string t) { Console.WriteLine(t);});\n Console.ReadKey();\n }\n"
},
{
"answer_id": 5114231,
"author": "gary",
"author_id": 63844,
"author_profile": "https://Stackoverflow.com/users/63844",
"pm_score": 3,
"selected": false,
"text": "public static void RemoveAdjacentDuplicates<T>(this List<T> List, IComparer<T> Comparer)\n{\n int NumUnique = 0;\n for (int i = 0; i < List.Count; i++)\n if ((i == 0) || (Comparer.Compare(List[NumUnique - 1], List[i]) != 0))\n List[NumUnique++] = List[i];\n List.RemoveRange(NumUnique, List.Count - NumUnique);\n}\n"
},
{
"answer_id": 5609895,
"author": "Ravi Ganesan",
"author_id": 700589,
"author_profile": "https://Stackoverflow.com/users/700589",
"pm_score": 2,
"selected": false,
"text": "List<Container> containerList = LoadContainer();//Assume it has duplicates\nList<Container> filteredList = new List<Container>();\nforeach (var container in containerList)\n{ \n Container duplicateContainer = containerList.Find(delegate(Container checkContainer)\n { return (checkContainer.UniqueId == container.UniqueId); });\n //Assume 'UniqueId' is the property of the Container class on which u r making a search\n\n if(!containerList.Contains(duplicateContainer) //Add object when not found in the new class object\n {\n filteredList.Add(container);\n }\n }\n"
},
{
"answer_id": 9276761,
"author": "David J.",
"author_id": 1209045,
"author_profile": "https://Stackoverflow.com/users/1209045",
"pm_score": 2,
"selected": false,
"text": " private static void CheckForDuplicateItems(List<string> items)\n {\n if (items == null ||\n items.Count == 0)\n return;\n\n for (int outerIndex = 0; outerIndex < items.Count; outerIndex++)\n {\n for (int innerIndex = 0; innerIndex < items.Count; innerIndex++)\n {\n if (innerIndex == outerIndex) continue;\n if (items[outerIndex].Equals(items[innerIndex]))\n {\n // Duplicate Found\n }\n }\n }\n }\n"
},
{
"answer_id": 11255357,
"author": "Chris",
"author_id": 1490135,
"author_profile": "https://Stackoverflow.com/users/1490135",
"pm_score": 2,
"selected": false,
"text": "if(items.IndexOf(new_item) < 0) \n items.add(new_item)\n"
},
{
"answer_id": 11694032,
"author": "Eric",
"author_id": 803629,
"author_profile": "https://Stackoverflow.com/users/803629",
"pm_score": 5,
"selected": false,
"text": "List<Store> myStoreList = Service.GetStoreListbyProvince(provinceId)\n .GroupBy(s => s.City)\n .Select(grp => grp.FirstOrDefault())\n .OrderBy(s => s.City)\n .ToList();\n"
},
{
"answer_id": 13404160,
"author": "Hossein Sarshar",
"author_id": 1202836,
"author_profile": "https://Stackoverflow.com/users/1202836",
"pm_score": 5,
"selected": false,
"text": "List<Type> liIDs = liIDs.Distinct().ToList<Type>();\n"
},
{
"answer_id": 19516222,
"author": "Guest",
"author_id": 2906798,
"author_profile": "https://Stackoverflow.com/users/2906798",
"pm_score": 2,
"selected": false,
"text": "for (int innerIndex = items.Count - 1; innerIndex > outerIndex ; innerIndex--)"
},
{
"answer_id": 23652999,
"author": "Paul Richards",
"author_id": 2282723,
"author_profile": "https://Stackoverflow.com/users/2282723",
"pm_score": 1,
"selected": false,
"text": " public static void RemoveDuplicates<T>(IList<T> list )\n {\n if (list == null)\n {\n return;\n }\n int i = 1;\n while(i<list.Count)\n {\n int j = 0;\n bool remove = false;\n while (j < i && !remove)\n {\n if (list[i].Equals(list[j]))\n {\n remove = true;\n }\n j++;\n }\n if (remove)\n {\n list.RemoveAt(i);\n }\n else\n {\n i++;\n }\n } \n }\n"
},
{
"answer_id": 27004677,
"author": "Grant",
"author_id": 1618538,
"author_profile": "https://Stackoverflow.com/users/1618538",
"pm_score": 3,
"selected": false,
"text": "public static List<T> Distinct<T>(this List<T> list)\n{\n return (new HashSet<T>(list)).ToList();\n}\n"
},
{
"answer_id": 42813216,
"author": "dush88c",
"author_id": 5097602,
"author_profile": "https://Stackoverflow.com/users/5097602",
"pm_score": 3,
"selected": false,
"text": "IEnumerable<Catalogue> distinctCatalogues = catalogues.DistinctBy(c => c.CatalogueCode); \n"
},
{
"answer_id": 45533433,
"author": "flagamba",
"author_id": 2352444,
"author_profile": "https://Stackoverflow.com/users/2352444",
"pm_score": 2,
"selected": false,
"text": "obj2 = obj1.Union(obj1).ToList();\n"
},
{
"answer_id": 48767398,
"author": "WonderWorker",
"author_id": 1271898,
"author_profile": "https://Stackoverflow.com/users/1271898",
"pm_score": 3,
"selected": false,
"text": "using System.Linq;\n obj1 obj1 = obj1.Union(obj1).ToList();\n obj1 ToList() Union"
},
{
"answer_id": 49916992,
"author": "Moctar Haiz",
"author_id": 3142365,
"author_profile": "https://Stackoverflow.com/users/3142365",
"pm_score": 2,
"selected": false,
"text": "public static List<PointF> RemoveDuplicates(List<PointF> listPoints)\n{\n List<PointF> result = new List<PointF>();\n\n for (int i = 0; i < listPoints.Count; i++)\n {\n if (!result.Contains(listPoints[i]))\n result.Add(listPoints[i]);\n }\n\n return result;\n }\n"
},
{
"answer_id": 53579622,
"author": "Reza Jenabi",
"author_id": 9549856,
"author_profile": "https://Stackoverflow.com/users/9549856",
"pm_score": 3,
"selected": false,
"text": "Product Customer public class Product\n{\n public int Id { get; set; }\n public string ProductName { get; set; }\n}\n\npublic class Customer\n{\n public int Id { get; set; }\n public string CustomerName { get; set; }\n\n}\n public class ItemEqualityComparer<T> : IEqualityComparer<T> where T : class\n{\n private readonly PropertyInfo _propertyInfo;\n\n public ItemEqualityComparer(string keyItem)\n {\n _propertyInfo = typeof(T).GetProperty(keyItem, BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);\n }\n\n public bool Equals(T x, T y)\n {\n var xValue = _propertyInfo?.GetValue(x, null);\n var yValue = _propertyInfo?.GetValue(y, null);\n return xValue != null && yValue != null && xValue.Equals(yValue);\n }\n\n public int GetHashCode(T obj)\n {\n var propertyValue = _propertyInfo.GetValue(obj, null);\n return propertyValue == null ? 0 : propertyValue.GetHashCode();\n }\n}\n var products = new List<Product>\n {\n new Product{ProductName = \"product 1\" ,Id = 1,},\n new Product{ProductName = \"product 2\" ,Id = 2,},\n new Product{ProductName = \"product 2\" ,Id = 4,},\n new Product{ProductName = \"product 2\" ,Id = 4,},\n };\nvar productList = products.Distinct(new ItemEqualityComparer<Product>(nameof(Product.Id))).ToList();\n\nvar customers = new List<Customer>\n {\n new Customer{CustomerName = \"Customer 1\" ,Id = 5,},\n new Customer{CustomerName = \"Customer 2\" ,Id = 5,},\n new Customer{CustomerName = \"Customer 2\" ,Id = 5,},\n new Customer{CustomerName = \"Customer 2\" ,Id = 5,},\n };\nvar customerList = customers.Distinct(new ItemEqualityComparer<Customer>(nameof(Customer.Id))).ToList();\n Id nameof(YourClass.DuplicateProperty) nameof(Customer.CustomerName) CustomerName"
},
{
"answer_id": 55140260,
"author": "Alfred Udah",
"author_id": 6468488,
"author_profile": "https://Stackoverflow.com/users/6468488",
"pm_score": 4,
"selected": false,
"text": "List<type> myNoneDuplicateValue = listValueWithDuplicate.Distinct().ToList();\n"
},
{
"answer_id": 56344965,
"author": "Darkgaze",
"author_id": 772739,
"author_profile": "https://Stackoverflow.com/users/772739",
"pm_score": 2,
"selected": false,
"text": "// Duplicates will be noticed after a sort O(nLogn)\nlist.Sort();\n\n// Store the current and last items. Current item declaration is not really needed, and probably optimized by the compiler, but in case it's not...\nint lastItem = -1;\nint currItem = -1;\n\nint size = list.Count;\n\n// Store the index pointing to the last item we want to keep in the list\nint last = size - 1;\n\n// Travel the items from last to first O(n)\nfor (int i = last; i >= 0; --i)\n{\n currItem = list[i];\n\n // If this item was the same as the previous one, we don't want it\n if (currItem == lastItem)\n {\n // Overwrite last in current place. It is a swap but we don't need the last\n list[i] = list[last];\n\n // Reduce the last index, we don't want that one anymore\n last--;\n }\n\n // A new item, we store it and continue\n else\n lastItem = currItem;\n}\n\n// We now have an unsorted list with the duplicates at the end.\n\n// Remove the last items just once\nlist.RemoveRange(last + 1, size - last - 1);\n\n// Sort again O(n logn)\nlist.Sort();\n"
},
{
"answer_id": 63762013,
"author": "user3150241",
"author_id": 3150241,
"author_profile": "https://Stackoverflow.com/users/3150241",
"pm_score": 0,
"selected": false,
"text": " class MyList{\n int id;\n string date;\n string email;\n }\n \n List<MyList> ml = new Mylist();\n\nml.Add(new MyList(){\nid = 1;\ndate = \"2020/09/06\";\nemail = \"zarezadeh@gmailcom\"\n});\n\nml.Add(new MyList(){\nid = 2;\ndate = \"2020/09/01\";\nemail = \"zarezadeh@gmailcom\"\n});\n\n List<MyList> New_ml = new Mylist();\n\nforeach (var item in ml)\n {\n if (New_ml.Where(w => w.email == item.email).SingleOrDefault() == null)\n {\n New_ml.Add(new MyList()\n {\n id = item.id,\n date = item.date,\n email = item.email\n });\n }\n }\n"
},
{
"answer_id": 68057196,
"author": "Lahiru Gamage",
"author_id": 4991516,
"author_profile": "https://Stackoverflow.com/users/4991516",
"pm_score": 2,
"selected": false,
"text": "List<int> listWithDuplicates = new List<int> { 1, 2, 1, 2, 3, 4, 5 };\nHashSet<int> hashWithoutDuplicates = new HashSet<int> ( listWithDuplicates );\nList<int> listWithoutDuplicates = hashWithoutDuplicates.ToList();\n"
},
{
"answer_id": 68962170,
"author": "Shravankumar Prajapati",
"author_id": 16772141,
"author_profile": "https://Stackoverflow.com/users/16772141",
"pm_score": 0,
"selected": false,
"text": "public class Program\n{\n\n public static void Main(string[] arges)\n {\n List<string> cities = new List<string>() { \"Chennai\", \"Kolkata\", \"Mumbai\", \"Mumbai\",\"Chennai\", \"Delhi\", \"Delhi\", \"Delhi\", \"Chennai\", \"Kolkata\", \"Mumbai\", \"Chennai\" };\n cities = RemoveDuplicate(cities);\n\n foreach (var city in cities)\n {\n Console.WriteLine(city);\n }\n }\n\n public static List<string> RemoveDuplicate(List<string> cities)\n {\n if (cities.Count < 2)\n {\n return cities;\n }\n\n int size = cities.Count;\n for (int i = 0; i < size; i++)\n {\n for (int j = i+1; j < size; j++)\n {\n if (cities[i] == cities[j])\n {\n cities.RemoveAt(j);\n size--;\n j--;\n }\n }\n }\n return cities;\n }\n}\n"
},
{
"answer_id": 69658860,
"author": "Infosunny",
"author_id": 10070007,
"author_profile": "https://Stackoverflow.com/users/10070007",
"pm_score": 1,
"selected": false,
"text": "list = new HashSet<T>(list).ToList();"
},
{
"answer_id": 70162977,
"author": "Onat Korucu",
"author_id": 10037278,
"author_profile": "https://Stackoverflow.com/users/10037278",
"pm_score": 1,
"selected": false,
"text": "private void GetDistinctItemList(List<MyListItem> _listWithDuplicates)\n{\n //It might be a good idea to create MyListItemComparer \n //elsewhere and cache it for performance.\n List<MyListItem> _listWithoutDuplicates = _listWithDuplicates.Distinct(new MyListItemComparer()).ToList();\n \n //Choose the line below instead, if you have a situation where there is a chance to change the list while Distinct() is running.\n //ToArray() is used to solve \"Collection was modified; enumeration operation may not execute\" error.\n //List<MyListItem> _listWithoutDuplicates = _listWithDuplicates.ToArray().Distinct(new MyListItemComparer()).ToList();\n\n return _listWithoutDuplicates;\n}\n public class MyListItemComparer : IEqualityComparer<MyListItem>\n{\n public bool Equals(MyListItem x, MyListItem y)\n {\n return x != null \n && y != null \n && x.A == y.A \n && x.B.Equals(y.B); \n && x.C.ToString().Equals(y.C.ToString());\n }\n\n public int GetHashCode(MyListItem codeh)\n {\n return codeh.GetHashCode();\n }\n}\n public class MyListItem\n{\n public int A { get; }\n public string B { get; }\n public MyEnum C { get; }\n\n public MyListItem(int a, string b, MyEnum c)\n {\n A = a;\n B = b;\n C = c;\n }\n}\n"
},
{
"answer_id": 73453803,
"author": "Hasan Tuna Oruç",
"author_id": 4578450,
"author_profile": "https://Stackoverflow.com/users/4578450",
"pm_score": 0,
"selected": false,
"text": " for(int i1 = 0; i1 < lastValues.Count; i1++)\n {\n for(int i2 = 0; i2 < lastValues.Count; i2++)\n {\n if(lastValues[i1].UserId == lastValues[i2].UserId)\n {\n lastValues.RemoveAt(i2);\n }\n }\n }\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] |
47,762 |
<p>I have a webapp development problem that I've developed one solution for, but am trying to find other ideas that might get around some performance issues I'm seeing.</p>
<p>problem statement: </p>
<ul>
<li>a user enters several keywords/tokens</li>
<li>the application searches for matches to the tokens</li>
<li>need one result for each token
<ul>
<li>ie, if an entry has 3 tokens, i need the entry id 3 times</li>
</ul></li>
<li>rank the results
<ul>
<li>assign X points for token match</li>
<li>sort the entry ids based on points</li>
<li>if point values are the same, use date to sort results</li>
</ul></li>
</ul>
<p>What I want to be able to do, but have not figured out, is to send 1 query that returns something akin to the results of an in(), but returns a duplicate entry id for each token matches for each entry id checked.</p>
<p>Is there a better way to do this than what I'm doing, of using multiple, individual queries running one query per token? If so, what's the easiest way to implement those?</p>
<p><strong>edit</strong><br>
I've already tokenized the entries, so, for example, "see spot run" has an entry id of 1, and three tokens, 'see', 'spot', 'run', and those are in a separate token table, with entry ids relevant to them so the table might look like this:</p>
<pre><code>'see', 1
'spot', 1
'run', 1
'run', 2
'spot', 3
</code></pre>
|
[
{
"answer_id": 47796,
"author": "Robin Barnes",
"author_id": 1349865,
"author_profile": "https://Stackoverflow.com/users/1349865",
"pm_score": 4,
"selected": true,
"text": "SELECT * FROM `entries` \nWHERE token like \"%x%\" union all \n SELECT * FROM `entries` \n WHERE token like \"%y%\" union all \n SELECT * FROM `entries` \n WHERE token like \"%z%\" ORDER BY score ect...\n"
},
{
"answer_id": 47853,
"author": "Erik",
"author_id": 4484,
"author_profile": "https://Stackoverflow.com/users/4484",
"pm_score": 1,
"selected": false,
"text": "SELECT COUNT(*) AS C\n...\nGROUP BY ID\nORDER BY c DESC\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4418/"
] |
47,780 |
<p>I have an inherited project that uses a build script (not make) to build and link the project with various libraries.</p>
<p>When it performs a build I would like to parse the build output to determine what and where the actual static libraries being linked into the final executable are and where are they coming from.</p>
<p>The script is compiling and linking with GNU tools.</p>
|
[
{
"answer_id": 47809,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 1,
"selected": false,
"text": "nm #!/bin/sh\n\nnm -Ag $* | sed 's/^.*\\/\\(.*\\.a\\):/\\1/' | sort -k 3 | grep -v ' U '\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] |
47,786 |
<p>Simple one really. In SQL, if I want to search a text field for a couple of characters, I can do:</p>
<pre><code>SELECT blah FROM blah WHERE blah LIKE '%text%'
</code></pre>
<p>The documentation for App Engine makes no mention of how to achieve this, but surely it's a common enough problem?</p>
|
[
{
"answer_id": 47811,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 7,
"selected": true,
"text": "= > < != > < index.yaml LIKE"
},
{
"answer_id": 1096744,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "db.GqlQuery(\"SELECT * FROM MyModel WHERE prop >= :1 AND prop < :2\",\n \"abc\",\n u\"abc\" + u\"\\ufffd\")\n"
},
{
"answer_id": 2136253,
"author": "jbochi",
"author_id": 230636,
"author_profile": "https://Stackoverflow.com/users/230636",
"pm_score": 4,
"selected": false,
"text": "list_property = value"
},
{
"answer_id": 6204951,
"author": "fernandohur",
"author_id": 718333,
"author_profile": "https://Stackoverflow.com/users/718333",
"pm_score": 2,
"selected": false,
"text": "String start = \"foo\";\n ... = ofy.query(MyEntity.class).filter(\"field >=\", start).filter(\"field <\", start + \"\\uFFFD\");\n"
},
{
"answer_id": 7529428,
"author": "topchef",
"author_id": 59470,
"author_profile": "https://Stackoverflow.com/users/59470",
"pm_score": 0,
"selected": false,
"text": "LIKE '%text%'"
},
{
"answer_id": 11112100,
"author": "gzerone",
"author_id": 1070813,
"author_profile": "https://Stackoverflow.com/users/1070813",
"pm_score": 1,
"selected": false,
"text": "class Article(search.SearchableModel):\n text = db.TextProperty()\n ...\n\n article = Article(text=...)\n article.save()\n\nTo search the full text index, use the SearchableModel.all() method to get an\ninstance of SearchableModel.Query, which subclasses db.Query. Use its search()\nmethod to provide a search query, in addition to any other filters or sort\norders, e.g.:\n\n query = article.all().search('a search query').filter(...).order(...)\n"
},
{
"answer_id": 20204585,
"author": "musketyr",
"author_id": 227419,
"author_profile": "https://Stackoverflow.com/users/227419",
"pm_score": 3,
"selected": false,
"text": "LIKE fern thriller def documents = search.search {\n select all from books\n sort desc by published, SearchApiLimits.MINIMUM_DATE_VALUE\n where title =~ 'fern'\n and genre = 'thriller'\n limit 10\n}\n =~ distance(geopoint(lat, lon), location)"
},
{
"answer_id": 24414573,
"author": "Edy Aguirre",
"author_id": 1617646,
"author_profile": "https://Stackoverflow.com/users/1617646",
"pm_score": 1,
"selected": false,
"text": " Query q = new Query(Directorio.class.getSimpleName());\n\n Filter filterNombreGreater = new FilterPredicate(\"nombre\", FilterOperator.GREATER_THAN_OR_EQUAL, query);\n Filter filterNombreLess = new FilterPredicate(\"nombre\", FilterOperator.LESS_THAN, query+\"\\uFFFD\");\n Filter filterNombre = CompositeFilterOperator.and(filterNombreGreater, filterNombreLess);\n\n q.setFilter(filter);\n"
},
{
"answer_id": 29152005,
"author": "chuycepeda",
"author_id": 2178032,
"author_profile": "https://Stackoverflow.com/users/2178032",
"pm_score": 1,
"selected": false,
"text": "users = []\nqry = self.user_model.query(ndb.OR(self.user_model.name >= q.lower(),self.user_model.email >= q.lower(),self.user_model.username >= q.lower()))\n\nfor _qry in qry:\n if q.lower() in _qry.name.lower() or q.lower() in _qry.email.lower() or q.lower() in _qry.username.lower():\n users.append(_qry)\n"
},
{
"answer_id": 38926030,
"author": "Jose Salas",
"author_id": 3878671,
"author_profile": "https://Stackoverflow.com/users/3878671",
"pm_score": 1,
"selected": false,
"text": "@Index\n public ArrayList<String> searchName;\n List<Profiles> list1 = ofy().load().type(Profiles.class).filter(\"searchName =\",search).list();\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366/"
] |
47,789 |
<p>When should you use generator expressions and when should you use list comprehensions in Python?</p>
<pre><code># Generator expression
(x*2 for x in range(256))
# List comprehension
[x*2 for x in range(256)]
</code></pre>
|
[
{
"answer_id": 47826,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 9,
"selected": true,
"text": "def gen():\n return (something for something in get_some_stuff())\n\nprint gen()[:2] # generators don't support indexing or slicing\nprint [5,6] + gen() # generators can't be added to lists\n"
},
{
"answer_id": 189840,
"author": "Chuck",
"author_id": 23788,
"author_profile": "https://Stackoverflow.com/users/23788",
"pm_score": 6,
"selected": false,
"text": "sum(x*2 for x in xrange(256))\n\ndict( (k, some_func(k)) for k in some_list_of_keys )\n reversed( [x*2 for x in xrange(256)] )\n"
},
{
"answer_id": 22858478,
"author": "tylerl",
"author_id": 86060,
"author_profile": "https://Stackoverflow.com/users/86060",
"pm_score": 6,
"selected": false,
"text": "logfile = open(\"hugefile.txt\",\"r\")\nentry_lines = [(line,len(line)) for line in logfile if line.startswith(\"ENTRY\")]\n logfile = open(\"hugefile.txt\",\"r\")\nentry_lines = ((line,len(line)) for line in logfile if line.startswith(\"ENTRY\"))\n long_entries = ((line,length) for (line,length) in entry_lines if length > 80)\n outfile = open(\"filtered.txt\",\"a\")\nfor entry,length in long_entries:\n outfile.write(entry)\n for long_entries entry_lines entry_lines logfile"
},
{
"answer_id": 34599335,
"author": "Murphy",
"author_id": 4909533,
"author_profile": "https://Stackoverflow.com/users/4909533",
"pm_score": 2,
"selected": false,
"text": "import mincemeat\n\ndef mapfn(k,v):\n for w in v:\n yield 'sum',w\n #yield 'count',1\n\n\ndef reducefn(k,v): \n r1=sum(v)\n r2=len(v)\n print r2\n m=r1/r2\n std=0\n for i in range(r2):\n std+=pow(abs(v[i]-m),2) \n res=pow((std/r2),0.5)\n return r1,r2,res\n"
},
{
"answer_id": 35964024,
"author": "freaker",
"author_id": 1555083,
"author_profile": "https://Stackoverflow.com/users/1555083",
"pm_score": 4,
"selected": false,
"text": ">>> mylist = [\"a\", \"b\", \"c\"]\n>>> gen = (elem + \"1\" for elem in mylist)\n>>> mylist.clear()\n>>> for x in gen: print (x)\n# nothing\n"
},
{
"answer_id": 65724791,
"author": "Yilmaz",
"author_id": 10262805,
"author_profile": "https://Stackoverflow.com/users/10262805",
"pm_score": 2,
"selected": false,
"text": "next() next() next()"
},
{
"answer_id": 70735656,
"author": "JayS",
"author_id": 1812942,
"author_profile": "https://Stackoverflow.com/users/1812942",
"pm_score": 0,
"selected": false,
"text": "from itertools import islice\n\ndef slice_and_continue(sequence):\n ret = []\n seq_i = iter(sequence) #create an iterator from the list\n\n seq_slice = islice(seq_i,3) #take first 3 elements and print\n for x in seq_slice: print(x),\n\n for x in seq_i: print(x**2), #square the rest of the numbers\n\nslice_and_continue([1,2,3,4,5])\n"
},
{
"answer_id": 73214760,
"author": "Karl Knechtel",
"author_id": 523612,
"author_profile": "https://Stackoverflow.com/users/523612",
"pm_score": 1,
"selected": false,
"text": "any all any all min max sum max $ python -m timeit \"max(_ for _ in range(1))\"\n500000 loops, best of 5: 476 nsec per loop\n$ python -m timeit \"max([_ for _ in range(1)])\"\n500000 loops, best of 5: 425 nsec per loop\n$ python -m timeit \"max(_ for _ in range(100))\"\n50000 loops, best of 5: 4.42 usec per loop\n$ python -m timeit \"max([_ for _ in range(100)])\"\n100000 loops, best of 5: 3.79 usec per loop\n$ python -m timeit \"max(_ for _ in range(10000))\"\n500 loops, best of 5: 468 usec per loop\n$ python -m timeit \"max([_ for _ in range(10000)])\"\n500 loops, best of 5: 442 usec per loop\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
47,817 |
<p>Html Textarea elements only wrap when they reach a space or tab character. This is fine, until the user types a looooooooooooooooooooooong enough word. I'm looking for a way to strictly enforce line breaks (eg.: even if it results in "loooooooooooo \n ooooooooooong").</p>
<p><img src="https://i.stack.imgur.com/sUmHB.png" alt="alt text"></p>
<p>The best I've found is to add a zero-width unicode space after every letter, but this breaks copy and paste operations. Anyone know of a better way?</p>
<p>Note: I'm referring to the "textarea" element here (i.e.: the one that behaves similarly to a text input) - not just a plain old block of text.</p>
|
[
{
"answer_id": 47866,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 3,
"selected": false,
"text": "word-wrap: break-word"
},
{
"answer_id": 604928,
"author": "Kim Reece",
"author_id": 1911072,
"author_profile": "https://Stackoverflow.com/users/1911072",
"pm_score": 5,
"selected": true,
"text": "word-wrap:break-word text-wrap:unrestricted"
},
{
"answer_id": 38422582,
"author": "crisc2000",
"author_id": 4481831,
"author_profile": "https://Stackoverflow.com/users/4481831",
"pm_score": 2,
"selected": false,
"text": "textarea { word-break: break-all; }\n textarea { -ms-word-break: break-all; }\n @media all and (-ms-high-contrast:none) {\n*::-ms-backdrop, textarea { white-space: pre; } \n}\n"
},
{
"answer_id": 42537857,
"author": "SeekLoad",
"author_id": 7371886,
"author_profile": "https://Stackoverflow.com/users/7371886",
"pm_score": 0,
"selected": false,
"text": "wrap=\"soft\" wrap=\"hard\" wrap=\"off\" wrap=\"off\" wrap=\"off\" <textarea name=\"tbox\" cols=\"24\" rows=\"4\" wrap=\"soft\"></textarea>\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4939/"
] |
47,824 |
<p>Using core jQuery, how do you remove all the options of a select box, then add one option and select it?</p>
<p>My select box is the following.</p>
<pre><code><Select id="mySelect" size="9"> </Select>
</code></pre>
<p>EDIT: The following code was helpful with chaining. However, (in Internet Explorer) <code>.val('whatever')</code> did not select the option that was added. (I did use the same 'value' in both <code>.append</code> and <code>.val</code>.)</p>
<pre><code>$('#mySelect').find('option').remove().end()
.append('<option value="whatever">text</option>').val('whatever');
</code></pre>
<p>EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. <code>.focus()</code> was closer, but the option did not appear selected like it does with <code>.selected= "true"</code>. Nothing is wrong with my existing code - I am just trying to learn jQuery.</p>
<pre><code>var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");
mySelect.options[0].selected="true";
</code></pre>
<p>EDIT: selected answer was close to what I needed. This worked for me:</p>
<pre><code>$('#mySelect').children().remove().end()
.append('<option selected value="whatever">text</option>') ;
</code></pre>
<p>But both answers led me to my final solution..</p>
|
[
{
"answer_id": 47829,
"author": "Matt",
"author_id": 2338,
"author_profile": "https://Stackoverflow.com/users/2338",
"pm_score": 12,
"selected": true,
"text": "$('#mySelect')\n .find('option')\n .remove()\n .end()\n .append('<option value=\"whatever\">text</option>')\n .val('whatever')\n;\n"
},
{
"answer_id": 50412,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 6,
"selected": false,
"text": "$('select').children().remove();\n$('select').append('<option id=\"foo\">foo</option>');\n$('#foo').focus();\n <select> <input type=\"radio\">"
},
{
"answer_id": 53013,
"author": "Jay Corbett",
"author_id": 2755,
"author_profile": "https://Stackoverflow.com/users/2755",
"pm_score": 4,
"selected": false,
"text": "$(function() {\n $('#mySelect').children().remove().end().append('<option selected value=\"One\">One option</option>') ; // clear the select box, then add one option which is selected\n $(\"input[name='myRadio']\").filter( \"[value='1']\" ).attr( \"checked\", \"checked\" ); // select radio button with value 1\n // Bind click event to each radio button.\n $(\"input[name='myRadio']\").bind(\"click\",\n function() {\n switch(this.value) {\n case \"1\":\n $('#mySelect').find('option').remove().end().append('<option selected value=\"One\">One option</option>') ;\n break ;\n case \"2\":\n $('#mySelect').find('option').remove() ;\n var items = [\"Item1\", \"Item2\", \"Item3\"] ; // Set locally for demo\n var options = '' ;\n for (var i = 0; i < items.length; i++) {\n if (i==0) {\n options += '<option selected value=\"' + items[i] + '\">' + items[i] + '</option>';\n }\n else {\n options += '<option value=\"' + items[i] + '\">' + items[i] + '</option>';\n }\n }\n $('#mySelect').html(options); // Populate select box with array\n break ;\n } // Switch end\n } // Bind function end\n ); // bind end\n}); // Event listener end <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<label>One<input name=\"myRadio\" type=\"radio\" value=\"1\" /></label>\n<label>Two<input name=\"myRadio\" type=\"radio\" value=\"2\" /></label>\n<select id=\"mySelect\" size=\"9\"></select>"
},
{
"answer_id": 947152,
"author": "Hayden Chambers",
"author_id": 61509,
"author_profile": "https://Stackoverflow.com/users/61509",
"pm_score": 5,
"selected": false,
"text": "$('#mySelect')\n .empty()\n .append('<option value=\"whatever\">text</option>')\n .find('option:first')\n .attr(\"selected\",\"selected\")\n;\n"
},
{
"answer_id": 1917744,
"author": "Mahzilla",
"author_id": 233288,
"author_profile": "https://Stackoverflow.com/users/233288",
"pm_score": 10,
"selected": false,
"text": "$('#mySelect')\n .empty()\n .append('<option selected=\"selected\" value=\"whatever\">text</option>')\n;\n"
},
{
"answer_id": 2040837,
"author": "row1",
"author_id": 79835,
"author_profile": "https://Stackoverflow.com/users/79835",
"pm_score": 6,
"selected": false,
"text": "$('#mySelect')[0].options.length = 0;\n"
},
{
"answer_id": 5481232,
"author": "jvarandas",
"author_id": 487966,
"author_profile": "https://Stackoverflow.com/users/487966",
"pm_score": 5,
"selected": false,
"text": "$(\"#control\").html(\"<option selected=\\\"selected\\\">The Option...</option>\");\n"
},
{
"answer_id": 15655982,
"author": "mauretto",
"author_id": 487545,
"author_profile": "https://Stackoverflow.com/users/487545",
"pm_score": 7,
"selected": false,
"text": "$('#mySelect').find('option:not(:first)').remove();\n"
},
{
"answer_id": 19444202,
"author": "Barun",
"author_id": 1251570,
"author_profile": "https://Stackoverflow.com/users/1251570",
"pm_score": 2,
"selected": false,
"text": "$('#mySelect').replaceWith('<Select id=\"mySelect\" size=\"9\">\n <option value=\"whatever\" selected=\"selected\" >text</option>\n </Select>');\n"
},
{
"answer_id": 19962931,
"author": "Shawn",
"author_id": 1807604,
"author_profile": "https://Stackoverflow.com/users/1807604",
"pm_score": 7,
"selected": false,
"text": "document.getElementById(\"selectID\").options.length = 0;\n"
},
{
"answer_id": 21497276,
"author": "mehrdad",
"author_id": 2053048,
"author_profile": "https://Stackoverflow.com/users/2053048",
"pm_score": 2,
"selected": false,
"text": "$('#mySelect option:selected').prop('selected', false);\n"
},
{
"answer_id": 26886200,
"author": "Shiv",
"author_id": 1197461,
"author_profile": "https://Stackoverflow.com/users/1197461",
"pm_score": 3,
"selected": false,
"text": "$('#mySelect').html('<option value=\"whatever\">text</option>');\n $('#mySelect').html('\n <option value=\"1\" selected>text1</option>\n <option value=\"2\">text2</option>\n <option value=\"3\" disabled>text3</option>\n');\n"
},
{
"answer_id": 29511141,
"author": "marioosh",
"author_id": 404395,
"author_profile": "https://Stackoverflow.com/users/404395",
"pm_score": 3,
"selected": false,
"text": ".empty() .find().remove() var ClearOptionsFast = function(id) {\n var selectObj = document.getElementById(id);\n var selectParentNode = selectObj.parentNode;\n var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy\n selectParentNode.replaceChild(newSelectObj, selectObj);\n return newSelectObj;\n}\n"
},
{
"answer_id": 30917315,
"author": "humbads",
"author_id": 553396,
"author_profile": "https://Stackoverflow.com/users/553396",
"pm_score": 3,
"selected": false,
"text": "$('#mySelect').find('option').not(':first').remove();\n $('#mySelect').find('option').not('[value=123]').remove();\n"
},
{
"answer_id": 32859761,
"author": "Jaydeep Shil",
"author_id": 3428626,
"author_profile": "https://Stackoverflow.com/users/3428626",
"pm_score": 3,
"selected": false,
"text": "$('#ddlCustomer').find('option:not(:first)').remove();\nfor (var i = 0; i < oResult.length; i++) {\n $(\"#ddlCustomer\").append(new Option(oResult[i].CustomerName, oResult[i].CustomerID + '/' + oResult[i].ID));\n}\n"
},
{
"answer_id": 39842290,
"author": "Nadeem Manzoor",
"author_id": 1308493,
"author_profile": "https://Stackoverflow.com/users/1308493",
"pm_score": 2,
"selected": false,
"text": "$('#mySelect')\n.html('<option value=\"whatever\" selected>text</option>')\n.trigger('change');\n"
},
{
"answer_id": 40199412,
"author": "Md. Russel Hussain",
"author_id": 4295653,
"author_profile": "https://Stackoverflow.com/users/4295653",
"pm_score": 1,
"selected": false,
"text": "$('#myselect').find('option').remove()\n.append($('<option></option>').val('value1').html('option1'));\n"
},
{
"answer_id": 45085734,
"author": "Jhon Intriago Thoth",
"author_id": 5598325,
"author_profile": "https://Stackoverflow.com/users/5598325",
"pm_score": 3,
"selected": false,
"text": "$('#select').empty().append($('<option>').text('---------').attr('value',''));\n"
},
{
"answer_id": 51920107,
"author": "LN Nitharsan",
"author_id": 10222327,
"author_profile": "https://Stackoverflow.com/users/10222327",
"pm_score": 1,
"selected": false,
"text": "var select = $('#mySelect');\nselect.find('option').remove().end()\n.append($('<option/>').val('').text('Select'));\nvar data = [{\"id\":1,\"title\":\"Option one\"}, {\"id\":2,\"title\":\"Option two\"}];\nfor(var i in data) {\n var d = data[i];\n var option = $('<option/>').val(d.id).text(d.title);\n select.append(option);\n}\nselect.val('');\n"
},
{
"answer_id": 52148696,
"author": "Nifemi Sola-Ojo",
"author_id": 6155890,
"author_profile": "https://Stackoverflow.com/users/6155890",
"pm_score": 2,
"selected": false,
"text": "var listToAppend = {'':'Select Vehicle','mc': 'Motor Cyle', 'tr': 'Tricycle'};\n\n$('#selectID').empty();\n\n$.each(listToAppend, function(val, text) {\n $('#selectID').append( new Option(text,val) );\n }); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>"
},
{
"answer_id": 52776203,
"author": "Devkinandan Chauhan",
"author_id": 9715631,
"author_profile": "https://Stackoverflow.com/users/9715631",
"pm_score": 3,
"selected": false,
"text": "$(\"#id option\").remove();\n$(\"#id\").append('<option value=\"testValue\" >TestText</option>');\n"
},
{
"answer_id": 54360083,
"author": "michael01angelo",
"author_id": 5775650,
"author_profile": "https://Stackoverflow.com/users/5775650",
"pm_score": 2,
"selected": false,
"text": "$('#mySelect').val(null).trigger('change');\n"
},
{
"answer_id": 57069759,
"author": "Kaushik shrimali",
"author_id": 9106811,
"author_profile": "https://Stackoverflow.com/users/9106811",
"pm_score": 4,
"selected": false,
"text": "$('.ddlsl').empty();\n\n$('.ddlsl').append(new Option('Select all', 'all'));\n $('.ddlsl').empty().append(new Option('Select all', 'all'));\n"
},
{
"answer_id": 63236844,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 0,
"selected": false,
"text": "mySelect.innerHTML = `<option selected value=\"whatever\">text</option>`\n function setOne() {\n console.log({mySelect});\n mySelect.innerHTML = `<option selected value=\"whatever\">text</option>`;\n} <button onclick=\"setOne()\" >set one</button>\n<Select id=\"mySelect\" size=\"9\"> \n <option value=\"1\">old1</option>\n <option value=\"2\">old2</option>\n <option value=\"3\">old3</option>\n</Select>"
},
{
"answer_id": 68149249,
"author": "double_u1",
"author_id": 11914028,
"author_profile": "https://Stackoverflow.com/users/11914028",
"pm_score": 0,
"selected": false,
"text": "$('#mySelect option').remove().append('<option selected value=\"whatever\">text</option>');\n"
},
{
"answer_id": 68623771,
"author": "Kazeem Quadri",
"author_id": 11084443,
"author_profile": "https://Stackoverflow.com/users/11084443",
"pm_score": 2,
"selected": false,
"text": "let select = document.getElementById(\"mySelect\");\nselect.innerHTML = \"\";\n"
},
{
"answer_id": 70946153,
"author": "Carlos",
"author_id": 10145865,
"author_profile": "https://Stackoverflow.com/users/10145865",
"pm_score": 2,
"selected": false,
"text": " let data= []\n\n let inp = $('#mySelect')\n inp.empty()\n\n data.forEach(el=> inp.append( new Option(el.Nombre, el.Id) ))\n"
},
{
"answer_id": 72759663,
"author": "rsmdh",
"author_id": 10995048,
"author_profile": "https://Stackoverflow.com/users/10995048",
"pm_score": 0,
"selected": false,
"text": "$('#mySelect')\n.html('<option value=\"whatever\">text</option>')\n.find('option:first')\n.attr(\"selected\",\"selected\");\n $('#mySelect').html('<option value=\"4\">Value 4</option>\n <option value=\"5\">Value 5</option>\n<option value=\"6\">Value 6</option>\n<option value=\"7\">Value 7</option>\n<option value=\"8\">Value 8</option>')\n.find('option:first')\n.prop(\"selected\",true);\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
] |
47,827 |
<p>At work, we have a dedicated SEO Analyst who's job is to pour over lots of data (KeyNote/Compete etc) and generate up fancy reports for the executives so they can see how we are doing against our competitors in organic search ranking. He also leads initiatives to improve the SEO rankings on our sites by optimizing things as best we can.</p>
<p>We also have a longstanding mission to decrease our page load time, which right now is pretty shoddy on some pages.</p>
<p>The SEO guy mentioned that semantic, valid HTML gets more points by crawlers than jumbled messy HTML. I've been working on a real time HTML compressor that will decrease our page sizes my a pretty good chunk. Will compressing the HTML hurt us in site rankings?</p>
|
[
{
"answer_id": 47834,
"author": "Brian Lyttle",
"author_id": 636,
"author_profile": "https://Stackoverflow.com/users/636",
"pm_score": 3,
"selected": false,
"text": "<p class=\"headerOne\">Header 1</"
},
{
"answer_id": 30213963,
"author": "East End",
"author_id": 4887099,
"author_profile": "https://Stackoverflow.com/users/4887099",
"pm_score": 0,
"selected": false,
"text": "HTML & CSS"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
47,833 |
<p>I know you can look at the row.count or tables.count, but are there other ways to tell if a dataset is empty?</p>
|
[
{
"answer_id": 47841,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 5,
"selected": true,
"text": " bool nonEmptyDataSet = dataSet != null && \n (from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any();\n public static class ExtensionMethods {\n public static bool IsEmpty(this DataSet dataSet) {\n return dataSet == null ||\n !(from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any();\n }\n }\n"
},
{
"answer_id": 47979,
"author": "dance2die",
"author_id": 4035,
"author_profile": "https://Stackoverflow.com/users/4035",
"pm_score": 2,
"selected": false,
"text": " public static bool DataSetIsEmpty(DataSet ds)\n {\n return !DataTableExists(ds) && !DataRowExists(ds.Tables[0].Rows);\n }\n\n public static bool DataTableExists(DataSet ds)\n {\n return ds.Tables != null && ds.Tables.Count > 0;\n }\n\n public static bool DataRowExists(DataRowCollection rows)\n {\n return rows != null && rows.Count > 0;\n }\n if (DataAccessUtil.DataSetIsEmpty(ds)) {\n return null;\n }\n"
},
{
"answer_id": 48547,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "public static bool IsNotEmpty ( this dataset ) \n{\n return dataSet != null && (\n from DataTable t in dataSet.Tables \n where t.Rows.AsQueryable().Any()\n select t).AsQueryable().Any();\n}\n\n//then the check would be\nDataSet ds = /* get data */;\n\nds.IsNotEmpty();\n ds.IsNotEmpty();\n\n//becomes\n\nDataSetExtensions.IsNotEmpty( ds );\n"
},
{
"answer_id": 11556606,
"author": "Milan Barać",
"author_id": 1537223,
"author_profile": "https://Stackoverflow.com/users/1537223",
"pm_score": 0,
"selected": false,
"text": "#region Extension methods\n\npublic static class ExtensionMethods\n{\n public static bool IsEmpty(this DataSet dataSet)\n {\n return dataSet == null || dataSet.Tables.Count == 0 || !dataSet.Tables.Cast<DataTable>().Any(i => i.Rows.Count > 0);\n }\n}\n\n#endregion\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445815/"
] |
47,837 |
<p>I'm struggling to find the right terminology here, but if you have jQuery object...</p>
<pre><code>$('#MyObject')
</code></pre>
<p>...is it possible to extract the base element? Meaning, the equivalent of this:</p>
<pre><code>document.getElementById('MyObject')
</code></pre>
|
[
{
"answer_id": 47844,
"author": "VolkerK",
"author_id": 4833,
"author_profile": "https://Stackoverflow.com/users/4833",
"pm_score": 7,
"selected": true,
"text": ".get(index) .get()"
},
{
"answer_id": 47848,
"author": "Aaron Wagner",
"author_id": 3909,
"author_profile": "https://Stackoverflow.com/users/3909",
"pm_score": 7,
"selected": false,
"text": "$('#MyObject').get(0);\n $('#MyObject')[0];\n"
},
{
"answer_id": 16839707,
"author": "VeeTheSecond",
"author_id": 652876,
"author_profile": "https://Stackoverflow.com/users/652876",
"pm_score": 3,
"selected": false,
"text": "$('#MyObject').get(0);\n $('#MyObject')[0];\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1923/"
] |
47,838 |
<p>I have wondered about the appropriateness of reflection in C# code. For example I have written a function which iterates through the properties of a given source object and creates a new instance of a specified type, then copies the values of properties with the same name from one to the other. I created this to copy data from one auto-generated LINQ object to another in order to get around the lack of inheritance from multiple tables in LINQ.</p>
<p>However, I can't help but think code like this is really 'cheating', i.e. rather than using using the provided language constructs to achieve a given end it allows you to circumvent them.</p>
<p>To what degree is this sort of code acceptable? What are the risks? What are legitimate uses of this approach?</p>
|
[
{
"answer_id": 48223,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 1,
"selected": false,
"text": "static class AtoBCopier\n{\n public static B Copy(A item)\n {\n return new B() { Prop1 = item.Prop1, Prop2 = item.Prop2 };\n }\n}\n"
},
{
"answer_id": 48273,
"author": "Bjorn Reppen",
"author_id": 1324220,
"author_profile": "https://Stackoverflow.com/users/1324220",
"pm_score": 2,
"selected": false,
"text": "ExternalColor c = (ExternalColor)Enum.Parse(typeof(ExternalColor), \n internalColor.ToString());\n"
},
{
"answer_id": 48282,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "foreach IEnumerable Add"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] |
47,845 |
<p>I've heard that creating a new process on a Windows box is more expensive than on Linux. Is this true? Can somebody explain the technical reasons for why it's more expensive and provide any historical reasons for the design decisions behind those reasons?</p>
|
[
{
"answer_id": 47964,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 4,
"selected": false,
"text": "fork"
},
{
"answer_id": 67293,
"author": "Chris Smith",
"author_id": 9073,
"author_profile": "https://Stackoverflow.com/users/9073",
"pm_score": 5,
"selected": false,
"text": "CSRSS"
},
{
"answer_id": 51396188,
"author": "ctrl-alt-delor",
"author_id": 537980,
"author_profile": "https://Stackoverflow.com/users/537980",
"pm_score": 2,
"selected": false,
"text": "fork CreateThread"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
47,849 |
<p>I'm trying to refer to a drive whose letter may change. I'd like to refer to it by its label (e.g., MyLabel (v:) within a Batch File. It can be referred to by V:\ . I'd like to refer to it by MyLabel.</p>
<p>(This was posted on Experts Echange for a month with no answer. Let's see how fast SO answers it )</p>
|
[
{
"answer_id": 47856,
"author": "VolkerK",
"author_id": 4833,
"author_profile": "https://Stackoverflow.com/users/4833",
"pm_score": 1,
"selected": false,
"text": "SELECT * FROM Win32_LogicalDisk WHERE VolumeName=\"MyLabel\""
},
{
"answer_id": 47860,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": true,
"text": "Option Explicit\nDim num, args, objWMIService, objItem, colItems\n\nset args = WScript.Arguments\nnum = args.Count\n\nif num <> 1 then\n WScript.Echo \"Usage: CScript DriveFromLabel.vbs <label>\"\n WScript.Quit 1\nend if\n\nSet objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\nSet colItems = objWMIService.ExecQuery(\"Select * from Win32_LogicalDisk\")\n\nFor Each objItem in colItems\n If strcomp(objItem.VolumeName, args.Item(0), 1) = 0 Then\n Wscript.Echo objItem.Name\n End If\nNext\n\nWScript.Quit 0\n cscript /nologo DriveFromLabel.vbs label\n"
},
{
"answer_id": 69542,
"author": "Philibert Perusse",
"author_id": 7984,
"author_profile": "https://Stackoverflow.com/users/7984",
"pm_score": 1,
"selected": false,
"text": "@echo off\nsetlocal\n\n:: Initial variables\nset TMPFILE=%~dp0getdrive.tmp\nset driveletters=abcdefghijklmnopqrstuvwxyz\nset MatchLabel_res=\n\nfor /L %%g in (2,1,25) do call :MatchLabel %%g %*\n\nif not \"%MatchLabel_res%\"==\"\" echo %MatchLabel_res%\n\ngoto :END\n\n\n:: Function to match a label with a drive letter. \n::\n:: The first parameter is an integer from 1..26 that needs to be \n:: converted in a letter. It is easier looping on a number\n:: than looping on letters.\n::\n:: The second parameter is the volume name passed-on to the script\n:MatchLabel\n\n:: result already found, just do nothing \n:: (necessary because there is no break for for loops)\nif not \"%MatchLabel_res%\"==\"\" goto :eof\n\n:: get the proper drive letter\ncall set dl=%%driveletters:~%1,1%%\n\n:: strip-off the \" in the volume name to be able to add them again further\nset volname=%2\nset volname=%volname:\"=%\n\n:: get the volume information on that disk\nvol %dl%: > \"%TMPFILE%\" 2>&1\n\n:: Drive/Volume does not exist, just quit\nif not \"%ERRORLEVEL%\"==\"0\" goto :eof\n\nset found=0\nfor /F \"usebackq tokens=3 delims=:\" %%g in (`find /C /I \"%volname%\" \"%TMPFILE%\"`) do set found=%%g\n\n:: trick to stip any whitespaces\nset /A found=%found% + 0\n\n\nif not \"%found%\"==\"0\" set MatchLabel_res=%dl%:\ngoto :eof\n\n\n\n\n\n\n\n\n:END\n\nif exist \"%TMPFILE%\" del \"%TMPFILE%\"\nendlocal\n"
},
{
"answer_id": 9066694,
"author": "dbenham",
"author_id": 1012053,
"author_profile": "https://Stackoverflow.com/users/1012053",
"pm_score": 3,
"selected": false,
"text": "for /f %%D in ('wmic volume get DriveLetter^, Label ^| find \"My Label\"') do set myDrive=%%D\n %myDrive% dir %myDrive%\\someFolder\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4906/"
] |
47,862 |
<p>I'm loading a <strong><em>SQL Server 2000</em></strong> database into my new <strong><em>SQL Server 2005</em></strong> <strong><em>instance</em></strong>. <strong><em>As expected, the full-text catalogs don't come with it.</strong> <strong>How can I rebuild them?</em></strong></p>
<p>Right-clicking my full text catalogs and hitting "<strong><em>rebuild indexes</em></strong>" just hangs for hours and hours without doing anything, so it doesn't appear to be that simple...</p>
|
[
{
"answer_id": 47900,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": true,
"text": "--Change to accent insensitive\nUSE AdventureWorks;\nGO\nALTER FULLTEXT CATALOG ftCatalog \nREBUILD WITH ACCENT_SENSITIVITY=OFF;\nGO\n-- Check Accentsensitivity\nSELECT FULLTEXTCATALOGPROPERTY('ftCatalog', 'accentsensitivity');\nGO\n--Returned 0, which means the catalog is not accent sensitive.\n"
},
{
"answer_id": 47959,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 0,
"selected": false,
"text": "USE mydb\nGO\n\nALTER DATABASE mydb SET COMPATIBILITY_LEVEL = 90\nGO\n SELECT name \n FROM sys.master_files mf \n WHERE type = 4 \n AND EXISTS( SELECT * \n FROM sys.databases db \n WHERE db.database_id = mf.database_id \n AND name = 'mydb')\n ALTER DATABASE mydb \nMODIFY FILE( NAME = {full text catalog name}, FILENAME=\"N:\\ew\\path\\to\\wherever\")\n SELECT name FROM sys.sysfulltextcatalogs\n ALTER FULLTEXT CATALOG {full text catalog name} REBUILD\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2590/"
] |
47,864 |
<p>ValidateEvents is a great ASP.net function, but the Yellow Screen of Death is not so nice. I found a way how to handle the HttpRequestValidationException gracefully <a href="http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html" rel="nofollow noreferrer">here</a>, but that does not work with ASP.net AJAX properly.</p>
<p>Basically, I got an UpdatePanel with a TextBox and a Button, and when the user types in HTML into the Textbox, a JavaScript Popup with a Error message saying not to modify the Response pops up.</p>
<p>So I wonder what is the best way to handle HttpRequestValidationException gracefully? For "normal" requests I would like to just display an error message, but when it's an AJAX Request i'd like to throw the request away and return something to indicate an error, so that my frontend page can react on it?</p>
|
[
{
"answer_id": 50671,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 3,
"selected": true,
"text": "<script type=\"text/javascript\" language=\"javascript\">\nvar prm = Sys.WebForms.PageRequestManager.getInstance();\nprm.add_endRequest(EndRequestHandler);\n\nfunction EndRequestHandler(sender, args) {\n if (args.get_error() != undefined)\n {\n var errorMessage;\n if (args.get_response().get_statusCode() == '200')\n {\n errorMessage = args.get_error().message;\n }\n else\n {\n // Error occurred somewhere other than the server page.\n errorMessage = 'An unspecified error occurred. ';\n }\n args.set_errorHandled(true);\n $get('<%= this.newsletterLabel.ClientID %>').innerHTML = errorMessage;\n }\n}\n</script>\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
47,882 |
<p>What is a magic number?</p>
<p>Why should it be avoided?</p>
<p>Are there cases where it's appropriate?</p>
|
[
{
"answer_id": 47890,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 7,
"selected": false,
"text": "SELECT TOP 50 * FROM orders for (i = 0; i < 50; i++) Session.Timeout = 50 if a < 50 then bla const int NumOrdersToDisplay = 50 if a < NumOrdersToDisplay SmtpClient.DefaultPort = 25 TCPPacketSize = whatever"
},
{
"answer_id": 47902,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 10,
"selected": true,
"text": "public class Foo {\n public void setPassword(String password) {\n // don't do this\n if (password.length() > 7) {\n throw new InvalidArgumentException(\"password\");\n }\n }\n}\n public class Foo {\n public static final int MAX_PASSWORD_SIZE = 7;\n\n public void setPassword(String password) {\n if (password.length() > MAX_PASSWORD_SIZE) {\n throw new InvalidArgumentException(\"password\");\n }\n }\n}\n Integer Character Math"
},
{
"answer_id": 1554616,
"author": "Ascalonian",
"author_id": 65230,
"author_profile": "https://Stackoverflow.com/users/65230",
"pm_score": 1,
"selected": false,
"text": "public class SomeClass {\n private int maxRows = 15000;\n ...\n // Inside another method\n for (int i = 0; i < maxRows; i++) {\n // Do something\n }\n\n public void setMaxRows(int maxRows) {\n this.maxRows = maxRows;\n }\n\n public int getMaxRows() {\n return this.maxRows;\n }\n private static final int DEFAULT_MAX_ROWS = 15000;\nprivate int maxRows = DEFAULT_MAX_ROWS;\n"
},
{
"answer_id": 18184180,
"author": "Oskytar",
"author_id": 400120,
"author_profile": "https://Stackoverflow.com/users/400120",
"pm_score": -1,
"selected": false,
"text": "int procGetIdCompanyByName(string companyName);\n int procGetIdCompanyByName(string companyName, bool existsCompany);\n bool procCompanyExists(string companyName);\nint procGetIdCompanyByName(string companyName);\n"
},
{
"answer_id": 30743302,
"author": "jguiraud",
"author_id": 3570922,
"author_profile": "https://Stackoverflow.com/users/3570922",
"pm_score": 0,
"selected": false,
"text": "public class Foo {\n /** \n * Max age in year to get child rate for airline tickets\n * \n * The value of the constant is {@value}\n */\n public static final int MAX_AGE_FOR_CHILD_RATE = 2;\n\n public void computeRate() {\n if (person.getAge() < MAX_AGE_FOR_CHILD_RATE) {\n applyChildRate();\n }\n }\n}\n"
},
{
"answer_id": 33325478,
"author": "Liberty Lover",
"author_id": 1096587,
"author_profile": "https://Stackoverflow.com/users/1096587",
"pm_score": 5,
"selected": false,
"text": "padding := 2 padding = 2 padding = default_padding default_padding = 2 default_padding default_padding default_padding life_force -10 .. 10 attack_elves seek_magic_healing_potion"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
] |
47,883 |
<p>I'm trying to install 'quadrupel', a library that relies on ffmpeg on Solaris x86.</p>
<p>I managed to build ffmpeg and its libraries live in /opt/gnu/lib and the includes are in /opt/gnu/include but when I try to build quadrupel, it can't find the ffmpeg headers.</p>
<p>What flags/configuration is required to include those two directories in the proper search paths for libraries and includes? I'm not much of a Makefile hacker.</p>
|
[
{
"answer_id": 47913,
"author": "stimms",
"author_id": 361,
"author_profile": "https://Stackoverflow.com/users/361",
"pm_score": 2,
"selected": true,
"text": "crle -l -c /var/ld/ld.config -l /usr/lib:/usr/local/lib:/opt/gnu/lib\n"
},
{
"answer_id": 47916,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 3,
"selected": false,
"text": "CFLAGS += -I/opt/gnu/include\nLDFLAGS += -L/opt/gnu/lib -R/opt/gnu/lib\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/555/"
] |
47,884 |
<p>I simply wondered whether people thought it was worth learning to use the MSBuild syntax in order to customise the build process for a .net project, or whether it is really not worth it given the ease with which one can build a project using visual studio. </p>
<p>I am thinking in terms of nightly builds, etc., but then couldn't I use a scheduled event which uses the command-line build option built into VS? Are there superior tools out there?</p>
|
[
{
"answer_id": 108691,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 1,
"selected": false,
"text": "msbuild /?"
},
{
"answer_id": 14589196,
"author": "yantaq",
"author_id": 554060,
"author_profile": "https://Stackoverflow.com/users/554060",
"pm_score": 1,
"selected": false,
"text": "<PropertyGroup>\n <PropertyKey>value</PropertyKey>\n</PropertyGroup>\n<ItemGroup>\n <ItemListKey>List values<ItemListKey>\n</ItemGroup>\n<Task Source=\"\" Target=\"\" />\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] |
47,886 |
<p>We have an SEO team at my office, and one of their dictums is that having lots of <script> blocks inline with the HTML is apocalypticly bad. As a developer that makes no sense to me at all. Surely the Google search engineers, who are the smartest people on the planet, know how to skip over such blocks? <br />
My gut instinct is that minimizing script blocks is a superstition that comes from the early ages of search engine optimizations, and that in today's world it means nothing. Does anyone have any insight on this?</p>
<hr>
<p>per our SEO guru, script blocks (especially those that are in-line, or occur before actual content) are very, very bad, and make the google bots give up before processing your actual content. Seems like bull to me, but I'd like to see what others say.</p>
|
[
{
"answer_id": 14243630,
"author": "Michael Thamm",
"author_id": 1964121,
"author_profile": "https://Stackoverflow.com/users/1964121",
"pm_score": 0,
"selected": false,
"text": "<p>"
},
{
"answer_id": 21980464,
"author": "Swift Computers",
"author_id": 3167778,
"author_profile": "https://Stackoverflow.com/users/3167778",
"pm_score": 0,
"selected": false,
"text": "<script> <script>"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757/"
] |
47,919 |
<p>I'm used to doing all my coding in one C file. However, I'm working on a project large enough that it becomes impractical to do so. I've been #including them together but I've run into cases where I'm #including some files multiple times, etc. I've heard of .h files, but I'm not sure what their function is (or why having 2 files is better than 1).</p>
<p>What strategies should I use for organizing my code? Is it possible to separate "public" functions from "private" ones for a particular file?</p>
<p><a href="https://stackoverflow.com/questions/47878/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data">This</a> question precipitated my inquiry. The tea.h file makes no reference to the tea.c file. Does the compiler "know" that every .h file has a corresponding .c file?</p>
|
[
{
"answer_id": 47928,
"author": "Andrew",
"author_id": 826,
"author_profile": "https://Stackoverflow.com/users/826",
"pm_score": 3,
"selected": false,
"text": "#ifndef ACCOUNTS_H\n#define ACCOUNTS_H\n....\n#endif\n"
},
{
"answer_id": 47955,
"author": "smh",
"author_id": 1077,
"author_profile": "https://Stackoverflow.com/users/1077",
"pm_score": 2,
"selected": false,
"text": "make compiler --options tea.c\n #include"
},
{
"answer_id": 47961,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
] |
47,941 |
<p>I'm trying to upload an application to the iPhone App Store, but I get this error message from iTunes Connect:</p>
<blockquote>
<p>The binary you uploaded was invalid. The signature was invalid, or it was not signed with an Apple submission certificate.</p>
</blockquote>
<hr>
<p>Note: The details of original question have been removed, as this page has turned into a repository for all information about possible causes of that particular error message.</p>
<p>For general information on submitting iPhone applications to the App Store, see <a href="https://stackoverflow.com/questions/796482/steps-to-upload-an-iphone-application-to-the-appstore">Steps to upload an iPhone application to the AppStore</a>.</p>
|
[
{
"answer_id": 956502,
"author": "Eddie",
"author_id": 118089,
"author_profile": "https://Stackoverflow.com/users/118089",
"pm_score": 4,
"selected": false,
"text": "C384C90C0F9939FA00E76E41 /* Distribution */ = {\nisa = XCBuildConfiguration;\nbuildSettings = {\nARCHS = \"$(ARCHS_STANDARD_32_BIT)\";\nCODE_SIGN_ENTITLEMENTS = \"\";\n\"CODE_SIGN_IDENTITY[sdk=iphoneos*]” = “iPhone Distribution: Edward McCreary”;\nGCC_C_LANGUAGE_STANDARD = c99;\nGCC_WARN_ABOUT_RETURN_TYPE = YES;\nGCC_WARN_UNUSED_VARIABLE = YES;\nPREBINDING = NO;\n“PROVISIONING_PROFILE[sdk=iphoneos*]” = “F00D3778-32B2-4550-9FCE-1A4090344400″;\nSDKROOT = iphoneos2.2.1;\n};\nname = Distribution;\n};\nC384C90D0F9939FA00E76E41 /* Distribution */ = {\nisa = XCBuildConfiguration;\nbuildSettings = {\nALWAYS_SEARCH_USER_PATHS = NO;\nCODE_SIGN_IDENTITY = “iPhone Developer: Edward McCreary”;\n“CODE_SIGN_IDENTITY[sdk=iphoneos*]” = “iPhone Developer: Edward McCreary”;\nCOPY_PHASE_STRIP = YES;\nGCC_PRECOMPILE_PREFIX_HEADER = YES;\nGCC_PREFIX_HEADER = GenPass_Prefix.pch;\nINFOPLIST_FILE = Info.plist;\nPRODUCT_NAME = GenPass;\nPROVISIONING_PROFILE = “DB12BCA7-FE72-42CA-9C2B-612F76619788″;\n“PROVISIONING_PROFILE[sdk=iphoneos*]” = “DB12BCA7-FE72-42CA-9C2B-612F76619788″;\n};\nname = Distribution;\n};\n C384C90C0F9939FA00E76E41 /* Distribution */ = {\nisa = XCBuildConfiguration;\nbuildSettings = {\nARCHS = \"$(ARCHS_STANDARD_32_BIT)\";\nCODE_SIGN_ENTITLEMENTS = \"\";\n\"CODE_SIGN_IDENTITY[sdk=iphoneos*]” = “iPhone Distribution: Edward McCreary”;\nGCC_C_LANGUAGE_STANDARD = c99;\nGCC_WARN_ABOUT_RETURN_TYPE = YES;\nGCC_WARN_UNUSED_VARIABLE = YES;\nPREBINDING = NO;\n“PROVISIONING_PROFILE[sdk=iphoneos*]” = “F00D3778-32B2-4550-9FCE-1A4090344400″;\nSDKROOT = iphoneos2.2.1;\n};\nname = Distribution;\n};\nC384C90D0F9939FA00E76E41 /* Distribution */ = {\nisa = XCBuildConfiguration;\nbuildSettings = {\nALWAYS_SEARCH_USER_PATHS = NO;\nCODE_SIGN_IDENTITY = “iPhone Distribution: Edward McCreary”;\n“CODE_SIGN_IDENTITY[sdk=iphoneos*]” = “iPhone Distribution: Edward McCreary”;\nCOPY_PHASE_STRIP = YES;\nGCC_PRECOMPILE_PREFIX_HEADER = YES;\nGCC_PREFIX_HEADER = GenPass_Prefix.pch;\nINFOPLIST_FILE = Info.plist;\nPRODUCT_NAME = GenPass;\nPROVISIONING_PROFILE = “F00D3778-32B2-4550-9FCE-1A4090344400″;\n“PROVISIONING_PROFILE[sdk=iphoneos*]” = “F00D3778-32B2-4550-9FCE-1A4090344400″;\n};\nname = Distribution;\n};\n"
},
{
"answer_id": 1541447,
"author": "Jorge Bernal",
"author_id": 127451,
"author_profile": "https://Stackoverflow.com/users/127451",
"pm_score": 3,
"selected": false,
"text": "zip -r myapp.zip myapp.app"
},
{
"answer_id": 5227265,
"author": "Seva Alekseyev",
"author_id": 219159,
"author_profile": "https://Stackoverflow.com/users/219159",
"pm_score": 3,
"selected": false,
"text": "info.plist: com.mydomain.foo\ndist.plist: com.mydomain.bar\nProfile: com.mydomain.*\n info.plist: com.mydomain.foo\ndist.plist: com.mydomain.bar\nProfile: com.mydomain.foo\n"
},
{
"answer_id": 8935553,
"author": "Dave Anderson",
"author_id": 371,
"author_profile": "https://Stackoverflow.com/users/371",
"pm_score": 2,
"selected": false,
"text": "._.DS_Store dot_clean /the/path/to/xcode/project\n"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175/"
] |
47,960 |
<p>What are the best code snippets for C#? (using visual studio) VB has a lot that are pre-defined, but there are only a handful for C#. Do you have any really useful ones for C#?</p>
<p>Anyone want to post a good custom one you created yourself?</p>
<p><a href="http://en.wikipedia.org/wiki/Ferris_Bueller" rel="noreferrer">Anyone?... Bueller?</a></p>
|
[
{
"answer_id": 1053225,
"author": "Dario",
"author_id": 105459,
"author_profile": "https://Stackoverflow.com/users/105459",
"pm_score": 3,
"selected": false,
"text": "cw"
},
{
"answer_id": 1053276,
"author": "Mark Seemann",
"author_id": 126014,
"author_profile": "https://Stackoverflow.com/users/126014",
"pm_score": 2,
"selected": false,
"text": "argnull"
}
] |
2008/09/06
|
[
"https://Stackoverflow.com/questions/47960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1874/"
] |
47,972 |
<p>I'm researching and experimenting more with Groovy and I'm trying to wrap my mind around the pros and cons of implementing things in Groovy that I can't/don't do in Java. Dynamic programming is still just a concept to me since I've been deeply steeped static and strongly typed languages. </p>
<p>Groovy gives me the ability to <a href="http://en.wikipedia.org/wiki/Duck_typing" rel="noreferrer">duck-type</a>, but I can't really see the value. How is duck-typing more productive than static typing? What kind of things can I do in my code practice to help me grasp the benefits of it?</p>
<p>I ask this question with Groovy in mind but I understand it isn't necessarily a Groovy question so I welcome answers from every code camp.</p>
|
[
{
"answer_id": 250119,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 4,
"selected": false,
"text": "class SimpleResults {\n def results\n def total\n def categories\n}\n results Map<String, List<ComplexType>> total List<ComplexType> categories Map"
},
{
"answer_id": 275962,
"author": "Miguel Ping",
"author_id": 22992,
"author_profile": "https://Stackoverflow.com/users/22992",
"pm_score": 3,
"selected": false,
"text": "class SimpleResults {\n def mapOfListResults\n def total\n def categories\n}\n Long calculateRating(A someObj, B, otherObj) {\n\n //some fake algorithm here:\n if(someObj.doStuff('foo') > otherObj.doStuff('bar')) return someObj.calcRating());\n else return otherObj.calcRating();\n\n}\n public interface MyService {\n public int doStuff(String input);\n}\n public long calculateRating(MyService A, MyServiceB);\n doStuff()"
},
{
"answer_id": 275998,
"author": "Charlie Martin",
"author_id": 35092,
"author_profile": "https://Stackoverflow.com/users/35092",
"pm_score": 4,
"selected": true,
"text": "foo* bar* bar* foo* typedef"
},
{
"answer_id": 2272415,
"author": "slim",
"author_id": 7512,
"author_profile": "https://Stackoverflow.com/users/7512",
"pm_score": 2,
"selected": false,
"text": "class BookFinder {\n def searchEngine\n\n def findBookByTitle(String title) {\n return searchEngine.find( [ \"Title\" : title ] ) \n }\n}\n void bookFinderTest() {\n // with Expando we can 'fake' any object at runtime.\n // alternatively you could write a MockSearchEngine class.\n def mockSearchEngine = new Expando()\n mockSearchEngine.find = {\n return new Book(\"Heart of Darkness\",\"Joseph Conrad\")\n }\n\n def bf = new BookFinder()\n bf.searchEngine = mockSearchEngine\n def book = bf.findBookByTitle(\"Heart of Darkness\")\n assert(book.author == \"Joseph Conrad\"\n}\n"
},
{
"answer_id": 20028746,
"author": "sukrit007",
"author_id": 3001206,
"author_profile": "https://Stackoverflow.com/users/3001206",
"pm_score": 3,
"selected": false,
"text": "//Static typing \nMap<String,List<Class1<Class2>>> someMap = [:] as HashMap<String,List<Class1<Class2>>>\n //Dynamic typing\ndef someMap = [:] \n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/47972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3030/"
] |
47,975 |
<p>More out of interest than anything else, but can you compile a DirectX app under linux?</p>
<p>Obviously there's no official SDK, but I was thinking it might be possible with wine.</p>
<p>Presumably wine has an implementation of the DirectX interface in order to run games? Is it possible to link against that? (edit: This is called winelib)</p>
<p>Failing that, maybe a mingw cross compiler with the app running under wine.</p>
<p>Half answered my own question here, but wondered if anyone had heard of anything like this being done?</p>
|
[
{
"answer_id": 70695,
"author": "Nick",
"author_id": 4949,
"author_profile": "https://Stackoverflow.com/users/4949",
"pm_score": 4,
"selected": true,
"text": "wineg++ -ld3d9 -ld3dx9 triangle.cpp\n"
},
{
"answer_id": 15586569,
"author": "Guest1337",
"author_id": 2202177,
"author_profile": "https://Stackoverflow.com/users/2202177",
"pm_score": 1,
"selected": false,
"text": "winemaker --lower-uppercase -icomdlg32 -ishell32 -ishlwapi -iuser32 -igdi32 -iadvapi32 -ld3d9 .\nmake\nwine yourexecutable.exe.so\n main.c:95:5: error: ‘struct IDirect3D9’ has no member named ‘CreateDevice’\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/47975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4949/"
] |
47,980 |
<p>I'm really beginning to understand what people mean when they say that C++'s error messages are pretty terrible in regards to templates. I've seen horrendously long errors for things as simple as a function not matching its prototype.</p>
<p>Are there any tricks to deciphering these errors?</p>
<p>EDIT: I'm using both gcc and MSVC. They both seem to be pretty terrible.</p>
|
[
{
"answer_id": 48263,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 3,
"selected": false,
"text": "s/std::basic_string<char,std::char_traits<char>,std::allocator<char>>/string/g \n std::basic_string<char,std::char_traits<char>,std::allocator<char>>\n string\n"
},
{
"answer_id": 61526908,
"author": "tom",
"author_id": 10184846,
"author_profile": "https://Stackoverflow.com/users/10184846",
"pm_score": 2,
"selected": false,
"text": "MyClass<std::vector<double>, std::array<double, 3>> MyClass<...> /path/to/program | tee log | /path/to/parser -f /path/to/inputFile.json /path/to/program /path/to/parser -f /path/to/inputFile.json {\n \"ignoreCompleteLineIfItContainsSubstring\" : [\n \"should be suppressed\"\n ],\n \"ignoreContentBetweenDelimiter\" : [\n {\n \"startingDelimiter\" : \"<\",\n \"endingDelimiter\" : \">\",\n \"replaceContentBy\" : \"...\"\n }\n ],\n \"styleLineContainingKeywords\" : [\n {\n \"keyword\" : \"error\",\n \"removeDuplicates\" : true,\n \"applyStyle\" : \"onKeyword\",\n \"color\" : \"red\",\n \"style\" : \"bold\"\n }\n ]\n}\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/47980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
47,981 |
<p>How do I set, clear, and toggle a bit?</p>
|
[
{
"answer_id": 47990,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 13,
"selected": true,
"text": "| number |= 1UL << n;\n n number n 1 n-1 n 1ULL number unsigned long 1UL << n 1UL << n long & number &= ~(1UL << n);\n n number ~ ^ number ^= 1UL << n;\n n number bit = (number >> n) & 1U;\n n number bit n 1 0 number ^= (-x ^ number) & (1UL << n);\n n x 1 x 0 x x = !!x -1 number ^= (-(unsigned long)x ^ number) & (1UL << n);\n unsigned long newbit = !!x; // Also booleanize to force 0 or 1\nnumber ^= (-newbit ^ number) & (1UL << n);\n number = (number & ~(1UL << n)) | (x << n);\n (number & ~(1UL << n)) n (x << n) n x"
},
{
"answer_id": 50691,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 7,
"selected": false,
"text": "enum enum ThingFlags = {\n ThingMask = 0x0000,\n ThingFlag0 = 1 << 0,\n ThingFlag1 = 1 << 1,\n ThingError = 1 << 8,\n}\n thingstate |= ThingFlag1;\nthingstate &= ~ThingFlag0;\nif (thing & ThingError) {...}\n"
},
{
"answer_id": 55584,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 8,
"selected": false,
"text": "struct bits {\n unsigned int a:1;\n unsigned int b:1;\n unsigned int c:1;\n};\n\nstruct bits mybits;\n mybits.b = 1;\nmybits.c = 0;\n mybits.a = !mybits.a;\nmybits.b = ~mybits.b;\nmybits.c ^= 1; /* all work */\n if (mybits.c) //if mybits.c is non zero the next line below will execute\n"
},
{
"answer_id": 79163,
"author": "yogeesh",
"author_id": 9030,
"author_profile": "https://Stackoverflow.com/users/9030",
"pm_score": 6,
"selected": false,
"text": "/*\n** Bit set, clear, and test operations\n**\n** public domain snippet by Bob Stout\n*/\n\ntypedef enum {ERROR = -1, FALSE, TRUE} LOGICAL;\n\n#define BOOL(x) (!(!(x)))\n\n#define BitSet(arg,posn) ((arg) | (1L << (posn)))\n#define BitClr(arg,posn) ((arg) & ~(1L << (posn)))\n#define BitTst(arg,posn) BOOL((arg) & (1L << (posn)))\n#define BitFlp(arg,posn) ((arg) ^ (1L << (posn)))\n 0000 0000 0000 0000 0000 0000 0000 0001 binary.\n 0000 0000 0000 0000 0000 0001 0000 0000 binary.\n #define BOOL(x) (!(!(x)))\n\n#define BitSet(arg,posn) ((arg) | (1L << (posn)))\n#define BitClr(arg,posn) ((arg) & ~(1L << (posn)))\n#define BitTst(arg,posn) BOOL((arg) & (1L << (posn)))\n#define BitFlp(arg,posn) ((arg) ^ (1L << (posn)))\n\nint bitmanip(int word)\n{\n word = BitSet(word, 2);\n word = BitSet(word, 7);\n word = BitClr(word, 3);\n word = BitFlp(word, 9);\n return word;\n}\n Module: C:\\BINK\\tst.c\nGroup: 'DGROUP' CONST,CONST2,_DATA,_BSS\n\nSegment: _TEXT BYTE 00000008 bytes \n 0000 0c 84 bitmanip_ or al,84H ; set bits 2 and 7\n 0002 80 f4 02 xor ah,02H ; flip bit 9 of EAX (bit 1 of AH)\n 0005 24 f7 and al,0f7H\n 0007 c3 ret \n\nNo disassembly errors\n"
},
{
"answer_id": 83645,
"author": "Tim Ring",
"author_id": 3685,
"author_profile": "https://Stackoverflow.com/users/3685",
"pm_score": 4,
"selected": false,
"text": "const unsigned char TQuickByteMask[8] =\n{\n 0x01, 0x02, 0x04, 0x08,\n 0x10, 0x20, 0x40, 0x80,\n};\n\n\n/** Set bit in any sized bit mask.\n *\n * @return none\n *\n * @param bit - Bit number.\n * @param bitmap - Pointer to bitmap.\n */\nvoid TSetBit( short bit, unsigned char *bitmap)\n{\n short n, x;\n\n x = bit / 8; // Index to byte.\n n = bit % 8; // Specific bit in byte.\n\n bitmap[x] |= TQuickByteMask[n]; // Set bit.\n}\n\n\n/** Reset bit in any sized mask.\n *\n * @return None\n *\n * @param bit - Bit number.\n * @param bitmap - Pointer to bitmap.\n */\nvoid TResetBit( short bit, unsigned char *bitmap)\n{\n short n, x;\n\n x = bit / 8; // Index to byte.\n n = bit % 8; // Specific bit in byte.\n\n bitmap[x] &= (~TQuickByteMask[n]); // Reset bit.\n}\n\n\n/** Toggle bit in any sized bit mask.\n *\n * @return none\n *\n * @param bit - Bit number.\n * @param bitmap - Pointer to bitmap.\n */\nvoid TToggleBit( short bit, unsigned char *bitmap)\n{\n short n, x;\n\n x = bit / 8; // Index to byte.\n n = bit % 8; // Specific bit in byte.\n\n bitmap[x] ^= TQuickByteMask[n]; // Toggle bit.\n}\n\n\n/** Checks specified bit.\n *\n * @return 1 if bit set else 0.\n *\n * @param bit - Bit number.\n * @param bitmap - Pointer to bitmap.\n */\nshort TIsBitSet( short bit, const unsigned char *bitmap)\n{\n short n, x;\n\n x = bit / 8; // Index to byte.\n n = bit % 8; // Specific bit in byte.\n\n // Test bit (logigal AND).\n if (bitmap[x] & TQuickByteMask[n])\n return 1;\n\n return 0;\n}\n\n\n/** Checks specified bit.\n *\n * @return 1 if bit reset else 0.\n *\n * @param bit - Bit number.\n * @param bitmap - Pointer to bitmap.\n */\nshort TIsBitReset( short bit, const unsigned char *bitmap)\n{\n return TIsBitSet(bit, bitmap) ^ 1;\n}\n\n\n/** Count number of bits set in a bitmap.\n *\n * @return Number of bits set.\n *\n * @param bitmap - Pointer to bitmap.\n * @param size - Bitmap size (in bits).\n *\n * @note Not very efficient in terms of execution speed. If you are doing\n * some computationally intense stuff you may need a more complex\n * implementation which would be faster (especially for big bitmaps).\n * See (http://graphics.stanford.edu/~seander/bithacks.html).\n */\nint TCountBits( const unsigned char *bitmap, int size)\n{\n int i, count = 0;\n\n for (i=0; i<size; i++)\n if (TIsBitSet(i, bitmap))\n count++;\n\n return count;\n}\n TSetBit( n, &my_int);\n"
},
{
"answer_id": 88934,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 9,
"selected": false,
"text": "std::bitset<N> boost::dynamic_bitset #include <bitset>\n#include <iostream>\n\nint main()\n{\n std::bitset<5> x;\n\n x[1] = 1;\n x[2] = 0;\n // Note x[0-4] valid\n\n std::cout << x << std::endl;\n}\n [Alpha:] > ./a.out\n00010\n"
},
{
"answer_id": 263738,
"author": "Steve Karg",
"author_id": 9016,
"author_profile": "https://Stackoverflow.com/users/9016",
"pm_score": 8,
"selected": false,
"text": "/* a=target variable, b=bit number to act upon 0-n */\n#define BIT_SET(a,b) ((a) |= (1ULL<<(b)))\n#define BIT_CLEAR(a,b) ((a) &= ~(1ULL<<(b)))\n#define BIT_FLIP(a,b) ((a) ^= (1ULL<<(b)))\n#define BIT_CHECK(a,b) (!!((a) & (1ULL<<(b)))) // '!!' to make sure this returns 0 or 1\n\n#define BITMASK_SET(x, mask) ((x) |= (mask))\n#define BITMASK_CLEAR(x, mask) ((x) &= (~(mask)))\n#define BITMASK_FLIP(x, mask) ((x) ^= (mask))\n#define BITMASK_CHECK_ALL(x, mask) (!(~(x) & (mask)))\n#define BITMASK_CHECK_ANY(x, mask) ((x) & (mask))\n"
},
{
"answer_id": 268356,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 5,
"selected": false,
"text": "struct HwRegister {\n unsigned int errorFlag:1; // one-bit flag field\n unsigned int Mode:3; // three-bit mode field\n unsigned int StatusCode:4; // four-bit status code\n};\n\nstruct HwRegister CR3342_AReg;\n"
},
{
"answer_id": 410101,
"author": "John Zwinck",
"author_id": 4323,
"author_profile": "https://Stackoverflow.com/users/4323",
"pm_score": 5,
"selected": false,
"text": "#define bit_test(x, y) ( ( ((const char*)&(x))[(y)>>3] & 0x80 >> ((y)&0x07)) >> (7-((y)&0x07) ) )\n int main(void)\n{\n unsigned char arr[8] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };\n\n for (int ix = 0; ix < 64; ++ix)\n printf(\"bit %d is %d\\n\", ix, bit_test(arr, ix));\n\n return 0;\n}\n"
},
{
"answer_id": 740953,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "int ToggleNthBit ( unsigned char n, int num )\n{\n if(num & (1 << n))\n num &= ~(1 << n);\n else\n num |= (1 << n);\n\n return num;\n}\n"
},
{
"answer_id": 991546,
"author": "bill",
"author_id": 121958,
"author_profile": "https://Stackoverflow.com/users/121958",
"pm_score": 5,
"selected": false,
"text": "#define BITS 8\n#define BIT_SET( p, n) (p[(n)/BITS] |= (0x80>>((n)%BITS)))\n#define BIT_CLEAR(p, n) (p[(n)/BITS] &= ~(0x80>>((n)%BITS)))\n#define BIT_ISSET(p, n) (p[(n)/BITS] & (0x80>>((n)%BITS)))\n"
},
{
"answer_id": 3234773,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 379897,
"author_profile": "https://Stackoverflow.com/users/379897",
"pm_score": 5,
"selected": false,
"text": "unsigned char size_t #define BITOP(a,b,op) \\\n ((a)[(size_t)(b)/(8*sizeof *(a))] op ((size_t)1<<((size_t)(b)%(8*sizeof *(a)))))\n BITOP(array, bit, |=);\n BITOP(array, bit, &=~);\n BITOP(array, bit, ^=);\n if (BITOP(array, bit, &)) ...\n"
},
{
"answer_id": 9488379,
"author": "Gokul Naathan",
"author_id": 1190788,
"author_profile": "https://Stackoverflow.com/users/1190788",
"pm_score": 4,
"selected": false,
"text": "{\n unsigned int data = 0x000000F0;\n int bitpos = 4;\n int bitvalue = 1;\n unsigned int bit = data;\n bit = (bit>>bitpos)&0x00000001;\n int invbitvalue = 0x00000001&(~bitvalue);\n printf(\"%x\\n\",bit);\n\n if (bitvalue == 0)\n {\n if (bit == 0)\n printf(\"%x\\n\", data);\n else\n {\n data = (data^(invbitvalue<<bitpos));\n printf(\"%x\\n\", data);\n }\n }\n else\n {\n if (bit == 1)\n printf(\"elseif %x\\n\", data);\n else\n {\n data = (data|(bitvalue<<bitpos));\n printf(\"else %x\\n\", data);\n }\n }\n}\n"
},
{
"answer_id": 10899060,
"author": "kapilddit",
"author_id": 555911,
"author_profile": "https://Stackoverflow.com/users/555911",
"pm_score": 5,
"selected": false,
"text": "value is 0x55;\nbitnum : 3rd.\n & 0101 0101\n&\n0000 1000\n___________\n0000 0000 (mean 0: False). It will work fine if the third bit is 1 (then the answer will be True)\n 0101 0101\n^\n0000 1000\n___________\n0101 1101 (Flip the third bit without affecting other bits)\n | 0101 0101\n|\n0000 1000\n___________\n0101 1101 (set the third bit without affecting other bits)\n"
},
{
"answer_id": 14087800,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "sizeof() bool IsGph[256], IsNotGph[256];\n\n// Initialize boolean array to detect printable characters\nfor(i=0; i<sizeof(IsGph); i++) {\n IsGph[i] = isgraph((unsigned char)i);\n}\n IsGph[i] =1 IsGph[i] =0 // Initialize boolean array to detect UN-printable characters, \n// then call function to toggle required bits true, while initializing a 2nd\n// boolean array as the complement of the 1st.\nfor(i=0; i<sizeof(IsGph); i++) {\n if(IsGph[i]) {\n IsNotGph[i] = 0;\n } else {\n IsNotGph[i] = 1;\n }\n}\n"
},
{
"answer_id": 23532806,
"author": "kendotwill",
"author_id": 1713375,
"author_profile": "https://Stackoverflow.com/users/1713375",
"pm_score": 4,
"selected": false,
"text": "bitset #include <iostream>\n#include <bitset>\n#include <string>\n\nusing namespace std;\nint main() {\n bitset<8> byte(std::string(\"10010011\");\n\n // Set Bit\n byte.set(3); // 10010111\n\n // Clear Bit\n byte.reset(2); // 10010101\n\n // Toggle Bit\n byte.flip(7); // 00010101\n\n cout << byte << endl;\n\n return 0;\n}\n"
},
{
"answer_id": 23888594,
"author": "Vincet",
"author_id": 3679614,
"author_profile": "https://Stackoverflow.com/users/3679614",
"pm_score": -1,
"selected": false,
"text": "char bitfield;\n\n// Start at 0th position\n\nvoid chang_n_bit(int n, int value)\n{\n bitfield = (bitfield | (1 << n)) & (~( (1 << n) ^ (value << n) ));\n}\n void chang_n_bit(int n, int value)\n{\n bitfield = (bitfield | (1 << n)) & ((value << n) | ((~0) ^ (1 << n)));\n}\n void chang_n_bit(int n, int value)\n{\n if(value)\n bitfield |= 1 << n;\n else\n bitfield &= ~0 ^ (1 << n);\n}\n\nchar get_n_bit(int n)\n{\n return (bitfield & (1 << n)) ? 1 : 0;\n}\n"
},
{
"answer_id": 28376414,
"author": "sam msft",
"author_id": 640259,
"author_profile": "https://Stackoverflow.com/users/640259",
"pm_score": 3,
"selected": false,
"text": "SET_FLAG(Status, Flag) ((Status) |= (Flag))\nCLEAR_FLAG(Status, Flag) ((Status) &= ~(Flag))\nINVALID_FLAGS(ulFlags, ulAllowed) ((ulFlags) & ~(ulAllowed))\nTEST_FLAGS(t,ulMask, ulBit) (((t)&(ulMask)) == (ulBit))\nIS_FLAG_SET(t,ulMask) TEST_FLAGS(t,ulMask,ulMask)\nIS_FLAG_CLEAR(t,ulMask) TEST_FLAGS(t,ulMask,0)\n"
},
{
"answer_id": 37488546,
"author": "Jeegar Patel",
"author_id": 775964,
"author_profile": "https://Stackoverflow.com/users/775964",
"pm_score": 4,
"selected": false,
"text": "set_bit Atomically set a bit in memory\nclear_bit Clears a bit in memory\nchange_bit Toggle a bit in memory\ntest_and_set_bit Set a bit and return its old value\ntest_and_clear_bit Clear a bit and return its old value\ntest_and_change_bit Change a bit and return its old value\ntest_bit Determine whether a bit is set\n"
},
{
"answer_id": 46454677,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 3,
"selected": false,
"text": "1 number 1 x 1 << x x ~ // assume 32 bit int/unsigned\nunsigned long long number = foo();\n\nunsigned x = 40; \nnumber |= (1 << x); // UB\nnumber ^= (1 << x); // UB\nnumber &= ~(1 << x); // UB\n\nx = 10;\nnumber &= ~(1 << x); // Wrong mask, not wide enough\n 1ull (uintmax_t)1 number |= (1ull << x);\nnumber |= ((uintmax_t)1 << x);\n number |= (type_of_number)1 << x;\n 1 number number |= (number*0 + 1) << x;\n"
},
{
"answer_id": 48725080,
"author": "Joakim L. Christiansen",
"author_id": 4216153,
"author_profile": "https://Stackoverflow.com/users/4216153",
"pm_score": 2,
"selected": false,
"text": "namespace bit {\n template <typename T1, typename T2>\n constexpr inline T1 bitmask(T2 bit) \n {return (T1)1 << bit;}\n template <typename T1, typename T3, typename ...T2>\n constexpr inline T1 bitmask(T3 bit, T2 ...bits) \n {return ((T1)1 << bit) | bitmask<T1>(bits...);}\n\n /** Set these bits (others retain their state) */\n template <typename T1, typename ...T2>\n constexpr inline void set (T1 &variable, T2 ...bits) \n {variable |= bitmask<T1>(bits...);}\n /** Set only these bits (others will be cleared) */\n template <typename T1, typename ...T2>\n constexpr inline void setOnly (T1 &variable, T2 ...bits) \n {variable = bitmask<T1>(bits...);}\n /** Clear these bits (others retain their state) */\n template <typename T1, typename ...T2>\n constexpr inline void clear (T1 &variable, T2 ...bits) \n {variable &= ~bitmask<T1>(bits...);}\n /** Flip these bits (others retain their state) */\n template <typename T1, typename ...T2>\n constexpr inline void flip (T1 &variable, T2 ...bits) \n {variable ^= bitmask<T1>(bits...);}\n /** Check if any of these bits are set */\n template <typename T1, typename ...T2>\n constexpr inline bool isAnySet(const T1 &variable, T2 ...bits) \n {return variable & bitmask<T1>(bits...);}\n /** Check if all these bits are set */\n template <typename T1, typename ...T2>\n constexpr inline bool isSet (const T1 &variable, T2 ...bits) \n {return ((variable & bitmask<T1>(bits...)) == bitmask<T1>(bits...));}\n /** Check if all these bits are not set */\n template <typename T1, typename ...T2>\n constexpr inline bool isNotSet (const T1 &variable, T2 ...bits) \n {return ((variable & bitmask<T1>(bits...)) != bitmask<T1>(bits...));}\n}\n #include <iostream>\n#include <bitset> // for console output of binary values\n\n// and include the code above of course\n\nusing namespace std;\n\nint main() {\n uint8_t v = 0b1111'1100;\n bit::set(v, 0);\n cout << bitset<8>(v) << endl;\n\n bit::clear(v, 0,1);\n cout << bitset<8>(v) << endl;\n\n bit::flip(v, 0,1);\n cout << bitset<8>(v) << endl;\n\n bit::clear(v, 0,1,2,3,4,5,6,7);\n cout << bitset<8>(v) << endl;\n\n bit::flip(v, 0,7);\n cout << bitset<8>(v) << endl;\n}\n"
},
{
"answer_id": 48906086,
"author": "Sazzad Hissain Khan",
"author_id": 1084174,
"author_profile": "https://Stackoverflow.com/users/1084174",
"pm_score": 3,
"selected": false,
"text": "int set_nth_bit(int num, int n){ \n return (num | 1 << n);\n}\n\nint clear_nth_bit(int num, int n){ \n return (num & ~( 1 << n));\n}\n\nint toggle_nth_bit(int num, int n){ \n return num ^ (1 << n);\n}\n\nint check_nth_bit(int num, int n){ \n return num & (1 << n);\n}\n"
},
{
"answer_id": 56521123,
"author": "Pankaj Prakash",
"author_id": 2401088,
"author_profile": "https://Stackoverflow.com/users/2401088",
"pm_score": 5,
"selected": false,
"text": "num = 55 n = 4 nth num n & bit = (num >> n) & 1;\n 0011 0111 (55 in decimal)\n >> 4 (right shift 4 times)\n-----------------\n 0000 0011\n & 0000 0001 (1 in decimal)\n-----------------\n => 0000 0001 (final result)\n n | num num |= (1 << n); // Equivalent to; num = (1 << n) | num;\n 0000 0001 (1 in decimal)\n << 4 (left shift 4 times)\n-----------------\n 0001 0000\n | 0011 0111 (55 in decimal)\n-----------------\n => 0001 0000 (final result)\n n 1 << n ~ (1 << n) & num num & (~ (1 << n)) num &= (~(1 << n)); // Equivalent to; num = num & (~(1 << n));\n 0000 0001 (1 in decimal)\n << 4 (left shift 4 times)\n-----------------\n ~ 0001 0000\n-----------------\n 1110 1111\n & 0011 0111 (55 in decimal)\n-----------------\n => 0010 0111 (final result)\n ^ num ^= (1 << n); // Equivalent to; num = num ^ (1 << n);\n 0 ^ 1 => 1 1 ^ 1 => 0 0000 0001 (1 in decimal)\n << 4 (left shift 4 times)\n-----------------\n 0001 0000\n ^ 0011 0111 (55 in decimal)\n-----------------\n => 0010 0111 (final result)\n"
},
{
"answer_id": 61374583,
"author": "Balaji Boggaram Ramanarayan",
"author_id": 2101290,
"author_profile": "https://Stackoverflow.com/users/2101290",
"pm_score": 2,
"selected": false,
"text": "public class BitwiseOperations {\n\n public static void main(String args[]) {\n\n setABit(0, 4); // set the 4th bit, 0000 -> 1000 [8]\n clearABit(16, 5); // clear the 5th bit, 10000 -> 00000 [0]\n toggleABit(8, 4); // toggle the 4th bit, 1000 -> 0000 [0]\n checkABit(8,4); // check the 4th bit 1000 -> true \n }\n\n public static void setABit(int input, int n) {\n input = input | ( 1 << n-1);\n System.out.println(input);\n }\n\n\n public static void clearABit(int input, int n) {\n input = input & ~(1 << n-1);\n System.out.println(input);\n }\n\n public static void toggleABit(int input, int n) {\n input = input ^ (1 << n-1);\n System.out.println(input);\n }\n\n public static void checkABit(int input, int n) {\n boolean isSet = ((input >> n-1) & 1) == 1; \n System.out.println(isSet);\n }\n}\n\n\nOutput :\n8\n0\n0\ntrue\n"
},
{
"answer_id": 66075462,
"author": "Dominic van der Zypen",
"author_id": 8082048,
"author_profile": "https://Stackoverflow.com/users/8082048",
"pm_score": 0,
"selected": false,
"text": "number = (((number | (1 << n)) ^ (1 << n))) | (x << n);\n ((number | (1 << n) | (...) ^ (1 << n) (...) | x << n) x golang"
},
{
"answer_id": 66667330,
"author": "lckid2004",
"author_id": 15412355,
"author_profile": "https://Stackoverflow.com/users/15412355",
"pm_score": 2,
"selected": false,
"text": "#define INT_BIT (unsigned int) (sizeof(unsigned int) * 8U) //number of bits in unsigned int\n\nint main(void)\n{\n \n unsigned int k = 5; //k is the bit position; here it is the 5th bit from the LSb (0th bit)\n \n unsigned int regA = 0x00007C7C; //we perform bitwise operations on regA\n \n regA |= (1U << k); //Set kth bit\n \n regA &= ~(1U << k); //Clear kth bit\n \n regA ^= (1U << k); //Toggle kth bit\n \n regA = (regA << k) | regA >> (INT_BIT - k); //Rotate left by k bits\n \n regA = (regA >> k) | regA << (INT_BIT - k); //Rotate right by k bits\n\n return 0; \n}\n\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/47981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] |
48,006 |
<p>Right up front: I do <em>not</em> want to start a religious war.</p>
<p>I've used <em>vi</em> for as long as I can remember, and the few times I've tried to pick up <em>Emacs</em> I've been so lost that I've quickly given up. Lots of people find Emacs very powerful, however. Its programmability is somewhat legendary. I'm primarily doing Solaris+Java development, and I'd like to ask a simple question: will my productivity increase if I invest time in getting my head around Emacs? Is the functionality that it offers over <em>Vim</em> going to be paid back in productivity increases in a reasonable timeframe?</p>
<p><em>Repeat: I don't want a "my editor is better than yours" answer. I just want a yes or no answer as to whether it's worth investing the time or not. Will my productivity really increase?</em></p>
|
[
{
"answer_id": 71397,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 5,
"selected": false,
"text": ".vimrc"
},
{
"answer_id": 977462,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 1,
"selected": false,
"text": "flymake-mode"
},
{
"answer_id": 9232189,
"author": "quodlibetor",
"author_id": 25616,
"author_profile": "https://Stackoverflow.com/users/25616",
"pm_score": 1,
"selected": false,
"text": "git diff Alt-TAB Ctrl+a ESC ^ i a i o O"
},
{
"answer_id": 11218537,
"author": "MBR",
"author_id": 600529,
"author_profile": "https://Stackoverflow.com/users/600529",
"pm_score": 0,
"selected": false,
"text": "C-x ( start remembering keystrokes\nC-x ) stop remembering keystrokes\nC-x e replay the remembered keystrokes\n <a> target :g/^<a/s/>/ target=\"_blank\">/\n <a> 1. C-x (\n2. M-C-s <a\\>\n3. C-b\n4. C-s >\n5. C-b\n6. target=\"_blank\"\n7. C-x )\n8. C-u 10000 C-x e\n 1. start remembering keystrokes\n2. regex search for <a. Note that the \"\\>\" after the \"a\" is not HTML. It's emacs regex notation for end-of-word.\n3. back up one character - as a side-effect this gets you out of search mode\n4. search for the next \">\"\n5. back up over the \">\"\n6. enter space as an attribute-delimiter followed by the target=\"_blank\" attribute\n7. stop remembering keystrokes\n8. replay the remembered keystrokes 10,000 times or until the search fails\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/826/"
] |
48,009 |
<p>What are the performance, security, or "other" implications of using the following form to declare a new class instance in PHP</p>
<pre><code><?php
$class_name = 'SomeClassName';
$object = new $class_name;
?>
</code></pre>
<p>This is a contrived example, but I've seen this form used in Factories (OOP) to avoid having a big if/switch statement.</p>
<p>Problems that come immediately to mind are </p>
<ol>
<li><s>You lose the ability to pass arguments into a constructor</s> (LIES. Thanks Jeremy)</li>
<li>Smells like eval(), with all the security concerns it brings to the table (but not necessarily the performance concerns?)</li>
</ol>
<p>What other implications are there, or what search engine terms other than "Rank PHP Hackery" can someone use to research this?</p>
|
[
{
"answer_id": 48035,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": false,
"text": "<?php\n\nclass Test {\n function __construct($x) {\n echo $x;\n }\n}\n\n$class = 'Test';\n$object = new $class('test'); // echoes \"test\"\n\n?>\n"
},
{
"answer_id": 48736,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 4,
"selected": true,
"text": "$classname = 'SomeClassName';\nfor ($x = 0; $x < 100000; $x++){\n $object = new $classname;\n}\n"
},
{
"answer_id": 49586,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 2,
"selected": false,
"text": "Class.forClass('classname')"
},
{
"answer_id": 62327,
"author": "Seldaek",
"author_id": 6512,
"author_profile": "https://Stackoverflow.com/users/6512",
"pm_score": 3,
"selected": false,
"text": "<?php\n\n$class = \"Test\";\n$args = array('a', 'b');\n$ref = new ReflectionClass($class);\n$instance = $ref->newInstanceArgs($args);\n\n?>\n"
},
{
"answer_id": 62360,
"author": "Leonid Shevtsov",
"author_id": 6678,
"author_profile": "https://Stackoverflow.com/users/6678",
"pm_score": 0,
"selected": false,
"text": "<?php\n$className = 'ClassName';\n\n$className::someStaticMethod(); //doesn't work\n?>\n"
},
{
"answer_id": 63437,
"author": "Edoardo Vacchi",
"author_id": 7849,
"author_profile": "https://Stackoverflow.com/users/7849",
"pm_score": 0,
"selected": false,
"text": "call_user_func(array($className, 'someStaticMethod') call_user_func_array()"
},
{
"answer_id": 461564,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "class Test {\n function testExt() {\n print 'hello from testExt :P';\n }\n function test2Ext()\n {\n print 'hi from test2Ext :)';\n }\n}\n\n\n$class = 'Test';\n$method_1 = \"testExt\";\n$method_2 = \"test2Ext\";\n$object = new $class(); // echoes \"test\"\n$object->{$method_2}(); // will print 'hi from test2Ext :)'\n$object->{$method_1}(); // will print 'hello from testExt :P';\n"
},
{
"answer_id": 14203323,
"author": "FilmJ",
"author_id": 133221,
"author_profile": "https://Stackoverflow.com/users/133221",
"pm_score": 1,
"selected": false,
"text": "func_get_args() public function myFactoryMethod() \n{\n $class = 'SomeClass'; // e.g. you'd get this from a switch statement\n $obj = new $class( func_get_args() );\n return $obj;\n}\n new SomeClass( array( 'foo', 'bar' ) ) public function myFactoryMethod() \n{\n $class = 'SomeClass'; // e.g. you'd get this from a switch statement\n $ref = new ReflectionClass( $class );\n $obj = $ref->newInstanceArgs( func_get_args() );\n return $obj;\n}\n call_user_func_array"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4668/"
] |
48,017 |
<p>Can someone explain the mechanics of a jump table and why is would be needed in embedded systems?</p>
|
[
{
"answer_id": 48033,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 5,
"selected": false,
"text": "MyJump(int c)\n{\n switch(state)\n {\n case 0:\n goto func0label;\n case 1:\n goto func1label;\n case 2:\n goto func2label;\n }\n}\n"
},
{
"answer_id": 29079346,
"author": "Mawg says reinstate Monica",
"author_id": 192910,
"author_profile": "https://Stackoverflow.com/users/192910",
"pm_score": 2,
"selected": false,
"text": " switch (state)\n case A:\n switch (event):\n case e1: ....\n case e2: ....\n case B:\n switch (event):\n case e3: ....\n case e1: ....\n handleEvent[state][event]"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] |
48,053 |
<p>I read somewhere once that the modulus operator is inefficient on small embedded devices like 8 bit micro-controllers that do not have integer division instruction. Perhaps someone can confirm this but I thought the difference is 5-10 time slower than with an integer division operation.</p>
<p>Is there another way to do this other than keeping a counter variable and manually overflowing to 0 at the mod point?<p></p>
<pre><code>const int FIZZ = 6;
for(int x = 0; x < MAXCOUNT; x++)
{
if(!(x % FIZZ)) print("Fizz\n"); // slow on some systems
}
</code></pre>
<p>vs:</p>
<p>The way I am currently doing it:</p>
<pre><code>const int FIZZ = 6;
int fizzcount = 1;
for(int x = 1; x < MAXCOUNT; x++)
{
if(fizzcount >= FIZZ)
{
print("Fizz\n");
fizzcount = 0;
}
}
</code></pre>
|
[
{
"answer_id": 48058,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 1,
"selected": false,
"text": "& | >>"
},
{
"answer_id": 48075,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 0,
"selected": false,
"text": "FIZZ MAXCOUNT FIZZ"
},
{
"answer_id": 48078,
"author": "Rob Rolnick",
"author_id": 4798,
"author_profile": "https://Stackoverflow.com/users/4798",
"pm_score": 1,
"selected": false,
"text": "if((!(x & 1)) && (x % 3))\n{\n print(\"Fizz\\n\");\n}\n"
},
{
"answer_id": 48079,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 5,
"selected": false,
"text": "x % 8 == x & 7\nx % 256 == x & 255\n"
},
{
"answer_id": 48090,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 2,
"selected": false,
"text": "int main() {\n int i;\n for(i = 0; i<=1024; i++) {\n if (!(i & 0xFF)) printf(\"& i = %d\\n\", i);\n if (!(i % 0x100)) printf(\"mod i = %d\\n\", i);\n }\n}\n"
},
{
"answer_id": 48103,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 7,
"selected": true,
"text": " DOW = DOW_HI*256 + DOW_LO\n\n DOW%7 = (DOW_HI*256 + DOW_LO) % 7\n = ((DOW_HI*256)%7 + (DOW_LO % 7)) %7\n = ((DOW_HI%7 * 256%7) + (DOW_LO%7)) %7\n = ((DOW_HI%7 * 4) + (DOW_LO%7)) %7\n X = a*64 + b*8 + c\n X%7 = ((a%7)*(64%7) + (b%7)*(8%7) + c%7) % 7\n = (a%7 + b%7 + c%7) % 7\n = (a + b + c) % 7\n 64%7 = 8%7 = 1 c = X & 7\n b = (X>>3) & 7\n a = (X>>6) & 7 // (actually, a is only 2-bits).\n a+b+c 7+7+3 = 17 unsigned char Mod7Byte(unsigned char X)\n{\n X = (X&7) + ((X>>3)&7) + (X>>6);\n X = (X&7) + (X>>3);\n\n return X==7 ? 0 : X;\n}\n Mod7Byte:\n movwf temp1 ;\n andlw 7 ;W=c\n movwf temp2 ;temp2=c\n rlncf temp1,F ;\n swapf temp1,W ;W= a*8+b\n andlw 0x1F\n addwf temp2,W ;W= a*8+b+c\n movwf temp2 ;temp2 is now a 6-bit number\n andlw 0x38 ;get the high 3 bits == a'\n xorwf temp2,F ;temp2 now has the 3 low bits == b'\n rlncf WREG,F ;shift the high bits right 4\n swapf WREG,F ;\n addwf temp2,W ;W = a' + b'\n\n ; at this point, W is between 0 and 10\n\n\n addlw -7\n bc Mod7Byte_L2\nMod7Byte_L1:\n addlw 7\nMod7Byte_L2:\n return\n clrf x\n clrf count\n\nTestLoop:\n movf x,W\n RCALL Mod7Byte\n cpfseq count\n bra fail\n\n incf count,W\n xorlw 7\n skpz\n xorlw 7\n movwf count\n\n incfsz x,F\n bra TestLoop\npassed:\n uint16 Mod7Word(uint16 X)\n{\n return Mod7Byte(Mod7Byte(X & 0xff) + Mod7Byte(X>>8)*4);\n}\n"
},
{
"answer_id": 29655945,
"author": "Zeeshan",
"author_id": 559017,
"author_profile": "https://Stackoverflow.com/users/559017",
"pm_score": 2,
"selected": false,
"text": "x%y == (x-(x/y)*y)\n"
},
{
"answer_id": 54969894,
"author": "TigerTV.ru",
"author_id": 9210255,
"author_profile": "https://Stackoverflow.com/users/9210255",
"pm_score": 0,
"selected": false,
"text": "def mod6(number):\n while number > 7:\n number = (number >> 3 << 1) + (number & 0x7)\n if number > 5:\n number -= 6\n return number\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] |
48,070 |
<p>We are trying to lighten our page load as much as possible. Since ViewState can sometimes swell up to 100k of the page, I'd love to completely eliminate it.</p>
<p>I'd love to hear some techniques other people have used to move ViewState to a custom provider.</p>
<p>That said, a few caveats:</p>
<ul>
<li>We serve on average 2 Million unique visitors per hour.</li>
<li>Because of this, Database reads have been a serious issue in performance, so I don't want to store ViewState in the database.</li>
<li>We also are behind a load balancer, so any solution has to work with the user bouncing from machine to machine per postback.</li>
</ul>
<p>Ideas?</p>
|
[
{
"answer_id": 48133,
"author": "Mike",
"author_id": 1573,
"author_profile": "https://Stackoverflow.com/users/1573",
"pm_score": 3,
"selected": false,
"text": " protected override PageStatePersister PageStatePersister {\n get { return new SessionPageStatePersister(this); }\n }\n"
},
{
"answer_id": 82346,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 2,
"selected": false,
"text": "string vsid;\n\nprotected override object LoadPageStateFromPersistenceMedium()\n{\n Pair vs = base.LoadPageStateFromPersistenceMedium() as Pair;\n vsid = vs.First as string;\n object result = Session[vsid];\n Session.Remove(vsid);\n return result;\n}\n\nprotected override void SavePageStateToPersistenceMedium(object state)\n{\n if (vsid == null)\n {\n vsid = Guid.NewGuid().ToString();\n }\n Session[vsid] = state;\n base.SavePageStateToPersistenceMedium(new Pair(vsid, null));\n}\n"
},
{
"answer_id": 5446743,
"author": "saille",
"author_id": 30246,
"author_profile": "https://Stackoverflow.com/users/30246",
"pm_score": 1,
"selected": false,
"text": "public partial class _Default : System.Web.UI.Page {\n\n protected override object LoadPageStateFromPersistenceMedium() {\n string viewState = Request.Form[\"__VSTATE\"];\n byte[] bytes = Convert.FromBase64String(viewState);\n bytes = Compressor.Decompress(bytes);\n LosFormatter formatter = new LosFormatter();\n return formatter.Deserialize(Convert.ToBase64String(bytes));\n }\n\n protected override void SavePageStateToPersistenceMedium(object viewState) {\n LosFormatter formatter = new LosFormatter();\n StringWriter writer = new StringWriter();\n formatter.Serialize(writer, viewState);\n string viewStateString = writer.ToString();\n byte[] bytes = Convert.FromBase64String(viewStateString);\n bytes = Compressor.Compress(bytes);\n ClientScript.RegisterHiddenField(\"__VSTATE\", Convert.ToBase64String(bytes));\n }\n\n // ...\n\n}\n\nusing System.IO;\nusing System.IO.Compression;\n\npublic static class Compressor {\n\n public static byte[] Compress(byte[] data) {\n MemoryStream output = new MemoryStream();\n GZipStream gzip = new GZipStream(output, \n CompressionMode.Compress, true);\n gzip.Write(data, 0, data.Length);\n gzip.Close();\n return output.ToArray();\n }\n\n public static byte[] Decompress(byte[] data) {\n MemoryStream input = new MemoryStream();\n input.Write(data, 0, data.Length);\n input.Position = 0;\n GZipStream gzip = new GZipStream(input, \n CompressionMode.Decompress, true);\n MemoryStream output = new MemoryStream();\n byte[] buff = new byte[64];\n int read = -1;\n read = gzip.Read(buff, 0, buff.Length);\n while(read > 0) {\n output.Write(buff, 0, read);\n read = gzip.Read(buff, 0, buff.Length);\n }\n gzip.Close();\n return output.ToArray();\n }\n}\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
48,087 |
<p>I need a quick algorithm to select 5 random elements from a generic list. For example, I'd like to get 5 random elements from a <code>List<string></code>.</p>
|
[
{
"answer_id": 48114,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 5,
"selected": false,
"text": "# Returns a container s with k distinct random numbers from {0, 1, ..., n-1}\ndef ChooseRandomSubset(n, k):\n for i in range(k):\n r = UniformRandom(0, n-i) # May be 0, must be < n-i\n q = s.FirstIndexSuchThat( s[q] - q > r ) # This is the search.\n s.InsertInOrder(q ? r + q : r + len(s)) # Inserts right before q.\n return s\n"
},
{
"answer_id": 48138,
"author": "IanStallings",
"author_id": 4933,
"author_profile": "https://Stackoverflow.com/users/4933",
"pm_score": 2,
"selected": false,
"text": "public List<String> getRandomItemsFromList(int returnCount, List<String> list)\n{\n List<String> returnList = new List<String>();\n Dictionary<int, int> randoms = new Dictionary<int, int>();\n\n while (randoms.Count != returnCount)\n {\n //generate new random between one and total list count\n int randomInt = new Random().Next(list.Count);\n\n // store this in dictionary to ensure uniqueness\n try\n {\n randoms.Add(randomInt, randomInt);\n }\n catch (ArgumentException aex)\n {\n Console.Write(aex.Message);\n } //we can assume this element exists in the dictonary already \n\n //check for randoms length and then iterate through the original list \n //adding items we select via random to the return list\n if (randoms.Count == returnCount)\n {\n foreach (int key in randoms.Keys)\n returnList.Add(list[randoms[key]]);\n\n break; //break out of _while_ loop\n }\n }\n\n return returnList;\n}\n"
},
{
"answer_id": 48141,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 3,
"selected": false,
"text": "int k = 10; // items to select\nvar items = new List<int>(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });\nvar selected = new List<int>();\ndouble needed = k;\ndouble available = items.Count;\nvar rand = new Random();\nwhile (selected.Count < k) {\n if( rand.NextDouble() < needed / available ) {\n selected.Add(items[(int)available-1])\n needed--;\n }\n available--;\n}\n"
},
{
"answer_id": 48188,
"author": "hitec",
"author_id": 120,
"author_profile": "https://Stackoverflow.com/users/120",
"pm_score": 0,
"selected": false,
"text": " private class QuestionSorter : IComparable<QuestionSorter>\n {\n public double SortingKey\n {\n get;\n set;\n }\n\n public Question QuestionObject\n {\n get;\n set;\n }\n\n public QuestionSorter(Question q)\n {\n this.SortingKey = RandomNumberGenerator.RandomDouble;\n this.QuestionObject = q;\n }\n\n public int CompareTo(QuestionSorter other)\n {\n if (this.SortingKey < other.SortingKey)\n {\n return -1;\n }\n else if (this.SortingKey > other.SortingKey)\n {\n return 1;\n }\n else\n {\n return 0;\n }\n }\n }\n List<QuestionSorter> unsortedQuestions = new List<QuestionSorter>();\n\n // add the questions here\n\n unsortedQuestions.Sort(unsortedQuestions as IComparer<QuestionSorter>);\n\n // select the first k elements\n"
},
{
"answer_id": 250976,
"author": "Cameron A. Ellis",
"author_id": 1748529,
"author_profile": "https://Stackoverflow.com/users/1748529",
"pm_score": 0,
"selected": false,
"text": " Dim ar As New ArrayList\n Dim numToGet As Integer = 5\n 'hard code just to test\n ar.Add(\"12\")\n ar.Add(\"11\")\n ar.Add(\"10\")\n ar.Add(\"15\")\n ar.Add(\"16\")\n ar.Add(\"17\")\n\n Dim randomListOfProductIds As New ArrayList\n\n Dim toAdd As String = \"\"\n For i = 0 To numToGet - 1\n toAdd = ar(CInt((ar.Count - 1) * Rnd()))\n\n randomListOfProductIds.Add(toAdd)\n 'remove from id list\n ar.Remove(toAdd)\n\n Next\n'sorry i'm lazy and have to write vb at work :( and didn't feel like converting to c#\n"
},
{
"answer_id": 451540,
"author": "Frank Schwieterman",
"author_id": 32203,
"author_profile": "https://Stackoverflow.com/users/32203",
"pm_score": 4,
"selected": false,
"text": " static IEnumerable<SomeType> PickSomeInRandomOrder<SomeType>(\n IEnumerable<SomeType> someTypes,\n int maxCount)\n {\n Random random = new Random(DateTime.Now.Millisecond);\n\n Dictionary<double, SomeType> randomSortTable = new Dictionary<double,SomeType>();\n\n foreach(SomeType someType in someTypes)\n randomSortTable[random.NextDouble()] = someType;\n\n return randomSortTable.OrderBy(KVP => KVP.Key).Take(maxCount).Select(KVP => KVP.Value);\n }\n"
},
{
"answer_id": 2312911,
"author": "Ers",
"author_id": 205743,
"author_profile": "https://Stackoverflow.com/users/205743",
"pm_score": 8,
"selected": false,
"text": "YourList.OrderBy(x => rnd.Next()).Take(5)\n"
},
{
"answer_id": 3288539,
"author": "Tine M.",
"author_id": 315524,
"author_profile": "https://Stackoverflow.com/users/315524",
"pm_score": 2,
"selected": false,
"text": "List<Object> temp = OriginalList.ToList();\nList<Object> selectedItems = new List<Object>();\nRandom rnd = new Random();\nObject o;\nint i = 0;\nwhile (i < NumberOfSelectedItems)\n{\n o = temp[rnd.Next(temp.Count)];\n selectedItems.Add(o);\n temp.Remove(o);\n i++;\n }\n"
},
{
"answer_id": 3530489,
"author": "Kristofer",
"author_id": 348439,
"author_profile": "https://Stackoverflow.com/users/348439",
"pm_score": 0,
"selected": false,
"text": "public <T> List<T> take(List<T> source, int k) {\n int n = source.size();\n if (k > n) {\n throw new IllegalStateException(\n \"Can not take \" + k +\n \" elements from a list with \" + n +\n \" elements\");\n }\n List<T> result = new ArrayList<T>(k);\n Map<Integer,Integer> used = new HashMap<Integer,Integer>();\n int metric = 0;\n for (int i = 0; i < k; i++) {\n int off = random.nextInt(n - i);\n while (true) {\n metric++;\n Integer redirect = used.put(off, n - i - 1);\n if (redirect == null) {\n break;\n }\n off = redirect;\n }\n result.add(source.get(off));\n }\n assert metric <= 2*k;\n return result;\n}\n"
},
{
"answer_id": 8876593,
"author": "dhakim",
"author_id": 1151342,
"author_profile": "https://Stackoverflow.com/users/1151342",
"pm_score": 4,
"selected": false,
"text": " for i from n − 1 downto 1 do\n j ← random integer with 0 ≤ j ≤ i\n exchange a[j] and a[i]\n for (i = n − 1; i >= n-k; i--)\n {\n j = random integer with 0 ≤ j ≤ i\n exchange a[j] and a[i]\n }\n"
},
{
"answer_id": 9842947,
"author": "Marwan Roushdy",
"author_id": 964658,
"author_profile": "https://Stackoverflow.com/users/964658",
"pm_score": 3,
"selected": false,
"text": " .AsEnumerable().OrderBy(n => Guid.NewGuid()).Take(5);\n"
},
{
"answer_id": 12654300,
"author": "vag",
"author_id": 1708444,
"author_profile": "https://Stackoverflow.com/users/1708444",
"pm_score": 6,
"selected": false,
"text": "public static List<T> GetRandomElements<T>(this IEnumerable<T> list, int elementsCount)\n{\n return list.OrderBy(arg => Guid.NewGuid()).Take(elementsCount).ToList();\n}\n"
},
{
"answer_id": 13537208,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 3,
"selected": false,
"text": "public static List<T> GetTrueRandom<T>(this IList<T> source, int count, \n bool throwArgumentOutOfRangeException = true)\n{\n if (throwArgumentOutOfRangeException && count > source.Count)\n throw new ArgumentOutOfRangeException();\n\n var randoms = new List<T>(count);\n randoms.AddRandomly(source, count);\n return randoms;\n}\n public static List<T> GetDistinctRandom<T>(this IList<T> source, int count)\n{\n if (count > source.Count)\n throw new ArgumentOutOfRangeException();\n\n if (count == source.Count)\n return new List<T>(source);\n\n var sourceDict = source.ToIndexedDictionary();\n\n if (count > source.Count / 2)\n {\n while (sourceDict.Count > count)\n sourceDict.Remove(source.GetRandomIndex());\n\n return sourceDict.Select(kvp => kvp.Value).ToList();\n }\n\n var randomDict = new Dictionary<int, T>(count);\n while (randomDict.Count < count)\n {\n int key = source.GetRandomIndex();\n if (!randomDict.ContainsKey(key))\n randomDict.Add(key, sourceDict[key]);\n }\n\n return randomDict.Select(kvp => kvp.Value).ToList();\n}\n count source.Count 1, 2, 3, 4, 5 1, 3, 4, 2, 5 1, 2, 3, 4, 5 1, 2, 3, 4 1, 3, 5, 2 2, 3, 5, 4 source.Count - count count source sourceDict HashSet public static List<T> GetTrueDistinctRandom<T>(this IList<T> source, int count, \n bool throwArgumentOutOfRangeException = true)\n{\n if (count > source.Count)\n throw new ArgumentOutOfRangeException();\n\n var set = new HashSet<T>(source);\n\n if (throwArgumentOutOfRangeException && count > set.Count)\n throw new ArgumentOutOfRangeException();\n\n List<T> list = hash.ToList();\n\n if (count >= set.Count)\n return list;\n\n if (count > set.Count / 2)\n {\n while (set.Count > count)\n set.Remove(list.GetRandom());\n\n return set.ToList();\n }\n\n var randoms = new HashSet<T>();\n randoms.AddRandomly(list, count);\n return randoms.ToList();\n}\n randoms HashSet Random.Next static Random rnd = new Random();\npublic static int GetRandomIndex<T>(this ICollection<T> source)\n{\n return rnd.Next(source.Count);\n}\n\npublic static T GetRandom<T>(this IList<T> source)\n{\n return source[source.GetRandomIndex()];\n}\n\nstatic void AddRandomly<T>(this ICollection<T> toCol, IList<T> fromList, int count)\n{\n while (toCol.Count < count)\n toCol.Add(fromList.GetRandom());\n}\n\npublic static Dictionary<int, T> ToIndexedDictionary<T>(this IEnumerable<T> lst)\n{\n return lst.ToIndexedDictionary(t => t);\n}\n\npublic static Dictionary<int, T> ToIndexedDictionary<S, T>(this IEnumerable<S> lst, \n Func<S, T> valueSelector)\n{\n int index = -1;\n return lst.ToDictionary(t => ++index, valueSelector);\n}\n System.Random"
},
{
"answer_id": 16663098,
"author": "apdnu",
"author_id": 1103939,
"author_profile": "https://Stackoverflow.com/users/1103939",
"pm_score": 0,
"selected": false,
"text": "import numpy\n\nN = 20\nK = 5\n\nidx = np.arange(N)\nnumpy.random.shuffle(idx)\n\nprint idx[:K]\n"
},
{
"answer_id": 17244160,
"author": "drzaus",
"author_id": 1037948,
"author_profile": "https://Stackoverflow.com/users/1037948",
"pm_score": 3,
"selected": false,
"text": "subset public static class EnumerableExtensions {\n\n public static Random randomizer = new Random(); // you'd ideally be able to replace this with whatever makes you comfortable\n\n public static IEnumerable<T> GetRandom<T>(this IEnumerable<T> list, int numItems) {\n return (list as T[] ?? list.ToArray()).GetRandom(numItems);\n\n // because ReSharper whined about duplicate enumeration...\n /*\n items.Add(list.ElementAt(randomizer.Next(list.Count()))) ) numItems--;\n */\n }\n\n // just because the parentheses were getting confusing\n public static IEnumerable<T> GetRandom<T>(this T[] list, int numItems) {\n var items = new HashSet<T>(); // don't want to add the same item twice; otherwise use a list\n while (numItems > 0 )\n // if we successfully added it, move on\n if( items.Add(list[randomizer.Next(list.Length)]) ) numItems--;\n\n return items;\n }\n\n // and because it's really fun; note -- you may get repetition\n public static IEnumerable<T> PluckRandomly<T>(this IEnumerable<T> list) {\n while( true )\n yield return list.ElementAt(randomizer.Next(list.Count()));\n }\n\n}\n HashSet [TestClass]\npublic class RandomizingTests : UnitTestBase {\n [TestMethod]\n public void GetRandomFromList() {\n this.testGetRandomFromList((list, num) => list.GetRandom(num));\n }\n\n [TestMethod]\n public void PluckRandomly() {\n this.testGetRandomFromList((list, num) => list.PluckRandomly().Take(num), requireDistinct:false);\n }\n\n private void testGetRandomFromList(Func<IEnumerable<int>, int, IEnumerable<int>> methodToGetRandomItems, int numToTake = 10, int repetitions = 100000, bool requireDistinct = true) {\n var items = Enumerable.Range(0, 100);\n IEnumerable<int> randomItems = null;\n\n while( repetitions-- > 0 ) {\n randomItems = methodToGetRandomItems(items, numToTake);\n Assert.AreEqual(numToTake, randomItems.Count(),\n \"Did not get expected number of items {0}; failed at {1} repetition--\", numToTake, repetitions);\n if(requireDistinct) Assert.AreEqual(numToTake, randomItems.Distinct().Count(),\n \"Collisions (non-unique values) found, failed at {0} repetition--\", repetitions);\n Assert.IsTrue(randomItems.All(o => items.Contains(o)),\n \"Some unknown values found; failed at {0} repetition--\", repetitions);\n }\n }\n}\n"
},
{
"answer_id": 17598162,
"author": "Tom Gullen",
"author_id": 356635,
"author_profile": "https://Stackoverflow.com/users/356635",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Picks random selection of available game ID's\n/// </summary>\nprivate static List<int> GetRandomGameIDs(int count)\n{ \n var gameIDs = (int[])HttpContext.Current.Application[\"NonDeletedArcadeGameIDs\"];\n var totalGameIDs = gameIDs.Count();\n if (count > totalGameIDs) count = totalGameIDs;\n\n var rnd = new Random();\n var leftToPick = count;\n var itemsLeft = totalGameIDs;\n var arrPickIndex = 0;\n var returnIDs = new List<int>();\n while (leftToPick > 0)\n {\n if (rnd.Next(0, itemsLeft) < leftToPick)\n {\n returnIDs .Add(gameIDs[arrPickIndex]);\n leftToPick--;\n }\n arrPickIndex++;\n itemsLeft--;\n }\n\n return returnIDs ;\n}\n"
},
{
"answer_id": 28186730,
"author": "Alex Gilbert",
"author_id": 4501713,
"author_profile": "https://Stackoverflow.com/users/4501713",
"pm_score": 2,
"selected": false,
"text": "Random rand = new Random();\nfor(int i = 0; k>0; ++i) \n{\n int r = rand.Next(0, n-i);\n if(r<k) \n {\n //include element i\n k--;\n }\n} \n"
},
{
"answer_id": 30925976,
"author": "Paul Chernoch",
"author_id": 127251,
"author_profile": "https://Stackoverflow.com/users/127251",
"pm_score": 3,
"selected": false,
"text": " /// <summary>\n /// Takes k elements from the next n elements at random, preserving their order.\n /// \n /// If there are fewer than n elements in items, this may return fewer than k elements.\n /// </summary>\n /// <typeparam name=\"TElem\">Type of element in the items collection.</typeparam>\n /// <param name=\"items\">Items to be randomly selected.</param>\n /// <param name=\"k\">Number of items to pick.</param>\n /// <param name=\"n\">Total number of items to choose from.\n /// If the items collection contains more than this number, the extra members will be skipped.\n /// If the items collection contains fewer than this number, it is possible that fewer than k items will be returned.</param>\n /// <returns>Enumerable over the retained items.\n /// \n /// See http://stackoverflow.com/questions/48087/select-a-random-n-elements-from-listt-in-c-sharp for the commentary.\n /// </returns>\n public static IEnumerable<TElem> TakeRandom<TElem>(this IEnumerable<TElem> items, int k, int n)\n {\n var r = new FastRandom();\n var itemsList = items as IList<TElem>;\n\n if (k >= n || (itemsList != null && k >= itemsList.Count))\n foreach (var item in items) yield return item;\n else\n { \n // If we have a list, we can infer more information and choose a better algorithm.\n // When using an IList, this is about 7 times faster (on one benchmark)!\n if (itemsList != null && k < n/2)\n {\n // Since we have a List, we can use an algorithm suitable for Lists.\n // If there are fewer than n elements, reduce n.\n n = Math.Min(n, itemsList.Count);\n\n // This algorithm picks K index-values randomly and directly chooses those items to be selected.\n // If k is more than half of n, then we will spend a fair amount of time thrashing, picking\n // indices that we have already picked and having to try again. \n var invertSet = k >= n/2; \n var positions = invertSet ? (ISet<int>) new HashSet<int>() : (ISet<int>) new SortedSet<int>();\n\n var numbersNeeded = invertSet ? n - k : k;\n while (numbersNeeded > 0)\n if (positions.Add(r.Next(0, n))) numbersNeeded--;\n\n if (invertSet)\n {\n // positions contains all the indices of elements to Skip.\n for (var itemIndex = 0; itemIndex < n; itemIndex++)\n {\n if (!positions.Contains(itemIndex))\n yield return itemsList[itemIndex];\n }\n }\n else\n {\n // positions contains all the indices of elements to Take.\n foreach (var itemIndex in positions)\n yield return itemsList[itemIndex]; \n }\n }\n else\n {\n // Since we do not have a list, we will use an online algorithm.\n // This permits is to skip the rest as soon as we have enough items.\n var found = 0;\n var scanned = 0;\n foreach (var item in items)\n {\n var rand = r.Next(0,n-scanned);\n if (rand < k - found)\n {\n yield return item;\n found++;\n }\n scanned++;\n if (found >= k || scanned >= n)\n break;\n }\n }\n } \n } \n [TestClass]\npublic class TakeRandomTests\n{\n /// <summary>\n /// Ensure that when randomly choosing items from an array, all items are chosen with roughly equal probability.\n /// </summary>\n [TestMethod]\n public void TakeRandom_Array_Uniformity()\n {\n const int numTrials = 2000000;\n const int expectedCount = numTrials/20;\n var timesChosen = new int[100];\n var century = new int[100];\n for (var i = 0; i < century.Length; i++)\n century[i] = i;\n\n for (var trial = 0; trial < numTrials; trial++)\n {\n foreach (var i in century.TakeRandom(5, 100))\n timesChosen[i]++;\n }\n var avg = timesChosen.Average();\n var max = timesChosen.Max();\n var min = timesChosen.Min();\n var allowedDifference = expectedCount/100;\n AssertBetween(avg, expectedCount - 2, expectedCount + 2, \"Average\");\n //AssertBetween(min, expectedCount - allowedDifference, expectedCount, \"Min\");\n //AssertBetween(max, expectedCount, expectedCount + allowedDifference, \"Max\");\n\n var countInRange = timesChosen.Count(i => i >= expectedCount - allowedDifference && i <= expectedCount + allowedDifference);\n Assert.IsTrue(countInRange >= 90, String.Format(\"Not enough were in range: {0}\", countInRange));\n }\n\n /// <summary>\n /// Ensure that when randomly choosing items from an IEnumerable that is not an IList, \n /// all items are chosen with roughly equal probability.\n /// </summary>\n [TestMethod]\n public void TakeRandom_IEnumerable_Uniformity()\n {\n const int numTrials = 2000000;\n const int expectedCount = numTrials / 20;\n var timesChosen = new int[100];\n\n for (var trial = 0; trial < numTrials; trial++)\n {\n foreach (var i in Range(0,100).TakeRandom(5, 100))\n timesChosen[i]++;\n }\n var avg = timesChosen.Average();\n var max = timesChosen.Max();\n var min = timesChosen.Min();\n var allowedDifference = expectedCount / 100;\n var countInRange =\n timesChosen.Count(i => i >= expectedCount - allowedDifference && i <= expectedCount + allowedDifference);\n Assert.IsTrue(countInRange >= 90, String.Format(\"Not enough were in range: {0}\", countInRange));\n }\n\n private IEnumerable<int> Range(int low, int count)\n {\n for (var i = low; i < low + count; i++)\n yield return i;\n }\n\n private static void AssertBetween(int x, int low, int high, String message)\n {\n Assert.IsTrue(x > low, String.Format(\"Value {0} is less than lower limit of {1}. {2}\", x, low, message));\n Assert.IsTrue(x < high, String.Format(\"Value {0} is more than upper limit of {1}. {2}\", x, high, message));\n }\n\n private static void AssertBetween(double x, double low, double high, String message)\n {\n Assert.IsTrue(x > low, String.Format(\"Value {0} is less than lower limit of {1}. {2}\", x, low, message));\n Assert.IsTrue(x < high, String.Format(\"Value {0} is more than upper limit of {1}. {2}\", x, high, message));\n }\n}\n"
},
{
"answer_id": 32066958,
"author": "Kvam",
"author_id": 1392287,
"author_profile": "https://Stackoverflow.com/users/1392287",
"pm_score": 0,
"selected": false,
"text": " public static IEnumerable<T> TakeRandom<T>(this IEnumerable<T> elements, int countToTake)\n {\n var random = new Random();\n\n var internalList = elements.ToList();\n\n var selected = new List<T>();\n for (var i = 0; i < countToTake; ++i)\n {\n var next = random.Next(0, internalList.Count - selected.Count);\n selected.Add(internalList[next]);\n internalList[next] = internalList[internalList.Count - selected.Count];\n }\n return selected;\n }\n"
},
{
"answer_id": 34190704,
"author": "Wolf5",
"author_id": 37643,
"author_profile": "https://Stackoverflow.com/users/37643",
"pm_score": 0,
"selected": false,
"text": "new int[5].Select(o => (int)(rnd.NextDouble() * maxIndex)).Select(i => YourIEnum.ElementAt(i))\n"
},
{
"answer_id": 34696413,
"author": "Cardinal",
"author_id": 1180397,
"author_profile": "https://Stackoverflow.com/users/1180397",
"pm_score": 1,
"selected": false,
"text": "public static IEnumerable<T> GetRandom<T>(IList<T> list, int count, Random random)\n {\n // Probably you should throw exception if count > list.Count\n count = Math.Min(list.Count, count);\n\n var selectedIndices = new SortedSet<int>();\n\n // Random upper bound (exclusive)\n int randomMax = list.Count;\n\n while (selectedIndices.Count < count)\n {\n int randomIndex = random.Next(0, randomMax);\n\n // skip over already selected indices\n foreach (var selectedIndex in selectedIndices)\n if (selectedIndex <= randomIndex)\n ++randomIndex;\n else\n break;\n\n yield return list[randomIndex];\n\n selectedIndices.Add(randomIndex);\n --randomMax;\n }\n }\n"
},
{
"answer_id": 35050572,
"author": "Dai",
"author_id": 5849502,
"author_profile": "https://Stackoverflow.com/users/5849502",
"pm_score": -1,
"selected": false,
"text": "def random_selection_indices(num_samples, N):\n modified_entries = {}\n seq = []\n for n in xrange(num_samples):\n i = N - n - 1\n j = random.randrange(i)\n\n # swap a[j] and a[i] \n a_j = modified_entries[j] if j in modified_entries else j \n a_i = modified_entries[i] if i in modified_entries else i\n\n if a_i != j:\n modified_entries[j] = a_i \n elif j in modified_entries: # no need to store the modified value if it is the same as index\n modified_entries.pop(j)\n\n if a_j != i:\n modified_entries[i] = a_j \n elif i in modified_entries: # no need to store the modified value if it is the same as index\n modified_entries.pop(i)\n seq.append(a_j)\n return seq\n"
},
{
"answer_id": 37836199,
"author": "Jesús López",
"author_id": 4540020,
"author_profile": "https://Stackoverflow.com/users/4540020",
"pm_score": 3,
"selected": false,
"text": "public static IEnumerable<T> GetRandomSample<T>(this IList<T> list, int sampleSize)\n{\n if (list == null) throw new ArgumentNullException(\"list\");\n if (sampleSize > list.Count) throw new ArgumentException(\"sampleSize may not be greater than list count\", \"sampleSize\");\n var indices = new Dictionary<int, int>(); int index;\n var rnd = new Random();\n\n for (int i = 0; i < sampleSize; i++)\n {\n int j = rnd.Next(i, list.Count);\n if (!indices.TryGetValue(j, out index)) index = j;\n\n yield return list[index];\n\n if (!indices.TryGetValue(i, out index)) index = i;\n indices[j] = index;\n }\n}\n"
},
{
"answer_id": 51801413,
"author": "hardsetting",
"author_id": 2779525,
"author_profile": "https://Stackoverflow.com/users/2779525",
"pm_score": 3,
"selected": false,
"text": "// Instead of this\nYourList.OrderBy(x => rnd.Next()).Take(5)\n\n// Temporarily transform \nYourList\n .Select(v => new {v, i = rnd.Next()}) // Associate a random index to each entry\n .OrderBy(x => x.i).Take(5) // Sort by (at this point fixed) random index \n .Select(x => x.v); // Go back to enumerable of entry\n"
},
{
"answer_id": 52261608,
"author": "Jesse Gador",
"author_id": 10142676,
"author_profile": "https://Stackoverflow.com/users/10142676",
"pm_score": 1,
"selected": false,
"text": "public static class CollectionExtension\n{\n public static IList<TSource> RandomizeCollection<TSource>(this IList<TSource> source, int maxItems)\n {\n int randomCount = source.Count > maxItems ? maxItems : source.Count;\n int?[] randomizedIndices = new int?[randomCount];\n Random random = new Random();\n\n for (int i = 0; i < randomizedIndices.Length; i++)\n {\n int randomResult = -1;\n while (randomizedIndices.Contains((randomResult = random.Next(0, source.Count))))\n {\n //0 -> since all list starts from index 0; source.Count -> maximum number of items that can be randomize\n //continue looping while the generated random number is already in the list of randomizedIndices\n }\n\n randomizedIndices[i] = randomResult;\n }\n\n IList<TSource> result = new List<TSource>();\n foreach (int index in randomizedIndices)\n result.Add(source.ElementAt(index));\n\n return result;\n }\n}\n"
},
{
"answer_id": 62440602,
"author": "Cyrille",
"author_id": 5974529,
"author_profile": "https://Stackoverflow.com/users/5974529",
"pm_score": -1,
"selected": false,
"text": "var entries=new List<T>();\nvar selectedItems = new List<T>();\n\n\n for (var i = 0; i !=10; i++)\n {\n var rdm = new Random().Next(entries.Count);\n while (selectedItems.Contains(entries[rdm]))\n rdm = new Random().Next(entries.Count);\n\n selectedItems.Add(entries[rdm]);\n }\n"
},
{
"answer_id": 63948082,
"author": "DontPanic345",
"author_id": 3281460,
"author_profile": "https://Stackoverflow.com/users/3281460",
"pm_score": 3,
"selected": false,
"text": "public IEnumerable<T> TakeRandom<T>(IEnumerable<T> collection, int take)\n{\n var random = new Random();\n var available = collection.Count();\n var needed = take;\n foreach (var item in collection)\n {\n if (random.Next(available) < needed)\n {\n needed--;\n yield return item;\n if (needed == 0)\n {\n break;\n }\n }\n available--;\n }\n}\n"
},
{
"answer_id": 65986513,
"author": "Leaky",
"author_id": 2906385,
"author_profile": "https://Stackoverflow.com/users/2906385",
"pm_score": 2,
"selected": false,
"text": "O(n) Random.Next() static void Main()\n{\n BenchmarkRunner.Run<Benchmarks>();\n\n new Benchmarks() { ListSize = 100, SelectionSize = 10 }\n .BenchmarkStdDev();\n}\n\n[MemoryDiagnoser]\npublic class Benchmarks\n{\n [Params(50, 500, 5000)]\n public int ListSize;\n\n [Params(5, 10, 25, 50)]\n public int SelectionSize;\n\n private Random _rnd;\n private List<int> _list;\n private int[] _hits;\n\n [GlobalSetup]\n public void Setup()\n {\n _rnd = new Random(12345);\n _list = Enumerable.Range(0, ListSize).ToList();\n _hits = new int[ListSize];\n }\n\n [Benchmark]\n public void Test_IterateSelect()\n => Random_IterateSelect(_list, SelectionSize).ToList();\n\n [Benchmark]\n public void Test_RandomIndices() \n => Random_RandomIdices(_list, SelectionSize).ToList();\n\n [Benchmark]\n public void Test_FisherYates() \n => Random_FisherYates(_list, SelectionSize).ToList();\n\n public void BenchmarkStdDev()\n {\n RunOnce(Random_IterateSelect, \"IterateSelect\");\n RunOnce(Random_RandomIdices, \"RandomIndices\");\n RunOnce(Random_FisherYates, \"FisherYates\");\n\n void RunOnce(Func<IEnumerable<int>, int, IEnumerable<int>> method, string methodName)\n {\n Setup();\n for (int i = 0; i < 1000000; i++)\n {\n var selected = method(_list, SelectionSize).ToList();\n Debug.Assert(selected.Count() == SelectionSize);\n foreach (var item in selected) _hits[item]++;\n }\n var stdDev = GetStdDev(_hits);\n Console.WriteLine($\"StdDev of {methodName}: {stdDev :n} (% of average: {stdDev / (_hits.Average() / 100) :n})\");\n }\n\n double GetStdDev(IEnumerable<int> hits)\n {\n var average = hits.Average();\n return Math.Sqrt(hits.Average(v => Math.Pow(v - average, 2)));\n }\n }\n\n public IEnumerable<T> Random_IterateSelect<T>(IEnumerable<T> collection, int needed)\n {\n var count = collection.Count();\n for (int i = 0; i < count; i++)\n {\n if (_rnd.Next(count - i) < needed)\n {\n yield return collection.ElementAt(i);\n if (--needed == 0)\n yield break;\n }\n }\n }\n\n public IEnumerable<T> Random_RandomIdices<T>(IEnumerable<T> list, int needed)\n {\n var selectedItems = new HashSet<T>();\n var count = list.Count();\n\n while (needed > 0)\n if (selectedItems.Add(list.ElementAt(_rnd.Next(count))))\n needed--;\n\n return selectedItems;\n }\n\n public IEnumerable<T> Random_FisherYates<T>(IEnumerable<T> list, int sampleSize)\n {\n var count = list.Count();\n if (sampleSize > count) throw new ArgumentException(\"sampleSize may not be greater than list count\", \"sampleSize\");\n var indices = new Dictionary<int, int>(); int index;\n\n for (int i = 0; i < sampleSize; i++)\n {\n int j = _rnd.Next(i, count);\n if (!indices.TryGetValue(j, out index)) index = j;\n\n yield return list.ElementAt(index);\n\n if (!indices.TryGetValue(i, out index)) index = i;\n indices[j] = index;\n }\n }\n}\n | Method | ListSize | Select | Mean | Error | StdDev | Gen 0 | Allocated |\n|-------------- |--------- |------- |------------:|----------:|----------:|-------:|----------:|\n| IterateSelect | 50 | 5 | 711.5 ns | 5.19 ns | 4.85 ns | 0.0305 | 144 B |\n| RandomIndices | 50 | 5 | 341.1 ns | 4.48 ns | 4.19 ns | 0.0644 | 304 B |\n| FisherYates | 50 | 5 | 573.5 ns | 6.12 ns | 5.72 ns | 0.0944 | 447 B |\n\n| IterateSelect | 50 | 10 | 967.2 ns | 4.64 ns | 3.87 ns | 0.0458 | 220 B |\n| RandomIndices | 50 | 10 | 709.9 ns | 11.27 ns | 9.99 ns | 0.1307 | 621 B |\n| FisherYates | 50 | 10 | 1,204.4 ns | 10.63 ns | 9.94 ns | 0.1850 | 875 B |\n\n| IterateSelect | 50 | 25 | 1,358.5 ns | 7.97 ns | 6.65 ns | 0.0763 | 361 B |\n| RandomIndices | 50 | 25 | 1,958.1 ns | 15.69 ns | 13.91 ns | 0.2747 | 1298 B |\n| FisherYates | 50 | 25 | 2,878.9 ns | 31.42 ns | 29.39 ns | 0.3471 | 1653 B |\n\n| IterateSelect | 50 | 50 | 1,739.1 ns | 15.86 ns | 14.06 ns | 0.1316 | 629 B |\n| RandomIndices | 50 | 50 | 8,906.1 ns | 88.92 ns | 74.25 ns | 0.5951 | 2848 B |\n| FisherYates | 50 | 50 | 4,899.9 ns | 38.10 ns | 33.78 ns | 0.4349 | 2063 B |\n\n| IterateSelect | 500 | 5 | 4,775.3 ns | 46.96 ns | 41.63 ns | 0.0305 | 144 B |\n| RandomIndices | 500 | 5 | 327.8 ns | 2.82 ns | 2.50 ns | 0.0644 | 304 B |\n| FisherYates | 500 | 5 | 558.5 ns | 7.95 ns | 7.44 ns | 0.0944 | 449 B |\n\n| IterateSelect | 500 | 10 | 5,387.1 ns | 44.57 ns | 41.69 ns | 0.0458 | 220 B |\n| RandomIndices | 500 | 10 | 648.0 ns | 9.12 ns | 8.54 ns | 0.1307 | 621 B |\n| FisherYates | 500 | 10 | 1,154.6 ns | 13.66 ns | 12.78 ns | 0.1869 | 889 B |\n\n| IterateSelect | 500 | 25 | 6,442.3 ns | 48.90 ns | 40.83 ns | 0.0763 | 361 B |\n| RandomIndices | 500 | 25 | 1,569.6 ns | 15.79 ns | 14.77 ns | 0.2747 | 1298 B |\n| FisherYates | 500 | 25 | 2,726.1 ns | 25.32 ns | 22.44 ns | 0.3777 | 1795 B |\n\n| IterateSelect | 500 | 50 | 7,775.4 ns | 35.47 ns | 31.45 ns | 0.1221 | 629 B |\n| RandomIndices | 500 | 50 | 2,976.9 ns | 27.11 ns | 24.03 ns | 0.6027 | 2848 B |\n| FisherYates | 500 | 50 | 5,383.2 ns | 36.49 ns | 32.35 ns | 0.8163 | 3870 B |\n\n| IterateSelect | 5000 | 5 | 45,208.6 ns | 459.92 ns | 430.21 ns | - | 144 B |\n| RandomIndices | 5000 | 5 | 328.7 ns | 5.15 ns | 4.81 ns | 0.0644 | 304 B |\n| FisherYates | 5000 | 5 | 556.1 ns | 10.75 ns | 10.05 ns | 0.0944 | 449 B |\n\n| IterateSelect | 5000 | 10 | 49,253.9 ns | 420.26 ns | 393.11 ns | - | 220 B |\n| RandomIndices | 5000 | 10 | 642.9 ns | 4.95 ns | 4.13 ns | 0.1307 | 621 B |\n| FisherYates | 5000 | 10 | 1,141.9 ns | 12.81 ns | 11.98 ns | 0.1869 | 889 B |\n\n| IterateSelect | 5000 | 25 | 54,044.4 ns | 208.92 ns | 174.46 ns | 0.0610 | 361 B |\n| RandomIndices | 5000 | 25 | 1,480.5 ns | 11.56 ns | 10.81 ns | 0.2747 | 1298 B |\n| FisherYates | 5000 | 25 | 2,713.9 ns | 27.31 ns | 24.21 ns | 0.3777 | 1795 B |\n\n| IterateSelect | 5000 | 50 | 54,418.2 ns | 329.62 ns | 308.32 ns | 0.1221 | 629 B |\n| RandomIndices | 5000 | 50 | 2,886.4 ns | 36.53 ns | 34.17 ns | 0.6027 | 2848 B |\n| FisherYates | 5000 | 50 | 5,347.2 ns | 59.45 ns | 55.61 ns | 0.8163 | 3870 B |\n\nStdDev of IterateSelect: 671.88 (% of average: 0.67)\nStdDev of RandomIndices: 296.07 (% of average: 0.30)\nStdDev of FisherYates: 280.47 (% of average: 0.28)\n"
},
{
"answer_id": 72070751,
"author": "TXNPRS",
"author_id": 19002336,
"author_profile": "https://Stackoverflow.com/users/19002336",
"pm_score": 1,
"selected": false,
"text": "if (list.Count > maxListCount)\n{\n var rndList = new List<YourEntity>();\n var r = new Random();\n \n while (rndList.Count < maxListCount)\n {\n var addingElement = list[r.Next(list.Count)];\n\n //element uniqueness checking\n //choose your case\n //if (rndList.Contains(addingElement))\n //if (rndList.Any(p => p.Id == addingElement.Id))\n continue;\n \n rndList.Add(addingElement);\n }\n \n return rndList;\n}\n"
},
{
"answer_id": 72335120,
"author": "Kuba Szostak",
"author_id": 2524798,
"author_profile": "https://Stackoverflow.com/users/2524798",
"pm_score": 1,
"selected": false,
"text": "public static IEnumerable<TItem> RandomSample<TItem>(this IReadOnlyList<TItem> items, int count) \n{\n if (count < 1 || count > items.Count)\n {\n throw new ArgumentOutOfRangeException(nameof(count));\n }\n List<int> indexes = Enumerable.Range(0, items.Count).ToList();\n int yieldedCount = 0;\n\n while (yieldedCount < count)\n {\n int i = RandomNumberGenerator.GetInt32(indexes.Count);\n int randomIndex = indexes[i];\n yield return items[randomIndex];\n\n // indexes.RemoveAt(i); // Avoid removing items from the middle of the list\n indexes[i] = indexes[indexes.Count - 1]; // Replace yielded index with the last one\n indexes.RemoveAt(indexes.Count - 1); \n yieldedCount++;\n }\n}\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] |
48,088 |
<p>I was surprised recently to find that it's possible to have a return statement in a finally block in Java.</p>
<p>It seems like lots of people think it's a bad thing to do as described in '<a href="https://web.archive.org/web/20070922061412/http://weblogs.java.net/blog/staufferjames/archive/2007/06/_dont_return_in.html" rel="noreferrer">Don't return in a finally clause</a>'. Scratching a little deeper, I also found '<a href="https://web.archive.org/web/20190528011825/http://www.cs.arizona.edu/projects/sumatra/hallofshame/" rel="noreferrer">Java's return doesn't always</a>' which shows some pretty horrible examples of other types of flow control in finally blocks.</p>
<p>So, my question is, can anyone give me an example where a return statement (or other flow control) in a finally block produces better / more readable code?</p>
|
[
{
"answer_id": 48740,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 7,
"selected": false,
"text": "Object problemMethod() {\n Object rtn = null;\n try {\n rtn = somethingThatThrewAnException();\n }\n finally {\n doSomeCleanup();\n return rtn;\n }\n}\n somethingThatThrewAnException() problemMethod()"
},
{
"answer_id": 5196685,
"author": "Prof. Ondino",
"author_id": 645117,
"author_profile": "https://Stackoverflow.com/users/645117",
"pm_score": 3,
"selected": false,
"text": "public class Instance {\n\n List<String> runningThreads = new ArrayList<String>()\n\n void test(boolean returnInFinally) {\n\n println \"\\ntest(returnInFinally: $returnInFinally)\"\n println \"--------------------------------------------------------------------------\"\n println \"before execute\"\n String result = execute(returnInFinally, false)\n println \"after execute -> result: \" + result\n println \"--------------------------------------------------------------------------\"\n\n println \"before execute\"\n try {\n result = execute(returnInFinally, true)\n println \"after execute -> result: \" + result\n } catch (Exception ex) {\n println \"execute threw exception: \" + ex.getMessage()\n } \n println \"--------------------------------------------------------------------------\\n\"\n\n }\n\n String execute(boolean returnInFinally, boolean throwError) {\n String thread = Thread.currentThread().getName()\n println \"...execute(returnInFinally: $returnInFinally, throwError: $throwError) - thread: $thread\"\n runningThreads.add(thread)\n try {\n if (throwError) {\n println \"...error in execute, throw exception\"\n throw new Exception(\"as you liked :-)\")\n }\n println \"...return 'OK' from execute\"\n return \"OK\"\n } finally {\n println \"...pass finally block\"\n if (returnInFinally) return \"return value from FINALLY ^^\"\n // runningThreads.remove(thread)\n }\n }\n}\n\nInstance instance = new Instance()\ninstance.test(false)\ninstance.test(true)\n test(returnInFinally: false)\n-----------------------------------------------------------------------------\nbefore execute\n...execute(returnInFinally: false, throwError: false) - thread: Thread-116\n...return 'OK' from execute\n...pass finally block\nafter execute -> result: OK\n-----------------------------------------------------------------------------\nbefore execute\n...execute(returnInFinally: false, throwError: true) - thread: Thread-116\n...error in execute, throw exception\n...pass finally block\nexecute threw exception: as you liked :-)\n-----------------------------------------------------------------------------\n\n\ntest(returnInFinally: true)\n-----------------------------------------------------------------------------\nbefore execute\n...execute(returnInFinally: true, throwError: false) - thread: Thread-116\n...return 'OK' from execute\n...pass finally block\nafter execute -> result: return value from FINALLY ^^\n-----------------------------------------------------------------------------\nbefore execute\n...execute(returnInFinally: true, throwError: true) - thread: Thread-116\n...error in execute, throw exception\n...pass finally block\nafter execute -> result: return value from FINALLY ^^\n-----------------------------------------------------------------------------\n"
},
{
"answer_id": 60124650,
"author": "Ankur Lathi",
"author_id": 2099208,
"author_profile": "https://Stackoverflow.com/users/2099208",
"pm_score": 2,
"selected": false,
"text": "finally exceptions If the finally block completes normally, then the try statement\n completes abruptly for reason R.\n\n If the finally block completes abruptly for reason S, then the try\n statement completes abruptly for reason S (and reason R is\n discarded).\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] |
48,094 |
<p>So I have a pointer to an array of pointers. If I delete it like this:</p>
<pre><code>delete [] PointerToPointers;
</code></pre>
<p>Will that delete all the pointed to pointers as well? If not, do I have to loop over all of the pointers and delete them as well, or is there an easier way to do it? My google-fu doesn't seem to give me any good answers to this question.</p>
<p>(And yeah, I know I need to use a vector. This is one of those "catch up on C++" type assignments in school.)</p>
|
[
{
"answer_id": 48670,
"author": "Ray",
"author_id": 456786,
"author_profile": "https://Stackoverflow.com/users/456786",
"pm_score": 4,
"selected": false,
"text": "int main()\n{\n int *pI = new int;\n int *pArr = new int[10];\n delete pI;\n delete [] pArr;\n int ppArr = new int *[10];\n\n for( int indx = 0; indx < 10; ++indx )\n {\n ppArr[indx] = new int;\n }\n for( int indx = 0; indx < 10; ++indx )\n {\n delete ppArr[indx];\n }\n delete [] ppArr;\n int a=0;\n int b=1;\n int c=2;\n\n ppArr = new int *[3];\n\n ppArr[0] = &a;\n ppArr[1] = &b;\n ppArr[2] = &c;\n delete [] ppArr;\n\n return 0;\n\n}\n"
},
{
"answer_id": 3822166,
"author": "RikSaunderson",
"author_id": 450460,
"author_profile": "https://Stackoverflow.com/users/450460",
"pm_score": 2,
"selected": false,
"text": "class Street\n{\n public:\n Street();\n ~Street();\n private:\n int HouseNumbers_[];\n}\n\ntypedef *Street StreetSign;\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
48,115 |
<p>I'm using an Ubuntu 8.04 (x86_64) machine to connect to my employer's Cisco VPN. (The client didn't compile out of the box, but I found <a href="http://projects.tuxx-home.at/?id=cisco_vpn_client" rel="nofollow noreferrer">patches to update the client to compile on kernels released in the last two years</a>.) This all works great, until my DHCP client decides to renew its lease and updates /etc/resolv.conf, replacing the VPN-specific name servers with my general network servers.</p>
<p>Is there a good way to prevent my DHCP client from updating /etc/resolv.conf while my VPN is active?</p>
|
[
{
"answer_id": 48130,
"author": "Sean",
"author_id": 4919,
"author_profile": "https://Stackoverflow.com/users/4919",
"pm_score": 3,
"selected": false,
"text": "sudo apt-get install resolvconf sudo apt-get remove resolvconf vpn resolv.conf"
},
{
"answer_id": 202040,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "--- /sbin/dhclient-script.orig 2007-03-08 19:19:56.000000000 +0000\n+++ /sbin/dhclient-script 2007-03-08 19:19:46.000000000 +0000\n@@ -13,6 +13,10 @@\n # The alias handling in here probably still sucks. -mdz\n\n make_resolv_conf() {\n+ # don't overwrite resolv.conf at RENEW time, since a VPN/PPTP tunnel may\n+ # have updated it with remote DNS servers\n+ [ \"$reason\" = \"RENEW\" ] && return\n+\n if [ -n \"$new_domain_name\" -o -n \"$new_domain_name_servers\" ]; then\n # Find out whether we are going to mount / rw\n exec 9>&0 </etc/fstab\n /sbin/dhcp-script /etc/resolv.conf"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4659/"
] |
48,123 |
<p>I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade.</p>
<p>The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade.</p>
<p>I was wondering if the more experienced ones among us (remember, I'm just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem).</p>
|
[
{
"answer_id": 524614,
"author": "Bruce van der Kooij",
"author_id": 63736,
"author_profile": "https://Stackoverflow.com/users/63736",
"pm_score": 2,
"selected": false,
"text": "container = gtk.HBox()\nlabel = gtk.Label(str=\"test\")\ncontainer.add(label)\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/802/"
] |
48,124 |
<p>How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?</p>
|
[
{
"answer_id": 48125,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 8,
"selected": true,
"text": " $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';\n $characters $string = '';\n $max = strlen($characters) - 1;\n for ($i = 0; $i < $random_string_length; $i++) {\n $string .= $characters[mt_rand(0, $max)];\n }\n $random_string_length"
},
{
"answer_id": 48285,
"author": "Daniel",
"author_id": 416,
"author_profile": "https://Stackoverflow.com/users/416",
"pm_score": 2,
"selected": false,
"text": "// range is numbers (48) through capital and lower case letters (122)\n$range_start = 48;\n$range_end = 122;\n$random_string = \"\";\n$random_string_length = 10;\n\nfor ($i = 0; $i < $random_string_length; $i++) {\n $ascii_no = round( mt_rand( $range_start , $range_end ) ); // generates a number within the range\n // finds the character represented by $ascii_no and adds it to the random string\n // study **chr** function for a better understanding\n $random_string .= chr( $ascii_no );\n}\n\necho $random_string;\n"
},
{
"answer_id": 1037136,
"author": "Salman A",
"author_id": 87015,
"author_profile": "https://Stackoverflow.com/users/87015",
"pm_score": 2,
"selected": false,
"text": "function random_string() {\n // 8 characters: 7 lower-case alphabets and 1 digit\n $character_sets = [\n [\"count\" => 7, \"characters\" => \"abcdefghijklmnopqrstuvwxyz\"],\n [\"count\" => 1, \"characters\" => \"0123456789\"]\n ];\n $temp_array = array();\n foreach ($character_sets as $character_set) {\n for ($i = 0; $i < $character_set[\"count\"]; $i++) {\n $random = random_int(0, strlen($character_set[\"characters\"]) - 1);\n $temp_array[] = $character_set[\"characters\"][$random];\n }\n }\n shuffle($temp_array);\n return implode(\"\", $temp_array);\n}\n"
},
{
"answer_id": 3096086,
"author": "Josh Smith",
"author_id": 373496,
"author_profile": "https://Stackoverflow.com/users/373496",
"pm_score": 0,
"selected": false,
"text": "<?php\n$character_array = array_merge(range('a', 'z'), range(0, 9));\n$string = \"\";\n for($i = 0; $i < 6; $i++) {\n $string .= $character_array[rand(0, (count($character_array) - 1))];\n }\necho $string;\n?>\n"
},
{
"answer_id": 28925556,
"author": "Molla Rasel",
"author_id": 4646424,
"author_profile": "https://Stackoverflow.com/users/4646424",
"pm_score": 1,
"selected": false,
"text": "function generateRandomString($length = 10) {\n $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n $charactersLength = strlen($characters);\n $randomString = '';\n for ($i = 0; $i < $length; $i++) {\n $randomString .= $characters[rand(0, $charactersLength - 1)];\n }\n return $randomString;\n}\necho generateRandomString();\n"
},
{
"answer_id": 33690821,
"author": "diegoiglesias",
"author_id": 972813,
"author_profile": "https://Stackoverflow.com/users/972813",
"pm_score": 2,
"selected": false,
"text": " class RandomString\n {\n private static $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';\n private static $string;\n private static $length = 8; //default random string length\n\n public static function generate($length = null)\n {\n\n if($length){\n self::$length = $length;\n }\n\n $characters_length = strlen(self::$characters) - 1;\n\n for ($i = 0; $i < self::$length; $i++) {\n self::$string .= self::$characters[mt_rand(0, $characters_length)];\n }\n\n return self::$string;\n\n }\n\n }\n"
},
{
"answer_id": 33971950,
"author": "azerafati",
"author_id": 3160597,
"author_profile": "https://Stackoverflow.com/users/3160597",
"pm_score": 4,
"selected": false,
"text": "function randomKey($length) {\n $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));\n\n for($i=0; $i < $length; $i++) {\n $key .= $pool[mt_rand(0, count($pool) - 1)];\n }\n return $key;\n}\n\necho randomKey(20);\n"
},
{
"answer_id": 35605166,
"author": "emix",
"author_id": 997162,
"author_profile": "https://Stackoverflow.com/users/997162",
"pm_score": 4,
"selected": false,
"text": "echo bin2hex(openssl_random_pseudo_bytes(4));\n function randomString(int $length): string\n{\n return bin2hex(openssl_random_pseudo_bytes($length));\n}\n random_x() function randomString($length)\n{\n return bin2hex(random_bytes($length));\n}\n"
},
{
"answer_id": 36932671,
"author": "Peter",
"author_id": 3169577,
"author_profile": "https://Stackoverflow.com/users/3169577",
"pm_score": 2,
"selected": false,
"text": "range() Function pseudostring($length = 50) {\n\n // Generate arrays with characters and numbers\n $lowerAlpha = range('a', 'z');\n $upperAlpha = range('A', 'Z');\n $numeric = range('0', '9');\n\n // Merge the arrays\n $workArray = array_merge($numeric, array_merge($lowerAlpha, $upperAlpha));\n $returnString = \"\";\n\n // Add random characters from the created array to a string\n for ($i = 0; $i < $length; $i++) {\n $character = $workArray[rand(0, 61)];\n $returnString .= $character;\n }\n\n return $returnString;\n}\n"
},
{
"answer_id": 41361411,
"author": "Zeeshan",
"author_id": 3354721,
"author_profile": "https://Stackoverflow.com/users/3354721",
"pm_score": 0,
"selected": false,
"text": "$cryptoStrong = true; // can be false\n$length = 16; // Any length you want\n$bytes = openssl_random_pseudo_bytes($length, $cryptoStrong);\n$randomString = bin2hex($bytes);\n"
},
{
"answer_id": 43919537,
"author": "HausO",
"author_id": 2842514,
"author_profile": "https://Stackoverflow.com/users/2842514",
"pm_score": 0,
"selected": false,
"text": "$FROM = 0; $TO = 'zzzz';\n$code = base_convert(rand( $FROM ,base_convert( $TO , 36,10)),10,36);\necho $code;\n"
},
{
"answer_id": 45577038,
"author": "Marco Panichi",
"author_id": 162049,
"author_profile": "https://Stackoverflow.com/users/162049",
"pm_score": 3,
"selected": false,
"text": "echo substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 7 );\n"
},
{
"answer_id": 49860249,
"author": "DiMono",
"author_id": 2069424,
"author_profile": "https://Stackoverflow.com/users/2069424",
"pm_score": 1,
"selected": false,
"text": "substr( sha1( time() ), 0, 15 ) time() sha1() substr()"
},
{
"answer_id": 53157130,
"author": "lyrixx",
"author_id": 685587,
"author_profile": "https://Stackoverflow.com/users/685587",
"pm_score": 0,
"selected": false,
"text": "function random_string(int $size): string\n{\n $characters = array_merge(\n range(0, 9),\n range('A', 'Z')\n );\n\n $string = '';\n $max = count($characters) - 1;\n for ($i = 0; $i < $size; $i++) {\n $string .= $characters[random_int(0, $max)];\n }\n\n return $string;\n}\n"
},
{
"answer_id": 55955195,
"author": "David Young",
"author_id": 11442440,
"author_profile": "https://Stackoverflow.com/users/11442440",
"pm_score": 2,
"selected": false,
"text": "$str = bin2hex(random_bytes(32)); // 64 character string returned\n"
},
{
"answer_id": 56090016,
"author": "Shravan M",
"author_id": 9512364,
"author_profile": "https://Stackoverflow.com/users/9512364",
"pm_score": 1,
"selected": false,
"text": "$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n $alpha=substr(str_shuffle($chars), 0, 50);\n"
},
{
"answer_id": 56090053,
"author": "Александр Маринов",
"author_id": 8847970,
"author_profile": "https://Stackoverflow.com/users/8847970",
"pm_score": 0,
"selected": false,
"text": "public function randomString($length = 8)\n{\n $characters = implode([\n 'ABCDEFGHIJKLMNOPORRQSTUWVXYZ',\n 'abcdefghijklmnoprqstuwvxyz',\n '0123456789',\n //'!@#$%^&*?'\n ]);\n\n $charactersLength = strlen($characters) - 1;\n $string = '';\n\n while ($length) {\n $string .= $characters[mt_rand(0, $charactersLength)];\n --$length;\n }\n\n return $string;\n}\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
48,126 |
<p>Documentation is severely lacking on anything to do with stored procedures in mysql with PHP. I currently have a stored procedure that I call via PHP, how can I get the value of an out parameter?</p>
|
[
{
"answer_id": 48161,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 5,
"selected": true,
"text": "$mysqli = new mysqli( \"HOST\", \"USR\", \"PWD\", \"DBNAME\" );\n$ivalue=1;\n$res = $mysqli->multi_query( \"CALL myproc($ivalue,@x);SELECT @x\" );\nif( $res ) {\n $results = 0;\n do {\n if ($result = $mysqli->store_result()) {\n printf( \"<b>Result #%u</b>:<br/>\", ++$results );\n while( $row = $result->fetch_row() ) {\n foreach( $row as $cell ) echo $cell, \" \";\n }\n $result->close();\n if( $mysqli->more_results() ) echo \"<br/>\";\n }\n } while( $mysqli->next_result() );\n}\n$mysqli->close();\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
48,176 |
<p>You can embed the <a href="http://ipython.scipy.org/" rel="noreferrer">IPython</a> shell inside of your application so that it launches the shell in the foreground. Is there a way to embed a telnet server in a python app so that you can telnet to a certain port and launch a remote IPython shell? </p>
<p>Any tips for redirecting the input/output streams for IPython or how to hook it up to a telnet server library or recommendations for other libraries that could be used to implement this are much appreciated. </p>
|
[
{
"answer_id": 48266,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 0,
"selected": false,
"text": "SocketServer RequestHandler ThreadingMixIn"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
48,198 |
<p>How do I find out which process is listening on a TCP or UDP port on Windows?</p>
|
[
{
"answer_id": 48199,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 13,
"selected": true,
"text": "Get-Process -Id (Get-NetTCPConnection -LocalPort YourPortNumberHere).OwningProcess\n Get-Process -Id (Get-NetUDPEndpoint -LocalPort YourPortNumberHere).OwningProcess\n netstat -a -b\n"
},
{
"answer_id": 48202,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 8,
"selected": false,
"text": "netstat -aon | find /i \"listening\"\n"
},
{
"answer_id": 13281291,
"author": "Cyborg",
"author_id": 1775540,
"author_profile": "https://Stackoverflow.com/users/1775540",
"pm_score": 6,
"selected": false,
"text": "netstat -abno"
},
{
"answer_id": 18175357,
"author": "Perl Fanatic",
"author_id": 2375759,
"author_profile": "https://Stackoverflow.com/users/2375759",
"pm_score": 3,
"selected": false,
"text": "C:\\> netstat -anob wmic c:\\> wmic process list brief /every:5\n /? c:\\> wmic /?\nc:\\> wmic process /?\nc:\\> wmic prcess list /?\n"
},
{
"answer_id": 18199735,
"author": "nisha",
"author_id": 468964,
"author_profile": "https://Stackoverflow.com/users/468964",
"pm_score": 3,
"selected": false,
"text": "netstat -a -o\n"
},
{
"answer_id": 19255965,
"author": "Nathan24",
"author_id": 1840368,
"author_profile": "https://Stackoverflow.com/users/1840368",
"pm_score": 7,
"selected": false,
"text": "netstat -aon | find /i \"listening\" |find \"port\"\n find /i \"listening\" /i | find \"port\""
},
{
"answer_id": 22389550,
"author": "Tony Delroy",
"author_id": 410767,
"author_profile": "https://Stackoverflow.com/users/410767",
"pm_score": 4,
"selected": false,
"text": "netstat -ao netstat -ab"
},
{
"answer_id": 23136177,
"author": "Monis Majeed",
"author_id": 3335813,
"author_profile": "https://Stackoverflow.com/users/3335813",
"pm_score": 5,
"selected": false,
"text": "netstat -ao |find /i \"listening\"\n Taskkill /F /IM PID of a process\n"
},
{
"answer_id": 23718720,
"author": "bcorso",
"author_id": 1290264,
"author_profile": "https://Stackoverflow.com/users/1290264",
"pm_score": 11,
"selected": false,
"text": "resmon.exe"
},
{
"answer_id": 25463469,
"author": "Pankaj Pateriya",
"author_id": 1989851,
"author_profile": "https://Stackoverflow.com/users/1989851",
"pm_score": 6,
"selected": false,
"text": "netstat -n -a -o\n taskkill /F /PID 3312\n netstat"
},
{
"answer_id": 35312370,
"author": "ROMANIA_engineer",
"author_id": 3885376,
"author_profile": "https://Stackoverflow.com/users/3885376",
"pm_score": 6,
"selected": false,
"text": "for /f \"tokens=5\" %a in ('netstat -aon ^| findstr 9000') do tasklist /FI \"PID eq %a\"\n 9000 Image Name PID Session Name Session# Mem Usage\n========================= ======== ================ =========== ============\njava.exe 5312 Services 0 130,768 K\n netstat -aon | findstr 9000\n %a 5 tasklist /FI \"PID eq 5312\"\n echo off & (for /f \"tokens=5\" %a in ('netstat -aon ^| findstr 9000') do tasklist /NH /FI \"PID eq %a\") & echo on\n java.exe 5312 Services 0 130,768 K\n"
},
{
"answer_id": 37519085,
"author": "Nishat Lakhani",
"author_id": 5715899,
"author_profile": "https://Stackoverflow.com/users/5715899",
"pm_score": 5,
"selected": false,
"text": "netstat -aon | findstr [port number]\n"
},
{
"answer_id": 39146858,
"author": "mikemaccana",
"author_id": 123671,
"author_profile": "https://Stackoverflow.com/users/123671",
"pm_score": 3,
"selected": false,
"text": "Get-NetworkStatistics > Get-NetworkStatistics | where Localport -eq 8000\n\n\nComputerName : DESKTOP-JL59SC6\nProtocol : TCP\nLocalAddress : 0.0.0.0\nLocalPort : 8000\nRemoteAddress : 0.0.0.0\nRemotePort : 0\nState : LISTENING\nProcessName : node\nPID : 11552\n"
},
{
"answer_id": 40388051,
"author": "bahrep",
"author_id": 761095,
"author_profile": "https://Stackoverflow.com/users/761095",
"pm_score": 5,
"selected": false,
"text": "Get-NetTCPConnection Get-NetTCPConnection OwningProcess PS C:\\> Get-NetTCPConnection -LocalPort 443 | Format-List\n\n LocalAddress : ::\n LocalPort : 443\n RemoteAddress : ::\n RemotePort : 0\n State : Listen\n AppliedSetting :\n OwningProcess : 4572\n CreationTime : 02.11.2016 21:55:43\n OffloadState : InHost\n PS C:\\> Get-NetTCPConnection -LocalPort 443 | Format-Table -Property LocalAddress, LocalPort, State, OwningProcess\n\n LocalAddress LocalPort State OwningProcess\n ------------ --------- ----- -------------\n :: 443 Listen 4572\n 0.0.0.0 443 Listen 4572\n PS C:\\> Get-Process -Id (Get-NetTCPConnection -LocalPort 443).OwningProcess\n\n Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName\n ------- ------ ----- ----- ------ -- -- -----------\n 143 15 3448 11024 4572 0 VisualSVNServer\n"
},
{
"answer_id": 40745929,
"author": "Technotronic",
"author_id": 3013005,
"author_profile": "https://Stackoverflow.com/users/3013005",
"pm_score": 4,
"selected": false,
"text": "netstat -aon | findstr :DESIRED_PORT_NUMBER netstat -aon | findstr :80"
},
{
"answer_id": 41839069,
"author": "Zoomzoom",
"author_id": 1371217,
"author_profile": "https://Stackoverflow.com/users/1371217",
"pm_score": 2,
"selected": false,
"text": "netstat -na | find \"1234\"\n"
},
{
"answer_id": 41841264,
"author": "Tajveer Singh Nijjar",
"author_id": 2243541,
"author_profile": "https://Stackoverflow.com/users/2243541",
"pm_score": 4,
"selected": false,
"text": "netstat -a -n -o | find \"123456\"\n Proto Local Address Foreign Address State PID\n TCP 0.0.0.0:37 0.0.0.0:0 LISTENING 1111\n"
},
{
"answer_id": 48004597,
"author": "Jpsy",
"author_id": 430742,
"author_profile": "https://Stackoverflow.com/users/430742",
"pm_score": 3,
"selected": false,
"text": " netstat -abno | Select-String -Context 0,1 -Pattern 8080\n > TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 2920\n [tnslsnr.exe]\n> TCP [::]:8080 [::]:0 LISTENING 2920\n [tnslsnr.exe]\n Select-String netstat -Pattern -Context 0,1"
},
{
"answer_id": 48414545,
"author": "Ram Sharma",
"author_id": 9137647,
"author_profile": "https://Stackoverflow.com/users/9137647",
"pm_score": 8,
"selected": false,
"text": "netstat -ano | findStr \"8080\"\n tasklist /fi \"pid eq 2216\"\n"
},
{
"answer_id": 50180952,
"author": "deshapriya debesh",
"author_id": 4257636,
"author_profile": "https://Stackoverflow.com/users/4257636",
"pm_score": 2,
"selected": false,
"text": "netstat @echo off\nset procName=%1\nfor /f \"tokens=2 delims=,\" %%F in ('tasklist /nh /fi \"imagename eq %1\" /fo csv') do call :Foo %%~F\ngoto End\n\n:Foo\nset z=%1\necho netstat for : \"%procName%\" which had pid \"%1\"\necho ----------------------------------------------------------------------\n\nnetstat -ano |findstr %z%\ngoto :eof\n\n:End\n"
},
{
"answer_id": 52463164,
"author": "Blue Clouds",
"author_id": 1501191,
"author_profile": "https://Stackoverflow.com/users/1501191",
"pm_score": 4,
"selected": false,
"text": "netstat -bano | findstr \"7002\"\n\nnetstat -ano > ano.txt \n"
},
{
"answer_id": 53774815,
"author": "Talha Imam",
"author_id": 5863938,
"author_profile": "https://Stackoverflow.com/users/5863938",
"pm_score": 5,
"selected": false,
"text": "netstat -anon | findstr 1234\n"
},
{
"answer_id": 54504013,
"author": "Angel Venchev",
"author_id": 1571349,
"author_profile": "https://Stackoverflow.com/users/1571349",
"pm_score": 3,
"selected": false,
"text": "$P = Get-Process -Id (Get-NetTCPConnection -LocalPort 3000).OwningProcess; Stop-Process $P.Id\n kill Stop-Process"
},
{
"answer_id": 56059282,
"author": "Anatole ABE",
"author_id": 2022273,
"author_profile": "https://Stackoverflow.com/users/2022273",
"pm_score": 4,
"selected": false,
"text": "cmd netstat -aon | findstr '[port_number]'\n [port_number] tasklist | findstr '[PID]'\n [PID]"
},
{
"answer_id": 58009506,
"author": "lczapski",
"author_id": 11733759,
"author_profile": "https://Stackoverflow.com/users/11733759",
"pm_score": 2,
"selected": false,
"text": "for /f \"tokens=3 delims=LISTENING\" %i in ('netstat -ano ^| findStr \"8080\" ^| findStr \"[\"') do @tasklist /nh /fi \"pid eq %i\"\n for /f \"tokens=3 delims=LISTENING\" %i in ('netstat -ano ^| findStr \"8080\" ^| findStr \"[\"') do @Taskkill /F /IM %i\n %i %%i portInfo.bat for /f \"tokens=3 delims=LISTENING\" %%i in (\n 'netstat -ano ^| findStr \"%1\" ^| findStr \"[\"'\n) do @tasklist /nh /fi \"pid eq %%i\"\n portKill.bat for /f \"tokens=3 delims=LISTENING\" %%i in (\n 'netstat -ano ^| findStr \"%1\" ^| findStr \"[\"'\n) do @Taskkill /F /IM %%i\n portInfo.bat 8080 portKill.bat 8080"
},
{
"answer_id": 62889072,
"author": "jiz",
"author_id": 4894302,
"author_profile": "https://Stackoverflow.com/users/4894302",
"pm_score": 3,
"selected": false,
"text": "netstat -aon | findstr '8000'\n taskkill /pid pid /f\n"
},
{
"answer_id": 63375462,
"author": "Benjamin Wen",
"author_id": 5492956,
"author_profile": "https://Stackoverflow.com/users/5492956",
"pm_score": 4,
"selected": false,
"text": "lsof -i tcp:8080 PID kill -9 <PID>"
},
{
"answer_id": 64988942,
"author": "Daniel Genezini",
"author_id": 4058784,
"author_profile": "https://Stackoverflow.com/users/4058784",
"pm_score": 3,
"selected": false,
"text": "netsh int ipv4 show excludedportrange protocol=tcp\n"
},
{
"answer_id": 66233917,
"author": "David Jesus",
"author_id": 5869384,
"author_profile": "https://Stackoverflow.com/users/5869384",
"pm_score": 5,
"selected": false,
"text": "netstat -aof | findstr :8080"
},
{
"answer_id": 71288879,
"author": "Oliver Gaida",
"author_id": 11000412,
"author_profile": "https://Stackoverflow.com/users/11000412",
"pm_score": 3,
"selected": false,
"text": "Get-NetTCPConnection -State Listen | Select-Object -Property *, `\n @{'Name' = 'ProcessName';'Expression'={(Get-Process -Id $_.OwningProcess).Name}} `\n | select ProcessName,LocalAddress,LocalPort\n ProcessName LocalAddress LocalPort\n----------- ------------ ---------\nservices :: 49755\njhi_service ::1 49673\nsvchost :: 135\nservices 0.0.0.0 49755\nspoolsv 0.0.0.0 49672\n Get-NetUDPEndpoint | Select-Object -Property *, `\n @{'Name' = 'ProcessName';'Expression'={(Get-Process -Id $_.OwningProcess).Name}} `\n | select ProcessName,LocalAddress,LocalPort\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
48,203 |
<p>Simply, are there any Java Developer specific Linux distros?</p>
|
[
{
"answer_id": 698093,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "[package manager command to install] jdk\n // begin hypocritical personal recomendation\n // end hypocritical personal recomendation\n"
},
{
"answer_id": 65344183,
"author": "perymerdeka",
"author_id": 13742665,
"author_profile": "https://Stackoverflow.com/users/13742665",
"pm_score": 0,
"selected": false,
"text": "sudo apt-get install default-jdk default-jre\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
] |
48,224 |
<p>I need to automate a process involving a website that is using a login form. I need to capture some data in the pages following the login page.</p>
<p>I know how to screen-scrape normal pages, but not those behind a secure site.</p>
<ol>
<li>Can this be done with the .NET WebClient class?
<ul>
<li>How would I automatically login?</li>
<li>How would I keep logged in for the other pages?</li>
</ul></li>
</ol>
|
[
{
"answer_id": 48228,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<form name=\"loginForm\" method=\"post\" Action=\"target_page.html\">\n <input type=\"Text\" name=\"Username\">\n <input type=\"Password\" name=\"Password\">\n</form>\n"
},
{
"answer_id": 48243,
"author": "Andrew Whitehouse",
"author_id": 4890,
"author_profile": "https://Stackoverflow.com/users/4890",
"pm_score": 0,
"selected": false,
"text": " def client = new HttpClient()\n\n def credentials = new UsernamePasswordCredentials( \"username\", \"password\" )\n def authScope = new AuthScope(\"api.del.icio.us\", 443, AuthScope.ANY_REALM)\n client.getState().setCredentials( authScope, credentials )\n\n def url = \"https://api.del.icio.us/v1/posts/get\"\n\n def method = new PostMethod( url )\n method.addParameter( \"tag\", tag )\n client.executeMethod( method )\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1583/"
] |
48,225 |
<p>I want to put songs on a web page and have a little play button, like you can see on Last.fm or Pandora. There can be multiple songs listed on the site, and if you start playing a different song with one already playing, it will pause the first track and begin playing the one you just clicked on. I think they use Flash for this, and I could probably implement it in a few hours, but is there already code I could use for this? Maybe just a flash swf file that you stick hidden on a web page with a basic Javascript API that I can use to stream mp3 files?</p>
<p>Also, what about WMA or AAC files? Is there a universal solution that will play these 3 file types?</p>
<hr>
<p><a href="http://musicplayer.sourceforge.net/" rel="nofollow noreferrer">http://musicplayer.sourceforge.net/</a></p>
|
[
{
"answer_id": 48231,
"author": "Sean",
"author_id": 4919,
"author_profile": "https://Stackoverflow.com/users/4919",
"pm_score": 1,
"selected": false,
"text": "flash mp3 player"
},
{
"answer_id": 48368,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": "<OBJECT id=\"VIDEO\" width=\"320\" height=\"240\" \n style=\"position:absolute; left:0;top:0;\"\n CLASSID=\"CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6\"\n type=\"application/x-oleobject\">\n\n <PARAM NAME=\"URL\" VALUE=\"your file or url\">\n <PARAM NAME=\"SendPlayStateChangeEvents\" VALUE=\"True\">\n <PARAM NAME=\"AutoStart\" VALUE=\"True\">\n <PARAM name=\"uiMode\" value=\"none\">\n <PARAM name=\"PlayCount\" value=\"9999\">\n</OBJECT>\n <script type=\"javascript\">\nobj = document.getElementById(\"VIDEO\"); //Where video is the id of the object above.\nobj.URL=\"filename\"; //You can use this to both start and change the current file.\nobj.controls.stop(); //Will stop\nobj.controls.Pause(); //Pause\n</script>\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] |
48,235 |
<p>I really enjoy Chrome, and the sheer exercise of helping a port would boost my knowledge-base.</p>
<p>Where do I start?</p>
<p>What are the fundamental similarities and differences between the code which will operated under Windows and Linux?</p>
<p>What skills and software do I need?</p>
<hr />
<h3>Note:</h3>
<p>The official website is Visual Studio oriented!<br />
Netbeans or Eclipse are my only options.<br />
I will not pay Microsoft to help an Open Source project.</p>
|
[
{
"answer_id": 48236,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": false,
"text": "$ sudo apt-get install subversion pkg-config python perl g++ bison flex gperf libnss3-dev\n"
},
{
"answer_id": 692397,
"author": "Paul",
"author_id": 37865,
"author_profile": "https://Stackoverflow.com/users/37865",
"pm_score": 5,
"selected": true,
"text": "deb http://ppa.launchpad.net/chromium-daily/ppa/ubuntu jaunty main\ndeb-src http://ppa.launchpad.net/chromium-daily/ppa/ubuntu jaunty main\n aptitude update\naptitude install chromium-browser\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
] |
48,239 |
<p>Is there any way to get the ID of the element that fires an event?</p>
<p>I'm thinking something like:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
$("a").click(function() {
var test = caller.id;
alert(test.val());
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="starterkit/jquery.js"></script>
<form class="item" id="aaa">
<input class="title"></input>
</form>
<form class="item" id="bbb">
<input class="title"></input>
</form></code></pre>
</div>
</div>
</p>
<p>Except of course that the var <code>test</code> should contain the id <code>"aaa"</code>, if the event is fired from the first form, and <code>"bbb"</code>, if the event is fired from the second form.</p>
|
[
{
"answer_id": 48242,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 6,
"selected": false,
"text": "(this) 'this'"
},
{
"answer_id": 48684,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 11,
"selected": true,
"text": "event.target event $(document).ready(function() {\n $(\"a\").click(function(event) {\n alert(event.target.id);\n });\n});\n this $(this) $(document).ready(function() {\n $(\"a\").click(function(event) {\n // this.append wouldn't work\n $(this).append(\" Clicked\");\n });\n});\n"
},
{
"answer_id": 3624837,
"author": "Gemma",
"author_id": 437705,
"author_profile": "https://Stackoverflow.com/users/437705",
"pm_score": 8,
"selected": false,
"text": "jQuery(\"classNameofDiv\").click(function() {\n var contentPanelId = jQuery(this).attr(\"id\");\n alert(contentPanelId);\n});\n"
},
{
"answer_id": 7389282,
"author": "SMut",
"author_id": 940734,
"author_profile": "https://Stackoverflow.com/users/940734",
"pm_score": 5,
"selected": false,
"text": "ID $(\"table\").delegate(\"tr\", \"click\", function() {\n var id=$(this).attr('id');\n alert(\"ID:\"+id); \n});\n"
},
{
"answer_id": 9825688,
"author": "Morvael",
"author_id": 1286358,
"author_profile": "https://Stackoverflow.com/users/1286358",
"pm_score": 4,
"selected": false,
"text": "var $el = $(event.target);\n $(\"tr\").click(function(event){\n var $td = $(event.target);\n});\n"
},
{
"answer_id": 11562933,
"author": "Ally",
"author_id": 837649,
"author_profile": "https://Stackoverflow.com/users/837649",
"pm_score": 7,
"selected": false,
"text": "var target = event.target || event.srcElement;\nvar id = target.id\n event.target event.srcElement"
},
{
"answer_id": 13211759,
"author": "Darius",
"author_id": 1696922,
"author_profile": "https://Stackoverflow.com/users/1696922",
"pm_score": 3,
"selected": false,
"text": "$('*').live('click', function() {\n console.log(this.id);\n return false;\n});\n"
},
{
"answer_id": 13252233,
"author": "dsch",
"author_id": 1803250,
"author_profile": "https://Stackoverflow.com/users/1803250",
"pm_score": 7,
"selected": false,
"text": "$(event.target).id $(event.target)[0].id event.target.id this.id $(this).id"
},
{
"answer_id": 16912421,
"author": "vml19",
"author_id": 256988,
"author_profile": "https://Stackoverflow.com/users/256988",
"pm_score": 2,
"selected": false,
"text": "this.element.attr(\"id\")"
},
{
"answer_id": 19882381,
"author": "Marcel Verwey",
"author_id": 2603657,
"author_profile": "https://Stackoverflow.com/users/2603657",
"pm_score": 3,
"selected": false,
"text": "z-index $(\"#mydiv li\").click(function(){\n\n ClickedElement = this.id;\n alert(ClickedElement);\n});\n id li"
},
{
"answer_id": 21684620,
"author": "Moji",
"author_id": 639390,
"author_profile": "https://Stackoverflow.com/users/639390",
"pm_score": 2,
"selected": false,
"text": "jQuery(this).attr(\"id\");\n alert(this.id);\n"
},
{
"answer_id": 28245626,
"author": "shmuli",
"author_id": 2399980,
"author_profile": "https://Stackoverflow.com/users/2399980",
"pm_score": 2,
"selected": false,
"text": "var buttons = document.getElementsByTagName('button');\nvar buttonsLength = buttons.length;\nfor (var i = 0; i < buttonsLength; i++){\n buttons[i].addEventListener('click', clickResponse, false);\n};\nfunction clickResponse(){\n // do something based on button selection here...\n alert(this.id);\n}\n"
},
{
"answer_id": 30925343,
"author": "Isochronous",
"author_id": 462210,
"author_profile": "https://Stackoverflow.com/users/462210",
"pm_score": 3,
"selected": false,
"text": "<ul>\n <li data-id=\"1\">\n <span>Item 1</span>\n </li>\n <li data-id=\"2\">\n <span>Item 2</span>\n </li>\n <li data-id=\"3\">\n <span>Item 3</span>\n </li>\n <li data-id=\"4\">\n <span>Item 4</span>\n </li>\n <li data-id=\"5\">\n <span>Item 5</span>\n </li>\n</ul>\n $(document).ready(function() {\n $('ul').on('click li', function(event) {\n var $target = $(event.target),\n itemId = $target.data('id');\n\n //do something with itemId\n });\n});\n undefined <span> <span> $(document).ready(function() {\n $('ul').on('click li', function(event) {\n var $target = $(event.target).is('li') ? $(event.target) : $(event.target).closest('li'),\n itemId = $target.data('id');\n\n //do something with itemId\n });\n});\n $(document).ready(function() {\n $('ul').on('click li', function(event) {\n var $target = $(event.target),\n itemId;\n\n $target = $target.is('li') ? $target : $target.closest('li');\n itemId = $target.data('id');\n\n //do something with itemId\n });\n});\n .is() .closest(selector) .find(selector) .first() .find(selector).first() .first() .closest() .find()"
},
{
"answer_id": 38762705,
"author": "Error404",
"author_id": 6304917,
"author_profile": "https://Stackoverflow.com/users/6304917",
"pm_score": 2,
"selected": false,
"text": "this $(this).attr(\"id\")\n $(this).prop(\"id\")\n"
},
{
"answer_id": 39673488,
"author": "Basant Rules",
"author_id": 2243229,
"author_profile": "https://Stackoverflow.com/users/2243229",
"pm_score": 3,
"selected": false,
"text": " $(\"table\").on(\"tr\", \"click\", function() {\n var id=$(this).attr('id');\n alert(\"ID:\"+id); \n });\n"
},
{
"answer_id": 40043918,
"author": "Maciej Sikora",
"author_id": 4420812,
"author_profile": "https://Stackoverflow.com/users/4420812",
"pm_score": 5,
"selected": false,
"text": "event.currentTarget\n event.target\n document.querySelector(\"someSelector\").addEventListener(function(event){\n\n console.log(event.target);\n console.log(event.currentTarget);\n\n});\n"
},
{
"answer_id": 48621503,
"author": "xeon",
"author_id": 5432368,
"author_profile": "https://Stackoverflow.com/users/5432368",
"pm_score": 1,
"selected": false,
"text": " $('select').change(\n function() {\n var val = this.value;\n var id = jQuery(this).attr(\"id\");\n console.log(\"value changed\" + String(val)+String(id));\n }\n );\n"
},
{
"answer_id": 52881201,
"author": "Cris",
"author_id": 1978831,
"author_profile": "https://Stackoverflow.com/users/1978831",
"pm_score": 4,
"selected": false,
"text": "$('selector').on('click',function(e){\n log(e.currentTarget.id);\n });\n"
},
{
"answer_id": 53251428,
"author": "DAB",
"author_id": 2004265,
"author_profile": "https://Stackoverflow.com/users/2004265",
"pm_score": 0,
"selected": false,
"text": "event this.element.attr(\"id\")"
},
{
"answer_id": 54894197,
"author": "David Dehghan",
"author_id": 705945,
"author_profile": "https://Stackoverflow.com/users/705945",
"pm_score": 0,
"selected": false,
"text": "myClickHandler($event) {\n this.selectedElement = <Element>$event.target;\n console.log(this.selectedElement.id)\n this.selectedElement.classList.remove('some-class');\n}\n <div class=\"list-item\" (click)=\"myClickHandler($event)\">...</div>\n"
},
{
"answer_id": 57583976,
"author": "chings228",
"author_id": 749827,
"author_profile": "https://Stackoverflow.com/users/749827",
"pm_score": 3,
"selected": false,
"text": "$(\".classobj\").click(function(e){\n console.log(e.currentTarget.id);\n})\n"
},
{
"answer_id": 62602366,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 2,
"selected": false,
"text": "aaa.onclick = handler;\nbbb.onclick = handler;\n\nfunction handler() { \n var test = this.id; \n console.log(test) \n}\n aaa.onclick = handler;\nbbb.onclick = handler;\n\nfunction handler() { \n var test = this.id; \n console.log(test) \n} <form class=\"item\" id=\"aaa\">\n <input class=\"title\"/>\n</form>\n<form class=\"item\" id=\"bbb\">\n <input class=\"title\"/>\n</form>"
},
{
"answer_id": 64854320,
"author": "vr_driver",
"author_id": 1190051,
"author_profile": "https://Stackoverflow.com/users/1190051",
"pm_score": 0,
"selected": false,
"text": "<script>\n $(document).ready(function() {\n $(window).keydown(function(event){\n if(event.keyCode == 13) {\n //There are 2 textarea forms that need the enter key to work.\n if((event.target.id==\"CommentsForOnAir\") || (event.target.id==\"CommentsForOnline\"))\n {\n // Prevent the form from triggering, but allowing multi-line to still work.\n }\n else\n {\n event.preventDefault();\n return false;\n } \n }\n });\n });\n</script>\n\n<textarea class=\"form-control\" rows=\"10\" cols=\"50\" id=\"CommentsForOnline\" name=\"CommentsForOnline\" type=\"text\" size=\"60\" maxlength=\"2000\"></textarea>\n"
},
{
"answer_id": 74002779,
"author": "MolyOxide",
"author_id": 13019063,
"author_profile": "https://Stackoverflow.com/users/13019063",
"pm_score": 0,
"selected": false,
"text": "$(this).attr(\"id\");\n $(event.target).attr(\"id\");\n $(this).attr(\"id\") $(event.target).attr(\"id\") <div> <p> $(event.target).attr(\"id\") <div> $(event.target).attr(\"id\") <p>"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1090/"
] |
48,240 |
<p>I am working with an API that provides bus arrival data. For every request, I get back (among other things) a list of which routes serve the stop in question. For example, if the list includes result for bus route #1, 2, and 5, then I know that those serve this stop.</p>
<p>I have a many-to-many relationship set up between Route and Stop, and I want to dynamically check and update these associations on every request. There is no "master list" of which routes serve which stops, so this seems like the best way to get this data.</p>
<p>I believe that the way I'm doing it now is very inefficient:</p>
<pre><code># routes is an array of [number, destination] that I build while iterating over the data
routes.uniq.each do |route|
number = route[0]
destination = route[1]
r = Route.find_by_number_and_destination(number, destination)
if !r
r = Route.new :number => number, :destination => destination
r.save
end
# I have to check if it already exists because I can't find a way
# to create a uniqueness constraint on the join table with 2 foreign keys
r.stops << stop unless r.stops.include? stop
end
</code></pre>
<p>Basically, I have to do 2 things for every route I find:
1) Create it if it doesn't already exist, 2) Add a relationship to the current stop if it doesn't already exist.</p>
<p>Is there a better way to do this, for example by getting a bunch of the data in memory and doing some of the processing on the app server side, in order to avoid the multitude of database calls I'm currently doing?</p>
|
[
{
"answer_id": 48529,
"author": "Can Berk Güder",
"author_id": 2119,
"author_profile": "https://Stackoverflow.com/users/2119",
"pm_score": 1,
"selected": false,
"text": "class Route < ActiveRecord::Base\n has_and_belongs_to_many :stops\n belongs_to :stop, :foreign_key => 'destination_id'\nend\n\nclass Stop < ActiveRecorde::Base\n has_and_belongs_to_many :routes\nend\n create_table :routes do |t|\n t.integer :destination_id\n # Any other information you want to store about routes\nend\n\ncreate_table :stops do |t|\n # Any other information you want to store about stops\nend\n\ncreate_table :routes_stops, :primary_key => [:route_id, :stop_id] do |t|\n t.integer :route_id\n t.integer :stop_id\nend\n # First, find all the relevant routes, just for caching.\nRoute.find(numbers)\n\nr = Route.find(number)\nr.destination_id = destination\nr.stops << stop\n"
},
{
"answer_id": 9577609,
"author": "GeekOnCoffee",
"author_id": 262162,
"author_profile": "https://Stackoverflow.com/users/262162",
"pm_score": 0,
"selected": false,
"text": "routes.uniq.each do |number, destination|\n\n r = Route.find_or_create_by_number_and_destination(route[0], destination)\n\n r.stops << stop unless r.stops.include? stop\n\nend\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124/"
] |
48,249 |
<p>Is there a way to embed a browser in Java? more specifically, is there a library that can emulate a browser?</p>
|
[
{
"answer_id": 10381446,
"author": "11684",
"author_id": 1087848,
"author_profile": "https://Stackoverflow.com/users/1087848",
"pm_score": 1,
"selected": false,
"text": "JEditorPane EditorKit"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
] |
48,253 |
<p>I know PHP scripts don't actually compile until they are run. However, say I want to create a small simple program and compile it to a binary without requiring the PHP binary. How could I do this?</p>
<p>I've seen a few IDE's out there that would do this, but either they are all for windows or the Linux versions don't actually build properly.<br>
What I would like is something like py2exe that does it in the script itself.</p>
|
[
{
"answer_id": 48264,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/php\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4985/"
] |
48,278 |
<p>I am using the webbrowser control in winforms and discovered now that background images which I apply with css are not included in the printouts.</p>
<p>Is there a way to make the webbrowser print the background of the displayed document too?</p>
<p>Edit:
Since I wanted to do this programatically, I opted for this solution:</p>
<pre><code>using Microsoft.Win32;
...
RegistryKey regKey = Registry.CurrentUser
.OpenSubKey("Software")
.OpenSubKey("Microsoft")
.OpenSubKey("Internet Explorer")
.OpenSubKey("Main");
//Get the current setting so that we can revert it after printjob
var defaultValue = regKey.GetValue("Print_Background");
regKey.SetValue("Print_Background", "yes");
//Do the printing
//Revert the registry key to the original value
regKey.SetValue("Print_Background", defaultValue);
</code></pre>
<p>Another way to handle this might be to just read the value, and notify the user to adjust this himself before printing. I have to agree that tweaking with the registry like this is not a good practice, so I am open for any suggestions.</p>
<p>Thanks for all your feedback</p>
|
[
{
"answer_id": 48292,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "* File > Page Setup > Check Off \"Print Background\"\n* File > Print Preview\n * Tools > Internet Options > Advanced > Printing\n* Check Off \"Print Background Images and Colors\"\n * File > Print Options > Check Off \"Print Page Background\"\n* File > Print Preview (You may have to scroll down/up to see it refresh)\n"
},
{
"answer_id": 51298,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": true,
"text": "Registry.LocalMachine\n LocalUser LocalMachine"
},
{
"answer_id": 2475422,
"author": "icliff",
"author_id": 297132,
"author_profile": "https://Stackoverflow.com/users/297132",
"pm_score": 0,
"selected": false,
"text": "var sh = new ActiveXObject(\"WScript.Shell\");\nkey = \"HKEY_CURRENT_USER\\\\Software\\\\Microsoft\\\\Internet Explorer\\\\Main\\\\Print_Background\";\nvar defaultValue = sh.RegRead(key); \nsh.RegWrite(key,\"yes\",\"REG_SZ\");\ndocument.frames['detailFrame'].focus(); \ndocument.frames['detailFrame'].print();\nsh.RegWrite(key,defaultValue,\"REG_SZ\"); \nreturn false; \n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4582/"
] |
48,288 |
<p>I've been trying to understand <a href="http://msdn.microsoft.com/en-gb/library/system.diagnostics.process.mainwindowhandle.aspx" rel="nofollow noreferrer">Process.MainWindowHandle</a>.</p>
<p>According to MSDN; "The main window is the window that is created when the process is started. After initialization, other windows may be opened, including the Modal and TopLevel windows, but <em>the first window associated with the process remains the main window</em>." (Emphasis added)</p>
<p>But while debugging I noticed that MainWindowHandle seemed to change value... which I wasn't expecting, especially after consulting the documentation above.</p>
<p>To confirm the behaviour I created a standalone WinForms app with a timer to check the MainWindowHandle of the "DEVENV" (Visual Studio) process every 100ms.</p>
<p>Here's the interesting part of this test app...</p>
<pre><code> IntPtr oldHWnd = IntPtr.Zero;
void GetMainwindowHandle()
{
Process[] processes = Process.GetProcessesByName("DEVENV");
if (processes.Length!=1)
return;
IntPtr newHWnd = processes[0].MainWindowHandle;
if (newHWnd != oldHWnd)
{
oldHWnd = newHWnd;
textBox1.AppendText(processes[0].MainWindowHandle.ToString("X")+"\r\n");
}
}
private void timer1Tick(object sender, EventArgs e)
{
GetMainwindowHandle();
}
</code></pre>
<p>You can see the value of MainWindowHandle changing when you (for example) click on a drop-down menu inside VS.</p>
<p><img src="https://i.stack.imgur.com/r54iB.png" alt="MainWindowHandleMystery"></p>
<p>Perhaps I've misunderstood the documentation. </p>
<p>Can anyone shed light?</p>
|
[
{
"answer_id": 48318,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 5,
"selected": true,
"text": "private bool IsMainWindow(IntPtr handle)\n{\n return (!(NativeMethods.GetWindow(new HandleRef(this, handle), 4) != IntPtr.Zero) \n && NativeMethods.IsWindowVisible(new HandleRef(this, handle)));\n}\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4200/"
] |
48,307 |
<p>I would like to know how people implement the following data structures in C# without using the base class library implementations:-</p>
<ul>
<li>Linked List</li>
<li>Hash Table</li>
<li>Binary Search Tree</li>
<li>Red-Black Tree</li>
<li>B-Tree</li>
<li>Binomial Heap</li>
<li>Fibonacci Heap</li>
</ul>
<p>and any other fundamental data structures people can think of!</p>
<p>I am curious as I want to improve my understanding of these data structures and it'd be nice to see C# versions rather than the typical C examples out there on the internet!</p>
|
[
{
"answer_id": 48319,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "Vector List<T>"
},
{
"answer_id": 48464,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": " class BSTNode<T> where T : IComparable<T>\n {\n private BSTNode<T> _left = null;\n private BSTNode<T> _right = null; \n private T _value = default(T);\n\n public T Value\n {\n get { return this._value; }\n set { this._value = value; }\n }\n\n public BSTNode<T> Left\n {\n get { return _left; }\n set { this._left = value; }\n }\n\n public BSTNode<T> Right\n {\n get { return _right; }\n set { this._right = value; }\n } \n }\n class BinarySearchTree<T> where T : IComparable<T>\n {\n private BSTNode<T> _root = null;\n private int _count = 0;\n\n public virtual void Clear()\n {\n _root = null;\n _count = 0;\n }\n\n public virtual int Count\n {\n get { return _count; }\n }\n\n public virtual void Add(T value)\n {\n BSTNode<T> newNode = new BSTNode<T>();\n int compareResult = 0;\n\n newNode.Value = value;\n\n if (_root == null)\n {\n this._count++;\n _root = newNode;\n }\n else\n {\n BSTNode<T> current = _root;\n BSTNode<T> parent = null;\n\n while (current != null)\n {\n compareResult = current.Value.CompareTo(newNode.Value);\n\n if (compareResult > 0)\n {\n parent = current;\n current = current.Left;\n }\n else if (compareResult < 0)\n {\n parent = current;\n current = current.Right;\n }\n else\n {\n // Node already exists\n throw new ArgumentException(\"Duplicate nodes are not allowed.\");\n }\n }\n\n this._count++;\n\n compareResult = parent.Value.CompareTo(newNode.Value);\n if (compareResult > 0)\n {\n parent.Left = newNode;\n }\n else\n {\n parent.Right = newNode;\n }\n }\n }\n\n public virtual BSTNode<T> FindByValue(T value)\n {\n BSTNode<T> current = this._root;\n\n if (current == null)\n return null; // Tree is empty.\n else\n {\n while (current != null)\n {\n int result = current.Value.CompareTo(value);\n if (result == 0)\n {\n // Found the corrent Node.\n return current;\n }\n else if (result > 0)\n {\n current = current.Left;\n }\n else\n {\n current = current.Right;\n }\n }\n\n return null;\n }\n }\n\n public virtual void Delete(T value)\n {\n\n BSTNode<T> current = this._root;\n BSTNode<T> parent = null;\n\n int result = current.Value.CompareTo(value);\n\n while (result != 0 && current != null)\n {\n if (result > 0)\n {\n parent = current;\n current = current.Left;\n }\n else if (result < 0)\n {\n parent = current;\n current = current.Right;\n }\n\n result = current.Value.CompareTo(value);\n }\n\n if (current == null)\n throw new ArgumentException(\"Cannot find item to delete.\");\n\n\n\n if (current.Right == null)\n {\n if (parent == null)\n this._root = current.Left;\n else\n {\n result = parent.Value.CompareTo(current.Value);\n if (result > 0)\n {\n parent.Left = current.Left;\n }\n else if (result < 0)\n {\n parent.Right = current.Left;\n }\n }\n }\n else if (current.Right.Left == null)\n {\n if (parent == null)\n this._root = current.Right;\n else\n {\n result = parent.Value.CompareTo(current.Value);\n if (result > 0)\n {\n parent.Left = current.Right;\n }\n else if (result < 0)\n {\n parent.Right = current.Right;\n }\n }\n }\n else\n {\n\n BSTNode<T> furthestLeft = current.Right.Left;\n BSTNode<T> furthestLeftParent = current.Right;\n\n while (furthestLeft.Left != null)\n {\n furthestLeftParent = furthestLeft;\n furthestLeft = furthestLeft.Left;\n }\n\n furthestLeftParent.Left = furthestLeft.Right;\n\n furthestLeft.Left = current.Left;\n furthestLeft.Right = current.Right;\n\n if (parent != null)\n {\n result = parent.Value.CompareTo(current.Value);\n if (result > 0)\n {\n parent.Left = furthestLeft;\n }\n else if (result < 0)\n {\n parent.Right = furthestLeft;\n }\n }\n else\n {\n this._root = furthestLeft;\n }\n }\n\n this._count--;\n }\n }\n}\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] |
48,340 |
<p>i have a wcf service that does an operation. and in this operation there could be a fault. i have stated that there could be a fault in my service contract. </p>
<p>here is the code below;</p>
<pre><code>public void Foo()
{
try
{
DoSomething(); // throws FaultException<FooFault>
}
catch (FaultException)
{
throw;
}
catch (Exception ex)
{
myProject.Exception.Throw<FooFault>(ex);
}
}
</code></pre>
<p>in service contract;</p>
<pre><code>[FaultException(typeof(FooFault))]
void Foo();
</code></pre>
<p>when a FaultException was thrown by DoSomething() method while i was running the application, firstly the exception was caught at "catch(Exception ex)" line and breaks in there. then when i pressed f5 again, it does what normally it has to. i wonder why that break exists? and if not could it be problem on publish?</p>
|
[
{
"answer_id": 284215,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 1,
"selected": false,
"text": "throw;\n"
},
{
"answer_id": 295188,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": -1,
"selected": false,
"text": " // Begin try\n DoSomething(); // throws FaultException<FooFault>\n // End try\n if (exceptionOccured)\n {\n if(exception is FaultException) // FE catch block.\n {\n throw;\n // Goto Exit\n }\n if(exception is Exception) // EX catch block\n {\n throw new FaultException<FooFault>();\n // Goto Exit\n }\n }\n\n // Exit\n try\n {\n try\n {\n DoSomething(); // throws FaultException<FooFault>\n }\n catch (Exception ex)\n {\n if (ex is FaultException<FooFault>)\n throw;\n else\n myProject.Exception.Throw<FooFault>(ex);\n }\n }\n catch (FaultException)\n {\n throw;\n }\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4215/"
] |
48,356 |
<p>Greetings, I'm trying to find a way to 'unbind' a socket from a particular IP/Port combination. My pseudocode looks like this:</p>
<pre><code>ClassA a = new ClassA(); //(class A instantiates socket and binds it to 127.0.0.1:4567)
//do something
//...much later, a has been garbage-collected away.
ClassA aa = new ClassA(); //crash here.
</code></pre>
<p>At this point, .Net informs me that I've already got a socket bound to 127.0.0.1:4567, which is technically true. But no matter what code I put in ClassA's destructor, or no matter what functions I call on the socket (I've tried .Close() and .Disconnect(true)), the socket remains proudly bound to 127.0.0.1:4567. What do I do to be able to 'un-bind' the socket?</p>
<hr>
<p>EDIT: I'm not relying solely on garbage collection (though I tried that approach as well). I tried calling a.Close() or a.Disconnect() and only then instantiating aa; this doesn't solve the problem.</p>
<hr>
<p>EDIT: I've also tried implementing IDisposable, but the code never got there without my calling the method (which was the equivalent of earlier attempts, as the method would simply try .Close and .Disconnect). Let me try calling .Dispose directly and get back to you.</p>
<hr>
<p>EDIT (lots of edits, apologies): Implementing IDisposable and calling a.Dispose() from where 'a' loses scope doesn't work - my Dispose implementation still has to call either .Close or .Disconnect(true) (or .Shutdown(Both)) but none of those unbind the socket.</p>
<p>Any help would be appreciated!</p>
|
[
{
"answer_id": 48362,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 0,
"selected": false,
"text": "Socket.Close() using (ClassA a = new ClassA()) \n{\n // code goes here\n}\n// 'a' is now disposed and the socket is closed\n"
},
{
"answer_id": 48383,
"author": "AlexeyMK",
"author_id": 5021,
"author_profile": "https://Stackoverflow.com/users/5021",
"pm_score": 3,
"selected": true,
"text": "socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress, true);\n"
}
] |
2008/09/07
|
[
"https://Stackoverflow.com/questions/48356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5021/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.