qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
72,240 | <p>How can I call a BizTalk Orchestration dynamically knowing the Orchestration name? </p>
<p>The call Orchestration shapes need to know the name and parameters of Orchestrations at design time. I've tried using 'call' XLang keyword but it also required Orchestration name as Design Time like in expression shape, we can write as </p>
<pre><code>call BizTalkApplication1.Orchestration1(param1,param2);
</code></pre>
<p>I'm looking for some way to specify calling orchestration name, coming from the incoming message or from SSO config store.</p>
<p>EDIT: I'musing BizTalk 2006 R1 (ESB Guidance is for R2 and I didn't get how it could solve my problem) </p>
| [
{
"answer_id": 72353,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Look at ESB Guidance (www.codeplex.com/esb) This package provides the functionality you are looking for</p>\n"
},
{
"answer_id": 92367,
"author": "tomasr",
"author_id": 10292,
"author_profile": "https://Stackoverflow.com/users/10292",
"pm_score": 3,
"selected": true,
"text": "<p>The way I've accomplished something similar in the past is by using direct binding ports in the orchestrations and letting the MsgBox do the dirty work for me. Basically, it goes something like this:</p>\n\n<ol>\n<li>Make the callable orchestrations use a direct-bound port attached to your activating receive shape.</li>\n<li>Set up a filter expression on your activating receive shape with a custom context-based property and set it equal to a value that uniquely identifies the orchestration (such as the orchestration name or whatever)</li>\n<li>In the calling orchestration, create the message you'll want to use to fire the new orchestration. In that message, set your custom context property to the value that matches the filter used in the specific orchestration you want to fire.</li>\n<li>Send the message through a direct-bound send port so that it gets sent to the MsgBox directly and the Pub/Sub mechanisms in BizTalk will take care of the rest.</li>\n</ol>\n\n<p>One thing to watch out in step 4: To have this work correctly, you will need to create a new Correlation Set type that includes your custom context property, and then make sure that the direct-bound send port \"follows\" the correlation set on the send. Otherwise, the custom property will only be written (and not promoted) to the msg context and the routing will fail.</p>\n\n<p>Hope this helps!</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7722/"
]
| How can I call a BizTalk Orchestration dynamically knowing the Orchestration name?
The call Orchestration shapes need to know the name and parameters of Orchestrations at design time. I've tried using 'call' XLang keyword but it also required Orchestration name as Design Time like in expression shape, we can write as
```
call BizTalkApplication1.Orchestration1(param1,param2);
```
I'm looking for some way to specify calling orchestration name, coming from the incoming message or from SSO config store.
EDIT: I'musing BizTalk 2006 R1 (ESB Guidance is for R2 and I didn't get how it could solve my problem) | The way I've accomplished something similar in the past is by using direct binding ports in the orchestrations and letting the MsgBox do the dirty work for me. Basically, it goes something like this:
1. Make the callable orchestrations use a direct-bound port attached to your activating receive shape.
2. Set up a filter expression on your activating receive shape with a custom context-based property and set it equal to a value that uniquely identifies the orchestration (such as the orchestration name or whatever)
3. In the calling orchestration, create the message you'll want to use to fire the new orchestration. In that message, set your custom context property to the value that matches the filter used in the specific orchestration you want to fire.
4. Send the message through a direct-bound send port so that it gets sent to the MsgBox directly and the Pub/Sub mechanisms in BizTalk will take care of the rest.
One thing to watch out in step 4: To have this work correctly, you will need to create a new Correlation Set type that includes your custom context property, and then make sure that the direct-bound send port "follows" the correlation set on the send. Otherwise, the custom property will only be written (and not promoted) to the msg context and the routing will fail.
Hope this helps! |
72,242 | <p>The page <em><a href="http://www.codinghorror.com/blog/archives/001167.html" rel="noreferrer">Protecting Your Cookies: HttpOnly</a></em> explains why making HttpOnly cookies is a good idea.</p>
<p>How do I set this property in Ruby on Rails?</p>
| [
{
"answer_id": 72287,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 3,
"selected": false,
"text": "<p>Just set :http_only to true as described in the <a href=\"http://dev.rubyonrails.org/changeset/7525\" rel=\"noreferrer\">changelog</a>.</p>\n"
},
{
"answer_id": 72621,
"author": "Laurie Young",
"author_id": 7473,
"author_profile": "https://Stackoverflow.com/users/7473",
"pm_score": 6,
"selected": true,
"text": "<p>Set the 'http_only' option in the hash used to set a cookie</p>\n\n<p>e.g. <pre>cookies[\"user_name\"] = { :value => \"david\", :httponly => true }</pre></p>\n\n<p>or, in Rails 2:</p>\n\n<p>e.g. <pre>cookies[\"user_name\"] = { :value => \"david\", :http_only => true }</pre></p>\n"
},
{
"answer_id": 168326,
"author": "Pelle",
"author_id": 10724,
"author_profile": "https://Stackoverflow.com/users/10724",
"pm_score": 1,
"selected": false,
"text": "<p>I also wrote a patch that is included in Rails 2.2, which defaults the CookieStore session to be http_only. </p>\n\n<p>Unfortunately session cookies are still by default regular cookies.</p>\n"
},
{
"answer_id": 4470104,
"author": "jim",
"author_id": 468629,
"author_profile": "https://Stackoverflow.com/users/468629",
"pm_score": 4,
"selected": false,
"text": "<p>Re Laurie's answer:</p>\n\n<p>Note that the option was renamed from <code>:http_only</code> to <code>:httponly</code> (no underscore) at some point.</p>\n\n<p>In actionpack 3.0.0, that is, Ruby on Rails 3, all references to <code>:http_only</code> are gone.</p>\n\n<p>That threw me for a while.</p>\n"
},
{
"answer_id": 40474742,
"author": "ilgam",
"author_id": 3834822,
"author_profile": "https://Stackoverflow.com/users/3834822",
"pm_score": 2,
"selected": false,
"text": "<p>If you’ve a file called config/session_store.rb including this line (Rails 3+), then it’s automatically set already.\n<code>config/initializers/session_store.rb</code>:</p>\n\n<pre><code># Be sure to restart your server when you modify this file.\nRails.application.config.session_store :cookie_store, key: \"_my_application_session\"\n</code></pre>\n\n<p>Also rails allows you to set following keys:</p>\n\n<p><strong>:expires</strong> - <em>The time at which this cookie expires, as a Time object.</em></p>\n\n<p><strong>:secure</strong> - <em>Whether this cookie is only transmitted to HTTPS servers. Default is false.</em></p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7473/"
]
| The page *[Protecting Your Cookies: HttpOnly](http://www.codinghorror.com/blog/archives/001167.html)* explains why making HttpOnly cookies is a good idea.
How do I set this property in Ruby on Rails? | Set the 'http\_only' option in the hash used to set a cookie
e.g.
```
cookies["user_name"] = { :value => "david", :httponly => true }
```
or, in Rails 2:
e.g.
```
cookies["user_name"] = { :value => "david", :http_only => true }
``` |
72,264 | <p>I have a Windows C# program that uses a C++ dll for data i/o. My goal is to deploy the application as a single EXE. </p>
<p>What are the steps to create such an executable?</p>
| [
{
"answer_id": 72296,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 5,
"selected": true,
"text": "<p>Single Assembly Deployment of Managed and Unmanaged Code\nSunday, February 4, 2007</p>\n\n<p>.NET developers love XCOPY deployment. And they love single assembly components. At least I always feel kinda uneasy, if I have to use some component and need remember a list of files to also include with the main assembly of that component. So when I recently had to develop a managed code component and had to augment it with some unmanaged code from a C DLL (thx to Marcus Heege for helping me with this!), I thought about how to make it easier to deploy the two DLLs. If this were just two assemblies I could have used ILmerge to pack them up in just one file. But this doesn´t work for mixed code components with managed as well as unmanaged DLLs.</p>\n\n<p>So here´s what I came up with for a solution:</p>\n\n<p>I include whatever DLLs I want to deploy with my component´s main assembly as embedded resources.\nThen I set up a class constructor to extract those DLLs like below. The class ctor is called just once within each AppDomain so it´s a neglible overhead, I think.</p>\n\n<pre><code>namespace MyLib\n{\n public class MyClass\n {\n static MyClass()\n {\n ResourceExtractor.ExtractResourceToFile(\"MyLib.ManagedService.dll\", \"managedservice.dll\");\n ResourceExtractor.ExtractResourceToFile(\"MyLib.UnmanagedService.dll\", \"unmanagedservice.dll\");\n }\n\n ...\n</code></pre>\n\n<p>In this example I included two DLLs as resources, one being an unmanaged code DLL, and one being a managed code DLL (just for demonstration purposes), to show, how this technique works for both kinds of code.</p>\n\n<p>The code to extract the DLLs into files of their own is simple:</p>\n\n<pre><code>public static class ResourceExtractor\n{\n public static void ExtractResourceToFile(string resourceName, string filename)\n {\n if (!System.IO.File.Exists(filename))\n using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))\n using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create))\n {\n byte[] b = new byte[s.Length];\n s.Read(b, 0, b.Length);\n fs.Write(b, 0, b.Length);\n }\n }\n}\n</code></pre>\n\n<p>Working with a managed code assembly like this is the same as usual - almost. You reference it (here: ManagedService.dll) in your component´s main project (here: MyLib), but set the Copy Local property to false. Additionally you link in the assembly as an Existing Item and set the Build Action to Embedded Resource.</p>\n\n<p>For the unmanaged code (here: UnmanagedService.dll) you just link in the DLL as an Existing Item and set the Build Action to Embedded Resource. To access its functions use the DllImport attribute as usual, e.g.</p>\n\n<pre><code>[DllImport(\"unmanagedservice.dll\")] public extern static int Add(int a, int b);\n</code></pre>\n\n<p>That´s it! As soon as you create the first instance of the class with the static ctor the embedded DLLs get extracted into files of their own and are ready to use as if you deployed them as separate files. As long as you have write permissions for the execution directory this should work fine for you. At least for prototypical code I think this way of single assembly deployment is quite convenient.</p>\n\n<p>Enjoy!</p>\n\n<p><a href=\"http://weblogs.asp.net/ralfw/archive/2007/02/04/single-assembly-deployment-of-managed-and-unmanaged-code.aspx\" rel=\"noreferrer\">http://weblogs.asp.net/ralfw/archive/2007/02/04/single-assembly-deployment-of-managed-and-unmanaged-code.aspx</a></p>\n"
},
{
"answer_id": 72299,
"author": "titanae",
"author_id": 2387,
"author_profile": "https://Stackoverflow.com/users/2387",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://thinstall.com/help/index.php?_netsupport.htm\" rel=\"nofollow noreferrer\">Thinstall</a> is one solution. For a native windows application I would suggest embedding the DLL as a binary resource object, then extracting it at runtime before you need it.</p>\n"
},
{
"answer_id": 72357,
"author": "Raithlin",
"author_id": 6528,
"author_profile": "https://Stackoverflow.com/users/6528",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried ILMerge? <a href=\"http://research.microsoft.com/~mbarnett/ILMerge.aspx\" rel=\"nofollow noreferrer\">http://research.microsoft.com/~mbarnett/ILMerge.aspx</a></p>\n\n<blockquote>\n <p>ILMerge is a utility that can be used to merge multiple .NET assemblies into a single assembly. It is freely available for use from the Tools & Utilities page at the Microsoft .NET Framework Developer Center. </p>\n</blockquote>\n\n<p>If you're building the C++ DLL with the <code>/clr</code> flag (all or partially C++/CLI), then it should work:</p>\n\n<pre><code>ilmerge /out:Composite.exe MyMainApp.exe Utility.dll\n</code></pre>\n\n<p>It will not work with an ordinary (native) Windows DLL however. </p>\n"
},
{
"answer_id": 135609,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Try <a href=\"http://boxedapp.com/\" rel=\"nofollow noreferrer\" title=\"boxedapp sdk\">boxedapp</a>; it allows to load all DLLs from memory. Also, it seems that you can even embed .net runtime. Good to create a really standalone applications...</p>\n"
},
{
"answer_id": 2614743,
"author": "Joel Lucsy",
"author_id": 645,
"author_profile": "https://Stackoverflow.com/users/645",
"pm_score": -1,
"selected": false,
"text": "<p>PostBuild from <a href=\"http://www.xenocode.com/\" rel=\"nofollow noreferrer\">Xenocode</a> can package up both managed and unmanged into a single exe.</p>\n"
},
{
"answer_id": 6362480,
"author": "Lars Holm Jensen",
"author_id": 348005,
"author_profile": "https://Stackoverflow.com/users/348005",
"pm_score": 2,
"selected": false,
"text": "<p>Just right-click your project in Visual Studio, choose Project Properties -> Resources -> Add Resource -> Add Existing File…\nAnd include the code below to your App.xaml.cs or equivalent.</p>\n\n<pre><code>public App()\n{\n AppDomain.CurrentDomain.AssemblyResolve +=new ResolveEventHandler(CurrentDomain_AssemblyResolve);\n}\n\nSystem.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n{\n string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(\".dll\",\"\");\n\n dllName = dllName.Replace(\".\", \"_\");\n\n if (dllName.EndsWith(\"_resources\")) return null;\n\n System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + \".Properties.Resources\", System.Reflection.Assembly.GetExecutingAssembly());\n\n byte[] bytes = (byte[])rm.GetObject(dllName);\n\n return System.Reflection.Assembly.Load(bytes);\n}\n</code></pre>\n\n<p>Here's my original blog post:\n<a href=\"http://codeblog.larsholm.net/2011/06/embed-dlls-easily-in-a-net-assembly/\" rel=\"nofollow\">http://codeblog.larsholm.net/2011/06/embed-dlls-easily-in-a-net-assembly/</a></p>\n"
},
{
"answer_id": 10599956,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.red-gate.com/products/dotnet-development/smartassembly/\" rel=\"nofollow noreferrer\">Smart Assembly</a> can do this and more. If your dll has unmanaged code, it wont let you merge the dlls to a single assembly, instead it can embed the required dependencies as resources to your main exe. Its flip-side, its not free.</p>\n\n<p>You can do this manually by embedding dll to your resources and then relying on AppDomain's Assembly <code>ResolveHandler</code>. When it comes to mixed mode dlls, I found many of the variants and flavours of <code>ResolveHandler</code> approach to not work for me (all which read dll bytes to memory and read from it). They all worked for managed dlls. Here is what worked for me:</p>\n\n<pre><code>static void Main()\n{\n AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>\n {\n string assemblyName = new AssemblyName(args.Name).Name;\n if (assemblyName.EndsWith(\".resources\"))\n return null;\n\n string dllName = assemblyName + \".dll\";\n string dllFullPath = Path.Combine(GetMyApplicationSpecificPath(), dllName);\n\n using (Stream s = Assembly.GetEntryAssembly().GetManifestResourceStream(typeof(Program).Namespace + \".Resources.\" + dllName))\n {\n byte[] data = new byte[stream.Length];\n s.Read(data, 0, data.Length);\n\n //or just byte[] data = new BinaryReader(s).ReadBytes((int)s.Length);\n\n File.WriteAllBytes(dllFullPath, data);\n }\n\n return Assembly.LoadFrom(dllFullPath);\n };\n}\n</code></pre>\n\n<p>The key here is to write the bytes to a file and load from its location. To avoid chicken and egg problem, you have to ensure you declare the handler before accessing assembly and that you do not access the assembly members (or instantiate anything that has to deal with the assembly) inside the loading (assembly resolving) part. Also take care to ensure <code>GetMyApplicationSpecificPath()</code> is not any temp directory since temp files could be attempted to get erased by other programs or by yourself (not that it will get deleted while your program is accessing the dll, but at least its a nuisance. AppData is good location). Also note that you have to write the bytes each time, you cant load from location just 'cos the dll already resides there.</p>\n\n<p>If the assembly is fully unmanaged, you can see this <a href=\"https://stackoverflow.com/questions/666799/embedding-unmanaged-dll-into-a-managed-c-sharp-dll\">link</a> or <a href=\"http://bsmadhu.wordpress.com/2012/03/19/embedding-c-libraryexe-inside-net-assembly/\" rel=\"nofollow noreferrer\">this</a> as to how to load such dlls.</p>\n"
},
{
"answer_id": 44854427,
"author": "automan",
"author_id": 7773916,
"author_profile": "https://Stackoverflow.com/users/7773916",
"pm_score": 2,
"selected": false,
"text": "<p>Use <strong>Fody.Costura</strong> nuget</p>\n\n<ol>\n<li>Open your solution -> Project -> Manage Nuget Packages</li>\n<li>Search for <strong>Fody.Costura</strong></li>\n<li><strong>Compile</strong> your <em>project</em>. </li>\n</ol>\n\n<p>That's it !</p>\n\n<blockquote>\n <p>Source:\n <a href=\"http://www.manuelmeyer.net/2016/01/net-power-tip-10-merging-assemblies/\" rel=\"nofollow noreferrer\">http://www.manuelmeyer.net/2016/01/net-power-tip-10-merging-assemblies/</a></p>\n</blockquote>\n"
},
{
"answer_id": 73619249,
"author": "Lampe2020",
"author_id": 17865928,
"author_profile": "https://Stackoverflow.com/users/17865928",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to pack an application that already exists (including its dlls and other resources, no matter what language it's coded in) into a single .exe you can use <a href=\"https://github.com/SerGreen/Appacker\" rel=\"nofollow noreferrer\">SerGreen's Appacker</a> for that purpose. But it'll be "detected" to "run malicious code from a hacker" because it unpacks itself:</p>\n<blockquote>\n<p>Appacker and packages created by it can be detected as malware by some antivirus software. That's because of a hacky way i used to package files: packed app reads its own executable and extracts other files from it, which antiviruses find hella suspicious. It's false positive, but it still gets in the way of using this app.<br />\n-SerGreen on <a href=\"https://github.com/SerGreen/Appacker\" rel=\"nofollow noreferrer\">GitHub</a></p>\n</blockquote>\n<p>To use it you can simply open it up, click away any virus warnings (and tell Windows Defender to not delete it!), then choose a directory that should be packed and the executable to be run after unpacking.<br />\nYou can optionally change the unpacking behaviour of the app (windowed/windowless unpacker, unpacking target directory, should it be repacked or changes to the unpacked files be ignored, ...)</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12113/"
]
| I have a Windows C# program that uses a C++ dll for data i/o. My goal is to deploy the application as a single EXE.
What are the steps to create such an executable? | Single Assembly Deployment of Managed and Unmanaged Code
Sunday, February 4, 2007
.NET developers love XCOPY deployment. And they love single assembly components. At least I always feel kinda uneasy, if I have to use some component and need remember a list of files to also include with the main assembly of that component. So when I recently had to develop a managed code component and had to augment it with some unmanaged code from a C DLL (thx to Marcus Heege for helping me with this!), I thought about how to make it easier to deploy the two DLLs. If this were just two assemblies I could have used ILmerge to pack them up in just one file. But this doesn´t work for mixed code components with managed as well as unmanaged DLLs.
So here´s what I came up with for a solution:
I include whatever DLLs I want to deploy with my component´s main assembly as embedded resources.
Then I set up a class constructor to extract those DLLs like below. The class ctor is called just once within each AppDomain so it´s a neglible overhead, I think.
```
namespace MyLib
{
public class MyClass
{
static MyClass()
{
ResourceExtractor.ExtractResourceToFile("MyLib.ManagedService.dll", "managedservice.dll");
ResourceExtractor.ExtractResourceToFile("MyLib.UnmanagedService.dll", "unmanagedservice.dll");
}
...
```
In this example I included two DLLs as resources, one being an unmanaged code DLL, and one being a managed code DLL (just for demonstration purposes), to show, how this technique works for both kinds of code.
The code to extract the DLLs into files of their own is simple:
```
public static class ResourceExtractor
{
public static void ExtractResourceToFile(string resourceName, string filename)
{
if (!System.IO.File.Exists(filename))
using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create))
{
byte[] b = new byte[s.Length];
s.Read(b, 0, b.Length);
fs.Write(b, 0, b.Length);
}
}
}
```
Working with a managed code assembly like this is the same as usual - almost. You reference it (here: ManagedService.dll) in your component´s main project (here: MyLib), but set the Copy Local property to false. Additionally you link in the assembly as an Existing Item and set the Build Action to Embedded Resource.
For the unmanaged code (here: UnmanagedService.dll) you just link in the DLL as an Existing Item and set the Build Action to Embedded Resource. To access its functions use the DllImport attribute as usual, e.g.
```
[DllImport("unmanagedservice.dll")] public extern static int Add(int a, int b);
```
That´s it! As soon as you create the first instance of the class with the static ctor the embedded DLLs get extracted into files of their own and are ready to use as if you deployed them as separate files. As long as you have write permissions for the execution directory this should work fine for you. At least for prototypical code I think this way of single assembly deployment is quite convenient.
Enjoy!
<http://weblogs.asp.net/ralfw/archive/2007/02/04/single-assembly-deployment-of-managed-and-unmanaged-code.aspx> |
72,281 | <p>Receiving the following error when attempting to run a CLR stored proc. Any help is much appreciated.</p>
<pre><code>Msg 10314, Level 16, State 11, Line 1
An error occurred in the Microsoft .NET Framework while trying to load assembly id 65752. The server may be running out of resources, or the assembly may not be trusted with PERMISSION_SET = EXTERNAL_ACCESS or UNSAFE. Run the query again, or check documentation to see how to solve the assembly trust issues. For more information about this error:
System.IO.FileLoadException: Could not load file or assembly 'orders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An error relating to security occurred. (Exception from HRESULT: 0x8013150A)
System.IO.FileLoadException:
at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.Load(String assemblyString)
</code></pre>
| [
{
"answer_id": 72445,
"author": "Craig Stuntz",
"author_id": 7714,
"author_profile": "https://Stackoverflow.com/users/7714",
"pm_score": 0,
"selected": false,
"text": "<p>Does your assembly do file I/O? If so, you must grant the assembly permission to do this. In SSMS:</p>\n\n<ol>\n<li>Expand \"Databases\" </li>\n<li>Expand the node for your database </li>\n<li>Expand \"Programmability\" </li>\n<li>Expand \"Assemblies\" </li>\n<li>Right-click your assembly, choose Properties </li>\n<li>On the \"General\" page, change \"Permission set\" to \"External access\"</li>\n</ol>\n"
},
{
"answer_id": 72463,
"author": "homeskillet",
"author_id": 3400,
"author_profile": "https://Stackoverflow.com/users/3400",
"pm_score": 6,
"selected": false,
"text": "<p>Ran the SQL commands below and the issue appears to be resolved.</p>\n\n<pre><code>USE database_name\nGO\n\nEXEC sp_changedbowner 'sa'\nALTER DATABASE database_name SET TRUSTWORTHY ON \n</code></pre>\n"
},
{
"answer_id": 7254737,
"author": "nuwanda",
"author_id": 921239,
"author_profile": "https://Stackoverflow.com/users/921239",
"pm_score": 3,
"selected": false,
"text": "<p>Build your project with ANY CPU configuration. I had this problem when compiled my own project with x86 configuration and tried to run it on x64 SQL server.</p>\n"
},
{
"answer_id": 10396277,
"author": "101V",
"author_id": 452045,
"author_profile": "https://Stackoverflow.com/users/452045",
"pm_score": 2,
"selected": false,
"text": "<p>Applied all of the above suggestion and it failed.\nThen I recompiled my source code with \"Any CPU\" option, and it worked!</p>\n\n<p>This link helped:\n<a href=\"http://www.codeproject.com/Tips/147250/SQL-Server-failed-to-load-assembly-with-PERMISSION\" rel=\"nofollow\">SQL Server failed to load assembly with PERMISSION</a></p>\n"
},
{
"answer_id": 25848214,
"author": "Musakkhir Sayyed",
"author_id": 3894854,
"author_profile": "https://Stackoverflow.com/users/3894854",
"pm_score": -1,
"selected": false,
"text": "<pre><code>ALTER AUTHORIZATION ON DATABASE::mydb TO sa;\nALTER DATABASE [myDB] SET TRUSTWORTHY ON\nGO\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3400/"
]
| Receiving the following error when attempting to run a CLR stored proc. Any help is much appreciated.
```
Msg 10314, Level 16, State 11, Line 1
An error occurred in the Microsoft .NET Framework while trying to load assembly id 65752. The server may be running out of resources, or the assembly may not be trusted with PERMISSION_SET = EXTERNAL_ACCESS or UNSAFE. Run the query again, or check documentation to see how to solve the assembly trust issues. For more information about this error:
System.IO.FileLoadException: Could not load file or assembly 'orders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An error relating to security occurred. (Exception from HRESULT: 0x8013150A)
System.IO.FileLoadException:
at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.Load(String assemblyString)
``` | Ran the SQL commands below and the issue appears to be resolved.
```
USE database_name
GO
EXEC sp_changedbowner 'sa'
ALTER DATABASE database_name SET TRUSTWORTHY ON
``` |
72,358 | <p>I am using Tomcat as a server and Internet Explorer 6 as a browser. A web page in our app has about 75 images. We are using SSL. It seems to be very slow at loading all the content. How can I configure Tomcat so that IE caches the images?</p>
| [
{
"answer_id": 72413,
"author": "Gabor",
"author_id": 10485,
"author_profile": "https://Stackoverflow.com/users/10485",
"pm_score": -1,
"selected": false,
"text": "<p>Content served over a HTTPS connection <strong>never gets cached</strong> in the browser. You cannot do much about it. </p>\n\n<p>Usually, images in your web site are not very sensitive and are served over HTTP for this very reason.</p>\n"
},
{
"answer_id": 72547,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 2,
"selected": false,
"text": "<p>75 images sounds like a lot. If it is a lot of small images, there are ways of bundling many images as one, you might see if you can find a library that does that. Also you can probably force the images to be cached in something like <a href=\"http://gears.google.com\" rel=\"nofollow noreferrer\">google gears</a>.</p>\n"
},
{
"answer_id": 74226,
"author": "junkforce",
"author_id": 2153,
"author_profile": "https://Stackoverflow.com/users/2153",
"pm_score": -1,
"selected": false,
"text": "<p>The first answer is correct that nothing is cached when using HTTPS. However, when you build your web page, you may consider referencing the images by their individual URL's. This way you can specify the images as originating from an HTTP source, and they'll(likely) be cache'd by the browser.</p>\n"
},
{
"answer_id": 83182,
"author": "Dave Cheney",
"author_id": 6449,
"author_profile": "https://Stackoverflow.com/users/6449",
"pm_score": 4,
"selected": true,
"text": "<p>If you are serving a page over https then you'll need to serve all the included static or dynamic resources over https (either from the same domain, or another domain, also over https) to avoid a security warning in the browser.</p>\n\n<p>Content delivered over a secure channel will not be written to disk by default by most browsers and so lives in the browsers memory cache, which is much smaller than the on disk cache. This cache also disappears when the application quits.</p>\n\n<p>Having said all of that there are things you can do to improve the cachability for SSL assets inside a single browser setting. For starters, ensure that all you assets have reasonable Expires and Cache-Control headers. If tomcat is sitting behind apache then use mod_expires to add them. This will avoid the browser having to check if the image has changed between pages</p>\n\n<pre><code><Location /images>\n FileEtag none\n ExpiresActive on\n ExpiresDefault \"access plus 1 month\"\n</Location>\n</code></pre>\n\n<p>Secondly, and this is specific to MSIE and Apache, most apache ssl configs include these lines</p>\n\n<pre><code>SetEnvIf User-Agent \".*MSIE.*\" \\\n nokeepalive ssl-unclean-shutdown \\\n downgrade-1.0 force-response-1.0\n</code></pre>\n\n<p>Which disables keepalive for ALL MSIE agents. IMHO this is far too conservative, the last MSIE browsers to have issues using SSL were 5.x and unpatched versions of 6.0 pre SP2, both of which are very uncommon now. The following is more lenient and will not disable keepalives when using MSIE and SSL</p>\n\n<pre><code>BrowserMatch \"MSIE [1-4]\" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0\nBrowserMatch \"MSIE [5-9]\" ssl-unclean-shutdown\n</code></pre>\n"
},
{
"answer_id": 84091,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 3,
"selected": false,
"text": "<p>Some browsers will cache SSL content. Firefox 2.0+ does not cache SSL resources on disc by default (for increased privacy). Firefox 3+ doesn't cache them on disc unless the Cache-control:public header appears.</p>\n\n<p>So set the Expires: header correctly and Cache-control:public. e.g.</p>\n\n<pre><code><Files ~ \"\\.(gif|jpe?g|png|ico|css|js|cab|jar|swf)$\">\n # Expire these things\n # Three days after access time\n ExpiresDefault \"now plus 3 days\"\n # This makes Firefox 3 cache images over SSL\n Header set Cache-Control public\n</Files>\n</code></pre>\n"
},
{
"answer_id": 85265,
"author": "Philip Helger",
"author_id": 15254,
"author_profile": "https://Stackoverflow.com/users/15254",
"pm_score": -1,
"selected": false,
"text": "<p>Maybe you can add an additional server/subdomain that provides the images without https?</p>\n"
},
{
"answer_id": 731198,
"author": "scotts",
"author_id": 69079,
"author_profile": "https://Stackoverflow.com/users/69079",
"pm_score": 2,
"selected": false,
"text": "<p>If a lot of those 75 images are icons or images that appear on every page, you can use CSS sprites to drastically reduce the number of HTTP requests and thus load the page faster:</p>\n\n<p><a href=\"http://www.alistapart.com/articles/sprites/\" rel=\"nofollow noreferrer\">http://www.alistapart.com/articles/sprites/</a></p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2959/"
]
| I am using Tomcat as a server and Internet Explorer 6 as a browser. A web page in our app has about 75 images. We are using SSL. It seems to be very slow at loading all the content. How can I configure Tomcat so that IE caches the images? | If you are serving a page over https then you'll need to serve all the included static or dynamic resources over https (either from the same domain, or another domain, also over https) to avoid a security warning in the browser.
Content delivered over a secure channel will not be written to disk by default by most browsers and so lives in the browsers memory cache, which is much smaller than the on disk cache. This cache also disappears when the application quits.
Having said all of that there are things you can do to improve the cachability for SSL assets inside a single browser setting. For starters, ensure that all you assets have reasonable Expires and Cache-Control headers. If tomcat is sitting behind apache then use mod\_expires to add them. This will avoid the browser having to check if the image has changed between pages
```
<Location /images>
FileEtag none
ExpiresActive on
ExpiresDefault "access plus 1 month"
</Location>
```
Secondly, and this is specific to MSIE and Apache, most apache ssl configs include these lines
```
SetEnvIf User-Agent ".*MSIE.*" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
```
Which disables keepalive for ALL MSIE agents. IMHO this is far too conservative, the last MSIE browsers to have issues using SSL were 5.x and unpatched versions of 6.0 pre SP2, both of which are very uncommon now. The following is more lenient and will not disable keepalives when using MSIE and SSL
```
BrowserMatch "MSIE [1-4]" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
BrowserMatch "MSIE [5-9]" ssl-unclean-shutdown
``` |
72,360 | <p>here is what a I'm doing: </p>
<pre><code>object ReturnMatch(System.Type type)
{
foreach(object obj in myObjects)
{
if (obj == type)
{
return obj;
}
}
}
</code></pre>
<p>However, if obj is a subclass of <code>type</code>, it will not match. But I would like the function to return the same way as if I was using the operator <code>is</code>.</p>
<p>I tried the following, but it won't compile:</p>
<pre><code>if (obj is type) // won't compile in C# 2.0
</code></pre>
<p>The best solution I came up with was:</p>
<pre><code>if (obj.GetType().Equals(type) || obj.GetType().IsSubclassOf(type))
</code></pre>
<p>Isn't there a way to use operator <code>is</code> to make the code cleaner?</p>
| [
{
"answer_id": 72384,
"author": "Thunder3",
"author_id": 2832,
"author_profile": "https://Stackoverflow.com/users/2832",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps </p>\n\n<pre><code>type.IsAssignableFrom(obj.GetType())\n</code></pre>\n"
},
{
"answer_id": 72407,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 0,
"selected": false,
"text": "<p>the is operator indicates whether or not it would be 'safe' to cast one object as another obeject (often a super class).</p>\n\n<pre><code>if(obj is type)\n</code></pre>\n\n<p>if obj is of type 'type' or a subclass thereof, then the if statement will succeede as it is 'safe' to cast obj as (type)obj.</p>\n\n<p>see: <a href=\"http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx</a></p>\n"
},
{
"answer_id": 72503,
"author": "icelava",
"author_id": 2663,
"author_profile": "https://Stackoverflow.com/users/2663",
"pm_score": 0,
"selected": false,
"text": "<p>Is there a reason why you cannot use the \"is\" keyword itself?</p>\n\n<pre><code>foreach(object obj in myObjects)\n{\n if (obj is type)\n {\n return obj;\n }\n}\n</code></pre>\n\n<p>EDIT - I see what I was missing. Isak's suggestion is the correct one; I have tested and confirmed it.</p>\n\n<pre><code> class Level1\n {\n }\n\n class Level2A : Level1\n {\n }\n\n class Level2B : Level1\n {\n }\n\n class Level3A2A : Level2A\n {\n }\n\n\n class Program\n {\n static void Main(string[] args)\n {\n object[] objects = new object[] {\"testing\", new Level1(), new Level2A(), new Level2B(), new Level3A2A(), new object() };\n\n\n ReturnMatch(typeof(Level1), objects);\n Console.ReadLine();\n }\n\n\n static void ReturnMatch(Type arbitraryType, object[] objects)\n {\n foreach (object obj in objects)\n {\n Type objType = obj.GetType();\n\n Console.Write(arbitraryType.ToString() + \" is \");\n\n if (!arbitraryType.IsAssignableFrom(objType))\n Console.Write(\"not \");\n\n Console.WriteLine(\"assignable from \" + objType.ToString());\n\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 72525,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 2,
"selected": false,
"text": "<p>Not using the is operator, but the Type.IsInstanceOfType Method appears to be what you're looking for.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.type.isinstanceoftype.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.type.isinstanceoftype.aspx</a></p>\n"
},
{
"answer_id": 72550,
"author": "Isak Savo",
"author_id": 8521,
"author_profile": "https://Stackoverflow.com/users/8521",
"pm_score": 4,
"selected": true,
"text": "<p>I've used the IsAssignableFrom method when faced with this problem.</p>\n\n<pre><code>Type theTypeWeWant; // From argument or whatever\nforeach (object o in myCollection)\n{\n if (theTypeWeWant.IsAssignableFrom(o.GetType))\n return o;\n}\n</code></pre>\n\n<p>Another approach that may or may not work with your problem is to use a generic method:</p>\n\n<pre><code>private T FindObjectOfType<T>() where T: class\n{\n foreach(object o in myCollection)\n {\n if (o is T)\n return (T) o;\n }\n return null;\n}\n</code></pre>\n\n<p>(Code written from memory and is not tested)</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10833/"
]
| here is what a I'm doing:
```
object ReturnMatch(System.Type type)
{
foreach(object obj in myObjects)
{
if (obj == type)
{
return obj;
}
}
}
```
However, if obj is a subclass of `type`, it will not match. But I would like the function to return the same way as if I was using the operator `is`.
I tried the following, but it won't compile:
```
if (obj is type) // won't compile in C# 2.0
```
The best solution I came up with was:
```
if (obj.GetType().Equals(type) || obj.GetType().IsSubclassOf(type))
```
Isn't there a way to use operator `is` to make the code cleaner? | I've used the IsAssignableFrom method when faced with this problem.
```
Type theTypeWeWant; // From argument or whatever
foreach (object o in myCollection)
{
if (theTypeWeWant.IsAssignableFrom(o.GetType))
return o;
}
```
Another approach that may or may not work with your problem is to use a generic method:
```
private T FindObjectOfType<T>() where T: class
{
foreach(object o in myCollection)
{
if (o is T)
return (T) o;
}
return null;
}
```
(Code written from memory and is not tested) |
72,381 | <p>I'm trying to use the following code but it's returning the wrong day of month.</p>
<pre><code>Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
cal.set(Calendar.MONTH, sampleDay.get(Calendar.MONTH)+1);
cal.set(Calendar.DAY_OF_MONTH, 0);
return cal.getTime();
</code></pre>
| [
{
"answer_id": 72411,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 2,
"selected": false,
"text": "<p>I would create a date object for the first day of the NEXT month, and then just subtract a single day from the date object.</p>\n"
},
{
"answer_id": 72438,
"author": "Argelbargel",
"author_id": 2992,
"author_profile": "https://Stackoverflow.com/users/2992",
"pm_score": 5,
"selected": true,
"text": "<p>Get the number of days for this month:</p>\n\n<p><pre><code>\nCalendar cal = Calendar.getInstance();\ncal.setTime(sampleDay.getTime());\nint noOfLastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);\n</pre></code></p>\n\n<p>Set the Calendar to the last day of this month:</p>\n\n<p><pre><code>\nCalendar cal = Calendar.getInstance();\ncal.setTime(sampleDay.getTime());\ncal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));\n</pre></code></p>\n"
},
{
"answer_id": 72460,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like you set the calendar to the first day of the next month, so you need one more line to subtract one day, to get the last day of the month that <em>sampleDay</em> is in:</p>\n\n<pre><code>Calendar cal = Calendar.getInstance();\ncal.setTime(sampleDay.getTime());\ncal.roll(Calendar.MONTH, true);\ncal.set(Calendar.DAY_OF_MONTH, 0);\ncal.add(Calendar.DAY_OF_MONTH, -1);\n</code></pre>\n\n<p>In general, it's much easier to do this kind of thing using <a href=\"http://joda-time.sourceforge.net/\" rel=\"nofollow noreferrer\">Joda Time</a>, eg:</p>\n\n<pre><code>DateTime date = new DateTime(sampleDay.getTime());\nreturn date.plusMonths(1).withDayOfMonth(0).minusDays(1).getMillis();\n</code></pre>\n"
},
{
"answer_id": 72526,
"author": "paul",
"author_id": 11249,
"author_profile": "https://Stackoverflow.com/users/11249",
"pm_score": 2,
"selected": false,
"text": "<p>Use calObject.getActualMaximum(calobject.DAY_OF_MONTH)</p>\n\n<p>See <a href=\"http://www.rgagnon.com/javadetails/java-0098.html\" rel=\"nofollow noreferrer\">Real's Java How-to</a> for more info on this.</p>\n"
},
{
"answer_id": 4981993,
"author": "John",
"author_id": 157080,
"author_profile": "https://Stackoverflow.com/users/157080",
"pm_score": 1,
"selected": false,
"text": "<p>If you use the <a href=\"http://www.date4j.net\" rel=\"nofollow\">date4j</a> library:</p>\n\n<pre><code>DateTime monthEnd = dt.getEndOfMonth();\n</code></pre>\n"
},
{
"answer_id": 13409132,
"author": "Nick",
"author_id": 1828375,
"author_profile": "https://Stackoverflow.com/users/1828375",
"pm_score": -1,
"selected": false,
"text": "<p>I think this should work nicely:</p>\n\n<pre><code>Dim MyDate As Date = #11/14/2012# 'This is just an example date\n\nMyDate = MyDate.AddDays(DateTime.DaysInMonth(MyDate.Year, MyDate.Month) - MyDate.Day)\n</code></pre>\n"
},
{
"answer_id": 38032903,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 2,
"selected": false,
"text": "<h1>tl;dr</h1>\n\n<pre><code>YearMonth.from(\n LocalDate.now( ZoneId.of( \"America/Montreal\" ) )\n).atEndOfMonth()\n</code></pre>\n\n<h1>java.time</h1>\n\n<p>The Question and other Answers use old outmoded classes. They have been supplanted by the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html\" rel=\"nofollow noreferrer\">java.time</a> classes built into Java 8 and later. See <a href=\"http://docs.oracle.com/javase/tutorial/datetime/TOC.html\" rel=\"nofollow noreferrer\">Oracle Tutorial</a>. Much of the functionality has been back-ported to Java 6 & 7 in <a href=\"http://www.threeten.org/threetenbp/\" rel=\"nofollow noreferrer\">ThreeTen-Backport</a> and further adapted to Android in <a href=\"https://github.com/JakeWharton/ThreeTenABP\" rel=\"nofollow noreferrer\">ThreeTenABP</a>.</p>\n\n<h2><code>LocalDate</code></h2>\n\n<p>The <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html\" rel=\"nofollow noreferrer\"><code>LocalDate</code></a> class represents a date-only value without time-of-day and without time zone. While these objects store no time zone, note that time zone is crucial in determining the current date. For any given moment the date varies around the globe by time zone.</p>\n\n<pre><code>ZoneId zoneId = ZoneId.of( \"America/Montreal\" );\nLocalDate today = LocalDate.now( zoneId ); // 2016-06-25\n</code></pre>\n\n<h2><code>YearMonth</code></h2>\n\n<p>Combine with the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/YearMonth.html\" rel=\"nofollow noreferrer\"><code>YearMonth</code></a> class to determine last day of any month.</p>\n\n<pre><code>YearMonth currentYearMonth = YearMonth.from( today ); // 2016-06\nLocalDate lastDayOfCurrentYearMonth = currentYearMonth.atEndOfMonth(); // 2016-06-30\n</code></pre>\n\n<p>By the way, both <code>LocalDate</code> and <code>YearMonth</code> use month numbers as you would expect (1-12) rather than the screwball 0-11 seen in the old date-time classes. One of many poor design decisions that make those old date-time classes so troublesome and confusing.</p>\n\n<h1><code>TemporalAdjuster</code></h1>\n\n<p>Another valid approach is using a <a href=\"https://docs.oracle.com/javase/9/docs/api/java/time/temporal/TemporalAdjuster.html\" rel=\"nofollow noreferrer\"><code>TemporalAdjuster</code></a>.\n See <a href=\"https://stackoverflow.com/a/46914556/642706\">the correct Answer by Pierre Henry</a>.</p>\n"
},
{
"answer_id": 46914556,
"author": "Pierre Henry",
"author_id": 315677,
"author_profile": "https://Stackoverflow.com/users/315677",
"pm_score": 2,
"selected": false,
"text": "<h1><code>TemporalAdjuster</code></h1>\n\n<p>Using the (relatively) <strong>new Java date API</strong>, it is actually very easy :</p>\n\n<p>Let <code>date</code> be an instance of <code>LocalDate</code>, for example :</p>\n\n<pre><code>LocalDate date = LocalDate.of(2018, 1, 22);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>LocalDate date = LocalDate.now();\n</code></pre>\n\n<p>or, of course, you could get it as a user input, from a database, etc.</p>\n\n<p>Then apply an implementation of the <a href=\"https://docs.oracle.com/javase/9/docs/api/java/time/temporal/TemporalAdjuster.html\" rel=\"nofollow noreferrer\"><code>TemporalAdjuster</code></a> interface found in the <a href=\"https://docs.oracle.com/javase/9/docs/api/java/time/temporal/TemporalAdjusters.html\" rel=\"nofollow noreferrer\"><code>TemporalAdjusters</code></a> class:</p>\n\n<pre><code>LocalDate first = date.with(TemporalAdjusters.firstDayOfMonth());\nLocalDate last = date.with(TemporalAdjusters.lastDayOfMonth());\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
]
| I'm trying to use the following code but it's returning the wrong day of month.
```
Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
cal.set(Calendar.MONTH, sampleDay.get(Calendar.MONTH)+1);
cal.set(Calendar.DAY_OF_MONTH, 0);
return cal.getTime();
``` | Get the number of days for this month:
```
Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
int noOfLastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
```
Set the Calendar to the last day of this month:
```
Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
``` |
72,393 | <p>A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed:</p>
<pre><code>result = re.match("a_regex_of_pure_awesomeness", "a string containing the awesomeness")
# result is None`
</code></pre>
<p>After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix but I would like to know how to change:</p>
<pre><code>regex = ".*(a_regex_of_pure_awesomeness)"
</code></pre>
<p>into</p>
<pre><code>regex = "a_regex_of_pure_awesomeness"
</code></pre>
<p>Okay, it's a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny.</p>
| [
{
"answer_id": 72449,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Are you using the <code>re.match()</code> or <code>re.search()</code> method? My understanding is that <code>re.match()</code> assumes a \"<code>^</code>\" at the beginning of your expression and will only search at the beginning of the text, while <code>re.search()</code> acts more like the Perl regular expressions and will only match the beginning of the text if you include a \"<code>^</code>\" at the beginning of your expression. Hope that helps.</p>\n"
},
{
"answer_id": 72470,
"author": "zweiterlinde",
"author_id": 6592,
"author_profile": "https://Stackoverflow.com/users/6592",
"pm_score": 5,
"selected": true,
"text": "<p>In Python, there's a distinction between \"match\" and \"search\"; match only looks for the pattern at the start of the string, and search looks for the pattern starting at any location within the string.</p>\n\n<p><a href=\"http://docs.python.org/lib/module-re.html\" rel=\"noreferrer\">Python regex docs</a><br>\n<a href=\"http://docs.python.org/lib/matching-searching.html\" rel=\"noreferrer\">Matching vs searching</a></p>\n"
},
{
"answer_id": 72501,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 2,
"selected": false,
"text": "<pre><code>>>> import re\n>>> pattern = re.compile(\"url\")\n>>> string = \" url\"\n>>> pattern.match(string)\n>>> pattern.search(string)\n<_sre.SRE_Match object at 0xb7f7a6e8>\n</code></pre>\n"
},
{
"answer_id": 78072,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "<pre><code>from BeautifulSoup import BeautifulSoup \n\nsoup = BeautifulSoup(your_html)\nfor a in soup.findAll('a', href=True):\n # do something with `a` w/ href attribute\n print a['href']\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
| A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed:
```
result = re.match("a_regex_of_pure_awesomeness", "a string containing the awesomeness")
# result is None`
```
After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix but I would like to know how to change:
```
regex = ".*(a_regex_of_pure_awesomeness)"
```
into
```
regex = "a_regex_of_pure_awesomeness"
```
Okay, it's a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny. | In Python, there's a distinction between "match" and "search"; match only looks for the pattern at the start of the string, and search looks for the pattern starting at any location within the string.
[Python regex docs](http://docs.python.org/lib/module-re.html)
[Matching vs searching](http://docs.python.org/lib/matching-searching.html) |
72,410 | <p>How should I store (and present) the text on a website intended for worldwide use, with several languages? The content is mostly in the form of 500+ word articles, although I will need to translate tiny snippets of text on each page too (such as "print this article" or "back to menu").</p>
<p>I know there are several CMS packages that handle multiple languages, but I have to integrate with our existing ASP systems too, so I am ignoring such solutions.</p>
<p>One concern I have is that Google should be able to find the pages, even for foreign users. I am less concerned about issues with processing dates and currencies.</p>
<p>I worry that, left to my own devices, I will invent a way of doing this which work, but eventually lead to disaster! I want to know what professional solutions you have actually used on real projects, not untried ideas! Thanks very much.</p>
<hr>
<p>I looked at RESX files, but felt they were unsuitable for all but the most trivial translation solutions (I will elaborate if anyone wants to know).</p>
<p>Google will help me with translating the text, but not storing/presenting it.</p>
<p>Has anyone worked on a multi-language project that relied on their own code for presentation?</p>
<hr>
<p>Any thoughts on serving up content in the following ways, and which is best?</p>
<ul>
<li><a href="http://www.website.com/text/view.asp?id=12345&lang=fr" rel="nofollow noreferrer">http://www.website.com/text/view.asp?id=12345&lang=fr</a></li>
<li><a href="http://www.website.com/text/12345/bonjour_mes_amis.htm" rel="nofollow noreferrer">http://www.website.com/text/12345/bonjour_mes_amis.htm</a></li>
<li><a href="http://fr.website.com/text/12345" rel="nofollow noreferrer">http://fr.website.com/text/12345</a></li>
</ul>
<p>(these are not real URLs, i was just showing examples)</p>
| [
{
"answer_id": 72451,
"author": "SaaS Developer",
"author_id": 7215,
"author_profile": "https://Stackoverflow.com/users/7215",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using .Net, I would recommend going with one or more resource files (.resx). There is plenty of documentation on this on MSDN.</p>\n"
},
{
"answer_id": 72473,
"author": "Michael Pliskin",
"author_id": 9777,
"author_profile": "https://Stackoverflow.com/users/9777",
"pm_score": 2,
"selected": false,
"text": "<p>You might want to check <a href=\"http://www.gnu.org/software/gettext/\" rel=\"nofollow noreferrer\">GNU Gettext</a> project out - at least something to start with.</p>\n\n<p><em>Edited to add info about projects:</em></p>\n\n<p>I've worked on several multilingual projects using Gettext technology in different technologies, including C++/MFC and J2EE/JSP, and it worked all fine. However, you need to write/find your own code to display the localized data of course.</p>\n"
},
{
"answer_id": 72524,
"author": "Dr. Bob",
"author_id": 12182,
"author_profile": "https://Stackoverflow.com/users/12182",
"pm_score": 0,
"selected": false,
"text": "<p>If you're just worried about the article content being translated, and do not need a fully integrated option, I have used <a href=\"http://www.google.com/language_tools\" rel=\"nofollow noreferrer\">google translation</a> in the past and it works great on a smaller scale.</p>\n"
},
{
"answer_id": 73406,
"author": "Rich McCollister",
"author_id": 9306,
"author_profile": "https://Stackoverflow.com/users/9306",
"pm_score": 1,
"selected": false,
"text": "<p>As with most general programming questions, it depends on your needs. </p>\n\n<p>For static text, I would use RESX files. For me, as .Net programmer, they are easy to use and the .Net Framework has good support for them. </p>\n\n<p>For any dynamic text, I tend to store such information in the database, especially if the site maintainer is going to be a non-developer. In the past I've used two approaches, adding a language column and creating different entries for the different languages or creating a separate table to store the language specific text. </p>\n\n<p>The table for the first approach might look something like this:</p>\n\n<p>Article Id | Language Id | Language Specific Article Text | Created By | Created Date</p>\n\n<p>This works for situations where you can create different entries for a given article and you don't need to keep any data associated with these different entries in sync (such as an Updated timestamp). </p>\n\n<p>The other approach is to have two separate tables, one for non-language specific text (id, created date, created user, updated date, etc) and another table containing the language specific text. So the tables might look something like this:</p>\n\n<p>First Table: Article Id | Created By | Created Date | Updated By | Updated Date</p>\n\n<p>Second Table: Article Id | Language Id | Language Specific Article Text</p>\n\n<p>For me, the question comes down to updating the non-language dependent data. If you are updating that data then I would lean towards the second approach, otherwise I would go with the first approach as I view that as simpler (can't forget the KISS principle).</p>\n"
},
{
"answer_id": 120364,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": true,
"text": "<p>Firstly put all code for all languages under one domain - it will help your google-rank.</p>\n\n<p>We have a fully multi-lingual system, with localisations stored in a database but cached with the web application.</p>\n\n<p>Wherever we want a localisation to appear we use:</p>\n\n<pre><code><%$ Resources: LanguageProvider, Path/To/Localisation %>\n</code></pre>\n\n<p>Then in our web.config:</p>\n\n<pre><code><globalization resourceProviderFactoryType=\"FactoryClassName, AssemblyName\"/>\n</code></pre>\n\n<p><code>FactoryClassName</code> then implements <code>ResourceProviderFactory</code> to provide the actual dynamic functionality. Localisations are stored in the DB with a string key \"Path/To/Localisation\"</p>\n\n<p>It is important to cache the localised values - you don't want to have lots of DB lookups on each page, and we cache thousands of localised strings with no performance issues.</p>\n\n<p>Use the user's current browser localisation to choose what language to serve up.</p>\n"
},
{
"answer_id": 933114,
"author": "ilya n.",
"author_id": 115200,
"author_profile": "https://Stackoverflow.com/users/115200",
"pm_score": 0,
"selected": false,
"text": "<p>Wonderful question. </p>\n\n<p>I solved this problem for the website I made (link in my profile) with a homemade Python 3 script that translates the general template on the fly and inserts a specific content page from a language requested (or guessed by Apache from Accept-Language).</p>\n\n<p>It was fun since I got to learn Python and write my own mini-library for creating content pages. One downside was that our hosting didn't have Python 3, but I made my script generate static HTML (the original one was examining User-agent) and then upload it to server. That works so far and making a new language version of the site is now a breeze :)</p>\n\n<p>The biggest downside of this method is that it is time-consuming to write things from scratch. So if you want, drop me line and I'll help you use my script :)</p>\n"
},
{
"answer_id": 933135,
"author": "ilya n.",
"author_id": 115200,
"author_profile": "https://Stackoverflow.com/users/115200",
"pm_score": 0,
"selected": false,
"text": "<p>As for the URL format, I use <code>site.com/content/example.fr</code> since this allows Apache to perform language negotiation in case somebody asks for <code>/content/example</code> and has a browser tell that it likes French language. When you do this Apache also adds <code>.html</code> or whatever as a bonus.</p>\n\n<p>So when a request is for <code>example</code> and I have files </p>\n\n<pre><code>example.fr\nexample.en\nexample.vi\n</code></pre>\n\n<p>Apache will automatically proceed with <code>example.vi</code> for a person with Vietnamese-configured browser or <code>example.en</code> for a person with German-configured browser. Pretty useful. </p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11461/"
]
| How should I store (and present) the text on a website intended for worldwide use, with several languages? The content is mostly in the form of 500+ word articles, although I will need to translate tiny snippets of text on each page too (such as "print this article" or "back to menu").
I know there are several CMS packages that handle multiple languages, but I have to integrate with our existing ASP systems too, so I am ignoring such solutions.
One concern I have is that Google should be able to find the pages, even for foreign users. I am less concerned about issues with processing dates and currencies.
I worry that, left to my own devices, I will invent a way of doing this which work, but eventually lead to disaster! I want to know what professional solutions you have actually used on real projects, not untried ideas! Thanks very much.
---
I looked at RESX files, but felt they were unsuitable for all but the most trivial translation solutions (I will elaborate if anyone wants to know).
Google will help me with translating the text, but not storing/presenting it.
Has anyone worked on a multi-language project that relied on their own code for presentation?
---
Any thoughts on serving up content in the following ways, and which is best?
* <http://www.website.com/text/view.asp?id=12345&lang=fr>
* <http://www.website.com/text/12345/bonjour_mes_amis.htm>
* <http://fr.website.com/text/12345>
(these are not real URLs, i was just showing examples) | Firstly put all code for all languages under one domain - it will help your google-rank.
We have a fully multi-lingual system, with localisations stored in a database but cached with the web application.
Wherever we want a localisation to appear we use:
```
<%$ Resources: LanguageProvider, Path/To/Localisation %>
```
Then in our web.config:
```
<globalization resourceProviderFactoryType="FactoryClassName, AssemblyName"/>
```
`FactoryClassName` then implements `ResourceProviderFactory` to provide the actual dynamic functionality. Localisations are stored in the DB with a string key "Path/To/Localisation"
It is important to cache the localised values - you don't want to have lots of DB lookups on each page, and we cache thousands of localised strings with no performance issues.
Use the user's current browser localisation to choose what language to serve up. |
72,422 | <p>Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test.</p>
<pre><code>>>> class MyTest(unittest.TestCase):
def setUp(self):
self.i = 1
def testA(self):
self.i = 3
self.assertEqual(self.i, 3)
def testB(self):
self.assertEqual(self.i, 3)
>>> unittest.main()
.F
======================================================================
FAIL: testB (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<pyshell#61>", line 8, in testB
AssertionError: 1 != 3
----------------------------------------------------------------------
Ran 2 tests in 0.016s
</code></pre>
| [
{
"answer_id": 72498,
"author": "mmaibaum",
"author_id": 12213,
"author_profile": "https://Stackoverflow.com/users/12213",
"pm_score": 0,
"selected": false,
"text": "<p>If I recall correctly in that test framework the setUp method is run before each test</p>\n"
},
{
"answer_id": 72504,
"author": "pjz",
"author_id": 8002,
"author_profile": "https://Stackoverflow.com/users/8002",
"pm_score": 4,
"selected": false,
"text": "<p>From <a href=\"http://docs.python.org/lib/minimal-example.html\" rel=\"noreferrer\">http://docs.python.org/lib/minimal-example.html</a> :</p>\n\n<blockquote>\n <p>When a setUp() method is defined, the\n test runner will run that method prior\n to each test.</p>\n</blockquote>\n\n<p>So setUp() gets run before both testA and testB, setting i to 1 each time. Behind the scenes, the entire test object is actually being re-instantiated for each test, with setUp() being run on each new instantiation before the test is executed.</p>\n"
},
{
"answer_id": 72702,
"author": "Jon Homan",
"author_id": 7589,
"author_profile": "https://Stackoverflow.com/users/7589",
"pm_score": -1,
"selected": false,
"text": "<p>The setUp method, as everyone else has said, runs before every test method you write. So, when testB runs, the value of i is 1, not 3.</p>\n\n<p>You can also use a tearDown method which runs after every test method. However if one of your tests crashes, your tearDown method will never run.</p>\n"
},
{
"answer_id": 73791,
"author": "Sebastian Rittau",
"author_id": 7779,
"author_profile": "https://Stackoverflow.com/users/7779",
"pm_score": 4,
"selected": true,
"text": "<p>Each test is run using a new instance of the MyTest class. That means if you change self in one test, changes will not carry over to other tests, since self will refer to a different instance.</p>\n\n<p>Additionally, as others have pointed out, setUp is called before each test.</p>\n"
},
{
"answer_id": 215576,
"author": "Roman Plášil",
"author_id": 16590,
"author_profile": "https://Stackoverflow.com/users/16590",
"pm_score": 0,
"selected": false,
"text": "<p>From a methodological point of view, individual tests should be independent, otherwise it can produce more hard-to-find bugs. Imagine for instance that testA and testB would be called in a different order.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9510/"
]
| Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test.
```
>>> class MyTest(unittest.TestCase):
def setUp(self):
self.i = 1
def testA(self):
self.i = 3
self.assertEqual(self.i, 3)
def testB(self):
self.assertEqual(self.i, 3)
>>> unittest.main()
.F
======================================================================
FAIL: testB (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<pyshell#61>", line 8, in testB
AssertionError: 1 != 3
----------------------------------------------------------------------
Ran 2 tests in 0.016s
``` | Each test is run using a new instance of the MyTest class. That means if you change self in one test, changes will not carry over to other tests, since self will refer to a different instance.
Additionally, as others have pointed out, setUp is called before each test. |
72,442 | <p>I have a nullable property, and I want to return a null value. How do I do that in VB.NET ?</p>
<p>Currently I use this solution, but I think there might be a better way.</p>
<pre><code> Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)
Get
If Current.Request.QueryString("rid") <> "" Then
Return CInt(Current.Request.QueryString("rid"))
Else
Return (New Nullable(Of Integer)).Value
End If
End Get
End Property
</code></pre>
| [
{
"answer_id": 72465,
"author": "Jon",
"author_id": 12261,
"author_profile": "https://Stackoverflow.com/users/12261",
"pm_score": 4,
"selected": true,
"text": "<p>Are you looking for the keyword \"Nothing\"?</p>\n"
},
{
"answer_id": 72542,
"author": "Luca Molteni",
"author_id": 4206,
"author_profile": "https://Stackoverflow.com/users/4206",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, it's Nothing in VB.NET, or null in C#.</p>\n\n<p>The Nullable generic datatype give the compiler the possibility to assign a \"Nothing\" (or null\" value to a value type. Without explicitally writing it, you can't do it.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx\" rel=\"nofollow noreferrer\">Nullable Types in C#</a></p>\n"
},
{
"answer_id": 78272,
"author": "gregmac",
"author_id": 7913,
"author_profile": "https://Stackoverflow.com/users/7913",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)\n Get\n If Current.Request.QueryString(\"rid\") <> \"\" Then\n Return CInt(Current.Request.QueryString(\"rid\"))\n Else\n Return Nothing\n End If\n End Get\nEnd Property\n</code></pre>\n"
},
{
"answer_id": 439923,
"author": "Barbaros Alp",
"author_id": 51734,
"author_profile": "https://Stackoverflow.com/users/51734",
"pm_score": 0,
"selected": false,
"text": "<p>Or this is the way i use, to be honest ReSharper has taught me :)</p>\n\n<pre><code>finder.Advisor = ucEstateFinder.Advisor == \"-1\" ? (long?)null : long.Parse(ucEstateFinder.Advisor);\n</code></pre>\n\n<p>On the assigning above if i directly assign null to finder.Advisor*(long?)* there would be no problem. But if i try to use if clause i need to cast it like that <code>(long?)null</code>.</p>\n"
},
{
"answer_id": 21494597,
"author": "Mark Hurd",
"author_id": 256431,
"author_profile": "https://Stackoverflow.com/users/256431",
"pm_score": 0,
"selected": false,
"text": "<p>Although <code>Nothing</code> can be used, your \"existing\" code is almost correct; just don't attempt to get the <code>.Value</code>:</p>\n\n<pre><code>Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)\n Get\n If Current.Request.QueryString(\"rid\") <> \"\" Then\n Return CInt(Current.Request.QueryString(\"rid\"))\n Else\n Return New Nullable(Of Integer)\n End If\n End Get\nEnd Property\n</code></pre>\n\n<p>This then becomes the simplest solution if you happen to want to reduce it to a <code>If</code> expression:</p>\n\n<pre><code>Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)\n Get\n Return If(Current.Request.QueryString(\"rid\") <> \"\", _\n CInt(Current.Request.QueryString(\"rid\")), _\n New Nullable(Of Integer))\n End Get\nEnd Property\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6776/"
]
| I have a nullable property, and I want to return a null value. How do I do that in VB.NET ?
Currently I use this solution, but I think there might be a better way.
```
Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)
Get
If Current.Request.QueryString("rid") <> "" Then
Return CInt(Current.Request.QueryString("rid"))
Else
Return (New Nullable(Of Integer)).Value
End If
End Get
End Property
``` | Are you looking for the keyword "Nothing"? |
72,458 | <p><strong>Problem</strong></p>
<p>I need to redirect some short convenience URLs to longer actual URLs. The site in question uses a set of subdomains to identify a set of development or live versions.</p>
<p>I would like the URL to which certain requests are redirected to include the HTTP_HOST such that I don't have to create a custom .htaccess file for each host.</p>
<p><strong>Host-specific Example (snipped from .htaccess file)</strong></p>
<pre><code>Redirect /terms http://support.dev01.example.com/articles/terms/
</code></pre>
<p>This example works fine for the development version running at dev01.example.com. If I use the same line in the main .htaccess file for the development version running under dev02.example.com I'd end up being redirected to the wrong place.</p>
<p><strong>Ideal rule (not sure of the correct syntax)</strong></p>
<pre><code>Redirect /terms http://support.{HTTP_HOST}/articles/terms/
</code></pre>
<p>This rule does not work and merely serves as an example of what I'd like to achieve. I could then use the exact same rule under many different hosts and get the correct result.</p>
<p><strong>Answers?</strong></p>
<ul>
<li>Can this be done with mod_alias or does it require the more complex mod_rewrite?</li>
<li>How can this be achieved using mod_alias or mod_rewrite? I'd prefer a mod_alias solution if possible.</li>
</ul>
<p><strong>Clarifications</strong></p>
<p>I'm not staying on the same server. I'd like:</p>
<ul>
<li>http://<strong>example.com</strong>/terms/ -> <a href="http://support" rel="nofollow noreferrer">http://support</a>.<strong>example.com</strong>/articles/terms/</li>
<li><a href="https://secure" rel="nofollow noreferrer">https://secure</a>.<strong>example.com</strong>/terms/ -> <a href="http://support" rel="nofollow noreferrer">http://support</a>.<strong>example.com</strong>/articles/terms/</li>
<li>http://<strong>dev.example.com</strong>/terms/ -> <a href="http://support" rel="nofollow noreferrer">http://support</a>.<strong>dev.example.com</strong>/articles/terms/</li>
<li><a href="https://secure" rel="nofollow noreferrer">https://secure</a>.<strong>dev.example.com</strong>/terms/ -> <a href="http://support" rel="nofollow noreferrer">http://support</a>.<strong>dev.example.com</strong>/articles/terms/</li>
</ul>
<p>I'd like to be able to use the same rule in the .htaccess file on both example.com and dev.example.com. In this situation I'd need to be able to refer to the HTTP_HOST as a variable rather than specifying it literally in the URL to which requests are redirected.</p>
<p>I'll investigate the HTTP_HOST parameter as suggested but was hoping for a working example.</p>
| [
{
"answer_id": 72530,
"author": "Nicholas",
"author_id": 8054,
"author_profile": "https://Stackoverflow.com/users/8054",
"pm_score": -1,
"selected": false,
"text": "<p>According to this cheatsheet ( <a href=\"http://www.addedbytes.com/download/mod_rewrite-cheat-sheet-v2/png/\" rel=\"nofollow noreferrer\">http://www.addedbytes.com/download/mod_rewrite-cheat-sheet-v2/png/</a> ) this should work</p>\n\n<pre><code>RewriteCond %{HTTP_HOST} ^www\\.domain\\.com$ [NC]\nRewriteRule ^(.*)$ http://www.domain2.com/$1\n</code></pre>\n\n<p>Note that i don't have a way to test this so this should be taken as a pointer in the right direction as opposed to an explicit answer.</p>\n"
},
{
"answer_id": 72597,
"author": "Colonel Sponsz",
"author_id": 11651,
"author_profile": "https://Stackoverflow.com/users/11651",
"pm_score": -1,
"selected": false,
"text": "<p>If you are staying on the same server then putting this in your .htaccess will work regardless of the server:</p>\n\n<pre><code>RedirectMatch 301 ^/terms$ /articles/terms/\n</code></pre>\n\n<p>Produces:</p>\n\n<pre><code>http://example.com/terms -> http://example.com/articles/terms\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>http://test.example.com/terms -> http://test.example.com/articles/terms\n</code></pre>\n\n<p>Obviously you'll need to adjust the REGEX matching and the like to make sure it copes with what you are going to throw at it. Same goes for the 301, you might want a 302 if you don't want browsers to cache the redirect.</p>\n\n<p>If you want:</p>\n\n<pre><code>http://example.com/terms -> http://server02.example.com/articles/terms\n</code></pre>\n\n<p>Then you'll need to use the HTTP_HOST parameter.</p>\n"
},
{
"answer_id": 72652,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": -1,
"selected": false,
"text": "<p>You don't need to include this information. Just provide a URI relative to the root.</p>\n\n<pre><code>Redirect temp /terms /articles/terms/\n</code></pre>\n\n<p>This is explained in <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_alias.html#redirect\" rel=\"nofollow noreferrer\">the mod_alias documentation</a>:</p>\n\n<blockquote>\n <p>The new URL should be an absolute URL beginning with a scheme and hostname, but a URL-path beginning with a slash may also be used, in which case the scheme and hostname of the current server will be added.</p>\n</blockquote>\n"
},
{
"answer_id": 72707,
"author": "Jaykul",
"author_id": 8718,
"author_profile": "https://Stackoverflow.com/users/8718",
"pm_score": -1,
"selected": false,
"text": "<p>It sounds like what you really need is just an alias?</p>\n\n<pre><code>Alias /terms /www/public/articles/terms/\n</code></pre>\n"
},
{
"answer_id": 72828,
"author": "Sean Carpenter",
"author_id": 729,
"author_profile": "https://Stackoverflow.com/users/729",
"pm_score": 0,
"selected": false,
"text": "<p>I think you'll want to capture the HTTP_HOST value and then use that in the rewrite rule: </p>\n\n<pre><code>RewriteCond %{HTTP_HOST} (.*)\nRewriteRule ^/terms http://support.%1/article/terms [NC,R=302]\n</code></pre>\n"
},
{
"answer_id": 10010128,
"author": "jornare",
"author_id": 1249477,
"author_profile": "https://Stackoverflow.com/users/1249477",
"pm_score": 0,
"selected": false,
"text": "<p>If I understand your question right, you want a 301 redirect (tell browser to go to other URL).\nIf my solution is not the correct one for you, try this tool: <a href=\"http://www.htaccessredirect.net/index.php\" rel=\"nofollow\">http://www.htaccessredirect.net/index.php</a> and figure out what works for you.</p>\n\n<pre><code>//301 Redirect Entire Directory\nRedirectMatch 301 /terms(.*) /articles/terms/$1\n\n//Change default directory page\nDirectoryIndex \n</code></pre>\n"
},
{
"answer_id": 10024434,
"author": "Olivier Pons",
"author_id": 106140,
"author_profile": "https://Stackoverflow.com/users/106140",
"pm_score": 3,
"selected": true,
"text": "<p>It's strange that nobody has done the actual <strong>working</strong> answer (lol):</p>\n\n<pre><code>RewriteCond %{HTTP_HOST} support\\.(([^\\.]+))\\.example\\.com\nRewriteRule ^/terms http://support.%1/article/terms [NC,QSA,R]\n</code></pre>\n\n<hr>\n\n<p>To help you doing the job faster, my favorite tool to check for regexp:</p>\n\n<p><a href=\"http://www.quanetic.com/Regex\" rel=\"nofollow\">http://www.quanetic.com/Regex</a> (don't forget to choose ereg(POSIX) instead of preg(PCRE)!)</p>\n\n<p>You use this tool when you want to check the URL and see if they're valid or not.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5343/"
]
| **Problem**
I need to redirect some short convenience URLs to longer actual URLs. The site in question uses a set of subdomains to identify a set of development or live versions.
I would like the URL to which certain requests are redirected to include the HTTP\_HOST such that I don't have to create a custom .htaccess file for each host.
**Host-specific Example (snipped from .htaccess file)**
```
Redirect /terms http://support.dev01.example.com/articles/terms/
```
This example works fine for the development version running at dev01.example.com. If I use the same line in the main .htaccess file for the development version running under dev02.example.com I'd end up being redirected to the wrong place.
**Ideal rule (not sure of the correct syntax)**
```
Redirect /terms http://support.{HTTP_HOST}/articles/terms/
```
This rule does not work and merely serves as an example of what I'd like to achieve. I could then use the exact same rule under many different hosts and get the correct result.
**Answers?**
* Can this be done with mod\_alias or does it require the more complex mod\_rewrite?
* How can this be achieved using mod\_alias or mod\_rewrite? I'd prefer a mod\_alias solution if possible.
**Clarifications**
I'm not staying on the same server. I'd like:
* http://**example.com**/terms/ -> <http://support>.**example.com**/articles/terms/
* <https://secure>.**example.com**/terms/ -> <http://support>.**example.com**/articles/terms/
* http://**dev.example.com**/terms/ -> <http://support>.**dev.example.com**/articles/terms/
* <https://secure>.**dev.example.com**/terms/ -> <http://support>.**dev.example.com**/articles/terms/
I'd like to be able to use the same rule in the .htaccess file on both example.com and dev.example.com. In this situation I'd need to be able to refer to the HTTP\_HOST as a variable rather than specifying it literally in the URL to which requests are redirected.
I'll investigate the HTTP\_HOST parameter as suggested but was hoping for a working example. | It's strange that nobody has done the actual **working** answer (lol):
```
RewriteCond %{HTTP_HOST} support\.(([^\.]+))\.example\.com
RewriteRule ^/terms http://support.%1/article/terms [NC,QSA,R]
```
---
To help you doing the job faster, my favorite tool to check for regexp:
<http://www.quanetic.com/Regex> (don't forget to choose ereg(POSIX) instead of preg(PCRE)!)
You use this tool when you want to check the URL and see if they're valid or not. |
72,479 | <p>Can anyone tell me what exactly does this Java code do?</p>
<pre><code>SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] bytes = new byte[20];
synchronized (random)
{
random.nextBytes(bytes);
}
return Base64.encode(bytes);
</code></pre>
<hr>
<p>Step by step explanation will be useful so that I can recreate this code in VB. Thanks</p>
| [
{
"answer_id": 72520,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>This creates a random number generator (SecureRandom). It then creates a byte array (byte[] bytes), length 20 bytes, and populates it with random data.</p>\n\n<p>This is then encoded using BASE64 and returned.</p>\n\n<p>So, in a nutshell,</p>\n\n<ol>\n<li>Generate 20 random bytes</li>\n<li>Encode using Base 64</li>\n</ol>\n"
},
{
"answer_id": 72531,
"author": "Aidos",
"author_id": 12040,
"author_profile": "https://Stackoverflow.com/users/12040",
"pm_score": 1,
"selected": false,
"text": "<p>It creates a SHA1 based random number generator (RNG), then Base64 encodes the next 20 bytes returned by the RNG.</p>\n\n<p>I can't tell you why it does this however without some more context :-).</p>\n"
},
{
"answer_id": 72588,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 1,
"selected": false,
"text": "<p>This code gets a cryptographically strong random number that is 20 bytes in length, then Base64 encodes it. There's a lot of Java library code here, so your guess is as good as mine as to how to do it in VB.</p>\n\n<pre><code>SecureRandom random = SecureRandom.getInstance(\"SHA1PRNG\");\nbyte[] bytes = new byte[20];\nsynchronized (random) { random.nextBytes(bytes); }\nreturn Base64.encode(bytes);\n</code></pre>\n\n<p>The first line creates an instance of the <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/security/SecureRandom.html\" rel=\"nofollow noreferrer\">SecureRandom</a> class. This class provides a cryptographically strong pseudo-random number generator.</p>\n\n<p>The second line declares a byte array of length 20.</p>\n\n<p>The third line reads the next 20 random bytes into the array created in line 2. It synchronizes on the SecureRandom object so that there are no conflicts from other threads that may be using the object. It's not apparent from this code why you need to do this.</p>\n\n<p>The fourth line Base64 encodes the resulting byte array. This is probably for transmission, storage, or display in a known format.</p>\n"
},
{
"answer_id": 72590,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 4,
"selected": true,
"text": "<p>Using code snippets you can get to something like this</p>\n\n<pre>\nDim randomNumGen As RandomNumberGenerator = RNGCryptoServiceProvider.Create()\nDim randomBytes(20) As Byte\nrandomNumGen.GetBytes(randomBytes)\nreturn Convert.ToBase64String(randomBytes)\n</pre>\n"
},
{
"answer_id": 72646,
"author": "Erlend",
"author_id": 5746,
"author_profile": "https://Stackoverflow.com/users/5746",
"pm_score": 0,
"selected": false,
"text": "<p>Basically the code above:</p>\n\n<ol>\n<li>Creates a secure random number generator (for VB see link below)</li>\n<li>Fills a bytearray of length 20 with random bytes</li>\n<li>Base64 encodes the result (you can probably use Convert.ToBase64String(...))</li>\n</ol>\n\n<p>You should find some help here:\n<a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx</a></p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12178/"
]
| Can anyone tell me what exactly does this Java code do?
```
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] bytes = new byte[20];
synchronized (random)
{
random.nextBytes(bytes);
}
return Base64.encode(bytes);
```
---
Step by step explanation will be useful so that I can recreate this code in VB. Thanks | Using code snippets you can get to something like this
```
Dim randomNumGen As RandomNumberGenerator = RNGCryptoServiceProvider.Create()
Dim randomBytes(20) As Byte
randomNumGen.GetBytes(randomBytes)
return Convert.ToBase64String(randomBytes)
``` |
72,515 | <p>I have a Windows application that uses a .NET PropertyGrid control. Is it possible to change the type of control that is used for the value field of a property?</p>
<p>I would like to be able to use a RichTextBox to allow better formatting of the input value.
Can this be done without creating a custom editor class?</p>
| [
{
"answer_id": 72538,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 0,
"selected": false,
"text": "<p>I think what you are looking for is Custom Type Descriptors.\nYou could read up a bit and get started here: <a href=\"http://www.codeproject.com/KB/miscctrl/bending_property.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/miscctrl/bending_property.aspx</a></p>\n\n<p>I am not sure you can do any control you want, but that article got me started on propertygrids.</p>\n"
},
{
"answer_id": 72607,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 1,
"selected": false,
"text": "<p>You can control whether the PropertyGrid displays a simple edit box, a drop-down arrow, or an ellipsis control.</p>\n\n<p>Look up EditorAttribute, and follow it on from there. I did have a sample somewhere; I'll try to dig it out.</p>\n"
},
{
"answer_id": 72651,
"author": "Phil Wright",
"author_id": 6276,
"author_profile": "https://Stackoverflow.com/users/6276",
"pm_score": 3,
"selected": true,
"text": "<p>To add your own custom editing when the user selects a property grid value you need to implement a class that derives from UITypeEditor. You then have the choice of showing just a small popup window below the property area or a full blown dialog box.</p>\n\n<p>What is nice is that you can reuse the existing implementations. So to add the ability to multiline edit a string you just do this...</p>\n\n<pre><code>[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]\npublic override string Text\n{\n get { return _string; }\n set { _string = value; }\n}\n</code></pre>\n\n<p>Another nice one they provide for you is the ability to edit an array of strings...</p>\n\n<pre><code>[Editor(\"System.Windows.Forms.Design.StringArrayEditor, \n System.Design, Version=2.0.0.0, \n Culture=neutral, \n PublicKeyToken=b03f5f7f11d50a3a\", \n typeof(UITypeEditor))]\npublic string[] Lines\n{\n get { return _lines; }\n set { _lines = value; }\n}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2533/"
]
| I have a Windows application that uses a .NET PropertyGrid control. Is it possible to change the type of control that is used for the value field of a property?
I would like to be able to use a RichTextBox to allow better formatting of the input value.
Can this be done without creating a custom editor class? | To add your own custom editing when the user selects a property grid value you need to implement a class that derives from UITypeEditor. You then have the choice of showing just a small popup window below the property area or a full blown dialog box.
What is nice is that you can reuse the existing implementations. So to add the ability to multiline edit a string you just do this...
```
[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]
public override string Text
{
get { return _string; }
set { _string = value; }
}
```
Another nice one they provide for you is the ability to edit an array of strings...
```
[Editor("System.Windows.Forms.Design.StringArrayEditor,
System.Design, Version=2.0.0.0,
Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a",
typeof(UITypeEditor))]
public string[] Lines
{
get { return _lines; }
set { _lines = value; }
}
``` |
72,552 | <p>What does the <code>volatile</code> keyword do? In C++ what problem does it solve?</p>
<p>In my case, I have never knowingly needed it.</p>
| [
{
"answer_id": 72576,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 7,
"selected": false,
"text": "<p><code>volatile</code> is needed when developing embedded systems or device drivers, where you need to read or write a memory-mapped hardware device. The contents of a particular device register could change at any time, so you need the <code>volatile</code> keyword to ensure that such accesses aren't optimised away by the compiler.</p>\n"
},
{
"answer_id": 72617,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 9,
"selected": true,
"text": "<p><code>volatile</code> is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to.</p>\n\n<p>I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially we did this:</p>\n\n<pre><code>void waitForSemaphore()\n{\n volatile uint16_t* semPtr = WELL_KNOWN_SEM_ADDR;/*well known address to my semaphore*/\n while ((*semPtr) != IS_OK_FOR_ME_TO_PROCEED);\n}\n</code></pre>\n\n<p>Without <code>volatile</code>, the optimizer sees the loop as useless (The guy never sets the value! He's nuts, get rid of that code!) and my code would proceed without having acquired the semaphore, causing problems later on.</p>\n"
},
{
"answer_id": 72629,
"author": "Mladen Janković",
"author_id": 6300,
"author_profile": "https://Stackoverflow.com/users/6300",
"pm_score": 3,
"selected": false,
"text": "<ol>\n<li>you must use it to implement spinlocks as well as some (all?) lock-free data structures</li>\n<li>use it with atomic operations/instructions</li>\n<li>helped me once to overcome compiler's bug (wrongly generated code during optimization)</li>\n</ol>\n"
},
{
"answer_id": 72666,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Developing for an embedded, I have a loop that checks on a variable that can be changed in an interrupt handler. Without \"volatile\", the loop becomes a noop - as far as the compiler can tell, the variable never changes, so it optimizes the check away.</p>\n\n<p>Same thing would apply to a variable that may be changed in a different thread in a more traditional environment, but there we often do synchronization calls, so compiler is not so free with optimization.</p>\n"
},
{
"answer_id": 72962,
"author": "MikeZ",
"author_id": 12402,
"author_profile": "https://Stackoverflow.com/users/12402",
"pm_score": 6,
"selected": false,
"text": "<p>From a <em>\"Volatile as a promise\"</em> article by Dan Saks:</p>\n\n<blockquote>\n <p>(...) a volatile object is one whose value might change spontaneously. That is, when you declare an object to be volatile, you're telling the compiler that the object might change state even though no statements in the program appear to change it.\"</p>\n</blockquote>\n\n<p>Here are links to three of his articles regarding the <code>volatile</code> keyword:</p>\n\n<ul>\n<li><a href=\"https://www.embedded.com/electronics-blogs/programming-pointers/4025583/Use-volatile-judiciously\" rel=\"noreferrer\">Use volatile judiciously</a></li>\n<li><a href=\"https://www.embedded.com/electronics-blogs/programming-pointers/4025609/Place-volatile-accurately\" rel=\"noreferrer\">Place volatile accurately</a></li>\n<li><a href=\"https://www.embedded.com/electronics-blogs/programming-pointers/4025624/Volatile-as-a-promise\" rel=\"noreferrer\">Volatile as a promise</a></li>\n</ul>\n"
},
{
"answer_id": 73520,
"author": "tfinniga",
"author_id": 9042,
"author_profile": "https://Stackoverflow.com/users/9042",
"pm_score": 6,
"selected": false,
"text": "<p>Some processors have floating point registers that have more than 64 bits of precision (eg. 32-bit x86 without SSE, see Peter's comment). That way, if you run several operations on double-precision numbers, you actually get a higher-precision answer than if you were to truncate each intermediate result to 64 bits.</p>\n\n<p>This is usually great, but it means that depending on how the compiler assigned registers and did optimizations you'll have different results for the exact same operations on the exact same inputs. If you need consistency then you can force each operation to go back to memory by using the volatile keyword.</p>\n\n<p>It's also useful for some algorithms that make no algebraic sense but reduce floating point error, such as Kahan summation. Algebraicly it's a nop, so it will often get incorrectly optimized out unless some intermediate variables are volatile.</p>\n"
},
{
"answer_id": 77042,
"author": "INS",
"author_id": 13136,
"author_profile": "https://Stackoverflow.com/users/13136",
"pm_score": 2,
"selected": false,
"text": "<p>Beside the fact that the volatile keyword is used for telling the compiler not to optimize the access to some variable (that can be modified by a thread or an interrupt routine), it can be also <strong>used to remove some compiler bugs</strong> -- <em>YES it can be</em> ---.</p>\n\n<p>For example I worked on an embedded platform were the compiler was making some wrong assuptions regarding a value of a variable. If the code wasn't optimized the program would run ok. With optimizations (which were really needed because it was a critical routine) the code wouldn't work correctly. The only solution (though not very correct) was to declare the 'faulty' variable as volatile.</p>\n"
},
{
"answer_id": 77057,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>A large application that I used to work on in the early 1990s contained C-based exception handling using setjmp and longjmp. The volatile keyword was necessary on variables whose values needed to be preserved in the block of code that served as the \"catch\" clause, lest those vars be stored in registers and wiped out by the longjmp.</p>\n"
},
{
"answer_id": 77141,
"author": "indentation",
"author_id": 7706,
"author_profile": "https://Stackoverflow.com/users/7706",
"pm_score": 3,
"selected": false,
"text": "<p>I've used it in debug builds when the compiler insists on optimizing away a variable that I want to be able to see as I step through code.</p>\n"
},
{
"answer_id": 81460,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 3,
"selected": false,
"text": "<p>Besides using it as intended, volatile is used in (template) metaprogramming. It can be used to prevent accidental overloading, as the volatile attribute (like const) takes part in overload resolution.</p>\n\n<pre><code>template <typename T> \nclass Foo {\n std::enable_if_t<sizeof(T)==4, void> f(T& t) \n { std::cout << 1 << t; }\n void f(T volatile& t) \n { std::cout << 2 << const_cast<T&>(t); }\n\n void bar() { T t; f(t); }\n};\n</code></pre>\n\n<p>This is legal; both overloads are potentially callable and do almost the same. The cast in the <code>volatile</code> overload is legal as we know bar won't pass a non-volatile <code>T</code> anyway. The <code>volatile</code> version is strictly worse, though, so never chosen in overload resolution if the non-volatile <code>f</code> is available.</p>\n\n<p>Note that the code never actually depends on <code>volatile</code> memory access.</p>\n"
},
{
"answer_id": 82306,
"author": "Frederik Slijkerman",
"author_id": 12416,
"author_profile": "https://Stackoverflow.com/users/12416",
"pm_score": 5,
"selected": false,
"text": "<p>You MUST use volatile when implementing lock-free data structures. Otherwise the compiler is free to optimize access to the variable, which will change the semantics.</p>\n\n<p>To put it another way, volatile tells the compiler that accesses to this variable must correspond to a physical memory read/write operation.</p>\n\n<p>For example, this is how InterlockedIncrement is declared in the Win32 API:</p>\n\n<pre><code>LONG __cdecl InterlockedIncrement(\n __inout LONG volatile *Addend\n);\n</code></pre>\n"
},
{
"answer_id": 17900959,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": false,
"text": "<p>In Standard C, one of the places to use <code>volatile</code> is with a signal handler. In fact, in Standard C, all you can safely do in a signal handler is modify a <code>volatile sig_atomic_t</code> variable, or exit quickly. Indeed, AFAIK, it is the only place in Standard C that the use of <code>volatile</code> is required to avoid undefined behaviour.</p>\n\n<blockquote>\n <h3>ISO/IEC 9899:2011 §7.14.1.1 The <code>signal</code> function</h3>\n \n <p>¶5 If the signal occurs other than as the result of calling the <code>abort</code> or <code>raise</code> function, the\n behavior is undefined if the signal handler refers to any object with static or thread\n storage duration that is not a lock-free atomic object other than by assigning a value to an\n object declared as <code>volatile sig_atomic_t</code>, or the signal handler calls any function\n in the standard library other than the <code>abort</code> function, the <code>_Exit</code> function, the\n <code>quick_exit</code> function, or the <code>signal</code> function with the first argument equal to the\n signal number corresponding to the signal that caused the invocation of the handler.\n Furthermore, if such a call to the <code>signal</code> function results in a SIG_ERR return, the\n value of <code>errno</code> is indeterminate.<sup>252)</sup></p>\n \n <p><sup>252)</sup> If any signal is generated by an asynchronous signal handler, the behavior is undefined.</p>\n</blockquote>\n\n<p>That means that in Standard C, you can write:</p>\n\n<pre><code>static volatile sig_atomic_t sig_num = 0;\n\nstatic void sig_handler(int signum)\n{\n signal(signum, sig_handler);\n sig_num = signum;\n}\n</code></pre>\n\n<p>and not much else.</p>\n\n<p>POSIX is a lot more lenient about what you can do in a signal handler, but there are still limitations (and one of the limitations is that the Standard I/O library — <code>printf()</code> et al — cannot be used safely).</p>\n"
},
{
"answer_id": 39875143,
"author": "roottraveller",
"author_id": 5167682,
"author_profile": "https://Stackoverflow.com/users/5167682",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>volatile</code> keyword is intended to prevent the compiler from applying any optimisations on objects that can change in ways that cannot be determined by the compiler.</p>\n\n<p>Objects declared as <code>volatile</code> are omitted from optimisation because their values can be changed by code outside the scope of current code at any time. The system always reads the current value of a <code>volatile</code> object from the memory location rather than keeping its value in temporary register at the point it is requested, even if a previous instruction asked for a value from the same object.</p>\n\n<p><strong>Consider the following cases</strong></p>\n\n<p>1) Global variables modified by an interrupt service routine outside the scope.</p>\n\n<p>2) Global variables within a multi-threaded application.</p>\n\n<p><strong>If we do not use volatile qualifier, the following problems may arise</strong></p>\n\n<p>1) Code may not work as expected when optimisation is turned on.</p>\n\n<p>2) Code may not work as expected when interrupts are enabled and used.</p>\n\n<p><a href=\"http://www.drdobbs.com/cpp/volatile-the-multithreaded-programmers-b/184403766\" rel=\"nofollow\">Volatile: A programmer’s best friend</a></p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Volatile_(computer_programming)\" rel=\"nofollow\">https://en.wikipedia.org/wiki/Volatile_(computer_programming)</a></p>\n"
},
{
"answer_id": 43802700,
"author": "bugs king",
"author_id": 1211764,
"author_profile": "https://Stackoverflow.com/users/1211764",
"pm_score": 1,
"selected": false,
"text": "<p>One use I should remind you is, in the signal handler function, if you want to access/modify a global variable (for example, mark it as exit = true) you have to declare that variable as 'volatile'.</p>\n"
},
{
"answer_id": 46888720,
"author": "Joachim",
"author_id": 1961484,
"author_profile": "https://Stackoverflow.com/users/1961484",
"pm_score": 2,
"selected": false,
"text": "<p>Your program seems to work even without <code>volatile</code> keyword? Perhaps this is the reason:</p>\n\n<p>As mentioned previously the <code>volatile</code> keyword helps for cases like</p>\n\n<pre><code>volatile int* p = ...; // point to some memory\nwhile( *p!=0 ) {} // loop until the memory becomes zero\n</code></pre>\n\n<p>But there seems to be almost no effect once an external or non-inline function is being called. E.g.:</p>\n\n<pre><code>while( *p!=0 ) { g(); }\n</code></pre>\n\n<p>Then with or without <code>volatile</code> almost the same result is generated.</p>\n\n<p>As long as g() can be completely inlined, the compiler can see everything that's going on and can therefore optimize. But when the program makes a call to a place where the compiler can't see what's going on, it isn't safe for the compiler to make any assumptions any more. Hence the compiler will generate code that always reads from memory directly.</p>\n\n<p>But beware of the day, when your function g() becomes inline (either due to explicit changes or due to compiler/linker cleverness) then your code might break if you forgot the <code>volatile</code> keyword!</p>\n\n<p>Therefore I recommend to add the <code>volatile</code> keyword even if your program seems to work without. It makes the intention clearer and more robust in respect to future changes.</p>\n"
},
{
"answer_id": 51598967,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 2,
"selected": false,
"text": "<p>In the early days of C, compilers would interpret all actions that read and write lvalues as memory operations, to be performed in the same sequence as the reads and writes appeared in the code. Efficiency could be greatly improved in many cases if compilers were given a certain amount of freedom to re-order and consolidate operations, but there was a problem with this. Even though operations were often specified in a certain order merely because it was necessary to specify them in <em>some</em> order, and thus the programmer picked one of many equally-good alternatives, that wasn't always the case. Sometimes it would be important that certain operations occur in a particular sequence.</p>\n<p>Exactly which details of sequencing are important will vary depending upon the target platform and application field. Rather than provide particularly detailed control, the Standard opted for a simple model: if a sequence of accesses are done with lvalues that are not qualified <code>volatile</code>, a compiler may reorder and consolidate them as it sees fit. If an action is done with a <code>volatile</code>-qualified lvalue, a quality implementation should offer whatever additional ordering guarantees might be required by code targeting its intended platform and application field, without requiring that programmers use non-standard syntax.</p>\n<p>Unfortunately, rather than identify what guarantees programmers would need, many compilers have opted instead to offer the bare minimum guarantees mandated by the Standard. This makes <code>volatile</code> much less useful than it should be. On gcc or clang, for example, a programmer needing to implement a basic "hand-off mutex" [one where a task that has acquired and released a mutex won't do so again until the other task has done so] must do one of four things:</p>\n<ol>\n<li><p>Put the acquisition and release of the mutex in a function that the compiler cannot inline, and to which it cannot apply Whole Program Optimization.</p>\n</li>\n<li><p>Qualify all the objects guarded by the mutex as <code>volatile</code>--something which shouldn't be necessary if all accesses occur after acquiring the mutex and before releasing it.</p>\n</li>\n<li><p>Use optimization level 0 to force the compiler to generate code as though all objects that aren't qualified <code>register</code> are <code>volatile</code>.</p>\n</li>\n<li><p>Use gcc-specific directives.</p>\n</li>\n</ol>\n<p>By contrast, when using a higher-quality compiler which is more suitable for systems programming, such as icc, one would have another option:</p>\n<ol start=\"5\">\n<li>Make sure that a <code>volatile</code>-qualified write gets performed everyplace an acquire or release is needed.</li>\n</ol>\n<p>Acquiring a basic "hand-off mutex" requires a <code>volatile</code> read (to see if it's ready), and shouldn't require a <code>volatile</code> write as well (the other side won't try to re-acquire it until it's handed back) but having to perform a meaningless <code>volatile</code> write is still better than any of the options available under gcc or clang.</p>\n"
},
{
"answer_id": 59002919,
"author": "curiousguy",
"author_id": 963864,
"author_profile": "https://Stackoverflow.com/users/963864",
"pm_score": 2,
"selected": false,
"text": "<p>Other answers already mention avoiding some optimization in order to:</p>\n\n<ul>\n<li>use memory mapped registers (or \"MMIO\")</li>\n<li>write device drivers</li>\n<li>allow easier debugging of programs</li>\n<li>make floating point computations more deterministic </li>\n</ul>\n\n<p>Volatile is essential whenever you need a value to appear to come from the outside and be unpredictable and avoid compiler optimizations based on a value being known, and when a result isn't actually used but you need it to be computed, or it's used but you want to compute it several times for a benchmark, and you need the computations to start and end at precise points.</p>\n\n<p>A volatile read is like an input operation (like <code>scanf</code> or a use of <code>cin</code>): <em>the value seems to come from the outside of the program, so any computation that has a dependency on the value needs to start after it</em>. </p>\n\n<p>A volatile write is like an output operation (like <code>printf</code> or a use of <code>cout</code>): <em>the value seems to be communicated outside of the program, so if the value depends on a computation, it needs to be finished before</em>.</p>\n\n<p>So <strong>a pair of volatile read/write can be used to tame benchmarks and make time measurement meaningful</strong>.</p>\n\n<p>Without volatile, your computation could be started by the compiler before, <strong>as nothing would prevent reordering of computations with functions such as time measurement</strong>.</p>\n"
},
{
"answer_id": 61495883,
"author": "Rohit",
"author_id": 3049983,
"author_profile": "https://Stackoverflow.com/users/3049983",
"pm_score": 2,
"selected": false,
"text": "<p>All answers are excellent. But on the top of that, I would like to share an example.</p>\n\n<p>Below is a little cpp program:</p>\n\n<pre><code>#include <iostream>\n\nint x;\n\nint main(){\n char buf[50];\n x = 8;\n\n if(x == 8)\n printf(\"x is 8\\n\");\n else\n sprintf(buf, \"x is not 8\\n\");\n\n x=1000;\n while(x > 5)\n x--;\n return 0;\n}\n</code></pre>\n\n<p>Now, lets generate the assembly of the above code (and I will paste only that portions of the assembly which relevant here):</p>\n\n<p>The command to generate assembly:</p>\n\n<pre><code>g++ -S -O3 -c -fverbose-asm -Wa,-adhln assembly.cpp\n</code></pre>\n\n<p>And the assembly:</p>\n\n<pre><code>main:\n.LFB1594:\n subq $40, %rsp #,\n .seh_stackalloc 40\n .seh_endprologue\n # assembly.cpp:5: int main(){\n call __main #\n # assembly.cpp:10: printf(\"x is 8\\n\");\n leaq .LC0(%rip), %rcx #,\n # assembly.cpp:7: x = 8;\n movl $8, x(%rip) #, x\n # assembly.cpp:10: printf(\"x is 8\\n\");\n call _ZL6printfPKcz.constprop.0 #\n # assembly.cpp:18: }\n xorl %eax, %eax #\n movl $5, x(%rip) #, x\n addq $40, %rsp #,\n ret \n .seh_endproc\n .p2align 4,,15\n .def _GLOBAL__sub_I_x; .scl 3; .type 32; .endef\n .seh_proc _GLOBAL__sub_I_x\n</code></pre>\n\n<p>You can see in the assembly that the assembly code was not generated for <code>sprintf</code> because the compiler assumed that <code>x</code> will not change outside of the program. And same is the case with the <code>while</code> loop. <code>while</code> loop was altogether removed due to the optimization because compiler saw it as a useless code and thus directly assigned <code>5</code> to <code>x</code> (see <code>movl $5, x(%rip)</code>).</p>\n\n<p>The problem occurs when what if an external process/ hardware would change the value of <code>x</code> somewhere between <code>x = 8;</code> and <code>if(x == 8)</code>. We would expect <code>else</code> block to work but unfortunately the compiler has trimmed out that part. </p>\n\n<p>Now, in order to solve this, in the <code>assembly.cpp</code>, let us change <code>int x;</code> to <code>volatile int x;</code> and quickly see the assembly code generated:</p>\n\n<pre><code>main:\n.LFB1594:\n subq $104, %rsp #,\n .seh_stackalloc 104\n .seh_endprologue\n # assembly.cpp:5: int main(){\n call __main #\n # assembly.cpp:7: x = 8;\n movl $8, x(%rip) #, x\n # assembly.cpp:9: if(x == 8)\n movl x(%rip), %eax # x, x.1_1\n # assembly.cpp:9: if(x == 8)\n cmpl $8, %eax #, x.1_1\n je .L11 #,\n # assembly.cpp:12: sprintf(buf, \"x is not 8\\n\");\n leaq 32(%rsp), %rcx #, tmp93\n leaq .LC0(%rip), %rdx #,\n call _ZL7sprintfPcPKcz.constprop.0 #\n.L7:\n # assembly.cpp:14: x=1000;\n movl $1000, x(%rip) #, x\n # assembly.cpp:15: while(x > 5)\n movl x(%rip), %eax # x, x.3_15\n cmpl $5, %eax #, x.3_15\n jle .L8 #,\n .p2align 4,,10\n.L9:\n # assembly.cpp:16: x--;\n movl x(%rip), %eax # x, x.4_3\n subl $1, %eax #, _4\n movl %eax, x(%rip) # _4, x\n # assembly.cpp:15: while(x > 5)\n movl x(%rip), %eax # x, x.3_2\n cmpl $5, %eax #, x.3_2\n jg .L9 #,\n.L8:\n # assembly.cpp:18: }\n xorl %eax, %eax #\n addq $104, %rsp #,\n ret \n.L11:\n # assembly.cpp:10: printf(\"x is 8\\n\");\n leaq .LC1(%rip), %rcx #,\n call _ZL6printfPKcz.constprop.1 #\n jmp .L7 #\n .seh_endproc\n .p2align 4,,15\n .def _GLOBAL__sub_I_x; .scl 3; .type 32; .endef\n .seh_proc _GLOBAL__sub_I_x\n</code></pre>\n\n<p>Here you can see that the assembly codes for <code>sprintf</code>, <code>printf</code> and <code>while</code> loop were generated. The advantage is that if the <code>x</code> variable is changed by some external program or hardware, <code>sprintf</code> part of the code will be executed. And similarly <code>while</code> loop can be used for busy waiting now.</p>\n"
},
{
"answer_id": 65641563,
"author": "alex_noname",
"author_id": 13782669,
"author_profile": "https://Stackoverflow.com/users/13782669",
"pm_score": 1,
"selected": false,
"text": "<p>I would like to quote Herb Sutter's words from his <a href=\"https://herbsutter.com/2014/01/13/gotw-95-solution-thread-safety-and-synchronization/\" rel=\"nofollow noreferrer\">GotW #95</a>, which can help to understand the meaning of the <code>volatile</code> variables:</p>\n<blockquote>\n<p><code>C++</code> <code>volatile</code> variables (which have no analog in languages like <code>C#</code> and <code>Java</code>) are always beyond the scope of this and any other article about the memory model and synchronization. That’s because <code>C++</code> <code>volatile</code> variables aren’t about threads or communication at all and don’t interact with those things. Rather, a <code>C++</code> <code>volatile</code> variable should be viewed as portal into a different universe beyond the language — a memory location that by definition does not obey the language’s memory model because that memory location is accessed by hardware (e.g., written to by a daughter card), have more than one address, or is otherwise “strange” and beyond the language. So <code>C++</code> <code>volatile</code> variables are universally an exception to every guideline about synchronization because are always inherently “racy” and unsynchronizable using the normal tools (mutexes, atomics, etc.) and more generally exist outside all normal of the language and compiler including that they generally cannot be optimized by the compiler (because the compiler isn’t allowed to know their semantics; a <code>volatile int vi;</code> may not behave anything like a normal <code>int</code>, and you can’t even assume that code like <code>vi = 5; int read_back = vi;</code> is guaranteed to result in <code>read_back == 5</code>, or that code like <code>int i = vi; int j = vi;</code> that reads vi twice will result in <code>i == j</code> which will not be true if <code>vi</code> is a hardware counter for example).</p>\n</blockquote>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2167252/"
]
| What does the `volatile` keyword do? In C++ what problem does it solve?
In my case, I have never knowingly needed it. | `volatile` is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to.
I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially we did this:
```
void waitForSemaphore()
{
volatile uint16_t* semPtr = WELL_KNOWN_SEM_ADDR;/*well known address to my semaphore*/
while ((*semPtr) != IS_OK_FOR_ME_TO_PROCEED);
}
```
Without `volatile`, the optimizer sees the loop as useless (The guy never sets the value! He's nuts, get rid of that code!) and my code would proceed without having acquired the semaphore, causing problems later on. |
72,556 | <p>I am playing with Microsoft's TreeView control and I am trying to force a data update of some sorts while editing a node's label, similar to UpdateData for a grid.</p>
<p>Basically, in my editor, I have a Save button and this TreeView control: what I want is when I am editing a node's label in the TreeView, if I click on the Save button I want to be able to commit the node's label I was editing.</p>
| [
{
"answer_id": 72576,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 7,
"selected": false,
"text": "<p><code>volatile</code> is needed when developing embedded systems or device drivers, where you need to read or write a memory-mapped hardware device. The contents of a particular device register could change at any time, so you need the <code>volatile</code> keyword to ensure that such accesses aren't optimised away by the compiler.</p>\n"
},
{
"answer_id": 72617,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 9,
"selected": true,
"text": "<p><code>volatile</code> is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to.</p>\n\n<p>I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially we did this:</p>\n\n<pre><code>void waitForSemaphore()\n{\n volatile uint16_t* semPtr = WELL_KNOWN_SEM_ADDR;/*well known address to my semaphore*/\n while ((*semPtr) != IS_OK_FOR_ME_TO_PROCEED);\n}\n</code></pre>\n\n<p>Without <code>volatile</code>, the optimizer sees the loop as useless (The guy never sets the value! He's nuts, get rid of that code!) and my code would proceed without having acquired the semaphore, causing problems later on.</p>\n"
},
{
"answer_id": 72629,
"author": "Mladen Janković",
"author_id": 6300,
"author_profile": "https://Stackoverflow.com/users/6300",
"pm_score": 3,
"selected": false,
"text": "<ol>\n<li>you must use it to implement spinlocks as well as some (all?) lock-free data structures</li>\n<li>use it with atomic operations/instructions</li>\n<li>helped me once to overcome compiler's bug (wrongly generated code during optimization)</li>\n</ol>\n"
},
{
"answer_id": 72666,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Developing for an embedded, I have a loop that checks on a variable that can be changed in an interrupt handler. Without \"volatile\", the loop becomes a noop - as far as the compiler can tell, the variable never changes, so it optimizes the check away.</p>\n\n<p>Same thing would apply to a variable that may be changed in a different thread in a more traditional environment, but there we often do synchronization calls, so compiler is not so free with optimization.</p>\n"
},
{
"answer_id": 72962,
"author": "MikeZ",
"author_id": 12402,
"author_profile": "https://Stackoverflow.com/users/12402",
"pm_score": 6,
"selected": false,
"text": "<p>From a <em>\"Volatile as a promise\"</em> article by Dan Saks:</p>\n\n<blockquote>\n <p>(...) a volatile object is one whose value might change spontaneously. That is, when you declare an object to be volatile, you're telling the compiler that the object might change state even though no statements in the program appear to change it.\"</p>\n</blockquote>\n\n<p>Here are links to three of his articles regarding the <code>volatile</code> keyword:</p>\n\n<ul>\n<li><a href=\"https://www.embedded.com/electronics-blogs/programming-pointers/4025583/Use-volatile-judiciously\" rel=\"noreferrer\">Use volatile judiciously</a></li>\n<li><a href=\"https://www.embedded.com/electronics-blogs/programming-pointers/4025609/Place-volatile-accurately\" rel=\"noreferrer\">Place volatile accurately</a></li>\n<li><a href=\"https://www.embedded.com/electronics-blogs/programming-pointers/4025624/Volatile-as-a-promise\" rel=\"noreferrer\">Volatile as a promise</a></li>\n</ul>\n"
},
{
"answer_id": 73520,
"author": "tfinniga",
"author_id": 9042,
"author_profile": "https://Stackoverflow.com/users/9042",
"pm_score": 6,
"selected": false,
"text": "<p>Some processors have floating point registers that have more than 64 bits of precision (eg. 32-bit x86 without SSE, see Peter's comment). That way, if you run several operations on double-precision numbers, you actually get a higher-precision answer than if you were to truncate each intermediate result to 64 bits.</p>\n\n<p>This is usually great, but it means that depending on how the compiler assigned registers and did optimizations you'll have different results for the exact same operations on the exact same inputs. If you need consistency then you can force each operation to go back to memory by using the volatile keyword.</p>\n\n<p>It's also useful for some algorithms that make no algebraic sense but reduce floating point error, such as Kahan summation. Algebraicly it's a nop, so it will often get incorrectly optimized out unless some intermediate variables are volatile.</p>\n"
},
{
"answer_id": 77042,
"author": "INS",
"author_id": 13136,
"author_profile": "https://Stackoverflow.com/users/13136",
"pm_score": 2,
"selected": false,
"text": "<p>Beside the fact that the volatile keyword is used for telling the compiler not to optimize the access to some variable (that can be modified by a thread or an interrupt routine), it can be also <strong>used to remove some compiler bugs</strong> -- <em>YES it can be</em> ---.</p>\n\n<p>For example I worked on an embedded platform were the compiler was making some wrong assuptions regarding a value of a variable. If the code wasn't optimized the program would run ok. With optimizations (which were really needed because it was a critical routine) the code wouldn't work correctly. The only solution (though not very correct) was to declare the 'faulty' variable as volatile.</p>\n"
},
{
"answer_id": 77057,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>A large application that I used to work on in the early 1990s contained C-based exception handling using setjmp and longjmp. The volatile keyword was necessary on variables whose values needed to be preserved in the block of code that served as the \"catch\" clause, lest those vars be stored in registers and wiped out by the longjmp.</p>\n"
},
{
"answer_id": 77141,
"author": "indentation",
"author_id": 7706,
"author_profile": "https://Stackoverflow.com/users/7706",
"pm_score": 3,
"selected": false,
"text": "<p>I've used it in debug builds when the compiler insists on optimizing away a variable that I want to be able to see as I step through code.</p>\n"
},
{
"answer_id": 81460,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 3,
"selected": false,
"text": "<p>Besides using it as intended, volatile is used in (template) metaprogramming. It can be used to prevent accidental overloading, as the volatile attribute (like const) takes part in overload resolution.</p>\n\n<pre><code>template <typename T> \nclass Foo {\n std::enable_if_t<sizeof(T)==4, void> f(T& t) \n { std::cout << 1 << t; }\n void f(T volatile& t) \n { std::cout << 2 << const_cast<T&>(t); }\n\n void bar() { T t; f(t); }\n};\n</code></pre>\n\n<p>This is legal; both overloads are potentially callable and do almost the same. The cast in the <code>volatile</code> overload is legal as we know bar won't pass a non-volatile <code>T</code> anyway. The <code>volatile</code> version is strictly worse, though, so never chosen in overload resolution if the non-volatile <code>f</code> is available.</p>\n\n<p>Note that the code never actually depends on <code>volatile</code> memory access.</p>\n"
},
{
"answer_id": 82306,
"author": "Frederik Slijkerman",
"author_id": 12416,
"author_profile": "https://Stackoverflow.com/users/12416",
"pm_score": 5,
"selected": false,
"text": "<p>You MUST use volatile when implementing lock-free data structures. Otherwise the compiler is free to optimize access to the variable, which will change the semantics.</p>\n\n<p>To put it another way, volatile tells the compiler that accesses to this variable must correspond to a physical memory read/write operation.</p>\n\n<p>For example, this is how InterlockedIncrement is declared in the Win32 API:</p>\n\n<pre><code>LONG __cdecl InterlockedIncrement(\n __inout LONG volatile *Addend\n);\n</code></pre>\n"
},
{
"answer_id": 17900959,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": false,
"text": "<p>In Standard C, one of the places to use <code>volatile</code> is with a signal handler. In fact, in Standard C, all you can safely do in a signal handler is modify a <code>volatile sig_atomic_t</code> variable, or exit quickly. Indeed, AFAIK, it is the only place in Standard C that the use of <code>volatile</code> is required to avoid undefined behaviour.</p>\n\n<blockquote>\n <h3>ISO/IEC 9899:2011 §7.14.1.1 The <code>signal</code> function</h3>\n \n <p>¶5 If the signal occurs other than as the result of calling the <code>abort</code> or <code>raise</code> function, the\n behavior is undefined if the signal handler refers to any object with static or thread\n storage duration that is not a lock-free atomic object other than by assigning a value to an\n object declared as <code>volatile sig_atomic_t</code>, or the signal handler calls any function\n in the standard library other than the <code>abort</code> function, the <code>_Exit</code> function, the\n <code>quick_exit</code> function, or the <code>signal</code> function with the first argument equal to the\n signal number corresponding to the signal that caused the invocation of the handler.\n Furthermore, if such a call to the <code>signal</code> function results in a SIG_ERR return, the\n value of <code>errno</code> is indeterminate.<sup>252)</sup></p>\n \n <p><sup>252)</sup> If any signal is generated by an asynchronous signal handler, the behavior is undefined.</p>\n</blockquote>\n\n<p>That means that in Standard C, you can write:</p>\n\n<pre><code>static volatile sig_atomic_t sig_num = 0;\n\nstatic void sig_handler(int signum)\n{\n signal(signum, sig_handler);\n sig_num = signum;\n}\n</code></pre>\n\n<p>and not much else.</p>\n\n<p>POSIX is a lot more lenient about what you can do in a signal handler, but there are still limitations (and one of the limitations is that the Standard I/O library — <code>printf()</code> et al — cannot be used safely).</p>\n"
},
{
"answer_id": 39875143,
"author": "roottraveller",
"author_id": 5167682,
"author_profile": "https://Stackoverflow.com/users/5167682",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>volatile</code> keyword is intended to prevent the compiler from applying any optimisations on objects that can change in ways that cannot be determined by the compiler.</p>\n\n<p>Objects declared as <code>volatile</code> are omitted from optimisation because their values can be changed by code outside the scope of current code at any time. The system always reads the current value of a <code>volatile</code> object from the memory location rather than keeping its value in temporary register at the point it is requested, even if a previous instruction asked for a value from the same object.</p>\n\n<p><strong>Consider the following cases</strong></p>\n\n<p>1) Global variables modified by an interrupt service routine outside the scope.</p>\n\n<p>2) Global variables within a multi-threaded application.</p>\n\n<p><strong>If we do not use volatile qualifier, the following problems may arise</strong></p>\n\n<p>1) Code may not work as expected when optimisation is turned on.</p>\n\n<p>2) Code may not work as expected when interrupts are enabled and used.</p>\n\n<p><a href=\"http://www.drdobbs.com/cpp/volatile-the-multithreaded-programmers-b/184403766\" rel=\"nofollow\">Volatile: A programmer’s best friend</a></p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Volatile_(computer_programming)\" rel=\"nofollow\">https://en.wikipedia.org/wiki/Volatile_(computer_programming)</a></p>\n"
},
{
"answer_id": 43802700,
"author": "bugs king",
"author_id": 1211764,
"author_profile": "https://Stackoverflow.com/users/1211764",
"pm_score": 1,
"selected": false,
"text": "<p>One use I should remind you is, in the signal handler function, if you want to access/modify a global variable (for example, mark it as exit = true) you have to declare that variable as 'volatile'.</p>\n"
},
{
"answer_id": 46888720,
"author": "Joachim",
"author_id": 1961484,
"author_profile": "https://Stackoverflow.com/users/1961484",
"pm_score": 2,
"selected": false,
"text": "<p>Your program seems to work even without <code>volatile</code> keyword? Perhaps this is the reason:</p>\n\n<p>As mentioned previously the <code>volatile</code> keyword helps for cases like</p>\n\n<pre><code>volatile int* p = ...; // point to some memory\nwhile( *p!=0 ) {} // loop until the memory becomes zero\n</code></pre>\n\n<p>But there seems to be almost no effect once an external or non-inline function is being called. E.g.:</p>\n\n<pre><code>while( *p!=0 ) { g(); }\n</code></pre>\n\n<p>Then with or without <code>volatile</code> almost the same result is generated.</p>\n\n<p>As long as g() can be completely inlined, the compiler can see everything that's going on and can therefore optimize. But when the program makes a call to a place where the compiler can't see what's going on, it isn't safe for the compiler to make any assumptions any more. Hence the compiler will generate code that always reads from memory directly.</p>\n\n<p>But beware of the day, when your function g() becomes inline (either due to explicit changes or due to compiler/linker cleverness) then your code might break if you forgot the <code>volatile</code> keyword!</p>\n\n<p>Therefore I recommend to add the <code>volatile</code> keyword even if your program seems to work without. It makes the intention clearer and more robust in respect to future changes.</p>\n"
},
{
"answer_id": 51598967,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 2,
"selected": false,
"text": "<p>In the early days of C, compilers would interpret all actions that read and write lvalues as memory operations, to be performed in the same sequence as the reads and writes appeared in the code. Efficiency could be greatly improved in many cases if compilers were given a certain amount of freedom to re-order and consolidate operations, but there was a problem with this. Even though operations were often specified in a certain order merely because it was necessary to specify them in <em>some</em> order, and thus the programmer picked one of many equally-good alternatives, that wasn't always the case. Sometimes it would be important that certain operations occur in a particular sequence.</p>\n<p>Exactly which details of sequencing are important will vary depending upon the target platform and application field. Rather than provide particularly detailed control, the Standard opted for a simple model: if a sequence of accesses are done with lvalues that are not qualified <code>volatile</code>, a compiler may reorder and consolidate them as it sees fit. If an action is done with a <code>volatile</code>-qualified lvalue, a quality implementation should offer whatever additional ordering guarantees might be required by code targeting its intended platform and application field, without requiring that programmers use non-standard syntax.</p>\n<p>Unfortunately, rather than identify what guarantees programmers would need, many compilers have opted instead to offer the bare minimum guarantees mandated by the Standard. This makes <code>volatile</code> much less useful than it should be. On gcc or clang, for example, a programmer needing to implement a basic "hand-off mutex" [one where a task that has acquired and released a mutex won't do so again until the other task has done so] must do one of four things:</p>\n<ol>\n<li><p>Put the acquisition and release of the mutex in a function that the compiler cannot inline, and to which it cannot apply Whole Program Optimization.</p>\n</li>\n<li><p>Qualify all the objects guarded by the mutex as <code>volatile</code>--something which shouldn't be necessary if all accesses occur after acquiring the mutex and before releasing it.</p>\n</li>\n<li><p>Use optimization level 0 to force the compiler to generate code as though all objects that aren't qualified <code>register</code> are <code>volatile</code>.</p>\n</li>\n<li><p>Use gcc-specific directives.</p>\n</li>\n</ol>\n<p>By contrast, when using a higher-quality compiler which is more suitable for systems programming, such as icc, one would have another option:</p>\n<ol start=\"5\">\n<li>Make sure that a <code>volatile</code>-qualified write gets performed everyplace an acquire or release is needed.</li>\n</ol>\n<p>Acquiring a basic "hand-off mutex" requires a <code>volatile</code> read (to see if it's ready), and shouldn't require a <code>volatile</code> write as well (the other side won't try to re-acquire it until it's handed back) but having to perform a meaningless <code>volatile</code> write is still better than any of the options available under gcc or clang.</p>\n"
},
{
"answer_id": 59002919,
"author": "curiousguy",
"author_id": 963864,
"author_profile": "https://Stackoverflow.com/users/963864",
"pm_score": 2,
"selected": false,
"text": "<p>Other answers already mention avoiding some optimization in order to:</p>\n\n<ul>\n<li>use memory mapped registers (or \"MMIO\")</li>\n<li>write device drivers</li>\n<li>allow easier debugging of programs</li>\n<li>make floating point computations more deterministic </li>\n</ul>\n\n<p>Volatile is essential whenever you need a value to appear to come from the outside and be unpredictable and avoid compiler optimizations based on a value being known, and when a result isn't actually used but you need it to be computed, or it's used but you want to compute it several times for a benchmark, and you need the computations to start and end at precise points.</p>\n\n<p>A volatile read is like an input operation (like <code>scanf</code> or a use of <code>cin</code>): <em>the value seems to come from the outside of the program, so any computation that has a dependency on the value needs to start after it</em>. </p>\n\n<p>A volatile write is like an output operation (like <code>printf</code> or a use of <code>cout</code>): <em>the value seems to be communicated outside of the program, so if the value depends on a computation, it needs to be finished before</em>.</p>\n\n<p>So <strong>a pair of volatile read/write can be used to tame benchmarks and make time measurement meaningful</strong>.</p>\n\n<p>Without volatile, your computation could be started by the compiler before, <strong>as nothing would prevent reordering of computations with functions such as time measurement</strong>.</p>\n"
},
{
"answer_id": 61495883,
"author": "Rohit",
"author_id": 3049983,
"author_profile": "https://Stackoverflow.com/users/3049983",
"pm_score": 2,
"selected": false,
"text": "<p>All answers are excellent. But on the top of that, I would like to share an example.</p>\n\n<p>Below is a little cpp program:</p>\n\n<pre><code>#include <iostream>\n\nint x;\n\nint main(){\n char buf[50];\n x = 8;\n\n if(x == 8)\n printf(\"x is 8\\n\");\n else\n sprintf(buf, \"x is not 8\\n\");\n\n x=1000;\n while(x > 5)\n x--;\n return 0;\n}\n</code></pre>\n\n<p>Now, lets generate the assembly of the above code (and I will paste only that portions of the assembly which relevant here):</p>\n\n<p>The command to generate assembly:</p>\n\n<pre><code>g++ -S -O3 -c -fverbose-asm -Wa,-adhln assembly.cpp\n</code></pre>\n\n<p>And the assembly:</p>\n\n<pre><code>main:\n.LFB1594:\n subq $40, %rsp #,\n .seh_stackalloc 40\n .seh_endprologue\n # assembly.cpp:5: int main(){\n call __main #\n # assembly.cpp:10: printf(\"x is 8\\n\");\n leaq .LC0(%rip), %rcx #,\n # assembly.cpp:7: x = 8;\n movl $8, x(%rip) #, x\n # assembly.cpp:10: printf(\"x is 8\\n\");\n call _ZL6printfPKcz.constprop.0 #\n # assembly.cpp:18: }\n xorl %eax, %eax #\n movl $5, x(%rip) #, x\n addq $40, %rsp #,\n ret \n .seh_endproc\n .p2align 4,,15\n .def _GLOBAL__sub_I_x; .scl 3; .type 32; .endef\n .seh_proc _GLOBAL__sub_I_x\n</code></pre>\n\n<p>You can see in the assembly that the assembly code was not generated for <code>sprintf</code> because the compiler assumed that <code>x</code> will not change outside of the program. And same is the case with the <code>while</code> loop. <code>while</code> loop was altogether removed due to the optimization because compiler saw it as a useless code and thus directly assigned <code>5</code> to <code>x</code> (see <code>movl $5, x(%rip)</code>).</p>\n\n<p>The problem occurs when what if an external process/ hardware would change the value of <code>x</code> somewhere between <code>x = 8;</code> and <code>if(x == 8)</code>. We would expect <code>else</code> block to work but unfortunately the compiler has trimmed out that part. </p>\n\n<p>Now, in order to solve this, in the <code>assembly.cpp</code>, let us change <code>int x;</code> to <code>volatile int x;</code> and quickly see the assembly code generated:</p>\n\n<pre><code>main:\n.LFB1594:\n subq $104, %rsp #,\n .seh_stackalloc 104\n .seh_endprologue\n # assembly.cpp:5: int main(){\n call __main #\n # assembly.cpp:7: x = 8;\n movl $8, x(%rip) #, x\n # assembly.cpp:9: if(x == 8)\n movl x(%rip), %eax # x, x.1_1\n # assembly.cpp:9: if(x == 8)\n cmpl $8, %eax #, x.1_1\n je .L11 #,\n # assembly.cpp:12: sprintf(buf, \"x is not 8\\n\");\n leaq 32(%rsp), %rcx #, tmp93\n leaq .LC0(%rip), %rdx #,\n call _ZL7sprintfPcPKcz.constprop.0 #\n.L7:\n # assembly.cpp:14: x=1000;\n movl $1000, x(%rip) #, x\n # assembly.cpp:15: while(x > 5)\n movl x(%rip), %eax # x, x.3_15\n cmpl $5, %eax #, x.3_15\n jle .L8 #,\n .p2align 4,,10\n.L9:\n # assembly.cpp:16: x--;\n movl x(%rip), %eax # x, x.4_3\n subl $1, %eax #, _4\n movl %eax, x(%rip) # _4, x\n # assembly.cpp:15: while(x > 5)\n movl x(%rip), %eax # x, x.3_2\n cmpl $5, %eax #, x.3_2\n jg .L9 #,\n.L8:\n # assembly.cpp:18: }\n xorl %eax, %eax #\n addq $104, %rsp #,\n ret \n.L11:\n # assembly.cpp:10: printf(\"x is 8\\n\");\n leaq .LC1(%rip), %rcx #,\n call _ZL6printfPKcz.constprop.1 #\n jmp .L7 #\n .seh_endproc\n .p2align 4,,15\n .def _GLOBAL__sub_I_x; .scl 3; .type 32; .endef\n .seh_proc _GLOBAL__sub_I_x\n</code></pre>\n\n<p>Here you can see that the assembly codes for <code>sprintf</code>, <code>printf</code> and <code>while</code> loop were generated. The advantage is that if the <code>x</code> variable is changed by some external program or hardware, <code>sprintf</code> part of the code will be executed. And similarly <code>while</code> loop can be used for busy waiting now.</p>\n"
},
{
"answer_id": 65641563,
"author": "alex_noname",
"author_id": 13782669,
"author_profile": "https://Stackoverflow.com/users/13782669",
"pm_score": 1,
"selected": false,
"text": "<p>I would like to quote Herb Sutter's words from his <a href=\"https://herbsutter.com/2014/01/13/gotw-95-solution-thread-safety-and-synchronization/\" rel=\"nofollow noreferrer\">GotW #95</a>, which can help to understand the meaning of the <code>volatile</code> variables:</p>\n<blockquote>\n<p><code>C++</code> <code>volatile</code> variables (which have no analog in languages like <code>C#</code> and <code>Java</code>) are always beyond the scope of this and any other article about the memory model and synchronization. That’s because <code>C++</code> <code>volatile</code> variables aren’t about threads or communication at all and don’t interact with those things. Rather, a <code>C++</code> <code>volatile</code> variable should be viewed as portal into a different universe beyond the language — a memory location that by definition does not obey the language’s memory model because that memory location is accessed by hardware (e.g., written to by a daughter card), have more than one address, or is otherwise “strange” and beyond the language. So <code>C++</code> <code>volatile</code> variables are universally an exception to every guideline about synchronization because are always inherently “racy” and unsynchronizable using the normal tools (mutexes, atomics, etc.) and more generally exist outside all normal of the language and compiler including that they generally cannot be optimized by the compiler (because the compiler isn’t allowed to know their semantics; a <code>volatile int vi;</code> may not behave anything like a normal <code>int</code>, and you can’t even assume that code like <code>vi = 5; int read_back = vi;</code> is guaranteed to result in <code>read_back == 5</code>, or that code like <code>int i = vi; int j = vi;</code> that reads vi twice will result in <code>i == j</code> which will not be true if <code>vi</code> is a hardware counter for example).</p>\n</blockquote>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12333/"
]
| I am playing with Microsoft's TreeView control and I am trying to force a data update of some sorts while editing a node's label, similar to UpdateData for a grid.
Basically, in my editor, I have a Save button and this TreeView control: what I want is when I am editing a node's label in the TreeView, if I click on the Save button I want to be able to commit the node's label I was editing. | `volatile` is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to.
I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially we did this:
```
void waitForSemaphore()
{
volatile uint16_t* semPtr = WELL_KNOWN_SEM_ADDR;/*well known address to my semaphore*/
while ((*semPtr) != IS_OK_FOR_ME_TO_PROCEED);
}
```
Without `volatile`, the optimizer sees the loop as useless (The guy never sets the value! He's nuts, get rid of that code!) and my code would proceed without having acquired the semaphore, causing problems later on. |
72,564 | <p>I'm kind of interested in getting some feedback about this technique I picked up from somewhere.</p>
<p>I use this when a function can either succeed or fail, but you'd like to get more information about why it failed. A standard way to do this same thing would be with exception handling, but I often find it a bit over the top for this sort of thing, plus PHP4 does not offer this.</p>
<p>Basically the technique involves returning true for success, and <em>something</em> which <em>equates</em> to false for failure. Here's an example to show what I mean:</p>
<pre><code>define ('DUPLICATE_USERNAME', false);
define ('DATABASE_ERROR', 0);
define ('INSUFFICIENT_DETAILS', 0.0);
define ('OK', true);
function createUser($username) {
// create the user and return the appropriate constant from the above
}
</code></pre>
<p>The beauty of this is that in your calling code, if you don't care WHY the user creation failed, you can write simple and readable code:</p>
<pre><code>if (createUser('fred')) {
// yay, it worked!
} else {
// aww, it didn't work.
}
</code></pre>
<p>If you particularly want to check why it didn't work (for logging, display to the user, or do whatever), use identity comparison with ===</p>
<pre><code>$status = createUser('fred');
if ($status) {
// yay, it worked!
} else if ($status === DUPLICATE_USERNAME) {
// tell the user about it and get them to try again.
} else {
// aww, it didn't work. log it and show a generic error message? whatever.
}
</code></pre>
<p>The way I see it, the benefits of this are that it is a normal expectation that a successful execution of a function like that would return true, and failure return false.</p>
<p>The downside is that you can only have <code>7 "error" return values: false, 0, 0.0, "0", null, "", and (object) null.</code> If you forget to use identity checking you could get your program flow all wrong. Someone else has told me that using constants like an <code>enum</code> where they all equate to false is <code>"ick"</code>.</p>
<hr>
<p>So, to restate the question: how acceptable is a practise like this? Would you recommend a different way to achieve the same thing? </p>
| [
{
"answer_id": 72589,
"author": "Chris Broadfoot",
"author_id": 3947,
"author_profile": "https://Stackoverflow.com/users/3947",
"pm_score": 2,
"selected": false,
"text": "<p>As long as it's documented and contracted, and not too WTFy, then there shouldn't be a problem.</p>\n\n<p>Then again, I would recommend using exceptions for something like this. It makes more sense. If you can use PHP5, then that would be the way to go. Otherwise you don't have much choice.</p>\n"
},
{
"answer_id": 72634,
"author": "mmaibaum",
"author_id": 12213,
"author_profile": "https://Stackoverflow.com/users/12213",
"pm_score": 2,
"selected": false,
"text": "<p>A more common approach I have seen when exceptions aren't available is to store the error type in a 'last_error' variable somewhere and then when a failure happens (ie it returns false) look up the error. </p>\n\n<p>Another approach is to use the venerable unix tool approach numbered error codes - return 0 for success and any integer (that maps to some error) for the various error conditions. </p>\n\n<p>Most of these suffer in comparison to exceptions when I've seen them used however.</p>\n\n<p>Just to respond to Andrew's comment - \nI agree that the last_error should not be a global and perhaps the 'somewhere' in my answer was a little vague - other people have suggested better places already so I won't bother to repeat them</p>\n"
},
{
"answer_id": 72656,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 2,
"selected": false,
"text": "<p>Often you will return 0 to indicate success, and 1, 2, 3, etc. to indicate different failures. Your way of doing it is kind of hackish, because you can only have so many errors, and this kind of coding <em>will</em> bite you sooner or later.</p>\n\n<p>I like defining a struct/object that includes a Boolean to indicate success, and an error message or other value indicate what kind of error occurred. You can also include other fields to indicate what kind of action was executed. </p>\n\n<p>This makes logging very easy, since you can then just pass the status-struct into the logger, and it will then insert the appropriate log entry.</p>\n"
},
{
"answer_id": 72661,
"author": "Argelbargel",
"author_id": 2992,
"author_profile": "https://Stackoverflow.com/users/2992",
"pm_score": -1,
"selected": false,
"text": "<p>In my opinion, you should use this technique only if failure is a \"normal part of operation\" of your method / function. For example, it's as probable that a call suceeds as that it fails. If failure is a exceptional event, then you should use exception handling so your program can terminate as early and gracefully as possible.</p>\n\n<p>As for your use of different \"false\" values, I'd better return an instance of a custom \"Result\"-class with an proper error code. Something like:</p>\n\n<pre><code>class Result\n{\n var $_result;\n var $_errormsg;\n\n function Result($res, $error)\n {\n $this->_result = $res;\n $ths->_errorMsg = $error\n }\n\n function getResult()\n {\n return $this->_result;\n }\n\n function isError()\n {\n return ! ((boolean) $this->_result);\n }\n\n function getErrorMessage()\n {\n return $this->_errorMsg;\n }\n</code></pre>\n"
},
{
"answer_id": 72665,
"author": "Jonathan Adelson",
"author_id": 8092,
"author_profile": "https://Stackoverflow.com/users/8092",
"pm_score": 0,
"selected": false,
"text": "<p>Ick.</p>\n\n<p>In Unix pre-exception this is done with errno. You return 0 for success or -1 for failure, then you have a value you can retrieve with an integer error code to get the actual error. This works in all cases, because you don't have a (realistic) limit to the number of error codes. INT_MAX is certainly more than 7, and you don't have to worry about the type (errno).</p>\n\n<p>I vote against the solution proposed in the question.</p>\n"
},
{
"answer_id": 72673,
"author": "ima",
"author_id": 5733,
"author_profile": "https://Stackoverflow.com/users/5733",
"pm_score": -1,
"selected": false,
"text": "<p>Look at COM HRESULT for a correct way to do it.</p>\n\n<p>But exceptions are generally better.</p>\n\n<p>Update: the correct way is: define as many error values as you want, not only \"false\" ones. Use function succeeded() to check if function succeeded.</p>\n\n<pre><code>if (succeeded(result = MyFunction()))\n ...\nelse\n ...\n</code></pre>\n"
},
{
"answer_id": 72730,
"author": "Jeremy Privett",
"author_id": 560,
"author_profile": "https://Stackoverflow.com/users/560",
"pm_score": 5,
"selected": true,
"text": "<p>I agree with the others who have stated that this is a little on the WTFy side. If it's clearly documented functionality, then it's less of an issue, but I think it'd be safer to take an alternate route of returning 0 for success and integers for error codes. If you don't like that idea or the idea of a global last error variable, consider redefining your function as:</p>\n\n<pre><code>function createUser($username, &$error)\n</code></pre>\n\n<p>Then you can use:</p>\n\n<pre><code>if (createUser('fred', $error)) {\n echo 'success';\n}\nelse {\n echo $error;\n}\n</code></pre>\n\n<p>Inside createUser, just populate $error with any error you encounter and it'll be accessible outside of the function scope due to the reference.</p>\n"
},
{
"answer_id": 72838,
"author": "ljorquera",
"author_id": 9132,
"author_profile": "https://Stackoverflow.com/users/9132",
"pm_score": 0,
"selected": false,
"text": "<p>If you really want to do this kind of thing, you should have different values for each error, and check for success. Something like</p>\n\n<pre><code>define ('OK', 0);\ndefine ('DUPLICATE_USERNAME', 1);\ndefine ('DATABASE_ERROR', 2);\ndefine ('INSUFFICIENT_DETAILS', 3);\n</code></pre>\n\n<p>And check:</p>\n\n<pre><code>if (createUser('fred') == OK) {\n //OK\n\n}\nelse {\n //Fail\n}\n</code></pre>\n"
},
{
"answer_id": 72926,
"author": "rami",
"author_id": 9629,
"author_profile": "https://Stackoverflow.com/users/9629",
"pm_score": 0,
"selected": false,
"text": "<p>It does make sense that a successful execution returns true. Handling generic errors will be much easier:</p>\n\n<pre><code>if (!createUser($username)) {\n// the dingo ate my user.\n// deal with it.\n}\n</code></pre>\n\n<p>But it doesn't make sense at all to associate meaning with different types of false. False should mean one thing and one thing only, regardless of the type or how the programming language treats it. If you're going to define error status constants anyway, better stick with switch/case</p>\n\n<pre><code>define(DUPLICATE_USERNAME, 4)\ndefine(USERNAME_NOT_ALPHANUM, 8)\n\nswitch ($status) {\ncase DUPLICATE_USERNAME:\n // sorry hun, there's someone else\n break;\ncase USERNAME_NOT_ALPHANUM:\n break;\ndefault:\n // yay, it worked\n}\n</code></pre>\n\n<p>Also with this technique, you'll be able to bitwise AND and OR status messages, so you can return status messages that carry more than one meaning like <code>DUPLICATE_USERNAME & USERNAME_NOT_ALPHANUM</code> and treat it appropriately. This isn't always a good idea, it depends on how you use it.</p>\n"
},
{
"answer_id": 73049,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>how acceptable is a practice like this?</p>\n</blockquote>\n\n<p>I'd say it's unacceptable.</p>\n\n<ol>\n<li>Requires the === operator, which is very dangerous. If the user used ==, it leads to a very hard to find bug.</li>\n<li>Using \"0\" and \"\" to denote false may change in future PHP versions. Plus in a lot of other languages \"0\" and \"\" does not evaluate to false which leads to great confusion</li>\n</ol>\n\n<p>Using getLastError() type of global function is probably the best practice in PHP because it <em>ties in well with the language</em>, since PHP is still mostly a procedural langauge. I think another problem with the approach you just gave is that very few other systems work like that. The programmer has to learn this way of error checking which is the source of errors. It's best to make things work like how most people expect.</p>\n\n<pre><code>if ( makeClient() )\n{ // happy scenario goes here }\n\nelse\n{\n // error handling all goes inside this block\n switch ( getMakeClientError() )\n { case: // .. }\n}\n</code></pre>\n"
},
{
"answer_id": 73100,
"author": "inxilpro",
"author_id": 12549,
"author_profile": "https://Stackoverflow.com/users/12549",
"pm_score": 1,
"selected": false,
"text": "<p>When exceptions aren't available, I'd use the <a href=\"http://en.wikipedia.org/wiki/PEAR\" rel=\"nofollow noreferrer\">PEAR</a> model and provide isError() functionality in all your classes.</p>\n"
},
{
"answer_id": 73455,
"author": "Markowitch",
"author_id": 11964,
"author_profile": "https://Stackoverflow.com/users/11964",
"pm_score": 0,
"selected": false,
"text": "<p>I like the way COM can handle both exception and non-exception capable callers. The example below show how a HRESULT is tested and an exception is thrown in case of failure. (usually autogenerated in tli files)</p>\n\n<pre><code>inline _bstr_t IMyClass::GetName ( ) {\n BSTR _result;\n HRESULT _hr = get_name(&_result);\n if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this));\n return _bstr_t(_result, false);\n}\n</code></pre>\n\n<p>Using return values will affect readability by having error handling scattered and worst case, the return values are never checked by the code. That's why I prefer exception when a contract is breached.</p>\n"
},
{
"answer_id": 73589,
"author": "Aquarion",
"author_id": 12696,
"author_profile": "https://Stackoverflow.com/users/12696",
"pm_score": 0,
"selected": false,
"text": "<p>Other ways include exceptions:</p>\n\n<pre><code>throw new Validation_Exception_SQLDuplicate(\"There's someone else, hun\");),\n</code></pre>\n\n<p>returning structures,</p>\n\n<pre><code>return new Result($status, $stuff);\nif ($result->status == 0) {\n $stuff = $result->data;\n}\nelse {\n die('Oh hell');\n}\n</code></pre>\n\n<p>I would hate to be the person who came after you for using the code pattern you suggested originally.</p>\n\n<p>And I mean \"Came after you\" as in \"followed you in employment and had to maintain the code\" rather than \"came after you\" \"with a wedgiematic\", though both are options.</p>\n"
},
{
"answer_id": 86759,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Reinventing the wheel here. Using squares.</p>\n\n<p>OK, you don't have exceptions in PHP 4. Welcome in the year 1982, take a look at C.</p>\n\n<p>You can have error codes. Consider negative values, they seem more intuitive, so you would just have to check if (createUser() > 0).</p>\n\n<p>You can have an error log if you want, with error messages (or just arbitrary error codes) pushed onto an array, dealt with elegance afterwards.</p>\n\n<p>But PHP is a loosely typed language for a reason, and throwing error codes that have different types but evaluate to the same \"false\" is something that shouldn't be done. </p>\n\n<p>What happens when you run out of built-in types?</p>\n\n<p>What happens when you get a new coder and have to explain how this thing works? Say, in 6 months, you won't remember.</p>\n\n<p>Is PHP === operator fast enough to get through it? Is it faster than error codes? or any other method?</p>\n\n<p>Just drop it.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
]
| I'm kind of interested in getting some feedback about this technique I picked up from somewhere.
I use this when a function can either succeed or fail, but you'd like to get more information about why it failed. A standard way to do this same thing would be with exception handling, but I often find it a bit over the top for this sort of thing, plus PHP4 does not offer this.
Basically the technique involves returning true for success, and *something* which *equates* to false for failure. Here's an example to show what I mean:
```
define ('DUPLICATE_USERNAME', false);
define ('DATABASE_ERROR', 0);
define ('INSUFFICIENT_DETAILS', 0.0);
define ('OK', true);
function createUser($username) {
// create the user and return the appropriate constant from the above
}
```
The beauty of this is that in your calling code, if you don't care WHY the user creation failed, you can write simple and readable code:
```
if (createUser('fred')) {
// yay, it worked!
} else {
// aww, it didn't work.
}
```
If you particularly want to check why it didn't work (for logging, display to the user, or do whatever), use identity comparison with ===
```
$status = createUser('fred');
if ($status) {
// yay, it worked!
} else if ($status === DUPLICATE_USERNAME) {
// tell the user about it and get them to try again.
} else {
// aww, it didn't work. log it and show a generic error message? whatever.
}
```
The way I see it, the benefits of this are that it is a normal expectation that a successful execution of a function like that would return true, and failure return false.
The downside is that you can only have `7 "error" return values: false, 0, 0.0, "0", null, "", and (object) null.` If you forget to use identity checking you could get your program flow all wrong. Someone else has told me that using constants like an `enum` where they all equate to false is `"ick"`.
---
So, to restate the question: how acceptable is a practise like this? Would you recommend a different way to achieve the same thing? | I agree with the others who have stated that this is a little on the WTFy side. If it's clearly documented functionality, then it's less of an issue, but I think it'd be safer to take an alternate route of returning 0 for success and integers for error codes. If you don't like that idea or the idea of a global last error variable, consider redefining your function as:
```
function createUser($username, &$error)
```
Then you can use:
```
if (createUser('fred', $error)) {
echo 'success';
}
else {
echo $error;
}
```
Inside createUser, just populate $error with any error you encounter and it'll be accessible outside of the function scope due to the reference. |
72,568 | <p>What's the best and/or fastest method of doing multijoin queries in Django using the ORM and QuerySet API? </p>
| [
{
"answer_id": 73349,
"author": "Aaron",
"author_id": 11176,
"author_profile": "https://Stackoverflow.com/users/11176",
"pm_score": 2,
"selected": false,
"text": "<p>If you are trying to join across tables linked by ForeignKeys or ManyToManyField relationships then you can use the double underscore syntax. For example if you have the following models:</p>\n\n<pre><code>class Foo(models.Model):\n name = models.CharField(max_length=255)\n\nclass FizzBuzz(models.Model):\n bleh = models.CharField(max_length=255)\n\nclass Bar(models.Model):\n foo = models.ForeignKey(Foo)\n fizzbuzz = models.ForeignKey(FizzBuzz) \n</code></pre>\n\n<p>You can do something like:</p>\n\n<pre><code>Fizzbuzz.objects.filter(bar__foo__name = \"Adrian\")\n</code></pre>\n"
},
{
"answer_id": 73462,
"author": "machineghost",
"author_id": 5921,
"author_profile": "https://Stackoverflow.com/users/5921",
"pm_score": 2,
"selected": false,
"text": "<p>Don't use the API ;-) Seriously, if your JOIN are complex, you should see significant performance increases by dropping down in to SQL rather than by using the API. And this doesn't mean you need to get dirty dirty SQL all over your beautiful Python code; just make a custom manager to handle the JOINs and then have the rest of your code use it rather than direct SQL.</p>\n\n<p>Also, I was just at DjangoCon where they had a seminar on high-performance Django, and one of the key things I took away from it was that if performance is a real concern (and you plan to have significant traffic someday), you really shouldn't be doing JOINs in the first place, because they make scaling your app while maintaining decent performance virtually impossible.</p>\n\n<p>Here's a video Google made of the talk:\n<a href=\"http://www.youtube.com/watch?v=D-4UN4MkSyI&feature=PlayList&p=D415FAF806EC47A1&index=20\" rel=\"nofollow noreferrer\">http://www.youtube.com/watch?v=D-4UN4MkSyI&feature=PlayList&p=D415FAF806EC47A1&index=20</a></p>\n\n<p>Of course, if you know that your application is never going to have to deal with that kind of scaling concern, JOIN away :-) And if you're also not worried about the performance hit of using the API, then you really don't need to worry about the (AFAIK) miniscule, if any, performance difference between using one API method over another.</p>\n\n<p>Just use:\n<a href=\"http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships\" rel=\"nofollow noreferrer\">http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships</a></p>\n\n<p>Hope that helps (and if it doesn't, hopefully some true Django hacker can jump in and explain why method X actually does have some noticeable performance difference).</p>\n"
},
{
"answer_id": 372079,
"author": "bnjmnhggns",
"author_id": 35254,
"author_profile": "https://Stackoverflow.com/users/35254",
"pm_score": 1,
"selected": false,
"text": "<p>Use the queryset.query.join method, but only if the other method described here (using double underscores) isn't adequate.</p>\n"
},
{
"answer_id": 1894381,
"author": "Viesturs",
"author_id": 1660,
"author_profile": "https://Stackoverflow.com/users/1660",
"pm_score": 0,
"selected": false,
"text": "<p>Caktus blog has an answer to this: <a href=\"http://www.caktusgroup.com/blog/2009/09/28/custom-joins-with-djangos-queryjoin/\" rel=\"nofollow noreferrer\">http://www.caktusgroup.com/blog/2009/09/28/custom-joins-with-djangos-queryjoin/</a></p>\n\n<p>Basically there is a hidden QuerySet.query.join method that allows adding custom joins.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| What's the best and/or fastest method of doing multijoin queries in Django using the ORM and QuerySet API? | If you are trying to join across tables linked by ForeignKeys or ManyToManyField relationships then you can use the double underscore syntax. For example if you have the following models:
```
class Foo(models.Model):
name = models.CharField(max_length=255)
class FizzBuzz(models.Model):
bleh = models.CharField(max_length=255)
class Bar(models.Model):
foo = models.ForeignKey(Foo)
fizzbuzz = models.ForeignKey(FizzBuzz)
```
You can do something like:
```
Fizzbuzz.objects.filter(bar__foo__name = "Adrian")
``` |
72,626 | <p>I save stuff in an <a href="http://msdn.microsoft.com/en-us/library/3ak841sy.aspx" rel="nofollow noreferrer">Isolated Storage</a> file (using class IsolatedStorageFile). It works well, and I can retrieve the saved values when calling the saving and retrieving methods in my <a href="http://en.wikipedia.org/wiki/Data_access_layer" rel="nofollow noreferrer">DAL</a> layer from my GUI layer. However, when I try to retrieve the same settings from another assembly in the same project, it gives me a FileNotFoundException. What do I do wrong? This is the general concept:</p>
<pre><code> public void Save(int number)
{
IsolatedStorageFile storage = IsolatedStorageFile.GetMachineStoreForAssembly();
IsolatedStorageFileStream fileStream =
new IsolatedStorageFileStream(filename, FileMode.OpenOrCreate, storage);
StreamWriter writer = new StreamWriter(fileStream);
writer.WriteLine(number);
writer.Close();
}
public int Retrieve()
{
IsolatedStorageFile storage = IsolatedStorageFile.GetMachineStoreForAssembly();
IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filename, FileMode.Open, storage);
StreamReader reader = new StreamReader(fileStream);
int number;
try
{
string line = reader.ReadLine();
number = int.Parse(line);
}
finally
{
reader.Close();
}
return number;
}
</code></pre>
<p>I've tried using all the GetMachineStoreFor* scopes.</p>
<p>EDIT: Since I need several assemblies to access the files, it doesn't seem possible to do with isolated storage, unless it's a <a href="http://en.wikipedia.org/wiki/ClickOnce" rel="nofollow noreferrer">ClickOnce</a> application.</p>
| [
{
"answer_id": 72736,
"author": "icelava",
"author_id": 2663,
"author_profile": "https://Stackoverflow.com/users/2663",
"pm_score": 3,
"selected": true,
"text": "<p>When you instantiated the IsolatedStorageFile, did you scope it to IsolatedStorageScope.Machine?</p>\n\n<p>Ok now that you have illustrated your code style and I have gone back to retesting the behaviour of the methods, here is the explanation:</p>\n\n<ul>\n<li>GetMachineStoreForAssembly() - scoped to the machine and the assembly identity. Different assemblies in the same application would have their own isolated storage.</li>\n<li>GetMachineStoreForDomain() - a misnomer in my opinion. scoped to the machine and the domain identity <em>on top of</em> the assembly identity. There should have been an option for just AppDomain alone.</li>\n<li>GetMachineStoreForApplication() - this is the one you are looking for. I have tested it and different assemblies can pick up the values written in another assembly. The only catch is, the <em>application identity</em> must be verifiable. When running locally, it cannot be properly determined and it will end up with exception \"Unable to determine application identity of the caller\". It can be verified by deploying the application via Click Once. Only then can this method apply and achieve its desired effect of shared isolated storage.</li>\n</ul>\n"
},
{
"answer_id": 73400,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": 1,
"selected": false,
"text": "<p>When you are saving, you are calling GetMachineStoreForDomain, but when you are retrieving, you are calling GetMachineStoreForAssembly.</p>\n\n<p>GetMachineStoreForAssembly is scoped to the assembly that the code is executing in, while the GetMachineStoreForDomain is scoped to the currently running AppDomain and the assembly where the code is executing. Just change your these calls to GetMachineStoreForApplication, and it should work.</p>\n\n<p>The documentation for IsolatedStorageFile can be found at <a href=\"http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile_members.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile_members.aspx</a></p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3397/"
]
| I save stuff in an [Isolated Storage](http://msdn.microsoft.com/en-us/library/3ak841sy.aspx) file (using class IsolatedStorageFile). It works well, and I can retrieve the saved values when calling the saving and retrieving methods in my [DAL](http://en.wikipedia.org/wiki/Data_access_layer) layer from my GUI layer. However, when I try to retrieve the same settings from another assembly in the same project, it gives me a FileNotFoundException. What do I do wrong? This is the general concept:
```
public void Save(int number)
{
IsolatedStorageFile storage = IsolatedStorageFile.GetMachineStoreForAssembly();
IsolatedStorageFileStream fileStream =
new IsolatedStorageFileStream(filename, FileMode.OpenOrCreate, storage);
StreamWriter writer = new StreamWriter(fileStream);
writer.WriteLine(number);
writer.Close();
}
public int Retrieve()
{
IsolatedStorageFile storage = IsolatedStorageFile.GetMachineStoreForAssembly();
IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filename, FileMode.Open, storage);
StreamReader reader = new StreamReader(fileStream);
int number;
try
{
string line = reader.ReadLine();
number = int.Parse(line);
}
finally
{
reader.Close();
}
return number;
}
```
I've tried using all the GetMachineStoreFor\* scopes.
EDIT: Since I need several assemblies to access the files, it doesn't seem possible to do with isolated storage, unless it's a [ClickOnce](http://en.wikipedia.org/wiki/ClickOnce) application. | When you instantiated the IsolatedStorageFile, did you scope it to IsolatedStorageScope.Machine?
Ok now that you have illustrated your code style and I have gone back to retesting the behaviour of the methods, here is the explanation:
* GetMachineStoreForAssembly() - scoped to the machine and the assembly identity. Different assemblies in the same application would have their own isolated storage.
* GetMachineStoreForDomain() - a misnomer in my opinion. scoped to the machine and the domain identity *on top of* the assembly identity. There should have been an option for just AppDomain alone.
* GetMachineStoreForApplication() - this is the one you are looking for. I have tested it and different assemblies can pick up the values written in another assembly. The only catch is, the *application identity* must be verifiable. When running locally, it cannot be properly determined and it will end up with exception "Unable to determine application identity of the caller". It can be verified by deploying the application via Click Once. Only then can this method apply and achieve its desired effect of shared isolated storage. |
72,639 | <p>I am importing data from MS Excel spreadsheets into a php/mySQL application. Several different parties are supplying the spreadsheets and they are in formats ranging from Excel 4.0 to Excel 2007.
The trouble is finding a technique to read ALL versions.</p>
<p>More info: </p>
<pre><code> - I am currently using php-ExcelReader.
- A script in a language other than php that can convert Excel to CSV would be an acceptable solution.
</code></pre>
| [
{
"answer_id": 72669,
"author": "Erratic",
"author_id": 2246765,
"author_profile": "https://Stackoverflow.com/users/2246765",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on the nature of your data and the parties that upload the excel files, you might want to consider having them save the data in .csv format. It will be much easier to parse on your end.</p>\n\n<p>Assuming that isn't an option a quick google search turned up <a href=\"http://sourceforge.net/projects/phpexcelreader/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/phpexcelreader/</a> which might suit your needs.</p>\n"
},
{
"answer_id": 75493,
"author": "gobansaor",
"author_id": 8967,
"author_profile": "https://Stackoverflow.com/users/8967",
"pm_score": 0,
"selected": false,
"text": "<p>The open-source ETL tool Talend (<a href=\"http://wwww.talend.com\" rel=\"nofollow noreferrer\">http://wwww.talend.com</a>) will generate Java or Perl code and package such code with the necessary 3rd party libraries. </p>\n\n<p>Talend should be able to handle all versions of Excel and output the result set in any format you require (including loading it directly into a database if need be).</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12231/"
]
| I am importing data from MS Excel spreadsheets into a php/mySQL application. Several different parties are supplying the spreadsheets and they are in formats ranging from Excel 4.0 to Excel 2007.
The trouble is finding a technique to read ALL versions.
More info:
```
- I am currently using php-ExcelReader.
- A script in a language other than php that can convert Excel to CSV would be an acceptable solution.
``` | Depending on the nature of your data and the parties that upload the excel files, you might want to consider having them save the data in .csv format. It will be much easier to parse on your end.
Assuming that isn't an option a quick google search turned up <http://sourceforge.net/projects/phpexcelreader/> which might suit your needs. |
72,671 | <p>I need to create a batch file which starts multiple console applications in a Windows .cmd file. This can be done using the start command.</p>
<p>However, the command has a path in it. I also need to pass paramaters which have spaces as well. How to do this?</p>
<p>E.g. batch file</p>
<pre><code>start "c:\path with spaces\app.exe" param1 "param with spaces"
</code></pre>
| [
{
"answer_id": 72726,
"author": "Curro",
"author_id": 10688,
"author_profile": "https://Stackoverflow.com/users/10688",
"pm_score": -1,
"selected": false,
"text": "<p>Surrounding the path and the argument with spaces inside quotes as in your example should do. The command may need to handle the quotes when the parameters are passed to it, but it usually is not a big deal.</p>\n"
},
{
"answer_id": 72758,
"author": "Steffen",
"author_id": 6919,
"author_profile": "https://Stackoverflow.com/users/6919",
"pm_score": 4,
"selected": false,
"text": "<p>Escaping the path with apostrophes is correct, but the start command takes a parameter containing the title of the new window. This parameter is detected by the surrounding apostrophes, so your application is not executed.</p>\n\n<p>Try something like this:</p>\n\n<pre><code>start \"Dummy Title\" \"c:\\path with spaces\\app.exe\" param1 \"param with spaces\"\n</code></pre>\n"
},
{
"answer_id": 72796,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 8,
"selected": true,
"text": "<p>Actually, his example won't work (although at first I thought that it would, too). Based on the help for the Start command, the first parameter is the name of the newly created Command Prompt window, and the second and third should be the path to the application and its parameters, respectively. If you add another \"\" before path to the app, it should work (at least it did for me). Use something like this:</p>\n\n<pre><code>start \"\" \"c:\\path with spaces\\app.exe\" param1 \"param with spaces\"\n</code></pre>\n\n<p>You can change the first argument to be whatever you want the title of the new command prompt to be. If it's a Windows app that is created, then the command prompt won't be displayed, and the title won't matter.</p>\n"
},
{
"answer_id": 2005695,
"author": "user243871",
"author_id": 243871,
"author_profile": "https://Stackoverflow.com/users/243871",
"pm_score": 0,
"selected": false,
"text": "<p>You are to use something like this:</p>\n<blockquote>\n<p>start /d C:\\Windows\\System32\\calc.exe</p>\n<p>start /d "C:\\Program Files\\Mozilla</p>\n<p>Firefox" firefox.exe start /d</p>\n<p>"C:\\Program Files\\Microsoft</p>\n<p>Office\\Office12" EXCEL.EXE</p>\n</blockquote>\n<p>Also I advice you to use special batch files editor - <a href=\"http://www.drbatcher.com\" rel=\"nofollow noreferrer\">Dr.Batcher</a></p>\n"
},
{
"answer_id": 11968030,
"author": "Mark Agate",
"author_id": 1600397,
"author_profile": "https://Stackoverflow.com/users/1600397",
"pm_score": 1,
"selected": false,
"text": "<p>Interestingly, it seems that in Windows Embedded Compact 7, you cannot specify a title string. The first parameter has to be the command or program.</p>\n"
},
{
"answer_id": 19316499,
"author": "Anupam Kapoor",
"author_id": 2870697,
"author_profile": "https://Stackoverflow.com/users/2870697",
"pm_score": -1,
"selected": false,
"text": "<p>I researched successfully and it is working fine for me. My requirement is to sent an email using vbscript which needs to be call from a batch file in windows. Here is the exact command I am using with no errors.</p>\n\n<pre><code>START C:\\Windows\\System32\\cscript.exe \"C:\\Documents and Settings\\akapoor\\Desktop\\Mail.vbs\"\n</code></pre>\n"
},
{
"answer_id": 43467194,
"author": "Mustafa Kemal",
"author_id": 3835640,
"author_profile": "https://Stackoverflow.com/users/3835640",
"pm_score": 2,
"selected": false,
"text": "<pre><code>start \"\" \"c:\\path with spaces\\app.exe\" \"C:\\path parameter\\param.exe\"\n</code></pre>\n\n<p>When I used above suggestion, I've got:</p>\n\n<blockquote>\n <p>'c:\\path' is not recognized a an internal or external command, operable program or batch file. </p>\n</blockquote>\n\n<p>I think second qoutation mark prevent command to run. After some search below solution save my day:</p>\n\n<pre><code>start \"\" CALL \"c:\\path with spaces\\app.exe\" \"C:\\path parameter\\param.exe\"\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I need to create a batch file which starts multiple console applications in a Windows .cmd file. This can be done using the start command.
However, the command has a path in it. I also need to pass paramaters which have spaces as well. How to do this?
E.g. batch file
```
start "c:\path with spaces\app.exe" param1 "param with spaces"
``` | Actually, his example won't work (although at first I thought that it would, too). Based on the help for the Start command, the first parameter is the name of the newly created Command Prompt window, and the second and third should be the path to the application and its parameters, respectively. If you add another "" before path to the app, it should work (at least it did for me). Use something like this:
```
start "" "c:\path with spaces\app.exe" param1 "param with spaces"
```
You can change the first argument to be whatever you want the title of the new command prompt to be. If it's a Windows app that is created, then the command prompt won't be displayed, and the title won't matter. |
72,672 | <p>Has anyone written an 'UnFormat' routine for Delphi?</p>
<p>What I'm imagining is the <em>inverse</em> of <em>SysUtils.Format</em> and looks something like this </p>
<p>UnFormat('a number %n and another %n',[float1, float2]); </p>
<p>So you could unpack a string into a series of variables using format strings.</p>
<p>I've looked at the 'Format' routine in SysUtils, but I've never used assembly so it is meaningless to me.</p>
| [
{
"answer_id": 72713,
"author": "PatrickvL",
"author_id": 12170,
"author_profile": "https://Stackoverflow.com/users/12170",
"pm_score": 5,
"selected": true,
"text": "<p>This is called scanf in C, I've made a Delphi look-a-like for this :</p>\n\n<pre><code>function ScanFormat(const Input, Format: string; Args: array of Pointer): Integer;\nvar\n InputOffset: Integer;\n FormatOffset: Integer;\n InputChar: Char;\n FormatChar: Char;\n\n function _GetInputChar: Char;\n begin\n if InputOffset <= Length(Input) then\n begin\n Result := Input[InputOffset];\n Inc(InputOffset);\n end\n else\n Result := #0;\n end;\n\n function _PeekFormatChar: Char;\n begin\n if FormatOffset <= Length(Format) then\n Result := Format[FormatOffset]\n else\n Result := #0;\n end;\n\n function _GetFormatChar: Char;\n begin\n Result := _PeekFormatChar;\n if Result <> #0 then\n Inc(FormatOffset);\n end;\n\n function _ScanInputString(const Arg: Pointer = nil): string;\n var\n EndChar: Char;\n begin\n Result := '';\n EndChar := _PeekFormatChar;\n InputChar := _GetInputChar;\n while (InputChar > ' ')\n and (InputChar <> EndChar) do\n begin\n Result := Result + InputChar;\n InputChar := _GetInputChar;\n end;\n\n if InputChar <> #0 then\n Dec(InputOffset);\n\n if Assigned(Arg) then\n PString(Arg)^ := Result;\n end;\n\n function _ScanInputInteger(const Arg: Pointer): Boolean;\n var\n Value: string;\n begin\n Value := _ScanInputString;\n Result := TryStrToInt(Value, {out} PInteger(Arg)^);\n end;\n\n procedure _Raise;\n begin\n raise EConvertError.CreateFmt('Unknown ScanFormat character : \"%s\"!', [FormatChar]);\n end;\n\nbegin\n Result := 0;\n InputOffset := 1;\n FormatOffset := 1;\n FormatChar := _GetFormatChar;\n while FormatChar <> #0 do\n begin\n if FormatChar <> '%' then\n begin\n InputChar := _GetInputChar;\n if (InputChar = #0)\n or (FormatChar <> InputChar) then\n Exit;\n end\n else\n begin\n FormatChar := _GetFormatChar;\n case FormatChar of\n '%':\n if _GetInputChar <> '%' then\n Exit;\n 's':\n begin\n _ScanInputString(Args[Result]);\n Inc(Result);\n end;\n 'd', 'u':\n begin\n if not _ScanInputInteger(Args[Result]) then\n Exit;\n\n Inc(Result);\n end;\n else\n _Raise;\n end;\n end;\n\n FormatChar := _GetFormatChar;\n end;\nend;\n</code></pre>\n"
},
{
"answer_id": 73750,
"author": "skamradt",
"author_id": 9217,
"author_profile": "https://Stackoverflow.com/users/9217",
"pm_score": 1,
"selected": false,
"text": "<p>I tend to take care of this using a simple parser. I have two functions, one is called NumStringParts which returns the number of \"parts\" in a string with a specific delimiter (in your case above the space) and GetStrPart returns the specific part from a string with a specific delimiter. Both of these routines have been used since my Turbo Pascal days in many a project.</p>\n\n<pre><code>function NumStringParts(SourceStr,Delimiter:String):Integer;\nvar\n offset : integer;\n curnum : integer;\nbegin\n curnum := 1;\n offset := 1;\n while (offset <> 0) do\n begin\n Offset := Pos(Delimiter,SourceStr);\n if Offset <> 0 then\n begin\n Inc(CurNum);\n Delete(SourceStr,1,(Offset-1)+Length(Delimiter));\n end;\n end;\n result := CurNum;\nend;\n\nfunction GetStringPart(SourceStr,Delimiter:String;Num:Integer):string;\nvar\n offset : integer;\n CurNum : integer;\n CurPart : String;\nbegin\n CurNum := 1;\n Offset := 1;\n While (CurNum <= Num) and (Offset <> 0) do\n begin\n Offset := Pos(Delimiter,SourceStr);\n if Offset <> 0 then\n begin\n CurPart := Copy(SourceStr,1,Offset-1);\n Delete(SourceStr,1,(Offset-1)+Length(Delimiter));\n Inc(CurNum)\n end\n else\n CurPart := SourceStr;\n end;\n if CurNum >= Num then\n Result := CurPart\n else\n Result := '';\nend;\n</code></pre>\n\n<p>Example of usage:</p>\n\n<pre><code> var\n st : string;\n f1,f2 : double; \n begin\n st := 'a number 12.35 and another 13.415';\n ShowMessage('Total String parts = '+IntToStr(NumStringParts(st,#32)));\n f1 := StrToFloatDef(GetStringPart(st,#32,3),0.0);\n f2 := StrToFloatDef(GetStringPart(st,#32,6),0.0);\n ShowMessage('Float 1 = '+FloatToStr(F1)+' and Float 2 = '+FloatToStr(F2)); \n end; \n</code></pre>\n\n<p>These routines work wonders for simple or strict comma delimited strings too. These routines work wonderfully in Delphi 2009/2010.</p>\n"
},
{
"answer_id": 76566,
"author": "Toby Allen",
"author_id": 6244,
"author_profile": "https://Stackoverflow.com/users/6244",
"pm_score": 2,
"selected": false,
"text": "<p>I know it tends to scare people, but you could write a simple function to do this using regular expressions </p>\n\n<pre><code>'a number (.*?) and another (.*?)\n</code></pre>\n\n<p>If you are worried about reg expressions take a look at <a href=\"http://www.regexbuddy.com\" rel=\"nofollow noreferrer\">www.regexbuddy.com</a> and you'll never look back.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12376/"
]
| Has anyone written an 'UnFormat' routine for Delphi?
What I'm imagining is the *inverse* of *SysUtils.Format* and looks something like this
UnFormat('a number %n and another %n',[float1, float2]);
So you could unpack a string into a series of variables using format strings.
I've looked at the 'Format' routine in SysUtils, but I've never used assembly so it is meaningless to me. | This is called scanf in C, I've made a Delphi look-a-like for this :
```
function ScanFormat(const Input, Format: string; Args: array of Pointer): Integer;
var
InputOffset: Integer;
FormatOffset: Integer;
InputChar: Char;
FormatChar: Char;
function _GetInputChar: Char;
begin
if InputOffset <= Length(Input) then
begin
Result := Input[InputOffset];
Inc(InputOffset);
end
else
Result := #0;
end;
function _PeekFormatChar: Char;
begin
if FormatOffset <= Length(Format) then
Result := Format[FormatOffset]
else
Result := #0;
end;
function _GetFormatChar: Char;
begin
Result := _PeekFormatChar;
if Result <> #0 then
Inc(FormatOffset);
end;
function _ScanInputString(const Arg: Pointer = nil): string;
var
EndChar: Char;
begin
Result := '';
EndChar := _PeekFormatChar;
InputChar := _GetInputChar;
while (InputChar > ' ')
and (InputChar <> EndChar) do
begin
Result := Result + InputChar;
InputChar := _GetInputChar;
end;
if InputChar <> #0 then
Dec(InputOffset);
if Assigned(Arg) then
PString(Arg)^ := Result;
end;
function _ScanInputInteger(const Arg: Pointer): Boolean;
var
Value: string;
begin
Value := _ScanInputString;
Result := TryStrToInt(Value, {out} PInteger(Arg)^);
end;
procedure _Raise;
begin
raise EConvertError.CreateFmt('Unknown ScanFormat character : "%s"!', [FormatChar]);
end;
begin
Result := 0;
InputOffset := 1;
FormatOffset := 1;
FormatChar := _GetFormatChar;
while FormatChar <> #0 do
begin
if FormatChar <> '%' then
begin
InputChar := _GetInputChar;
if (InputChar = #0)
or (FormatChar <> InputChar) then
Exit;
end
else
begin
FormatChar := _GetFormatChar;
case FormatChar of
'%':
if _GetInputChar <> '%' then
Exit;
's':
begin
_ScanInputString(Args[Result]);
Inc(Result);
end;
'd', 'u':
begin
if not _ScanInputInteger(Args[Result]) then
Exit;
Inc(Result);
end;
else
_Raise;
end;
end;
FormatChar := _GetFormatChar;
end;
end;
``` |
72,682 | <p>Let me start by saying that I do not advocate this approach, but I saw it recently and I was wondering if there was a name for it I could use to point the guilty party to. So here goes.</p>
<p>Now you have a method, and you want to return a value. You <em>also</em> want to return an error code. Of course, exceptions are a much better choice, but for whatever reason you want an error code instead. Remember, I'm playing devil's advocate here. So you create a generic class, like this:</p>
<pre><code>class FunctionResult<T>
{
public T payload;
public int result;
}
</code></pre>
<p>And then declare your functions like this:</p>
<pre><code>FunctionResult<string> MyFunction()
{
FunctionResult<string> result;
//...
return result;
}
</code></pre>
<p>One variation on this pattern is to use an enum for the error code instead of a string. Now, back to my question: is there a name for this, and if so what is it?</p>
| [
{
"answer_id": 72729,
"author": "noah",
"author_id": 12034,
"author_profile": "https://Stackoverflow.com/users/12034",
"pm_score": 1,
"selected": false,
"text": "<p>How about the \"Can't decide whether this is an error or not\" pattern. Seems like if you really had an exception but wanted to return a partial result, you'd wrap the result in the exception.</p>\n"
},
{
"answer_id": 72808,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": 2,
"selected": false,
"text": "<p>I am not sure this is an anti-pattern. I have commonly seen this used instead of exceptions for performance reasons, or perhaps to make the fact that the method can fail more explicit. To me, it seems to be a personal preference rather than an anti-pattern.</p>\n"
},
{
"answer_id": 72840,
"author": "rmaruszewski",
"author_id": 6856,
"author_profile": "https://Stackoverflow.com/users/6856",
"pm_score": 4,
"selected": false,
"text": "<p>It is called \"<a href=\"http://www.refactoring.com/catalog/replaceErrorCodeWithException.html\" rel=\"nofollow noreferrer\">Replace Error Code with Exception</a>\"</p>\n"
},
{
"answer_id": 72846,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<p>Well, it's <em>not</em> an antipattern. The C++ standard library makes use of this feature and .NET even offers a special <code>FunctionResult</code> class in the .NET framework. It's called <code>Nullable</code>. Yes, this isn't restricted to function results but it can be used for such cases and is actually very useful here. If .NET 1.0 had already had the <code>Nullable</code> class, it would certainly have been used for the <code>NumberType.TryParse</code> methods, instead of the <code>out</code> parameter.</p>\n"
},
{
"answer_id": 72884,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 2,
"selected": false,
"text": "<p>This approach is actually much better than some others that I have seen. Some functions in C, for example, when they encounter an error they return and seem to succeed. The only way to tell that they failed is to call a function that will get the latest error.</p>\n\n<p>I spent hours trying to debug semaphore code on my MacBook before I finally found out that sem_init doesn't work on OSX! It compiled without error and ran without causing any errors - yet the semaphore didn't work and I couldn't figure out why. I pity the people that port an application that uses <a href=\"http://www.csc.villanova.edu/~mdamian/threads/posixsem.html\" rel=\"nofollow noreferrer\">POSIX semaphores</a> to OSX and must deal with resource contention issues that have already been debugged.</p>\n"
},
{
"answer_id": 72906,
"author": "ugasoft",
"author_id": 10120,
"author_profile": "https://Stackoverflow.com/users/10120",
"pm_score": 3,
"selected": false,
"text": "<p>I usually pass the payload as (not const) reference and the error code as a return value.</p>\n\n<p>I'm a game developer, we banish exceptions</p>\n"
},
{
"answer_id": 72922,
"author": "Dan Fleet",
"author_id": 7470,
"author_profile": "https://Stackoverflow.com/users/7470",
"pm_score": 5,
"selected": true,
"text": "<p>I'd agree that this isn't specifically an antipattern. It might be a smell depending upon the usage. There are reasons why one would actually not want to use exceptions (e.g. the errors being returned are not 'exceptional', for starters).</p>\n\n<p>There are instances where you want to have a service return a common model for its results, including both errors and good values. This might be wrapped by a low level service interaction that translates the result into an exception or other error structure, but at the level of the service, it lets the service return a result and a status code without having to define some exception structure that might have to be translated across a remote boundary.</p>\n\n<p>This code may not necessarily be an error either: consider an HTTP response, which consists of a lot of different data, including a status code, along with the body of the response.</p>\n"
},
{
"answer_id": 72980,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't want to use exceptions, the cleanest way to do it is to have the function return the error/success code and take either a reference or pointer argument that gets filled in with the result.</p>\n\n<p>I would not call it an anti-pattern. It's a very well proven workable method that's often preferable to using exceptions. </p>\n"
},
{
"answer_id": 73016,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 1,
"selected": false,
"text": "<p>If you expect your method to fail occasionally, but don't consider that exceptional, I prefer this pattern as used in the .NET Framework:</p>\n\n<pre><code>bool TryMyFunction(out FunctionResult result){ \n\n //... \n result = new FunctionResult();\n}\n</code></pre>\n"
},
{
"answer_id": 73020,
"author": "Peter Davis",
"author_id": 12508,
"author_profile": "https://Stackoverflow.com/users/12508",
"pm_score": 3,
"selected": false,
"text": "<p>Konrad is right, C# uses dual return values all the time. But I kind of like the TryParse, Dictionary.TryGetValue, etc. methods in C#.</p>\n\n<pre><code>int value;\nif (int.TryParse(\"123\", out value)) {\n // use value\n}\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>int? value = int.TryParse(\"123\");\nif (value != null) {\n // use value\n}\n</code></pre>\n\n<p>...mostly because the Nullable pattern does not scale to non-Value return types (i.e., class instances). This wouldn't work with Dictionary.TryGetValue(). And TryGetValue is both nicer than a KeyNotFoundException (no \"first chance exceptions\" constantly in the debugger, arguably more efficient), nicer than Java's practice of get() returning null (what if null values are expected), and more efficient than having to call ContainsKey() first.</p>\n\n<p>But this <em>is</em> still a little bit screwy -- since this looks like C#, then it should be using an out parameter. All efficiency gains are probably lost by instantiating the class.</p>\n\n<p>(Could be Java except for the \"string\" type being in lowercase. In Java of course you have to use a class to emulate dual return values.)</p>\n"
},
{
"answer_id": 73706,
"author": "ARKBAN",
"author_id": 11889,
"author_profile": "https://Stackoverflow.com/users/11889",
"pm_score": 2,
"selected": false,
"text": "<p>I agree with those that say this is not an anti-pattern. Its a perfectly valid pattern in certain contexts. Exceptions are for <em>exceptional</em> situations, return values (like in your example) should be used in expected situations. Some domains expect valid and invalid results from classes, and neither of those should be modeled as exceptions.</p>\n\n<p>For example, given X amount of gas, can a car get from A to B, and if so how much gas is left over? That kind of question is ideal for the data structure you provided. Not being able to make the trip from A to B is expected, hence an exception should not be used.</p>\n"
},
{
"answer_id": 74585,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>In defense of the anti-pattern designation, this code lends itself to being used in a few ways:</p>\n\n<ol>\n<li>Object x = MyFunction().payload; <em>(ignoring the return result - very bad)</em> </li>\n<li>int code = MyFunction().result; <em>(throwing away the payload - may be okay if that's the intended use.)</em> </li>\n<li>FunctionResult x = MyFunction(); //... <em>(a bunch of extra FunctionResult objects and extra code to check them all over the place)</em></li>\n</ol>\n\n<p>If you need to use return codes, that's fine. But then use return codes. Don't try to pack an extra payload in with it. That's what <em>ref</em> and <em>out</em> parameters (C#) are for. Nullable types might be an exception, but only because there's extra sugar baked in the language to support it.</p>\n\n<p>If you still disagree with this assessment, DOWNVOTE this answer (not the whole question). If you do think it's an anti-pattern, then UPVOTE it. We'll use this answer to see what the community thinks.</p>\n"
},
{
"answer_id": 300661,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 1,
"selected": false,
"text": "<p>Debates about smells and anti-patterns remind me the \"Survivor\" TV shows, where you have various programming constructs trying to vote each other off the island. I'd prefer to see \"construct X has such-and-so pros and cons\", rather than a continually evolving list of edicts of what should and should not be done.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
]
| Let me start by saying that I do not advocate this approach, but I saw it recently and I was wondering if there was a name for it I could use to point the guilty party to. So here goes.
Now you have a method, and you want to return a value. You *also* want to return an error code. Of course, exceptions are a much better choice, but for whatever reason you want an error code instead. Remember, I'm playing devil's advocate here. So you create a generic class, like this:
```
class FunctionResult<T>
{
public T payload;
public int result;
}
```
And then declare your functions like this:
```
FunctionResult<string> MyFunction()
{
FunctionResult<string> result;
//...
return result;
}
```
One variation on this pattern is to use an enum for the error code instead of a string. Now, back to my question: is there a name for this, and if so what is it? | I'd agree that this isn't specifically an antipattern. It might be a smell depending upon the usage. There are reasons why one would actually not want to use exceptions (e.g. the errors being returned are not 'exceptional', for starters).
There are instances where you want to have a service return a common model for its results, including both errors and good values. This might be wrapped by a low level service interaction that translates the result into an exception or other error structure, but at the level of the service, it lets the service return a result and a status code without having to define some exception structure that might have to be translated across a remote boundary.
This code may not necessarily be an error either: consider an HTTP response, which consists of a lot of different data, including a status code, along with the body of the response. |
72,696 | <p>I have some code like this:</p>
<pre><code>If key.Equals("search", StringComparison.OrdinalIgnoreCase) Then
DoSomething()
End If
</code></pre>
<p>I don't care about the case. Should I use <code>OrdinalIgnoreCase</code>, <code>InvariantCultureIgnoreCase</code>, or <code>CurrentCultureIgnoreCase</code>?</p>
| [
{
"answer_id": 72718,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on what you want, though I'd shy away from invariantculture unless you're <em>very</em> sure you'll never want to localize the code for other languages. Use CurrentCulture instead.</p>\n\n<p>Also, OrdinalIgnoreCase should respect numbers, which may or may not be what you want.</p>\n"
},
{
"answer_id": 72766,
"author": "Robert Taylor",
"author_id": 6375,
"author_profile": "https://Stackoverflow.com/users/6375",
"pm_score": 9,
"selected": true,
"text": "<p><strong><a href=\"https://learn.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#choosing-a-stringcomparison-member-for-your-method-call\" rel=\"noreferrer\">Newer .Net Docs now has a table to help you decide which is best to use in your situation.</a></strong></p>\n\n<p>From MSDN's \"<a href=\"https://learn.microsoft.com/en-us/previous-versions/dotnet/articles/ms973919(v=msdn.10)\" rel=\"noreferrer\">New Recommendations for Using Strings in Microsoft .NET 2.0</a>\"</p>\n\n<blockquote>\n <p>Summary: Code owners previously using the <code>InvariantCulture</code> for string comparison, casing, and sorting should strongly consider using a new set of <code>String</code> overloads in Microsoft .NET 2.0. <em>Specifically, data that is designed to be culture-agnostic and linguistically irrelevant</em> should begin specifying overloads using either the <code>StringComparison.Ordinal</code> or <code>StringComparison.OrdinalIgnoreCase</code> members of the new <code>StringComparison</code> enumeration. These enforce a byte-by-byte comparison similar to <code>strcmp</code> that not only avoids bugs from linguistic interpretation of essentially symbolic strings, but provides better performance.</p>\n</blockquote>\n"
},
{
"answer_id": 72780,
"author": "Bullines",
"author_id": 27870,
"author_profile": "https://Stackoverflow.com/users/27870",
"pm_score": 2,
"selected": false,
"text": "<p>I guess it depends on your situation. Since ordinal comparisons are actually looking at the characters' numeric Unicode values, they won't be the best choice when you're sorting alphabetically. For string comparisons, though, ordinal would be a tad faster.</p>\n"
},
{
"answer_id": 6406284,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 6,
"selected": false,
"text": "<h3>It all depends</h3>\n<p>Comparing unicode strings is hard:</p>\n<blockquote>\n<p>The implementation of Unicode string\nsearches and comparisons in text\nprocessing software must take into\naccount the presence of equivalent\ncode points. In the absence of this\nfeature, users searching for a\nparticular code point sequence would\nbe unable to find other visually\nindistinguishable glyphs that have a\ndifferent, but canonically equivalent,\ncode point representation.</p>\n</blockquote>\n<p>see: <a href=\"http://en.wikipedia.org/wiki/Unicode_equivalence\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Unicode_equivalence</a></p>\n<hr />\n<p>If you are trying to compare 2 unicode strings in a case insensitive way and want it to work <strong>EVERYWHERE</strong>, you have an impossible problem.</p>\n<p>The classic example is the <a href=\"http://en.wikipedia.org/wiki/Turkish_dotted_and_dotless_I\" rel=\"noreferrer\">Turkish i</a>, which when uppercased becomes İ (notice the dot)</p>\n<p>By default, the .Net framework usually uses the <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.thread.currentculture.aspx\" rel=\"noreferrer\">CurrentCulture</a> for string related functions, with a very important exception of <code>.Equals</code> that uses an ordinal (byte by byte) compare.</p>\n<p>This leads, by design, to the various string functions behaving differently depending on the computer's culture.</p>\n<hr />\n<p>Nonetheless, sometimes we want a "general purpose", case insensitive, comparison.</p>\n<p>For example, you may want your string comparison to behave the same way, no matter what computer your application is installed on.</p>\n<p>To achieve this we have 3 options:</p>\n<ol>\n<li>Set the culture explicitly and perform a case insensitive compare using unicode equivalence rules.</li>\n<li>Set the culture to the Invariant Culture and perform case insensitive compare using unicode equivalence rules.</li>\n<li>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.stringcomparer.ordinalignorecase.aspx\" rel=\"noreferrer\">OrdinalIgnoreCase</a> which will uppercase the string using the InvariantCulture and then perform a byte by byte comparison.</li>\n</ol>\n<p>Unicode equivalence rules are complicated, which means using method 1) or 2) is more expensive than <code>OrdinalIgnoreCase</code>. The fact that <code>OrdinalIgnoreCase</code> does not perform any special unicode normalization, means that some strings that render in the same way on a computer screen, <em>will not</em> be considered identical. For example: <code>"\\u0061\\u030a"</code> and <code>"\\u00e5"</code> both render å. However in a ordinal compare will be considered different.</p>\n<p>Which you choose heavily depends on the application you are building.</p>\n<ul>\n<li>If I was writing a line-of-business app which was only used by Turkish users, I would be sure to use method 1.</li>\n<li>If I just needed a simple "fake" case insensitive compare, for say a column name in a db, which is usually English I would probably use method 3.</li>\n</ul>\n<p>Microsoft has their <a href=\"http://msdn.microsoft.com/en-us/library/ms973919.aspx\" rel=\"noreferrer\">set of recommendations</a> with explicit guidelines. However, it is really important to understand the notion of unicode equivalence prior to approaching these problems.</p>\n<p>Also, please keep in mind that OrdinalIgnoreCase is a <a href=\"http://www.siao2.com/2004/12/29/344136.aspx\" rel=\"noreferrer\">very special kind</a> of beast, that is picking and choosing a bit of an ordinal compare with some mixed in lexicographic aspects. This can be confusing.</p>\n"
},
{
"answer_id": 11548935,
"author": "TheMoot",
"author_id": 130112,
"author_profile": "https://Stackoverflow.com/users/130112",
"pm_score": -1,
"selected": false,
"text": "<p>The very simple answer is, unless you are using Turkish, you don't need to use InvariantCulture.</p>\n\n<p>See the following link:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/3550213/in-c-sharp-what-is-the-difference-between-toupper-and-toupperinvariant\">In C# what is the difference between ToUpper() and ToUpperInvariant()?</a> </p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7072/"
]
| I have some code like this:
```
If key.Equals("search", StringComparison.OrdinalIgnoreCase) Then
DoSomething()
End If
```
I don't care about the case. Should I use `OrdinalIgnoreCase`, `InvariantCultureIgnoreCase`, or `CurrentCultureIgnoreCase`? | **[Newer .Net Docs now has a table to help you decide which is best to use in your situation.](https://learn.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#choosing-a-stringcomparison-member-for-your-method-call)**
From MSDN's "[New Recommendations for Using Strings in Microsoft .NET 2.0](https://learn.microsoft.com/en-us/previous-versions/dotnet/articles/ms973919(v=msdn.10))"
>
> Summary: Code owners previously using the `InvariantCulture` for string comparison, casing, and sorting should strongly consider using a new set of `String` overloads in Microsoft .NET 2.0. *Specifically, data that is designed to be culture-agnostic and linguistically irrelevant* should begin specifying overloads using either the `StringComparison.Ordinal` or `StringComparison.OrdinalIgnoreCase` members of the new `StringComparison` enumeration. These enforce a byte-by-byte comparison similar to `strcmp` that not only avoids bugs from linguistic interpretation of essentially symbolic strings, but provides better performance.
>
>
> |
72,699 | <p>For example which is better:</p>
<pre><code>select * from t1, t2 where t1.country='US' and t2.country=t1.country and t1.id=t2.id
</code></pre>
<p>or</p>
<pre><code>select * from t1, t2 where t1.country'US' and t2.country='US' and t1.id=t2.id
</code></pre>
<p>better as in less work for the database, faster results.</p>
<p><strong>Note:</strong> Sybase, and there's an index on both tables of <code>country+id</code>.</p>
| [
{
"answer_id": 72738,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>I'd lean towards only including your constant in the code once. There might be a performance advantage one way or the other, but it's probably so small the maintenance advantage of only one parameter trumps it.</p>\n"
},
{
"answer_id": 72743,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>The correct answer probably depends on your SQL engine. For MS SQL Server, the first approach is clearly the better because the statistical optimizer is given an additional clue which may help it find a better (more optimal) resolution path.</p>\n"
},
{
"answer_id": 72745,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I think it depends on the library and database engine. Each one will execute the SQL differently, and there's no telling which one will be optimized.</p>\n"
},
{
"answer_id": 72746,
"author": "Alan",
"author_id": 5878,
"author_profile": "https://Stackoverflow.com/users/5878",
"pm_score": 0,
"selected": false,
"text": "<p>If you ever wish to make the query more general, perhaps substituting a parameter for the target country, then I'd go with your first example, as it requires only a single change. That's less to worry about getting wrong in the future.</p>\n"
},
{
"answer_id": 72754,
"author": "mmaibaum",
"author_id": 12213,
"author_profile": "https://Stackoverflow.com/users/12213",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect this is going to depend on the tables, the data and the meta-data. I expect I could work up examples that would show results both ways - benchmark!</p>\n"
},
{
"answer_id": 72764,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think there is a global answer to your question. It depends on the specific query. You would have to compare the execution plans for the two queries to see if there are significant differences.</p>\n\n<p>I personally prefer the first form:</p>\n\n<p>select * from t1, t2 where t1.country='US' and t2.country=t1.country and t1.id=t2.id </p>\n\n<p>because if I want to change the literal there is only one change needed.</p>\n"
},
{
"answer_id": 72774,
"author": "aggergren",
"author_id": 7742,
"author_profile": "https://Stackoverflow.com/users/7742",
"pm_score": 0,
"selected": false,
"text": "<p>The extressions should be equivalent with any decent optimizer, but it depends on which database you're using and what indexes are defined on your table. </p>\n\n<p>I would suggest using the EXPLAIN feature to figure out which of expressions is the most optimal.</p>\n"
},
{
"answer_id": 72804,
"author": "Clinton Pierce",
"author_id": 8173,
"author_profile": "https://Stackoverflow.com/users/8173",
"pm_score": 2,
"selected": false,
"text": "<p>There are a lot of factors at play here that you've left out. What kind of database is it? Are those tables indexed? How are they indexed? How large are those tables?</p>\n\n<p>(Premature optimization is the root of all evil!)</p>\n\n<p>It could be that if \"t1.id\" and \"t2.id\" are indexed, the database engine joins them together based on those fields, and then uses the rest of the WHERE clause to filter out rows.</p>\n\n<p>They could be indexed but incredibly small tables, and both fit in a page of memory. In which case the database engine might just do a full scan of both rather than bother loading up the index.</p>\n\n<p>You just don't know, really, until you try.</p>\n"
},
{
"answer_id": 73172,
"author": "Lost in Alabama",
"author_id": 5285,
"author_profile": "https://Stackoverflow.com/users/5285",
"pm_score": 0,
"selected": false,
"text": "<p>I think a better SQL would be:</p>\n\n<p>select * from t1, t2 where t1.id=t2.id \nand t1.country ='US'</p>\n\n<p>There's no need to use the second comparison to 'US' unless it's possisble that the country in t2 could be different than t1 for the same id.</p>\n"
},
{
"answer_id": 73890,
"author": "Jeremiah Peschka",
"author_id": 11780,
"author_profile": "https://Stackoverflow.com/users/11780",
"pm_score": 0,
"selected": false,
"text": "<p>Rather than use an implicit inner join, I would explicitly join the tables. </p>\n\n<p>Since you want both the id fields and country fields to be the same, and you mentioned that both are indexed (I'm presuming in the same index), I would include both columns in the join so you can make use of an index seek instead of a scan. Finally, add your where clause.</p>\n\n<pre><code>SELECT *\n FROM t1\n JOIN t2 ON t1.id = t2.id AND t1.country = t2.country\n WHERE t1.country = 'US'\n</code>\n</pre>\n"
},
{
"answer_id": 74676,
"author": "Arthur Miller",
"author_id": 13085,
"author_profile": "https://Stackoverflow.com/users/13085",
"pm_score": 2,
"selected": true,
"text": "<p>I had a situation similar to this and this was the solution I resorted to:</p>\n\n<p>Select * \nFROM t1 \nINNER JOIN t2 ON t1.id = t2.id AND t1.country = t2.country AND t1.country = 'US'</p>\n\n<p>I noticed that my query ran faster in this scenario. I made the assumption that joining on the constant saved the engine time because the WHERE clause will execute at the end. Joining and then filtering by 'US' means you still pulled all the other countries from your table and then had to filter out the ones you wanted. This method pulls less records in the end, because it will only find US records.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12386/"
]
| For example which is better:
```
select * from t1, t2 where t1.country='US' and t2.country=t1.country and t1.id=t2.id
```
or
```
select * from t1, t2 where t1.country'US' and t2.country='US' and t1.id=t2.id
```
better as in less work for the database, faster results.
**Note:** Sybase, and there's an index on both tables of `country+id`. | I had a situation similar to this and this was the solution I resorted to:
Select \*
FROM t1
INNER JOIN t2 ON t1.id = t2.id AND t1.country = t2.country AND t1.country = 'US'
I noticed that my query ran faster in this scenario. I made the assumption that joining on the constant saved the engine time because the WHERE clause will execute at the end. Joining and then filtering by 'US' means you still pulled all the other countries from your table and then had to filter out the ones you wanted. This method pulls less records in the end, because it will only find US records. |
72,723 | <p>I have a svn repository, R, that depends on a library, l, in another repository.</p>
<p>The goal is that when someone checks out R, they also check out l. We want l to still be in its own repository so that l can be updated without dependence on R.</p>
<p>I don't know much about external svn links, but I believe that when depending on a svn-based library one can link to it externally, 'ext'.</p>
<p>If l is in a git repository, can I do something similar? I'd like to preserve the goal stated above.</p>
| [
{
"answer_id": 72925,
"author": "jtimberman",
"author_id": 7672,
"author_profile": "https://Stackoverflow.com/users/7672",
"pm_score": 2,
"selected": false,
"text": "<p>I suggest using a script wrapper for svn co. </p>\n\n<pre><code>#!/bin/sh\nsvn co path://server/R svn-R\ngit clone path://server/l git-l\n</code></pre>\n\n<p>Or similar.</p>\n"
},
{
"answer_id": 72930,
"author": "Avi",
"author_id": 1605,
"author_profile": "https://Stackoverflow.com/users/1605",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://svnbook.red-bean.com/en/1.5/svn.advanced.externals.html\" rel=\"noreferrer\">svn:externals</a> is the way svn can be made to check out sources from more than one repository into one working copy. But it is only meant for dealing with svn repositories - it doesn't know how to check out a git repository.</p>\n\n<p>You might be able to do it the other way 'round, by including an svn repository inside a git repository, using something like 'git svn'.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a svn repository, R, that depends on a library, l, in another repository.
The goal is that when someone checks out R, they also check out l. We want l to still be in its own repository so that l can be updated without dependence on R.
I don't know much about external svn links, but I believe that when depending on a svn-based library one can link to it externally, 'ext'.
If l is in a git repository, can I do something similar? I'd like to preserve the goal stated above. | I suggest using a script wrapper for svn co.
```
#!/bin/sh
svn co path://server/R svn-R
git clone path://server/l git-l
```
Or similar. |
72,768 | <p>I'm trying to figure out how to detect the type of credit card based purely on its number. Does anyone know of a definitive, reliable way to find this?</p>
| [
{
"answer_id": 72801,
"author": "senfo",
"author_id": 10792,
"author_profile": "https://Stackoverflow.com/users/10792",
"pm_score": 11,
"selected": true,
"text": "<p>The credit/debit card number is referred to as a <strong>PAN</strong>, or <em>Primary Account Number</em>. The first six digits of the PAN are taken from the <strong>IIN</strong>, or <em>Issuer Identification Number</em>, belonging to the issuing bank (IINs were previously known as BIN — Bank Identification Numbers — so you may see references to that terminology in some documents). These six digits are subject to an international standard, <a href=\"http://en.wikipedia.org/wiki/ISO/IEC_7812\" rel=\"noreferrer\">ISO/IEC 7812</a>, and can be used to determine the type of card from the number.</p>\n<p>Unfortunately the actual ISO/IEC 7812 database is not publicly available, however, there are unofficial lists, both commercial and free, including <a href=\"http://en.wikipedia.org/wiki/Bank_card_number\" rel=\"noreferrer\">on Wikipedia</a>.</p>\n<p>Anyway, to detect the type from the number, you can use a regular expression like the ones below: <a href=\"http://www.regular-expressions.info/creditcard.html\" rel=\"noreferrer\">Credit for original expressions</a></p>\n<p><strong>Visa:</strong> <code>^4[0-9]{6,}$</code> Visa card numbers start with a 4.</p>\n<p><strong>MasterCard:</strong> <code>^5[1-5][0-9]{5,}|222[1-9][0-9]{3,}|22[3-9][0-9]{4,}|2[3-6][0-9]{5,}|27[01][0-9]{4,}|2720[0-9]{3,}$</code> Before 2016, MasterCard numbers start with the numbers 51 through 55, <strong>but this will only detect MasterCard credit cards</strong>; there are other cards issued using the MasterCard system that do not fall into this IIN range. In 2016, they will add numbers in the range (222100-272099).</p>\n<p><strong>American Express:</strong> <code>^3[47][0-9]{5,}$</code> American Express card numbers start with 34 or 37.</p>\n<p><strong>Diners Club:</strong> <code>^3(?:0[0-5]|[68][0-9])[0-9]{4,}$</code> Diners Club card numbers begin with 300 through 305, 36 or 38. There are Diners Club cards that begin with 5 and have 16 digits. These are a joint venture between Diners Club and MasterCard and should be processed like a MasterCard.</p>\n<p><strong>Discover:</strong> <code>^6(?:011|5[0-9]{2})[0-9]{3,}$</code> Discover card numbers begin with 6011 or 65.</p>\n<p><strong>JCB:</strong> <code>^(?:2131|1800|35[0-9]{3})[0-9]{3,}$</code> JCB cards begin with 2131, 1800 or 35.</p>\n<p>Unfortunately, there are a number of card types processed with the MasterCard system that do not live in MasterCard’s IIN range (numbers starting 51...55); the most important case is that of Maestro cards, many of which have been issued from other banks’ IIN ranges and so are located all over the number space. As a result, <strong>it may be best to assume that any card that is not of some other type you accept must be a MasterCard</strong>.</p>\n<p><strong>Important</strong>: card numbers do vary in length; for instance, Visa has in the past issued cards with 13 digit PANs and cards with 16 digit PANs. Visa’s documentation currently indicates that it may issue or may have issued numbers with between 12 and 19 digits. <strong>Therefore, you should not check the length of the card number, other than to verify that it has at least 7 digits</strong> (for a complete IIN plus one check digit, which should match the value predicted by <a href=\"http://en.wikipedia.org/wiki/Luhn_algorithm\" rel=\"noreferrer\">the Luhn algorithm</a>).</p>\n<p>One further hint: <strong>before processing a cardholder PAN, strip any whitespace and punctuation characters from the input</strong>. Why? Because it’s typically <em>much</em> easier to enter the digits in groups, similar to how they’re displayed on the front of an actual credit card, i.e.</p>\n<pre><code>4444 4444 4444 4444\n</code></pre>\n<p>is much easier to enter correctly than</p>\n<pre><code>4444444444444444\n</code></pre>\n<p>There’s really no benefit in chastising the user because they’ve entered characters you don't expect here.</p>\n<p><strong>This also implies making sure that your entry fields have room for <em>at least</em> 24 characters, otherwise users who enter spaces will run out of room.</strong> I’d recommend that you make the field wide enough to display 32 characters and allow up to 64; that gives plenty of headroom for expansion.</p>\n<p>Here's an image that gives a little more insight:</p>\n<p><strong>UPDATE (2016):</strong> Mastercard is to implement new BIN ranges starting <a href=\"http://achpayment.net/\" rel=\"noreferrer\">Ach Payment</a>.</p>\n<p><img src=\"https://i.stack.imgur.com/Cu7PG.jpg\" alt=\"Credit Card Verification\" /></p>\n"
},
{
"answer_id": 73248,
"author": "Shoban",
"author_id": 12178,
"author_profile": "https://Stackoverflow.com/users/12178",
"pm_score": 3,
"selected": false,
"text": "<p>The first numbers of the credit card can be used to approximate the vendor:</p>\n\n<ul>\n<li>Visa: 49,44 or 47</li>\n<li>Visa electron: 42, 45, 48, 49</li>\n<li>MasterCard: 51</li>\n<li>Amex:34</li>\n<li>Diners: 30, 36, 38</li>\n<li>JCB: 35</li>\n</ul>\n"
},
{
"answer_id": 1780382,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 4,
"selected": false,
"text": "<p>Here's <a href=\"http://www.codeproject.com/Articles/20271/Ultimate-NET-Credit-Card-Utility-Class\" rel=\"noreferrer\">Complete C# or VB code for all kinds of CC related things</a> on codeproject.</p>\n\n<ul>\n<li>IsValidNumber</li>\n<li>GetCardTypeFromNumber</li>\n<li>GetCardTestNumber</li>\n<li>PassesLuhnTest</li>\n</ul>\n\n<p>This article has been up for a couple years with no negative comments.</p>\n"
},
{
"answer_id": 2408585,
"author": "Rashy",
"author_id": 289587,
"author_profile": "https://Stackoverflow.com/users/289587",
"pm_score": 4,
"selected": false,
"text": "<p>Check this out:</p>\n\n<p><a href=\"http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CC70060A01B\" rel=\"nofollow noreferrer\">http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CC70060A01B</a></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function isValidCreditCard(type, ccnum) {\n /* Visa: length 16, prefix 4, dashes optional.\n Mastercard: length 16, prefix 51-55, dashes optional.\n Discover: length 16, prefix 6011, dashes optional.\n American Express: length 15, prefix 34 or 37.\n Diners: length 14, prefix 30, 36, or 38. */\n\n var re = new Regex({\n \"visa\": \"/^4\\d{3}-?\\d{4}-?\\d{4}-?\\d\",\n \"mc\": \"/^5[1-5]\\d{2}-?\\d{4}-?\\d{4}-?\\d{4}$/\",\n \"disc\": \"/^6011-?\\d{4}-?\\d{4}-?\\d{4}$/\",\n \"amex\": \"/^3[47]\\d{13}$/\",\n \"diners\": \"/^3[068]\\d{12}$/\"\n }[type.toLowerCase()])\n\n if (!re.test(ccnum)) return false;\n // Remove all dashes for the checksum checks to eliminate negative numbers\n ccnum = ccnum.split(\"-\").join(\"\");\n // Checksum (\"Mod 10\")\n // Add even digits in even length strings or odd digits in odd length strings.\n var checksum = 0;\n for (var i = (2 - (ccnum.length % 2)); i <= ccnum.length; i += 2) {\n checksum += parseInt(ccnum.charAt(i - 1));\n }\n // Analyze odd digits in even length strings or even digits in odd length strings.\n for (var i = (ccnum.length % 2) + 1; i < ccnum.length; i += 2) {\n var digit = parseInt(ccnum.charAt(i - 1)) * 2;\n if (digit < 10) { checksum += digit; } else { checksum += (digit - 9); }\n }\n if ((checksum % 10) == 0) return true;\n else return false;\n}\n</code></pre>\n"
},
{
"answer_id": 11529211,
"author": "Parvez",
"author_id": 1531583,
"author_profile": "https://Stackoverflow.com/users/1531583",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// abobjects.com, parvez ahmad ab bulk mailer\nuse below script\n\nfunction isValidCreditCard2(type, ccnum) {\n if (type == \"Visa\") {\n // Visa: length 16, prefix 4, dashes optional.\n var re = /^4\\d{3}?\\d{4}?\\d{4}?\\d{4}$/;\n } else if (type == \"MasterCard\") {\n // Mastercard: length 16, prefix 51-55, dashes optional.\n var re = /^5[1-5]\\d{2}?\\d{4}?\\d{4}?\\d{4}$/;\n } else if (type == \"Discover\") {\n // Discover: length 16, prefix 6011, dashes optional.\n var re = /^6011?\\d{4}?\\d{4}?\\d{4}$/;\n } else if (type == \"AmEx\") {\n // American Express: length 15, prefix 34 or 37.\n var re = /^3[4,7]\\d{13}$/;\n } else if (type == \"Diners\") {\n // Diners: length 14, prefix 30, 36, or 38.\n var re = /^3[0,6,8]\\d{12}$/;\n }\n if (!re.test(ccnum)) return false;\n return true;\n /*\n // Remove all dashes for the checksum checks to eliminate negative numbers\n ccnum = ccnum.split(\"-\").join(\"\");\n // Checksum (\"Mod 10\")\n // Add even digits in even length strings or odd digits in odd length strings.\n var checksum = 0;\n for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {\n checksum += parseInt(ccnum.charAt(i-1));\n }\n // Analyze odd digits in even length strings or even digits in odd length strings.\n for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {\n var digit = parseInt(ccnum.charAt(i-1)) * 2;\n if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }\n }\n if ((checksum % 10) == 0) return true; else return false;\n */\n\n }\njQuery.validator.addMethod(\"isValidCreditCard\", function(postalcode, element) { \n return isValidCreditCard2($(\"#cardType\").val(), $(\"#cardNum\").val()); \n\n}, \"<br>credit card is invalid\");\n\n\n Type</td>\n <td class=\"text\">&nbsp; <form:select path=\"cardType\" cssclass=\"fields\" style=\"border: 1px solid #D5D5D5;padding: 0px 0px 0px 0px;width: 130px;height: 22px;\">\n <option value=\"SELECT\">SELECT</option>\n <option value=\"MasterCard\">Mastercard</option>\n <option value=\"Visa\">Visa</option>\n <option value=\"AmEx\">American Express</option>\n <option value=\"Discover\">Discover</option>\n </form:select> <font color=\"#FF0000\">*</font> \n\n$(\"#signupForm\").validate({\n\n rules:{\n companyName:{required: true},\n address1:{required: true},\n city:{required: true},\n state:{required: true},\n zip:{required: true},\n country:{required: true},\n chkAgree:{required: true},\n confPassword:{required: true},\n lastName:{required: true},\n firstName:{required: true},\n ccAddress1:{required: true},\n ccZip:{ \n postalcode : true\n },\n phone:{required: true},\n email:{\n required: true,\n email: true\n },\n userName:{\n required: true,\n minlength: 6\n },\n password:{\n required: true,\n minlength: 6\n }, \n cardNum:{ \n isValidCreditCard : true\n },\n</code></pre>\n"
},
{
"answer_id": 13842374,
"author": "Usman Younas",
"author_id": 1728403,
"author_profile": "https://Stackoverflow.com/users/1728403",
"pm_score": 5,
"selected": false,
"text": "<pre class=\"lang-cs prettyprint-override\"><code>public string GetCreditCardType(string CreditCardNumber)\n{\n Regex regVisa = new Regex(\"^4[0-9]{12}(?:[0-9]{3})?$\");\n Regex regMaster = new Regex(\"^5[1-5][0-9]{14}$\");\n Regex regExpress = new Regex(\"^3[47][0-9]{13}$\");\n Regex regDiners = new Regex(\"^3(?:0[0-5]|[68][0-9])[0-9]{11}$\");\n Regex regDiscover = new Regex(\"^6(?:011|5[0-9]{2})[0-9]{12}$\");\n Regex regJCB = new Regex(\"^(?:2131|1800|35\\\\d{3})\\\\d{11}$\");\n\n\n if (regVisa.IsMatch(CreditCardNumber))\n return \"VISA\";\n else if (regMaster.IsMatch(CreditCardNumber))\n return \"MASTER\";\n else if (regExpress.IsMatch(CreditCardNumber))\n return \"AEXPRESS\";\n else if (regDiners.IsMatch(CreditCardNumber))\n return \"DINERS\";\n else if (regDiscover.IsMatch(CreditCardNumber))\n return \"DISCOVERS\";\n else if (regJCB.IsMatch(CreditCardNumber))\n return \"JCB\";\n else\n return \"invalid\";\n}\n</code></pre>\n\n<p>Here is the function to check Credit card type using Regex , c#</p>\n"
},
{
"answer_id": 15499262,
"author": "Fivell",
"author_id": 246544,
"author_profile": "https://Stackoverflow.com/users/246544",
"pm_score": 4,
"selected": false,
"text": "<p>recently I needed such functionality, I was porting Zend Framework Credit Card Validator to ruby.\nruby gem: <a href=\"https://github.com/Fivell/credit_card_validations\" rel=\"nofollow noreferrer\">https://github.com/Fivell/credit_card_validations</a> \nzend framework: <a href=\"https://github.com/zendframework/zf2/blob/master/library/Zend/Validator/CreditCard.php\" rel=\"nofollow noreferrer\">https://github.com/zendframework/zf2/blob/master/library/Zend/Validator/CreditCard.php</a></p>\n\n<p>They both use INN ranges for detecting type. Here you can read <a href=\"http://en.wikipedia.org/wiki/Bank_card_number\" rel=\"nofollow noreferrer\">about INN</a></p>\n\n<p>According to this you can detect credit card alternatively (without regexps,but declaring some rules about prefixes and possible length)</p>\n\n<p>So we have next rules for most used cards</p>\n\n<pre><code>######## most used brands #########\n\n visa: [\n {length: [13, 16], prefixes: ['4']}\n ],\n mastercard: [\n {length: [16], prefixes: ['51', '52', '53', '54', '55']}\n ],\n\n amex: [\n {length: [15], prefixes: ['34', '37']}\n ],\n ######## other brands ########\n diners: [\n {length: [14], prefixes: ['300', '301', '302', '303', '304', '305', '36', '38']},\n ],\n\n #There are Diners Club (North America) cards that begin with 5. These are a joint venture between Diners Club and MasterCard, and are processed like a MasterCard\n # will be removed in next major version\n\n diners_us: [\n {length: [16], prefixes: ['54', '55']}\n ],\n\n discover: [\n {length: [16], prefixes: ['6011', '644', '645', '646', '647', '648',\n '649', '65']}\n ],\n\n jcb: [\n {length: [16], prefixes: ['3528', '3529', '353', '354', '355', '356', '357', '358', '1800', '2131']}\n ],\n\n\n laser: [\n {length: [16, 17, 18, 19], prefixes: ['6304', '6706', '6771']}\n ],\n\n solo: [\n {length: [16, 18, 19], prefixes: ['6334', '6767']}\n ],\n\n switch: [\n {length: [16, 18, 19], prefixes: ['633110', '633312', '633304', '633303', '633301', '633300']}\n\n ],\n\n maestro: [\n {length: [12, 13, 14, 15, 16, 17, 18, 19], prefixes: ['5010', '5011', '5012', '5013', '5014', '5015', '5016', '5017', '5018',\n '502', '503', '504', '505', '506', '507', '508',\n '6012', '6013', '6014', '6015', '6016', '6017', '6018', '6019',\n '602', '603', '604', '605', '6060',\n '677', '675', '674', '673', '672', '671', '670',\n '6760', '6761', '6762', '6763', '6764', '6765', '6766', '6768', '6769']}\n ],\n\n # Luhn validation are skipped for union pay cards because they have unknown generation algoritm\n unionpay: [\n {length: [16, 17, 18, 19], prefixes: ['622', '624', '625', '626', '628'], skip_luhn: true}\n ],\n\n dankrot: [\n {length: [16], prefixes: ['5019']}\n ],\n\n rupay: [\n {length: [16], prefixes: ['6061', '6062', '6063', '6064', '6065', '6066', '6067', '6068', '6069', '607', '608'], skip_luhn: true}\n ]\n\n}\n</code></pre>\n\n<p>Then by searching prefix and comparing length you can detect credit card brand. Also don't forget about luhn algoritm (it is descibed here <a href=\"http://en.wikipedia.org/wiki/Luhn\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Luhn</a>).</p>\n\n<p>UPDATE </p>\n\n<p>updated list of rules can be found here <a href=\"https://raw.githubusercontent.com/Fivell/credit_card_validations/master/lib/data/brands.yaml\" rel=\"nofollow noreferrer\">https://raw.githubusercontent.com/Fivell/credit_card_validations/master/lib/data/brands.yaml</a></p>\n"
},
{
"answer_id": 18216511,
"author": "ismail",
"author_id": 2679740,
"author_profile": "https://Stackoverflow.com/users/2679740",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a php class function returns CCtype by CCnumber. \n<br>This code not validates the card or not runs Luhn algorithm only try to find credit card type based on table in <a href=\"http://en.wikipedia.org/wiki/Credit_card_number#Major_Industry_Identifier_.28MII.29\" rel=\"nofollow noreferrer\">this page</a>. basicly uses CCnumber length and CCcard prefix to determine CCcard type.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\nclass CreditcardType\n{\n public static $creditcardTypes = [\n [\n 'Name' => 'American Express',\n 'cardLength' => [15],\n 'cardPrefix' => ['34', '37'],\n ], [\n 'Name' => 'Maestro',\n 'cardLength' => [12, 13, 14, 15, 16, 17, 18, 19],\n 'cardPrefix' => ['5018', '5020', '5038', '6304', '6759', '6761', '6763'],\n ], [\n 'Name' => 'Mastercard',\n 'cardLength' => [16],\n 'cardPrefix' => ['51', '52', '53', '54', '55'],\n ], [\n 'Name' => 'Visa',\n 'cardLength' => [13, 16],\n 'cardPrefix' => ['4'],\n ], [\n 'Name' => 'JCB',\n 'cardLength' => [16],\n 'cardPrefix' => ['3528', '3529', '353', '354', '355', '356', '357', '358'],\n ], [\n 'Name' => 'Discover',\n 'cardLength' => [16],\n 'cardPrefix' => ['6011', '622126', '622127', '622128', '622129', '62213','62214', '62215', '62216', '62217', '62218', '62219','6222', '6223', '6224', '6225', '6226', '6227', '6228','62290', '62291', '622920', '622921', '622922', '622923','622924', '622925', '644', '645', '646', '647', '648','649', '65'],\n ], [\n 'Name' => 'Solo',\n 'cardLength' => [16, 18, 19],\n 'cardPrefix' => ['6334', '6767'],\n ], [\n 'Name' => 'Unionpay',\n 'cardLength' => [16, 17, 18, 19],\n 'cardPrefix' => ['622126', '622127', '622128', '622129', '62213', '62214','62215', '62216', '62217', '62218', '62219', '6222', '6223','6224', '6225', '6226', '6227', '6228', '62290', '62291','622920', '622921', '622922', '622923', '622924', '622925'],\n ], [\n 'Name' => 'Diners Club',\n 'cardLength' => [14],\n 'cardPrefix' => ['300', '301', '302', '303', '304', '305', '36'],\n ], [\n 'Name' => 'Diners Club US',\n 'cardLength' => [16],\n 'cardPrefix' => ['54', '55'],\n ], [\n 'Name' => 'Diners Club Carte Blanche',\n 'cardLength' => [14],\n 'cardPrefix' => ['300', '305'],\n ], [\n 'Name' => 'Laser',\n 'cardLength' => [16, 17, 18, 19],\n 'cardPrefix' => ['6304', '6706', '6771', '6709'],\n ],\n ];\n\n public static function getType($CCNumber)\n {\n $CCNumber = trim($CCNumber);\n $type = 'Unknown';\n foreach (CreditcardType::$creditcardTypes as $card) {\n if (! in_array(strlen($CCNumber), $card['cardLength'])) {\n continue;\n }\n $prefixes = '/^(' . implode('|', $card['cardPrefix']) . ')/';\n if (preg_match($prefixes, $CCNumber) == 1) {\n $type = $card['Name'];\n break;\n }\n }\n return $type;\n }\n}\n\n</code></pre>\n"
},
{
"answer_id": 19138852,
"author": "Anatoliy",
"author_id": 161832,
"author_profile": "https://Stackoverflow.com/users/161832",
"pm_score": 7,
"selected": false,
"text": "<p>In javascript:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function detectCardType(number) {\n var re = {\n electron: /^(4026|417500|4405|4508|4844|4913|4917)\\d+$/,\n maestro: /^(5018|5020|5038|5612|5893|6304|6759|6761|6762|6763|0604|6390)\\d+$/,\n dankort: /^(5019)\\d+$/,\n interpayment: /^(636)\\d+$/,\n unionpay: /^(62|88)\\d+$/,\n visa: /^4[0-9]{12}(?:[0-9]{3})?$/,\n mastercard: /^5[1-5][0-9]{14}$/,\n amex: /^3[47][0-9]{13}$/,\n diners: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,\n discover: /^6(?:011|5[0-9]{2})[0-9]{12}$/,\n jcb: /^(?:2131|1800|35\\d{3})\\d{11}$/\n }\n\n for(var key in re) {\n if(re[key].test(number)) {\n return key\n }\n }\n}\n</code></pre>\n\n<p>Unit test:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>describe('CreditCard', function() {\n describe('#detectCardType', function() {\n\n var cards = {\n '8800000000000000': 'UNIONPAY',\n\n '4026000000000000': 'ELECTRON',\n '4175000000000000': 'ELECTRON',\n '4405000000000000': 'ELECTRON',\n '4508000000000000': 'ELECTRON',\n '4844000000000000': 'ELECTRON',\n '4913000000000000': 'ELECTRON',\n '4917000000000000': 'ELECTRON',\n\n '5019000000000000': 'DANKORT',\n\n '5018000000000000': 'MAESTRO',\n '5020000000000000': 'MAESTRO',\n '5038000000000000': 'MAESTRO',\n '5612000000000000': 'MAESTRO',\n '5893000000000000': 'MAESTRO',\n '6304000000000000': 'MAESTRO',\n '6759000000000000': 'MAESTRO',\n '6761000000000000': 'MAESTRO',\n '6762000000000000': 'MAESTRO',\n '6763000000000000': 'MAESTRO',\n '0604000000000000': 'MAESTRO',\n '6390000000000000': 'MAESTRO',\n\n '3528000000000000': 'JCB',\n '3589000000000000': 'JCB',\n '3529000000000000': 'JCB',\n\n '6360000000000000': 'INTERPAYMENT',\n\n '4916338506082832': 'VISA',\n '4556015886206505': 'VISA',\n '4539048040151731': 'VISA',\n '4024007198964305': 'VISA',\n '4716175187624512': 'VISA',\n\n '5280934283171080': 'MASTERCARD',\n '5456060454627409': 'MASTERCARD',\n '5331113404316994': 'MASTERCARD',\n '5259474113320034': 'MASTERCARD',\n '5442179619690834': 'MASTERCARD',\n\n '6011894492395579': 'DISCOVER',\n '6011388644154687': 'DISCOVER',\n '6011880085013612': 'DISCOVER',\n '6011652795433988': 'DISCOVER',\n '6011375973328347': 'DISCOVER',\n\n '345936346788903': 'AMEX',\n '377669501013152': 'AMEX',\n '373083634595479': 'AMEX',\n '370710819865268': 'AMEX',\n '371095063560404': 'AMEX'\n };\n\n Object.keys(cards).forEach(function(number) {\n it('should detect card ' + number + ' as ' + cards[number], function() {\n Basket.detectCardType(number).should.equal(cards[number]);\n });\n });\n });\n});\n</code></pre>\n"
},
{
"answer_id": 21487404,
"author": "Pinch",
"author_id": 1513082,
"author_profile": "https://Stackoverflow.com/users/1513082",
"pm_score": 2,
"selected": false,
"text": "<p>Just a little spoon feeding:</p>\n\n<pre><code>$(\"#CreditCardNumber\").focusout(function () {\n\n\n var regVisa = /^4[0-9]{12}(?:[0-9]{3})?$/;\n var regMasterCard = /^5[1-5][0-9]{14}$/;\n var regAmex = /^3[47][0-9]{13}$/;\n var regDiscover = /^6(?:011|5[0-9]{2})[0-9]{12}$/;\n\n if (regVisa.test($(this).val())) {\n $(\"#CCImage\").html(\"<img height='40px' src='@Url.Content(\"~/images/visa.png\")'>\"); \n\n }\n\n else if (regMasterCard.test($(this).val())) {\n $(\"#CCImage\").html(\"<img height='40px' src='@Url.Content(\"~/images/mastercard.png\")'>\");\n\n }\n\n else if (regAmex.test($(this).val())) {\n\n $(\"#CCImage\").html(\"<img height='40px' src='@Url.Content(\"~/images/amex.png\")'>\");\n\n }\n else if (regDiscover.test($(this).val())) {\n\n $(\"#CCImage\").html(\"<img height='40px' src='@Url.Content(\"~/images/discover.png\")'>\");\n\n }\n else {\n $(\"#CCImage\").html(\"NA\");\n\n }\n\n });\n</code></pre>\n"
},
{
"answer_id": 21617574,
"author": "Janos Szabo",
"author_id": 1176373,
"author_profile": "https://Stackoverflow.com/users/1176373",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Updated: 15th June 2016</strong> (as an ultimate solution currently)</p>\n\n<p>Please note that I even give vote up for the one is top voted, but to make it clear these are the regexps actually works i tested it with thousands of real BIN codes. <strong>The most important is to use start strings (^) otherwise it will give false results in real world!</strong></p>\n\n<p><strong>JCB</strong> <code>^(?:2131|1800|35)[0-9]{0,}$</code> Start with: <strong>2131, 1800, 35 (3528-3589)</strong></p>\n\n<p><strong>American Express</strong> <code>^3[47][0-9]{0,}$</code> Start with: <strong>34, 37</strong></p>\n\n<p><strong>Diners Club</strong> <code>^3(?:0[0-59]{1}|[689])[0-9]{0,}$</code> Start with: <strong>300-305, 309, 36, 38-39</strong></p>\n\n<p><strong>Visa</strong> <code>^4[0-9]{0,}$</code> Start with: <strong>4</strong></p>\n\n<p><strong>MasterCard</strong> <code>^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)[0-9]{0,}$</code> Start with: <strong>2221-2720, 51-55</strong></p>\n\n<p><strong>Maestro</strong> <code>^(5[06789]|6)[0-9]{0,}$</code> Maestro always growing in the range: <strong>60-69</strong>, started with / not something else, but starting 5 must be encoded as mastercard anyway. Maestro cards must be detected in the end of the code because some others has in the range of 60-69. Please look at the code.</p>\n\n<p><strong>Discover</strong> <code>^(6011|65|64[4-9]|62212[6-9]|6221[3-9]|622[2-8]|6229[01]|62292[0-5])[0-9]{0,}$</code> Discover quite difficult to code, start with: <strong>6011, 622126-622925, 644-649, 65</strong></p>\n\n<p>In <strong>javascript</strong> I use this function. This is good when u assign it to an onkeyup event and it give result as soon as possible.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function cc_brand_id(cur_val) {\n // the regular expressions check for possible matches as you type, hence the OR operators based on the number of chars\n // regexp string length {0} provided for soonest detection of beginning of the card numbers this way it could be used for BIN CODE detection also\n\n //JCB\n jcb_regex = new RegExp('^(?:2131|1800|35)[0-9]{0,}$'); //2131, 1800, 35 (3528-3589)\n // American Express\n amex_regex = new RegExp('^3[47][0-9]{0,}$'); //34, 37\n // Diners Club\n diners_regex = new RegExp('^3(?:0[0-59]{1}|[689])[0-9]{0,}$'); //300-305, 309, 36, 38-39\n // Visa\n visa_regex = new RegExp('^4[0-9]{0,}$'); //4\n // MasterCard\n mastercard_regex = new RegExp('^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)[0-9]{0,}$'); //2221-2720, 51-55\n maestro_regex = new RegExp('^(5[06789]|6)[0-9]{0,}$'); //always growing in the range: 60-69, started with / not something else, but starting 5 must be encoded as mastercard anyway\n //Discover\n discover_regex = new RegExp('^(6011|65|64[4-9]|62212[6-9]|6221[3-9]|622[2-8]|6229[01]|62292[0-5])[0-9]{0,}$');\n ////6011, 622126-622925, 644-649, 65\n\n\n // get rid of anything but numbers\n cur_val = cur_val.replace(/\\D/g, '');\n\n // checks per each, as their could be multiple hits\n //fix: ordering matter in detection, otherwise can give false results in rare cases\n var sel_brand = \"unknown\";\n if (cur_val.match(jcb_regex)) {\n sel_brand = \"jcb\";\n } else if (cur_val.match(amex_regex)) {\n sel_brand = \"amex\";\n } else if (cur_val.match(diners_regex)) {\n sel_brand = \"diners_club\";\n } else if (cur_val.match(visa_regex)) {\n sel_brand = \"visa\";\n } else if (cur_val.match(mastercard_regex)) {\n sel_brand = \"mastercard\";\n } else if (cur_val.match(discover_regex)) {\n sel_brand = \"discover\";\n } else if (cur_val.match(maestro_regex)) {\n if (cur_val[0] == '5') { //started 5 must be mastercard\n sel_brand = \"mastercard\";\n } else {\n sel_brand = \"maestro\"; //maestro is all 60-69 which is not something else, thats why this condition in the end\n }\n }\n\n return sel_brand;\n}\n</code></pre>\n\n<p>Here you can play with it:</p>\n\n<p><a href=\"http://jsfiddle.net/upN3L/69/\" rel=\"noreferrer\">http://jsfiddle.net/upN3L/69/</a></p>\n\n<p><strong>For PHP use this function, this detects some sub VISA/MC cards too:</strong></p>\n\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Obtain a brand constant from a PAN\n *\n * @param string $pan Credit card number\n * @param bool $include_sub_types Include detection of sub visa brands\n * @return string\n */\npublic static function getCardBrand($pan, $include_sub_types = false)\n{\n //maximum length is not fixed now, there are growing number of CCs has more numbers in length, limiting can give false negatives atm\n\n //these regexps accept not whole cc numbers too\n //visa\n $visa_regex = \"/^4[0-9]{0,}$/\";\n $vpreca_regex = \"/^428485[0-9]{0,}$/\";\n $postepay_regex = \"/^(402360|402361|403035|417631|529948){0,}$/\";\n $cartasi_regex = \"/^(432917|432930|453998)[0-9]{0,}$/\";\n $entropay_regex = \"/^(406742|410162|431380|459061|533844|522093)[0-9]{0,}$/\";\n $o2money_regex = \"/^(422793|475743)[0-9]{0,}$/\";\n\n // MasterCard\n $mastercard_regex = \"/^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)[0-9]{0,}$/\";\n $maestro_regex = \"/^(5[06789]|6)[0-9]{0,}$/\";\n $kukuruza_regex = \"/^525477[0-9]{0,}$/\";\n $yunacard_regex = \"/^541275[0-9]{0,}$/\";\n\n // American Express\n $amex_regex = \"/^3[47][0-9]{0,}$/\";\n\n // Diners Club\n $diners_regex = \"/^3(?:0[0-59]{1}|[689])[0-9]{0,}$/\";\n\n //Discover\n $discover_regex = \"/^(6011|65|64[4-9]|62212[6-9]|6221[3-9]|622[2-8]|6229[01]|62292[0-5])[0-9]{0,}$/\";\n\n //JCB\n $jcb_regex = \"/^(?:2131|1800|35)[0-9]{0,}$/\";\n\n //ordering matter in detection, otherwise can give false results in rare cases\n if (preg_match($jcb_regex, $pan)) {\n return \"jcb\";\n }\n\n if (preg_match($amex_regex, $pan)) {\n return \"amex\";\n }\n\n if (preg_match($diners_regex, $pan)) {\n return \"diners_club\";\n }\n\n //sub visa/mastercard cards\n if ($include_sub_types) {\n if (preg_match($vpreca_regex, $pan)) {\n return \"v-preca\";\n }\n if (preg_match($postepay_regex, $pan)) {\n return \"postepay\";\n }\n if (preg_match($cartasi_regex, $pan)) {\n return \"cartasi\";\n }\n if (preg_match($entropay_regex, $pan)) {\n return \"entropay\";\n }\n if (preg_match($o2money_regex, $pan)) {\n return \"o2money\";\n }\n if (preg_match($kukuruza_regex, $pan)) {\n return \"kukuruza\";\n }\n if (preg_match($yunacard_regex, $pan)) {\n return \"yunacard\";\n }\n }\n\n if (preg_match($visa_regex, $pan)) {\n return \"visa\";\n }\n\n if (preg_match($mastercard_regex, $pan)) {\n return \"mastercard\";\n }\n\n if (preg_match($discover_regex, $pan)) {\n return \"discover\";\n }\n\n if (preg_match($maestro_regex, $pan)) {\n if ($pan[0] == '5') { //started 5 must be mastercard\n return \"mastercard\";\n }\n return \"maestro\"; //maestro is all 60-69 which is not something else, thats why this condition in the end\n\n }\n\n return \"unknown\"; //unknown for this system\n}\n</code></pre>\n"
},
{
"answer_id": 21998527,
"author": "rajan",
"author_id": 3348405,
"author_profile": "https://Stackoverflow.com/users/3348405",
"pm_score": 0,
"selected": false,
"text": "<p>The regular expression rules that match the <a href=\"http://www.techrecite.com/credit-card-validation-regex-script-in-php-using-luhn-algorithm/\" rel=\"nofollow\">respective card vendors</a>:</p>\n\n<ul>\n<li><code>(4\\d{12}(?:\\d{3})?)</code> for VISA.</li>\n<li><code>(5[1-5]\\d{14})</code> for MasterCard.</li>\n<li><code>(3[47]\\d{13})</code> for AMEX.</li>\n<li><code>((?:5020|5038|6304|6579|6761)\\d{12}(?:\\d\\d)?)</code> for Maestro.</li>\n<li><code>(3(?:0[0-5]|[68][0-9])[0-9]{11})</code> for Diners Club.</li>\n<li><code>(6(?:011|5[0-9]{2})[0-9]{12})</code> for Discover.</li>\n<li><code>(35[2-8][89]\\d\\d\\d{10})</code> for JCB.</li>\n</ul>\n"
},
{
"answer_id": 22034170,
"author": "Gajus",
"author_id": 368691,
"author_profile": "https://Stackoverflow.com/users/368691",
"pm_score": 3,
"selected": false,
"text": "<p>Do not try to detect credit card type as part of processing a payment. You are risking of declining valid transactions.</p>\n\n<p>If you need to provide information to your payment processor (e.g. PayPal credit card object requires to name the <a href=\"https://developer.paypal.com/docs/api/#store-a-credit-card\" rel=\"nofollow\">card type</a>), then guess it from the least information available, e.g.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$credit_card['pan'] = preg_replace('/[^0-9]/', '', $credit_card['pan']);\n$inn = (int) mb_substr($credit_card['pan'], 0, 2);\n\n// @see http://en.wikipedia.org/wiki/List_of_Bank_Identification_Numbers#Overview\nif ($inn >= 40 && $inn <= 49) {\n $type = 'visa';\n} else if ($inn >= 51 && $inn <= 55) {\n $type = 'mastercard';\n} else if ($inn >= 60 && $inn <= 65) {\n $type = 'discover';\n} else if ($inn >= 34 && $inn <= 37) {\n $type = 'amex';\n} else {\n throw new \\UnexpectedValueException('Unsupported card type.');\n}\n</code></pre>\n\n<p>This implementation (using only the first two digits) is enough to identify all of the major (and in PayPal's case all of the supported) card schemes. In fact, you might want to skip the exception altogether and default to the most popular card type. Let the payment gateway/processor tell you if there is a validation error in response to your request.</p>\n\n<p>The reality is that your payment gateway <a href=\"http://qr.ae/tOcrH\" rel=\"nofollow\">does not care about the value you provide</a>.</p>\n"
},
{
"answer_id": 22631832,
"author": "Nick",
"author_id": 956278,
"author_profile": "https://Stackoverflow.com/users/956278",
"pm_score": 3,
"selected": false,
"text": "<p>Compact javascript version</p>\n\n<pre><code> var getCardType = function (number) {\n var cards = {\n visa: /^4[0-9]{12}(?:[0-9]{3})?$/,\n mastercard: /^5[1-5][0-9]{14}$/,\n amex: /^3[47][0-9]{13}$/,\n diners: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,\n discover: /^6(?:011|5[0-9]{2})[0-9]{12}$/,\n jcb: /^(?:2131|1800|35\\d{3})\\d{11}$/\n };\n for (var card in cards) {\n if (cards[card].test(number)) {\n return card;\n }\n }\n };\n</code></pre>\n"
},
{
"answer_id": 24615110,
"author": "ZurabWeb",
"author_id": 1016530,
"author_profile": "https://Stackoverflow.com/users/1016530",
"pm_score": 2,
"selected": false,
"text": "<p>My solution with jQuery:</p>\n\n<pre><code>function detectCreditCardType() {\n var type = new Array;\n type[1] = '^4[0-9]{12}(?:[0-9]{3})?$'; // visa\n type[2] = '^5[1-5][0-9]{14}$'; // mastercard\n type[3] = '^6(?:011|5[0-9]{2})[0-9]{12}$'; // discover\n type[4] = '^3[47][0-9]{13}$'; // amex\n\n var ccnum = $('.creditcard').val().replace(/[^\\d.]/g, '');\n var returntype = 0;\n\n $.each(type, function(idx, re) {\n var regex = new RegExp(re);\n if(regex.test(ccnum) && idx>0) {\n returntype = idx;\n }\n });\n\n return returntype;\n}\n</code></pre>\n\n<p>In case 0 is returned, credit card type is undetected.</p>\n\n<p>\"creditcard\" class should be added to the credit card input field.</p>\n"
},
{
"answer_id": 27600969,
"author": "MikeRoger",
"author_id": 459655,
"author_profile": "https://Stackoverflow.com/users/459655",
"pm_score": 3,
"selected": false,
"text": "<p>In Card Range Recognition (CRR), a drawback with algorithms that use a series of regex or other hard-coded ranges, is that the BINs/IINs do change over time in my experience. The co-branding of cards is an ongoing complication. Different Card Acquirers / merchants may need you treat the same card differently, depending on e.g. geolocation. </p>\n\n<p>Additionally, in the last few years with e.g. UnionPay cards in wider circulation, existing models do not cope with new ranges that sometimes interleave with broader ranges that they supersede.<br>\nKnowing the geography your system needs to cover may help, as some ranges are restricted to use in particular countries. For example, ranges 62 include some AAA sub-ranges in the US, but if your merchant base is outside the US, you may be able to treat all 62 as UnionPay.<br>\nYou may be also asked to treat a card differently based on merchant location. E.g. to treat certain UK cards as debit domestically, but as credit internationally. </p>\n\n<p>There are very useful set of rules maintained by one major Acquiring Bank. E.g. <a href=\"https://www.barclaycard.co.uk/business/files/BIN-Rules-EIRE.pdf\" rel=\"nofollow noreferrer\">https://www.barclaycard.co.uk/business/files/BIN-Rules-EIRE.pdf</a> and <a href=\"https://www.barclaycard.co.uk/business/files/BIN-Rules-UK.pdf\" rel=\"nofollow noreferrer\">https://www.barclaycard.co.uk/business/files/BIN-Rules-UK.pdf</a>. (Valid links as of June 2017, thanks to the user who provided a link to updated reference.) But be aware of the caveat that, while these CRR rules may represent the Card Issuing universe as it applies to the merchants acquired by that entity, it does not include e.g. ranges identified as CUP/UPI.</p>\n\n<p>These comments apply to magnetic stripe (MagStripe) or PKE (Pan Key Entry) scenarios. The situation is different again in the ICC/EMV world.</p>\n\n<p>Update: Other answers on this page (and also the linked WikiPedia page) have JCB as always 16 long. However, in my company we have a dedicated team of engineers who certify our POS devices and software across multiple acquiring banks and geographies. The most recent Certification Pack of cards this team have from JCB, had a pass case for a 19 long PAN.</p>\n"
},
{
"answer_id": 29937208,
"author": "Nagama Inamdar",
"author_id": 2240243,
"author_profile": "https://Stackoverflow.com/users/2240243",
"pm_score": 2,
"selected": false,
"text": "<p>Stripe has provided this fantastic <strong>javascript</strong> library for card scheme detection. Let me add few code snippets and show you how to use it. </p>\n\n<p>Firstly Include it to your web page as</p>\n\n<pre><code><script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery.payment/1.2.3/jquery.payment.js \" ></script>\n</code></pre>\n\n<p>Secondly use the function cardType for detecting the card scheme.</p>\n\n<pre><code>$(document).ready(function() { \n var type = $.payment.cardType(\"4242 4242 4242 4242\"); //test card number\n console.log(type); \n}); \n</code></pre>\n\n<p>Here are the reference links for more examples and demos.</p>\n\n<ol>\n<li><a href=\"https://stripe.com/blog/jquery-payment\" rel=\"noreferrer\">Stripe blog for jquery.payment.js</a></li>\n<li><a href=\"https://github.com/stripe/jquery.payment\" rel=\"noreferrer\">Github repository</a></li>\n</ol>\n"
},
{
"answer_id": 30957202,
"author": "angelcool.net",
"author_id": 2425880,
"author_profile": "https://Stackoverflow.com/users/2425880",
"pm_score": 3,
"selected": false,
"text": "<p>Anatoliy's answer in PHP:</p>\n\n<pre><code> public static function detectCardType($num)\n {\n $re = array(\n \"visa\" => \"/^4[0-9]{12}(?:[0-9]{3})?$/\",\n \"mastercard\" => \"/^5[1-5][0-9]{14}$/\",\n \"amex\" => \"/^3[47][0-9]{13}$/\",\n \"discover\" => \"/^6(?:011|5[0-9]{2})[0-9]{12}$/\",\n );\n\n if (preg_match($re['visa'],$num))\n {\n return 'visa';\n }\n else if (preg_match($re['mastercard'],$num))\n {\n return 'mastercard';\n }\n else if (preg_match($re['amex'],$num))\n {\n return 'amex';\n }\n else if (preg_match($re['discover'],$num))\n {\n return 'discover';\n }\n else\n {\n return false;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 31734477,
"author": "ShadeTreeDeveloper",
"author_id": 633527,
"author_profile": "https://Stackoverflow.com/users/633527",
"pm_score": 2,
"selected": false,
"text": "<p>I searched around quite a bit for credit card formatting and phone number formatting. Found lots of good tips but nothing really suited my exact desires so I created <a href=\"http://quercusv.github.io/smartForm/\" rel=\"nofollow\">this bit of code</a>. You use it like this:</p>\n\n<pre><code>var sf = smartForm.formatCC(myInputString);\nvar cardType = sf.cardType;\n</code></pre>\n"
},
{
"answer_id": 36483754,
"author": "Daisy R.",
"author_id": 1855263,
"author_profile": "https://Stackoverflow.com/users/1855263",
"pm_score": 3,
"selected": false,
"text": "<p>Swift 2.1 Version of Usman Y's answer.\nUse a print statement to verify so call by some string value</p>\n\n<pre><code>print(self.validateCardType(self.creditCardField.text!))\n\nfunc validateCardType(testCard: String) -> String {\n\n let regVisa = \"^4[0-9]{12}(?:[0-9]{3})?$\"\n let regMaster = \"^5[1-5][0-9]{14}$\"\n let regExpress = \"^3[47][0-9]{13}$\"\n let regDiners = \"^3(?:0[0-5]|[68][0-9])[0-9]{11}$\"\n let regDiscover = \"^6(?:011|5[0-9]{2})[0-9]{12}$\"\n let regJCB = \"^(?:2131|1800|35\\\\d{3})\\\\d{11}$\"\n\n\n let regVisaTest = NSPredicate(format: \"SELF MATCHES %@\", regVisa)\n let regMasterTest = NSPredicate(format: \"SELF MATCHES %@\", regMaster)\n let regExpressTest = NSPredicate(format: \"SELF MATCHES %@\", regExpress)\n let regDinersTest = NSPredicate(format: \"SELF MATCHES %@\", regDiners)\n let regDiscoverTest = NSPredicate(format: \"SELF MATCHES %@\", regDiscover)\n let regJCBTest = NSPredicate(format: \"SELF MATCHES %@\", regJCB)\n\n\n if regVisaTest.evaluateWithObject(testCard){\n return \"Visa\"\n }\n else if regMasterTest.evaluateWithObject(testCard){\n return \"MasterCard\"\n }\n\n else if regExpressTest.evaluateWithObject(testCard){\n return \"American Express\"\n }\n\n else if regDinersTest.evaluateWithObject(testCard){\n return \"Diners Club\"\n }\n\n else if regDiscoverTest.evaluateWithObject(testCard){\n return \"Discover\"\n }\n\n else if regJCBTest.evaluateWithObject(testCard){\n return \"JCB\"\n }\n\n return \"\"\n\n}\n</code></pre>\n"
},
{
"answer_id": 36882835,
"author": "radtek",
"author_id": 2023392,
"author_profile": "https://Stackoverflow.com/users/2023392",
"pm_score": 2,
"selected": false,
"text": "<p>Here is an example of some boolean functions written in Python that return <code>True</code> if the card is detected as per the function name. </p>\n\n<pre><code>def is_american_express(cc_number):\n \"\"\"Checks if the card is an american express. If us billing address country code, & is_amex, use vpos\n https://en.wikipedia.org/wiki/Bank_card_number#cite_note-GenCardFeatures-3\n :param cc_number: unicode card number\n \"\"\"\n return bool(re.match(r'^3[47][0-9]{13}$', cc_number))\n\n\ndef is_visa(cc_number):\n \"\"\"Checks if the card is a visa, begins with 4 and 12 or 15 additional digits.\n :param cc_number: unicode card number\n \"\"\"\n\n # Standard Visa is 13 or 16, debit can be 19\n if bool(re.match(r'^4', cc_number)) and len(cc_number) in [13, 16, 19]:\n return True\n\n return False\n\n\ndef is_mastercard(cc_number):\n \"\"\"Checks if the card is a mastercard. Begins with 51-55 or 2221-2720 and 16 in length.\n :param cc_number: unicode card number\n \"\"\"\n if len(cc_number) == 16 and cc_number.isdigit(): # Check digit, before cast to int\n return bool(re.match(r'^5[1-5]', cc_number)) or int(cc_number[:4]) in range(2221, 2721)\n return False\n\n\ndef is_discover(cc_number):\n \"\"\"Checks if the card is discover, re would be too hard to maintain. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n if len(cc_number) == 16:\n try:\n # return bool(cc_number[:4] == '6011' or cc_number[:2] == '65' or cc_number[:6] in range(622126, 622926))\n return bool(cc_number[:4] == '6011' or cc_number[:2] == '65' or 622126 <= int(cc_number[:6]) <= 622925)\n except ValueError:\n return False\n return False\n\n\ndef is_jcb(cc_number):\n \"\"\"Checks if the card is a jcb. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n # return bool(re.match(r'^(?:2131|1800|35\\d{3})\\d{11}$', cc_number)) # wikipedia\n return bool(re.match(r'^35(2[89]|[3-8][0-9])[0-9]{12}$', cc_number)) # PawelDecowski\n\n\ndef is_diners_club(cc_number):\n \"\"\"Checks if the card is a diners club. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n return bool(re.match(r'^3(?:0[0-6]|[68][0-9])[0-9]{11}$', cc_number)) # 0-5 = carte blance, 6 = international\n\n\ndef is_laser(cc_number):\n \"\"\"Checks if the card is laser. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n return bool(re.match(r'^(6304|670[69]|6771)', cc_number))\n\n\ndef is_maestro(cc_number):\n \"\"\"Checks if the card is maestro. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n possible_lengths = [12, 13, 14, 15, 16, 17, 18, 19]\n return bool(re.match(r'^(50|5[6-9]|6[0-9])', cc_number)) and len(cc_number) in possible_lengths\n\n\n# Child cards\n\ndef is_visa_electron(cc_number):\n \"\"\"Child of visa. Checks if the card is a visa electron. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n return bool(re.match(r'^(4026|417500|4508|4844|491(3|7))', cc_number)) and len(cc_number) == 16\n\n\ndef is_total_rewards_visa(cc_number):\n \"\"\"Child of visa. Checks if the card is a Total Rewards Visa. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n return bool(re.match(r'^41277777[0-9]{8}$', cc_number))\n\n\ndef is_diners_club_carte_blanche(cc_number):\n \"\"\"Child card of diners. Checks if the card is a diners club carte blance. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n return bool(re.match(r'^30[0-5][0-9]{11}$', cc_number)) # github PawelDecowski, jquery-creditcardvalidator\n\n\ndef is_diners_club_carte_international(cc_number):\n \"\"\"Child card of diners. Checks if the card is a diners club international. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n return bool(re.match(r'^36[0-9]{12}$', cc_number)) # jquery-creditcardvalidator\n</code></pre>\n"
},
{
"answer_id": 37559946,
"author": "Vidyalaxmi",
"author_id": 2930683,
"author_profile": "https://Stackoverflow.com/users/2930683",
"pm_score": 2,
"selected": false,
"text": "<p>In swift you can create an enum to detect the credit card type.</p>\n\n<pre><code>enum CreditCardType: Int { // Enum which encapsulates different card types and method to find the type of card.\n\ncase Visa\ncase Master\ncase Amex\ncase Discover\n\nfunc validationRegex() -> String {\n var regex = \"\"\n switch self {\n case .Visa:\n regex = \"^4[0-9]{6,}$\"\n\n case .Master:\n regex = \"^5[1-5][0-9]{5,}$\"\n\n case .Amex:\n regex = \"^3[47][0-9]{13}$\"\n\n case .Discover:\n regex = \"^6(?:011|5[0-9]{2})[0-9]{12}$\"\n }\n\n return regex\n}\n\nfunc validate(cardNumber: String) -> Bool {\n let predicate = NSPredicate(format: \"SELF MATCHES %@\", validationRegex())\n return predicate.evaluateWithObject(cardNumber)\n}\n\n// Method returns the credit card type for given card number\nstatic func cardTypeForCreditCardNumber(cardNumber: String) -> CreditCardType? {\n var creditCardType: CreditCardType?\n\n var index = 0\n while let cardType = CreditCardType(rawValue: index) {\n if cardType.validate(cardNumber) {\n creditCardType = cardType\n break\n } else {\n index++\n }\n }\n return creditCardType\n }\n}\n</code></pre>\n\n<p>Call the method CreditCardType.cardTypeForCreditCardNumber(\"#card number\") which returns CreditCardType enum value.</p>\n"
},
{
"answer_id": 42667959,
"author": "Anoop M Maddasseri",
"author_id": 4694013,
"author_profile": "https://Stackoverflow.com/users/4694013",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>The first six digits of a card number (including the initial MII\n digit) are known as the <a href=\"https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_.28IIN.29\" rel=\"nofollow noreferrer\">issuer identification number</a> (IIN). These\n identify the card issuing institution that issued the card to the card\n holder. The rest of the number is allocated by the card issuer. The\n card number's length is its number of digits. Many card issuers print\n the entire IIN and account number on their card.</p>\n</blockquote>\n\n<p>Based on the above facts I would like to keep a snippet of <strong>JAVA</strong> code to identify card brand.</p>\n\n<blockquote>\n <p>Sample card types</p>\n</blockquote>\n\n<pre><code>public static final String AMERICAN_EXPRESS = \"American Express\";\npublic static final String DISCOVER = \"Discover\";\npublic static final String JCB = \"JCB\";\npublic static final String DINERS_CLUB = \"Diners Club\";\npublic static final String VISA = \"Visa\";\npublic static final String MASTERCARD = \"MasterCard\";\npublic static final String UNKNOWN = \"Unknown\";\n</code></pre>\n\n<blockquote>\n <p>Card Prefixes</p>\n</blockquote>\n\n<pre><code>// Based on http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29\npublic static final String[] PREFIXES_AMERICAN_EXPRESS = {\"34\", \"37\"};\npublic static final String[] PREFIXES_DISCOVER = {\"60\", \"62\", \"64\", \"65\"};\npublic static final String[] PREFIXES_JCB = {\"35\"};\npublic static final String[] PREFIXES_DINERS_CLUB = {\"300\", \"301\", \"302\", \"303\", \"304\", \"305\", \"309\", \"36\", \"38\", \"39\"};\npublic static final String[] PREFIXES_VISA = {\"4\"};\npublic static final String[] PREFIXES_MASTERCARD = {\n \"2221\", \"2222\", \"2223\", \"2224\", \"2225\", \"2226\", \"2227\", \"2228\", \"2229\",\n \"223\", \"224\", \"225\", \"226\", \"227\", \"228\", \"229\",\n \"23\", \"24\", \"25\", \"26\",\n \"270\", \"271\", \"2720\",\n \"50\", \"51\", \"52\", \"53\", \"54\", \"55\"\n };\n</code></pre>\n\n<blockquote>\n <p>Check to see if the input number has any of the given prefixes.</p>\n</blockquote>\n\n<pre><code>public String getBrand(String number) {\n\nString evaluatedType;\nif (StripeTextUtils.hasAnyPrefix(number, PREFIXES_AMERICAN_EXPRESS)) {\n evaluatedType = AMERICAN_EXPRESS;\n} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_DISCOVER)) {\n evaluatedType = DISCOVER;\n} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_JCB)) {\n evaluatedType = JCB;\n} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_DINERS_CLUB)) {\n evaluatedType = DINERS_CLUB;\n} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_VISA)) {\n evaluatedType = VISA;\n} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_MASTERCARD)) {\n evaluatedType = MASTERCARD;\n} else {\n evaluatedType = UNKNOWN;\n}\n return evaluatedType;\n}\n</code></pre>\n\n<blockquote>\n <p>Finally, The Utility method</p>\n</blockquote>\n\n<pre><code>/**\n * Check to see if the input number has any of the given prefixes.\n *\n * @param number the number to test\n * @param prefixes the prefixes to test against\n * @return {@code true} if number begins with any of the input prefixes\n*/\n\npublic static boolean hasAnyPrefix(String number, String... prefixes) {\n if (number == null) {\n return false;\n }\n for (String prefix : prefixes) {\n if (number.startsWith(prefix)) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p><strong>Reference</strong></p>\n\n<ul>\n<li><a href=\"https://github.com/stripe/stripe-android/blob/master/stripe/src/main/java/com/stripe/android/model/Card.java\" rel=\"nofollow noreferrer\">Stripe Card Builder</a></li>\n</ul>\n"
},
{
"answer_id": 49531091,
"author": "gaurav gupta",
"author_id": 5695805,
"author_profile": "https://Stackoverflow.com/users/5695805",
"pm_score": 0,
"selected": false,
"text": "<pre><code>follow Luhn’s algorithm\n\n private boolean validateCreditCardNumber(String str) {\n\n int[] ints = new int[str.length()];\n for (int i = 0; i < str.length(); i++) {\n ints[i] = Integer.parseInt(str.substring(i, i + 1));\n }\n for (int i = ints.length - 2; i >= 0; i = i - 2) {\n int j = ints[i];\n j = j * 2;\n if (j > 9) {\n j = j % 10 + 1;\n }\n ints[i] = j;\n }\n int sum = 0;\n for (int i = 0; i < ints.length; i++) {\n sum += ints[i];\n }\n if (sum % 10 == 0) {\n return true;\n } else {\n return false;\n }\n\n\n }\n\nthen call this method\n\nEdittext mCreditCardNumberEt;\n\n mCreditCardNumberEt.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n\n }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n\n int cardcount= s.toString().length();\n if(cardcount>=16) {\n boolean cardnumbervalid= validateCreditCardNumber(s.toString());\n if(cardnumbervalid) {\n cardvalidtesting.setText(\"Valid Card\");\n cardvalidtesting.setTextColor(ContextCompat.getColor(context,R.color.green));\n }\n else {\n cardvalidtesting.setText(\"Invalid Card\");\n cardvalidtesting.setTextColor(ContextCompat.getColor(context,R.color.red));\n }\n }\n else if(cardcount>0 &&cardcount<16) {\n cardvalidtesting.setText(\"Invalid Card\");\n cardvalidtesting.setTextColor(ContextCompat.getColor(context,R.color.red));\n }\n\n else {\n cardvalidtesting.setText(\"\");\n\n }\n\n\n }\n\n @Override\n public void afterTextChanged(Editable s) {\n\n }\n });\n</code></pre>\n"
},
{
"answer_id": 58241706,
"author": "OhhhThatVarun",
"author_id": 7436566,
"author_profile": "https://Stackoverflow.com/users/7436566",
"pm_score": 1,
"selected": false,
"text": "<p>Try this for kotlin. Add Regex and add to the when statement.</p>\n\n<pre><code>private fun getCardType(number: String): String {\n\n val visa = Regex(\"^4[0-9]{12}(?:[0-9]{3})?$\")\n val mastercard = Regex(\"^5[1-5][0-9]{14}$\")\n val amx = Regex(\"^3[47][0-9]{13}$\")\n\n return when {\n visa.matches(number) -> \"Visa\"\n mastercard.matches(number) -> \"Mastercard\"\n amx.matches(number) -> \"American Express\"\n else -> \"Unknown\"\n }\n }\n</code></pre>\n"
},
{
"answer_id": 62955455,
"author": "Emanuel",
"author_id": 6638583,
"author_profile": "https://Stackoverflow.com/users/6638583",
"pm_score": 2,
"selected": false,
"text": "<p>A javascript improve of @Anatoliy answer</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getCardType (number) {\n const numberFormated = number.replace(/\\D/g, '')\n var patterns = {\n VISA: /^4[0-9]{12}(?:[0-9]{3})?$/,\n MASTER: /^5[1-5][0-9]{14}$/,\n AMEX: /^3[47][0-9]{13}$/,\n ELO: /^((((636368)|(438935)|(504175)|(451416)|(636297))\\d{0,10})|((5067)|(4576)|(4011))\\d{0,12})$/,\n AURA: /^(5078\\d{2})(\\d{2})(\\d{11})$/,\n JCB: /^(?:2131|1800|35\\d{3})\\d{11}$/,\n DINERS: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,\n DISCOVERY: /^6(?:011|5[0-9]{2})[0-9]{12}$/,\n HIPERCARD: /^(606282\\d{10}(\\d{3})?)|(3841\\d{15})$/,\n ELECTRON: /^(4026|417500|4405|4508|4844|4913|4917)\\d+$/,\n MAESTRO: /^(5018|5020|5038|5612|5893|6304|6759|6761|6762|6763|0604|6390)\\d+$/,\n DANKORT: /^(5019)\\d+$/,\n INTERPAYMENT: /^(636)\\d+$/,\n UNIONPAY: /^(62|88)\\d+$/,\n }\n for (var key in patterns) {\n if (patterns[key].test(numberFormated)) {\n return key\n }\n }\n}\n\nconsole.log(getCardType(\"4539 5684 7526 2091\"))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 64923841,
"author": "Saharat Sittipanya",
"author_id": 10767168,
"author_profile": "https://Stackoverflow.com/users/10767168",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n<p><strong>Swift 5+</strong></p>\n</blockquote>\n<pre><code>extension String {\n \n func isMatch(_ Regex: String) -> Bool {\n \n do {\n let regex = try NSRegularExpression(pattern: Regex)\n let results = regex.matches(in: self, range: NSRange(self.startIndex..., in: self))\n return results.map {\n String(self[Range($0.range, in: self)!])\n }.count > 0\n } catch {\n return false\n }\n \n }\n \n func getCreditCardType() -> String? {\n \n let VISA_Regex = "^4[0-9]{6,}$"\n let MasterCard_Regex = "^5[1-5][0-9]{5,}|222[1-9][0-9]{3,}|22[3-9][0-9]{4,}|2[3-6][0-9]{5,}|27[01][0-9]{4,}|2720[0-9]{3,}$"\n let AmericanExpress_Regex = "^3[47][0-9]{5,}$"\n let DinersClub_Regex = "^3(?:0[0-5]|[68][0-9])[0-9]{4,}$"\n let Discover_Regex = "^6(?:011|5[0-9]{2})[0-9]{3,}$"\n let JCB_Regex = "^(?:2131|1800|35[0-9]{3})[0-9]{3,}$"\n \n if self.isMatch(VISA_Regex) {\n return "VISA"\n } else if self.isMatch(MasterCard_Regex) {\n return "MasterCard"\n } else if self.isMatch(AmericanExpress_Regex) {\n return "AmericanExpress"\n } else if self.isMatch(DinersClub_Regex) {\n return "DinersClub"\n } else if self.isMatch(Discover_Regex) {\n return "Discover"\n } else if self.isMatch(JCB_Regex) {\n return "JCB"\n } else {\n return nil\n }\n \n }\n \n}\n</code></pre>\n<blockquote>\n<p><strong>Use.</strong></p>\n</blockquote>\n<pre><code>"1234123412341234".getCreditCardType()\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12382/"
]
| I'm trying to figure out how to detect the type of credit card based purely on its number. Does anyone know of a definitive, reliable way to find this? | The credit/debit card number is referred to as a **PAN**, or *Primary Account Number*. The first six digits of the PAN are taken from the **IIN**, or *Issuer Identification Number*, belonging to the issuing bank (IINs were previously known as BIN — Bank Identification Numbers — so you may see references to that terminology in some documents). These six digits are subject to an international standard, [ISO/IEC 7812](http://en.wikipedia.org/wiki/ISO/IEC_7812), and can be used to determine the type of card from the number.
Unfortunately the actual ISO/IEC 7812 database is not publicly available, however, there are unofficial lists, both commercial and free, including [on Wikipedia](http://en.wikipedia.org/wiki/Bank_card_number).
Anyway, to detect the type from the number, you can use a regular expression like the ones below: [Credit for original expressions](http://www.regular-expressions.info/creditcard.html)
**Visa:** `^4[0-9]{6,}$` Visa card numbers start with a 4.
**MasterCard:** `^5[1-5][0-9]{5,}|222[1-9][0-9]{3,}|22[3-9][0-9]{4,}|2[3-6][0-9]{5,}|27[01][0-9]{4,}|2720[0-9]{3,}$` Before 2016, MasterCard numbers start with the numbers 51 through 55, **but this will only detect MasterCard credit cards**; there are other cards issued using the MasterCard system that do not fall into this IIN range. In 2016, they will add numbers in the range (222100-272099).
**American Express:** `^3[47][0-9]{5,}$` American Express card numbers start with 34 or 37.
**Diners Club:** `^3(?:0[0-5]|[68][0-9])[0-9]{4,}$` Diners Club card numbers begin with 300 through 305, 36 or 38. There are Diners Club cards that begin with 5 and have 16 digits. These are a joint venture between Diners Club and MasterCard and should be processed like a MasterCard.
**Discover:** `^6(?:011|5[0-9]{2})[0-9]{3,}$` Discover card numbers begin with 6011 or 65.
**JCB:** `^(?:2131|1800|35[0-9]{3})[0-9]{3,}$` JCB cards begin with 2131, 1800 or 35.
Unfortunately, there are a number of card types processed with the MasterCard system that do not live in MasterCard’s IIN range (numbers starting 51...55); the most important case is that of Maestro cards, many of which have been issued from other banks’ IIN ranges and so are located all over the number space. As a result, **it may be best to assume that any card that is not of some other type you accept must be a MasterCard**.
**Important**: card numbers do vary in length; for instance, Visa has in the past issued cards with 13 digit PANs and cards with 16 digit PANs. Visa’s documentation currently indicates that it may issue or may have issued numbers with between 12 and 19 digits. **Therefore, you should not check the length of the card number, other than to verify that it has at least 7 digits** (for a complete IIN plus one check digit, which should match the value predicted by [the Luhn algorithm](http://en.wikipedia.org/wiki/Luhn_algorithm)).
One further hint: **before processing a cardholder PAN, strip any whitespace and punctuation characters from the input**. Why? Because it’s typically *much* easier to enter the digits in groups, similar to how they’re displayed on the front of an actual credit card, i.e.
```
4444 4444 4444 4444
```
is much easier to enter correctly than
```
4444444444444444
```
There’s really no benefit in chastising the user because they’ve entered characters you don't expect here.
**This also implies making sure that your entry fields have room for *at least* 24 characters, otherwise users who enter spaces will run out of room.** I’d recommend that you make the field wide enough to display 32 characters and allow up to 64; that gives plenty of headroom for expansion.
Here's an image that gives a little more insight:
**UPDATE (2016):** Mastercard is to implement new BIN ranges starting [Ach Payment](http://achpayment.net/).
 |
72,769 | <p>Problem (simplified to make things clearer):</p>
<ul>
1. there is one statically-linked static.lib that has a function that increments:
<pre><code>
extern int CallCount = 0;
int TheFunction()
{
void *p = &CallCount;
printf("Function called");
return CallCount++;
}
</code></pre>
2. static.lib is linked into a managed C++/CLI managed.dll that wraps TheFunction method:
<pre><code>
int Managed::CallLibFunc()
{
return TheFunction();
}
</code></pre>
3. Test app has a reference to managed.dll and creates multiple domains that call C++/CLI wrapper:
<pre><code>
static void Main(string[] args)
{
Managed c1 = new Managed();
int val1 = c1.CallLibFunc();
// value is zero
AppDomain ad = AppDomain.CreateDomain("NewDomain");
Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;
int val2 = c.CallLibFunc();
// value is one
}
</code></pre>
</ul>
<p>Question:</p>
<p>Based on what I have read in Essential .NET Vol1 The CLR by Don Box, I would expect val2 to be zero since a brand new copy of managed.dll/static.lib is loaded when CreateInstanceAndUnwrap is called. Am I misunderstanding what is happening? The static library does not seem to be respecting the appdomain boundaries since it's unmanaged code. Is there a way to get around this issue other than by creating a brand new process for instantiating Managed?</p>
<p>Thank you very much everyone!</p>
| [
{
"answer_id": 73075,
"author": "gnobal",
"author_id": 7748,
"author_profile": "https://Stackoverflow.com/users/7748",
"pm_score": 3,
"selected": true,
"text": "<p>My hunch was that, as you suspected, unmanaged DLLs are loaded in the context of the process and not in the context of the AppDomain, so any static data in unmanaged code is shared among AppDomains.</p>\n\n<p><a href=\"http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/98cbabe0-33d6-4775-a3a7-04e71b7498dd/\" rel=\"nofollow noreferrer\">This link</a> shows someone with the same problem you have, still not 100% verification of this, but probably this is the case.</p>\n\n<p><a href=\"http://lambert.geek.nz/2007/05/29/unmanaged-appdomain-callback/\" rel=\"nofollow noreferrer\">This link</a> is about creating a callback from unmanaged code into an AppDomain using a thunking trick. I'm not sure this can help you but maybe you'll find this useful to create some kind of a workaround.</p>\n"
},
{
"answer_id": 73135,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "<p>In short, maybe. AppDomains are purely a managed concept. When an AppDomain is instantiated it doesn't map in new copies of the underlying DLLs, it can reuse the code already in memory (for example, you wouldn't expect it to load up new copies of all the System.* assemblies, right?)</p>\n\n<p>Within the managed world all static variables are scoped by AppDomain, but as you point out this doesn't apply in the unmanaged world.</p>\n\n<p>You could do something complex that forces a load of a unique managed.dll for each app domain, which would result in a new version of the static lib being brought along for the ride. For example, maybe using Assembly.Load with a byte array would work, but I don't know how the CLR will attempt to deal with the collision in types if the same assembly is loaded twice.</p>\n"
},
{
"answer_id": 73289,
"author": "Seb Rose",
"author_id": 12405,
"author_profile": "https://Stackoverflow.com/users/12405",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think we're getting to the actual issue here - <a href=\"http://www.ddj.com/windows/184405853\" rel=\"nofollow noreferrer\">see this DDJ article</a>.</p>\n\n<p>The default value of the loader optimization attribute is SingleDomain, which \"causes the AppDomain to load a private copy of each necessary assembly's code\". Even if it were one of the Multi domain values \"every AppDomain always maintains a distinct copy of static fields\".</p>\n\n<p>'managed.dll' is (as its name implies) is a managed assembly. The code in static.lib has been statically compiled (as IL code) into 'managed.dll', so I would expect the same behaviour as Lenik expects....</p>\n\n<p>... unless static.lib is a static export library for an unmanaged DLL. Lenik says this is not the case, so I'm still unsure what's going on here.</p>\n"
},
{
"answer_id": 93134,
"author": "Rick Minerich",
"author_id": 9251,
"author_profile": "https://Stackoverflow.com/users/9251",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried running in separate processes? A static library should not share memory instances outside of it's own process.</p>\n\n<p>This can be a pain to manage, I know. I'm not sure what your other options would be in this case though.</p>\n\n<p>Edit: After a little looking around I think you could do everything you needed to with the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process_members.aspx\" rel=\"nofollow noreferrer\">System.Diagnostics.Process</a> class. You would have a lot of options at this point for communication but <a href=\"http://msdn.microsoft.com/en-us/library/kwdt6w2k(VS.71).aspx\" rel=\"nofollow noreferrer\">.NET Remoting</a> or WCF would probably be good and easy choices.</p>\n"
},
{
"answer_id": 157738,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 0,
"selected": false,
"text": "<p>These are the best two articles I found on the subject</p>\n\n<ul>\n<li><a href=\"http://blogs.msdn.com/cbrumme/archive/2003/04/15/51317.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/cbrumme/archive/2003/04/15/51317.aspx</a></li>\n<li><a href=\"http://blogs.msdn.com/cbrumme/archive/2003/06/01/51466.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/cbrumme/archive/2003/06/01/51466.aspx</a></li>\n</ul>\n\n<p>The important part is:</p>\n\n<blockquote>\n <p>RVA-based static fields are process-global. These are restricted to scalars and value types, because we do not want to allow objects to bleed across AppDomain boundaries. That would cause all sorts of problems, especially during AppDomain unloads. Some languages like ILASM and MC++ make it convenient to define RVA-based static fields. Most languages do not.</p>\n</blockquote>\n\n<p>Ok, so if you control the code in the .lib, I'd try</p>\n\n<pre><code>class CallCountHolder {\n public:\n CallCountHolder(int i) : count(i) {}\n int count;\n};\n\nstatic CallCountHolder cc(0);\nint TheFunction()\n{\n printf(\"Function called\");\n return cc.count++;\n}\n</code></pre>\n\n<p>Since he said that RVA-based static fields are limited to scalars and value types. An int array might also work.</p>\n"
},
{
"answer_id": 693295,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>After you call </p>\n\n<pre><code>Managed c1 = new Managed(); \n</code></pre>\n\n<p>Your managed.dll wrapper will be loaded into main app domain of you application. Till it will be there domain unmanaged stuff from static.lib will be shared with other domains. \nInstead of creating separate process you just need to be sure (before each call) that managed.dll is not loaded into any application domain. </p>\n\n<p>Compare with that </p>\n\n<pre><code>static void Main(string[] args)\n{\n\n { \n AppDomain ad = AppDomain.CreateDomain(\"NewDomain\");\n Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;\n int val2 = c.CallLibFunc();\n // Value is zero\n\n AppDomain.Unload(ad)\n }\n { \n AppDomain ad = AppDomain.CreateDomain(\"NewDomain\");\n Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;\n int val2 = c.CallLibFunc();\n // I think value is zero\n\n AppDomain.Unload(ad)\n }\n\n\n}\n`\n</code></pre>\n\n<p>IMPORTANT and : If you add just one line JIT compiler will load managed.dll and the magic disappears. </p>\n\n<pre><code>static void Main(string[] args)\n{\n\n { \n AppDomain ad = AppDomain.CreateDomain(\"NewDomain\");\n Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;\n int val2 = c.CallLibFunc();\n // Value is zero \n\n AppDomain.Unload(ad)\n }\n { \n AppDomain ad = AppDomain.CreateDomain(\"NewDomain\");\n Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;\n int val2 = c.CallLibFunc();\n // I think value is one\n\n AppDomain.Unload(ad)\n }\nManaged c1 = new Managed(); \n\n\n}\n</code></pre>\n\n<p>If you don't want to depend on such lines you can create another one wrapper ManagedIsolated.dll that will reference managed.dll and will make each call in separate domain with domain unload just after the call. Main application will depend only on ManagedIsolated.dll types and Managed.dll will not be loaded into main app domain.</p>\n\n<p>That looks like a trick but may be it will be usefull for somebody.\n `</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2341/"
]
| Problem (simplified to make things clearer):
1. there is one statically-linked static.lib that has a function that increments:
```
extern int CallCount = 0;
int TheFunction()
{
void *p = &CallCount
printf("Function called");
return CallCount++;
}
```
2. static.lib is linked into a managed C++/CLI managed.dll that wraps TheFunction method:
```
int Managed::CallLibFunc()
{
return TheFunction();
}
```
3. Test app has a reference to managed.dll and creates multiple domains that call C++/CLI wrapper:
```
static void Main(string[] args)
{
Managed c1 = new Managed();
int val1 = c1.CallLibFunc();
// value is zero
AppDomain ad = AppDomain.CreateDomain("NewDomain");
Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;
int val2 = c.CallLibFunc();
// value is one
}
```
Question:
Based on what I have read in Essential .NET Vol1 The CLR by Don Box, I would expect val2 to be zero since a brand new copy of managed.dll/static.lib is loaded when CreateInstanceAndUnwrap is called. Am I misunderstanding what is happening? The static library does not seem to be respecting the appdomain boundaries since it's unmanaged code. Is there a way to get around this issue other than by creating a brand new process for instantiating Managed?
Thank you very much everyone! | My hunch was that, as you suspected, unmanaged DLLs are loaded in the context of the process and not in the context of the AppDomain, so any static data in unmanaged code is shared among AppDomains.
[This link](http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/98cbabe0-33d6-4775-a3a7-04e71b7498dd/) shows someone with the same problem you have, still not 100% verification of this, but probably this is the case.
[This link](http://lambert.geek.nz/2007/05/29/unmanaged-appdomain-callback/) is about creating a callback from unmanaged code into an AppDomain using a thunking trick. I'm not sure this can help you but maybe you'll find this useful to create some kind of a workaround. |
72,789 | <p>I'd like to use a different icon for the demo version of my game, and I'm building the demo with a different build config than I do for the full verison, using a preprocessor define to lockout some content, use different graphics, etc. Is there a way that I can make Visual Studio use a different icon for the app Icon in the demo config but continue to use the regular icon for the full version's config?</p>
| [
{
"answer_id": 72848,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 0,
"selected": false,
"text": "<p>This will get you halfway there: <a href=\"http://www.codeproject.com/KB/dotnet/embedmultipleiconsdotnet.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/dotnet/embedmultipleiconsdotnet.aspx</a></p>\n\n<p>Then you need to find the Win32 call which will set the displayed icon from the list of embedded icons.</p>\n"
},
{
"answer_id": 72857,
"author": "Thomas",
"author_id": 4980,
"author_profile": "https://Stackoverflow.com/users/4980",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know a way in visual studio, because the application settings are bound to the hole project. But a simple way is to use a PreBuild event and copy the app.demo.ico to app.ico or the app.release.ico to app.ico demanding on the value of the key $(ConfigurationName) and refer to the app.ico in your project directory.</p>\n"
},
{
"answer_id": 72877,
"author": "Serge",
"author_id": 1007,
"author_profile": "https://Stackoverflow.com/users/1007",
"pm_score": 4,
"selected": true,
"text": "<p>According to <a href=\"http://msdn.microsoft.com/en-us/library/aa381033(VS.85).aspx\" rel=\"noreferrer\">this page</a> you may use preprocessor directives in your *.rc file. You should write something like this</p>\n\n<pre><code>#ifdef _DEMO_VERSION_\nIDR_MAINFRAME ICON \"demo.ico\"\n#else\nIDR_MAINFRAME ICON \"full.ico\"\n#endif\n</code></pre>\n"
},
{
"answer_id": 72880,
"author": "Kevin",
"author_id": 6386,
"author_profile": "https://Stackoverflow.com/users/6386",
"pm_score": 2,
"selected": false,
"text": "<p>What I would do is setup a pre-build event (Project properties -> Configuration Properties -> Build Events -> Pre-Build Event). The pre-build event is a command line. I would use this to copy the appropriate icon file to the build icon. </p>\n\n<p>For example, let's say your build icon is 'app.ico'. I would make my fullicon 'app_full.ico' and my demo icon 'app_demo.ico'. Then I would set my pre-build events as follows:</p>\n\n<p>Full mode pre-build event:</p>\n\n<pre><code>del app.ico | copy app_full.ico app.ico\n</code></pre>\n\n<p>Demo mode pre-build event:</p>\n\n<pre><code>del app.ico | copy app_demo.ico app.ico\n</code></pre>\n\n<p>I hope that helps!</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12117/"
]
| I'd like to use a different icon for the demo version of my game, and I'm building the demo with a different build config than I do for the full verison, using a preprocessor define to lockout some content, use different graphics, etc. Is there a way that I can make Visual Studio use a different icon for the app Icon in the demo config but continue to use the regular icon for the full version's config? | According to [this page](http://msdn.microsoft.com/en-us/library/aa381033(VS.85).aspx) you may use preprocessor directives in your \*.rc file. You should write something like this
```
#ifdef _DEMO_VERSION_
IDR_MAINFRAME ICON "demo.ico"
#else
IDR_MAINFRAME ICON "full.ico"
#endif
``` |
72,831 | <p>Is there an easy way to capitalize the first letter of a string and lower the rest of it? Is there a built in method or do I need to make my own?</p>
| [
{
"answer_id": 72862,
"author": "ageektrapped",
"author_id": 631,
"author_profile": "https://Stackoverflow.com/users/631",
"pm_score": 9,
"selected": true,
"text": "<p><code>TextInfo.ToTitleCase()</code> capitalizes the first character in each token of a string.<br />\nIf there is no need to maintain Acronym Uppercasing, then you should include <code>ToLower()</code>.</p>\n\n<pre><code>string s = \"JOHN DOE\";\ns = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());\n// Produces \"John Doe\"\n</code></pre>\n\n<p>If CurrentCulture is unavailable, use:</p>\n\n<pre><code>string s = \"JOHN DOE\";\ns = new System.Globalization.CultureInfo(\"en-US\", false).TextInfo.ToTitleCase(s.ToLower());\n</code></pre>\n\n<p>See the <a href=\"http://msdn2.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx\" rel=\"noreferrer\">MSDN Link</a> for a detailed description.</p>\n"
},
{
"answer_id": 72864,
"author": "ckal",
"author_id": 10276,
"author_profile": "https://Stackoverflow.com/users/10276",
"pm_score": 3,
"selected": false,
"text": "<p>ToTitleCase() should work for you.</p>\n\n<p><a href=\"http://support.microsoft.com/kb/312890\" rel=\"noreferrer\">http://support.microsoft.com/kb/312890</a></p>\n"
},
{
"answer_id": 72871,
"author": "Nathan Baulch",
"author_id": 8799,
"author_profile": "https://Stackoverflow.com/users/8799",
"pm_score": 7,
"selected": false,
"text": "<pre><code>CultureInfo.CurrentCulture.TextInfo.ToTitleCase(\"hello world\");\n</code></pre>\n"
},
{
"answer_id": 72888,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 2,
"selected": false,
"text": "<p>The most direct option is going to be to use the <a href=\"http://support.microsoft.com/kb/312890\" rel=\"nofollow noreferrer\">ToTitleCase</a> function that is available in .NET which should take care of the name most of the time. As <a href=\"https://stackoverflow.com/questions/72831/how-do-i-capitalize-first-letter-of-first-name-and-last-name-in-c#72850\">edg</a> pointed out there are some names that it will not work for, but these are fairly rare so unless you are targeting a culture where such names are common it is not necessary something that you have to worry too much about.</p>\n\n<p>However if you are not working with a .NET langauge, then it depends on what the input looks like - if you have two separate fields for the first name and the last name then you can just capitalize the first letter lower the rest of it using substrings.</p>\n\n<pre><code>firstName = firstName.Substring(0, 1).ToUpper() + firstName.Substring(1).ToLower();\nlastName = lastName.Substring(0, 1).ToUpper() + lastName.Substring(1).ToLower();\n</code></pre>\n\n<p>However, if you are provided multiple names as part of the same string then you need to know how you are getting the information and <a href=\"http://msdn.microsoft.com/en-us/library/ms228388(VS.80).aspx\" rel=\"nofollow noreferrer\">split it</a> accordingly. So if you are getting a name like \"John Doe\" you an split the string based upon the space character. If it is in a format such as \"Doe, John\" you are going to need to split it based upon the comma. However, once you have it split apart you just apply the code shown previously.</p>\n"
},
{
"answer_id": 72901,
"author": "David C",
"author_id": 12385,
"author_profile": "https://Stackoverflow.com/users/12385",
"pm_score": 2,
"selected": false,
"text": "<p>CultureInfo.CurrentCulture.TextInfo.ToTitleCase (\"my name\");</p>\n\n<p>returns ~ My Name</p>\n\n<p>But the problem still exists with names like McFly as stated earlier.</p>\n"
},
{
"answer_id": 72910,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>If your using vS2k8, you can use an extension method to add it to the String class:</p>\n\n<pre><code>public static string FirstLetterToUpper(this String input)\n{\n return input = input.Substring(0, 1).ToUpper() + \n input.Substring(1, input.Length - 1);\n}\n</code></pre>\n"
},
{
"answer_id": 72939,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": -1,
"selected": false,
"text": "<p>Like edg indicated, you'll need a more complex algorithm to handle special names (this is probably why many places force everything to upper case).</p>\n\n<p>Something like this untested c# should handle the simple case you requested:</p>\n\n<pre><code>public string SentenceCase(string input)\n{\n return input(0, 1).ToUpper + input.Substring(1).ToLower;\n}\n</code></pre>\n"
},
{
"answer_id": 73688,
"author": "Tundey",
"author_id": 1453,
"author_profile": "https://Stackoverflow.com/users/1453",
"pm_score": 2,
"selected": false,
"text": "<p>The suggestions to use ToTitleCase won't work for strings that are all upper case. So you are gonna have to call ToUpper on the first char and ToLower on the remaining characters.</p>\n"
},
{
"answer_id": 73691,
"author": "Jamie Ide",
"author_id": 12752,
"author_profile": "https://Stackoverflow.com/users/12752",
"pm_score": 3,
"selected": false,
"text": "<p>Mc and Mac are common surname prefixes throughout the US, and there are others. TextInfo.ToTitleCase doesn't handle those cases and shouldn't be used for this purpose. Here's how I'm doing it:</p>\n\n<pre><code> public static string ToTitleCase(string str)\n {\n string result = str;\n if (!string.IsNullOrEmpty(str))\n {\n var words = str.Split(' ');\n for (int index = 0; index < words.Length; index++)\n {\n var s = words[index];\n if (s.Length > 0)\n {\n words[index] = s[0].ToString().ToUpper() + s.Substring(1);\n }\n }\n result = string.Join(\" \", words);\n }\n return result;\n }\n</code></pre>\n"
},
{
"answer_id": 74008,
"author": "Eddie Velasquez",
"author_id": 12851,
"author_profile": "https://Stackoverflow.com/users/12851",
"pm_score": 2,
"selected": false,
"text": "<p>This class does the trick. You can add new prefixes to the <strong>_prefixes</strong> static string array. </p>\n\n<pre><code>public static class StringExtensions\n{\n public static string ToProperCase( this string original )\n {\n if( String.IsNullOrEmpty( original ) )\n return original;\n\n string result = _properNameRx.Replace( original.ToLower( CultureInfo.CurrentCulture ), HandleWord );\n return result;\n }\n\n public static string WordToProperCase( this string word )\n {\n if( String.IsNullOrEmpty( word ) )\n return word;\n\n if( word.Length > 1 )\n return Char.ToUpper( word[0], CultureInfo.CurrentCulture ) + word.Substring( 1 );\n\n return word.ToUpper( CultureInfo.CurrentCulture );\n }\n\n private static readonly Regex _properNameRx = new Regex( @\"\\b(\\w+)\\b\" );\n private static readonly string[] _prefixes = {\n \"mc\"\n };\n\n private static string HandleWord( Match m )\n {\n string word = m.Groups[1].Value;\n\n foreach( string prefix in _prefixes )\n {\n if( word.StartsWith( prefix, StringComparison.CurrentCultureIgnoreCase ) )\n return prefix.WordToProperCase() + word.Substring( prefix.Length ).WordToProperCase();\n }\n\n return word.WordToProperCase();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 74023,
"author": "Andy Rose",
"author_id": 1762,
"author_profile": "https://Stackoverflow.com/users/1762",
"pm_score": 0,
"selected": false,
"text": "<p>To get round some of the issues/problems that have ben highlighted I would suggest converting the string to lower case first and then call the ToTitleCase method. You could then use IndexOf(\" Mc\") or IndexOf(\" O\\'\") to determine special cases that need more specific attention.</p>\n\n<pre><code>inputString = inputString.ToLower();\ninputString = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(inputString);\nint indexOfMc = inputString.IndexOf(\" Mc\");\nif(indexOfMc > 0)\n{\n inputString.Substring(0, indexOfMc + 3) + inputString[indexOfMc + 3].ToString().ToUpper() + inputString.Substring(indexOfMc + 4);\n}\n</code></pre>\n"
},
{
"answer_id": 3169381,
"author": "Ganesan SubbiahPandian",
"author_id": 382422,
"author_profile": "https://Stackoverflow.com/users/382422",
"pm_score": 5,
"selected": false,
"text": "<pre><code>String test = \"HELLO HOW ARE YOU\";\nstring s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test);\n</code></pre>\n\n<p>The above code wont work .....</p>\n\n<p>so put the below code by convert to lower then apply the function</p>\n\n<pre><code>String test = \"HELLO HOW ARE YOU\";\nstring s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test.ToLower());\n</code></pre>\n"
},
{
"answer_id": 4759134,
"author": "Ton Snoei",
"author_id": 584472,
"author_profile": "https://Stackoverflow.com/users/584472",
"pm_score": 2,
"selected": false,
"text": "<p>I use my own method to get this fixed:</p>\n\n<p>For example the phrase: \"hello world. hello this is the stackoverflow world.\" will be \"Hello World. Hello This Is The Stackoverflow World.\". Regex \\b (start of a word) \\w (first charactor of the word) will do the trick. </p>\n\n<pre><code>/// <summary>\n/// Makes each first letter of a word uppercase. The rest will be lowercase\n/// </summary>\n/// <param name=\"Phrase\"></param>\n/// <returns></returns>\npublic static string FormatWordsWithFirstCapital(string Phrase)\n{\n MatchCollection Matches = Regex.Matches(Phrase, \"\\\\b\\\\w\");\n Phrase = Phrase.ToLower();\n foreach (Match Match in Matches)\n Phrase = Phrase.Remove(Match.Index, 1).Insert(Match.Index, Match.Value.ToUpper());\n\n return Phrase;\n}\n</code></pre>\n"
},
{
"answer_id": 12413336,
"author": "TrentVB",
"author_id": 1118056,
"author_profile": "https://Stackoverflow.com/users/1118056",
"pm_score": 0,
"selected": false,
"text": "<p>I like this way:</p>\n\n<pre><code>using System.Globalization;\n...\nTextInfo myTi = new CultureInfo(\"en-Us\",false).TextInfo;\nstring raw = \"THIS IS ALL CAPS\";\nstring firstCapOnly = myTi.ToTitleCase(raw.ToLower());\n</code></pre>\n\n<p>Lifted from this <a href=\"http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase%28v=vs.100%29.aspx\" rel=\"nofollow\">MSDN article</a>.</p>\n"
},
{
"answer_id": 14121370,
"author": "Arun",
"author_id": 1063254,
"author_profile": "https://Stackoverflow.com/users/1063254",
"pm_score": 0,
"selected": false,
"text": "<p>Hope this helps you.</p>\n\n<pre><code>String fName = \"firstname\";\nString lName = \"lastname\";\nString capitalizedFName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(fName);\nString capitalizedLName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(lName);\n</code></pre>\n"
},
{
"answer_id": 19517670,
"author": "polkduran",
"author_id": 848634,
"author_profile": "https://Stackoverflow.com/users/848634",
"pm_score": 4,
"selected": false,
"text": "<p>There are some cases that <code>CultureInfo.CurrentCulture.TextInfo.ToTitleCase</code> cannot handle, for example : the apostrophe <code>'</code>.</p>\n\n<pre><code>string input = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(\"o'reilly, m'grego, d'angelo\");\n// input = O'reilly, M'grego, D'angelo\n</code></pre>\n\n<p>A <strong>regex</strong> can also be used <code>\\b[a-zA-Z]</code> to identify the starting character of a word after a word boundary <code>\\b</code>, then we need just to replace the match by its upper case equivalence thanks to the <a href=\"http://msdn.microsoft.com/fr-fr/library/vstudio/ht1sxswy%28v=vs.110%29.aspx\"><code>Regex.Replace(string input,string pattern,MatchEvaluator evaluator)</code></a> method : </p>\n\n<pre><code>string input = \"o'reilly, m'grego, d'angelo\";\ninput = Regex.Replace(input.ToLower(), @\"\\b[a-zA-Z]\", m => m.Value.ToUpper());\n// input = O'Reilly, M'Grego, D'Angelo\n</code></pre>\n\n<p>The <strong>regex</strong> can be tuned if needed, for instance, if we want to handle the <code>MacDonald</code> and <code>McFry</code> cases the regex becomes : <code>(?<=\\b(?:mc|mac)?)[a-zA-Z]</code></p>\n\n<pre><code>string input = \"o'reilly, m'grego, d'angelo, macdonald's, mcfry\";\ninput = Regex.Replace(input.ToLower(), @\"(?<=\\b(?:mc|mac)?)[a-zA-Z]\", m => m.Value.ToUpper());\n// input = O'Reilly, M'Grego, D'Angelo, MacDonald'S, McFry\n</code></pre>\n\n<p>If we need to handle more prefixes we only need to modify the group <code>(?:mc|mac)</code>, for example to add french prefixes <code>du, de</code> : <code>(?:mc|mac|du|de)</code>.</p>\n\n<p>Finally, we can realize that this <strong>regex</strong> will also match the case <code>MacDonald'S</code> for the last <code>'s</code> so we need to handle it in the <strong>regex</strong> with a negative look behind <code>(?<!'s\\b)</code>. At the end we have :</p>\n\n<pre><code>string input = \"o'reilly, m'grego, d'angelo, macdonald's, mcfry\";\ninput = Regex.Replace(input.ToLower(), @\"(?<=\\b(?:mc|mac)?)[a-zA-Z](?<!'s\\b)\", m => m.Value.ToUpper());\n// input = O'Reilly, M'Grego, D'Angelo, MacDonald's, McFry\n</code></pre>\n"
},
{
"answer_id": 40882007,
"author": "Govind Singh Rawat",
"author_id": 5580191,
"author_profile": "https://Stackoverflow.com/users/5580191",
"pm_score": 0,
"selected": false,
"text": "<pre><code> public static string ConvertToCaptilize(string input)\n {\n if (!string.IsNullOrEmpty(input))\n {\n string[] arrUserInput = input.Split(' ');\n\n\n // Initialize a string builder object for the output\n StringBuilder sbOutPut = new StringBuilder();\n\n\n // Loop thru each character in the string array\n foreach (string str in arrUserInput)\n {\n if (!string.IsNullOrEmpty(str))\n {\n var charArray = str.ToCharArray();\n int k = 0;\n foreach (var cr in charArray)\n {\n char c;\n c = k == 0 ? char.ToUpper(cr) : char.ToLower(cr);\n sbOutPut.Append(c);\n k++;\n }\n\n\n }\n sbOutPut.Append(\" \");\n }\n return sbOutPut.ToString();\n }\n return string.Empty;\n\n }\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9938/"
]
| Is there an easy way to capitalize the first letter of a string and lower the rest of it? Is there a built in method or do I need to make my own? | `TextInfo.ToTitleCase()` capitalizes the first character in each token of a string.
If there is no need to maintain Acronym Uppercasing, then you should include `ToLower()`.
```
string s = "JOHN DOE";
s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
// Produces "John Doe"
```
If CurrentCulture is unavailable, use:
```
string s = "JOHN DOE";
s = new System.Globalization.CultureInfo("en-US", false).TextInfo.ToTitleCase(s.ToLower());
```
See the [MSDN Link](http://msdn2.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx) for a detailed description. |
72,832 | <p>When you use Visual Studio's code analysic (FxCop), and want to suppress a message there are 3 options.</p>
<ol>
<li>Suppress a violation in code.</li>
<li>Suppress a violation in a GlobalSupression.cs file.</li>
<li>Disable the violation check in the project file (via Project -> Properties -> Code Analysic).</li>
</ol>
<p>The later is very hard to review when checking in to Source Control, and it is hard to get an overview of all disabled violations. So we would like to use option 2.</p>
<p>The problem with option 1 and 2 is that you get one suppression line for each violation. E.g like: </p>
<pre><code>[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Company.Project.Namespace2")]
[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Company.Project.Namespace1")]
</code></pre>
<p>We would love to do something like this ing GlobalSuppressions.cs:</p>
<pre><code>[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes")]
</code></pre>
<p>But is this possible?</p>
| [
{
"answer_id": 73369,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 4,
"selected": true,
"text": "<p>Suppressing multiple violations with a single <strong>SuppressMessage</strong> attribute is officially not supported. Apparently, this is by design.</p>\n\n<p>I agree, it might be annoying at times, but I can't say I disagree with the decision, since the attribute is their way to force you to say, \"Yes, I know what I am doing\", which should be evaluated in a case-by-case basis.</p>\n"
},
{
"answer_id": 18930943,
"author": "RenniePet",
"author_id": 253938,
"author_profile": "https://Stackoverflow.com/users/253938",
"pm_score": 1,
"selected": false,
"text": "<p>I think things have changed since this question was posted and answered. For Visual Studio 2010 and 2012 you can create a custom \"rule set\" file where you can specify which code analysis rules you want to suppress. </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/dd380660.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/dd380660.aspx</a></p>\n\n<p>So what I've done is to create a single custom rule set file which is in the top level folder of my repository source collection, and I reference this file in each Visual Studio project. This means I have one central place where I can suppress the code analysis rules that I simply can't stand. But if I ever change my mind, or decide I should reconsider my bad coding habits, I can very simply reenable the rule and see how many code analysis messages I get. </p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8547/"
]
| When you use Visual Studio's code analysic (FxCop), and want to suppress a message there are 3 options.
1. Suppress a violation in code.
2. Suppress a violation in a GlobalSupression.cs file.
3. Disable the violation check in the project file (via Project -> Properties -> Code Analysic).
The later is very hard to review when checking in to Source Control, and it is hard to get an overview of all disabled violations. So we would like to use option 2.
The problem with option 1 and 2 is that you get one suppression line for each violation. E.g like:
```
[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Company.Project.Namespace2")]
[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Company.Project.Namespace1")]
```
We would love to do something like this ing GlobalSuppressions.cs:
```
[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes")]
```
But is this possible? | Suppressing multiple violations with a single **SuppressMessage** attribute is officially not supported. Apparently, this is by design.
I agree, it might be annoying at times, but I can't say I disagree with the decision, since the attribute is their way to force you to say, "Yes, I know what I am doing", which should be evaluated in a case-by-case basis. |
72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/" rel="noreferrer">PEP 366</a> (thanks John B)</p>
| [
{
"answer_id": 73149,
"author": "John B",
"author_id": 9597,
"author_profile": "https://Stackoverflow.com/users/9597",
"pm_score": 10,
"selected": true,
"text": "<p>Everyone seems to want to tell you what you should be doing rather than just answering the question.</p>\n\n<p>The problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter.</p>\n\n<p>From <a href=\"http://www.python.org/dev/peps/pep-0328/\" rel=\"noreferrer\">PEP 328</a>:</p>\n\n<blockquote>\n <p>Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.</p>\n</blockquote>\n\n<p>In Python 2.6, they're adding the ability to reference modules relative to the main module. <a href=\"http://python.org/dev/peps/pep-0366/\" rel=\"noreferrer\">PEP 366</a> describes the change.</p>\n\n<p><strong>Update</strong>: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.</p>\n"
},
{
"answer_id": 465129,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 7,
"selected": false,
"text": "<pre><code>main.py\nsetup.py\napp/ ->\n __init__.py\n package_a/ ->\n __init__.py\n module_a.py\n package_b/ ->\n __init__.py\n module_b.py\n</code></pre>\n\n<ol>\n<li>You run <code>python main.py</code>.</li>\n<li><code>main.py</code> does: <code>import app.package_a.module_a</code></li>\n<li><code>module_a.py</code> does <code>import app.package_b.module_b</code></li>\n</ol>\n\n<p>Alternatively 2 or 3 could use: <code>from app.package_a import module_a</code></p>\n\n<p>That will work as long as you have <code>app</code> in your PYTHONPATH. <code>main.py</code> could be anywhere then.</p>\n\n<p>So you write a <code>setup.py</code> to copy (install) the whole app package and subpackages to the target system's python folders, and <code>main.py</code> to target system's script folders.</p>\n"
},
{
"answer_id": 1083169,
"author": "iElectric",
"author_id": 133235,
"author_profile": "https://Stackoverflow.com/users/133235",
"pm_score": 5,
"selected": false,
"text": "<pre><code>def import_path(fullpath):\n \"\"\" \n Import a file with full path specification. Allows one to\n import from anywhere, something __import__ does not do. \n \"\"\"\n path, filename = os.path.split(fullpath)\n filename, ext = os.path.splitext(filename)\n sys.path.append(path)\n module = __import__(filename)\n reload(module) # Might be out of date\n del sys.path[-1]\n return module\n</code></pre>\n\n<p>I'm using this snippet to import modules from paths, hope that helps</p>\n"
},
{
"answer_id": 6524846,
"author": "jung rhew",
"author_id": 821632,
"author_profile": "https://Stackoverflow.com/users/821632",
"pm_score": 2,
"selected": false,
"text": "<p>From <a href=\"http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports\" rel=\"nofollow\">Python doc</a>,</p>\n\n<blockquote>\n <p>In Python 2.5, you can switch import‘s behaviour to absolute imports using a <code>from __future__ import absolute_import</code> directive. This absolute- import behaviour will become the default in a future version (probably Python 2.7). Once absolute imports are the default, <code>import string</code> will always find the standard library’s version. It’s suggested that users should begin using absolute imports as much as possible, so it’s preferable to begin writing <code>from pkg import string</code> in your code</p>\n</blockquote>\n"
},
{
"answer_id": 7541369,
"author": "mossplix",
"author_id": 487623,
"author_profile": "https://Stackoverflow.com/users/487623",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at <a href=\"http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports\" rel=\"noreferrer\">http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports</a>. You could do </p>\n\n<pre><code>from .mod1 import stuff\n</code></pre>\n"
},
{
"answer_id": 8195271,
"author": "lesnik",
"author_id": 788775,
"author_profile": "https://Stackoverflow.com/users/788775",
"pm_score": 6,
"selected": false,
"text": "<p>\"Guido views running scripts within a package as an anti-pattern\" (rejected\n<a href=\"http://www.python.org/dev/peps/pep-3122/\">PEP-3122</a>)</p>\n\n<p>I have spent so much time trying to find a solution, reading related posts here on Stack Overflow and saying to myself \"there must be a better way!\". Looks like there is not.</p>\n"
},
{
"answer_id": 9541554,
"author": "Garrett Berg",
"author_id": 674076,
"author_profile": "https://Stackoverflow.com/users/674076",
"pm_score": 4,
"selected": false,
"text": "<p>This is unfortunately a sys.path hack, but it works quite well.</p>\n\n<p>I encountered this problem with another layer: I already had a module of the specified name, but it was the wrong module.</p>\n\n<p>what I wanted to do was the following (the module I was working from was module3):</p>\n\n<pre><code>mymodule\\\n __init__.py\n mymodule1\\\n __init__.py\n mymodule1_1\n mymodule2\\\n __init__.py\n mymodule2_1\n\n\nimport mymodule.mymodule1.mymodule1_1 \n</code></pre>\n\n<p>Note that I have already installed mymodule, but in my installation I do not have \"mymodule1\"</p>\n\n<p>and I would get an ImportError because it was trying to import from my installed modules.</p>\n\n<p>I tried to do a sys.path.append, and that didn't work. What did work was a <strong>sys.path.insert</strong></p>\n\n<pre><code>if __name__ == '__main__':\n sys.path.insert(0, '../..')\n</code></pre>\n\n<p>So kind of a hack, but got it all to work!\nSo keep in mind, if you want your decision to <strong>override other paths</strong> then you need to use sys.path.insert(0, pathname) to get it to work! This was a very frustrating sticking point for me, allot of people say to use the \"append\" function to sys.path, but that doesn't work if you already have a module defined (I find it very strange behavior)</p>\n"
},
{
"answer_id": 9748770,
"author": "Andrew_1510",
"author_id": 451718,
"author_profile": "https://Stackoverflow.com/users/451718",
"pm_score": 1,
"selected": false,
"text": "<p>I found it's more easy to set \"PYTHONPATH\" enviroment variable to the top folder:</p>\n\n<pre><code>bash$ export PYTHONPATH=/PATH/TO/APP\n</code></pre>\n\n<p>then:</p>\n\n<pre><code>import sub1.func1\n#...more import\n</code></pre>\n\n<p>of course, PYTHONPATH is \"global\", but it didn't raise trouble for me yet.</p>\n"
},
{
"answer_id": 12365065,
"author": "Gabriel",
"author_id": 1621769,
"author_profile": "https://Stackoverflow.com/users/1621769",
"pm_score": 1,
"selected": false,
"text": "<p>On top of what John B said, it seems like setting the <code>__package__</code> variable should help, instead of changing <code>__main__</code> which could screw up other things. But as far as I could test, it doesn't completely work as it should.</p>\n\n<p>I have the same problem and neither PEP 328 or 366 solve the problem completely, as both, by the end of the day, need the head of the package to be included in <code>sys.path</code>, as far as I could understand.</p>\n\n<p>I should also mention that I did not find how to format the string that should go into those variables. Is it <code>\"package_head.subfolder.module_name\"</code> or what? </p>\n"
},
{
"answer_id": 14189875,
"author": "milkypostman",
"author_id": 154508,
"author_profile": "https://Stackoverflow.com/users/154508",
"pm_score": 4,
"selected": false,
"text": "<p>Let me just put this here for my own reference. I know that it is not good Python code, but I needed a script for a project I was working on and I wanted to put the script in a <code>scripts</code> directory.</p>\n\n<pre><code>import os.path\nimport sys\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\")))\n</code></pre>\n"
},
{
"answer_id": 15458607,
"author": "Pankaj",
"author_id": 382630,
"author_profile": "https://Stackoverflow.com/users/382630",
"pm_score": 7,
"selected": false,
"text": "<p>Here is the solution which works for me:</p>\n\n<p>I do the relative imports as <code>from ..sub2 import mod2</code>\nand then, if I want to run <code>mod1.py</code> then I go to the parent directory of <code>app</code> and run the module using the python -m switch as <code>python -m app.sub1.mod1</code>.</p>\n\n<p>The real reason why this problem occurs with relative imports, is that relative imports works by taking the <code>__name__</code> property of the module. If the module is being directly run, then <code>__name__</code> is set to <code>__main__</code> and it doesn't contain any information about package structure. And, thats why python complains about the <code>relative import in non-package</code> error. </p>\n\n<p>So, by using the -m switch you provide the package structure information to python, through which it can resolve the relative imports successfully.</p>\n\n<p>I have encountered this problem many times while doing relative imports. And, after reading all the previous answers, I was still not able to figure out how to solve it, in a clean way, without needing to put boilerplate code in all files. (Though some of the comments were really helpful, thanks to @ncoghlan and @XiongChiamiov)</p>\n\n<p>Hope this helps someone who is fighting with relative imports problem, because going through PEP is really not fun.</p>\n"
},
{
"answer_id": 20449492,
"author": "suhailvs",
"author_id": 2351696,
"author_profile": "https://Stackoverflow.com/users/2351696",
"pm_score": 5,
"selected": false,
"text": "<p>explanation of <code>nosklo's</code> answer with examples</p>\n\n<p><em>note: all <code>__init__.py</code> files are empty.</em></p>\n\n<pre><code>main.py\napp/ ->\n __init__.py\n package_a/ ->\n __init__.py\n fun_a.py\n package_b/ ->\n __init__.py\n fun_b.py\n</code></pre>\n\n<h3>app/package_a/fun_a.py</h3>\n\n<pre><code>def print_a():\n print 'This is a function in dir package_a'\n</code></pre>\n\n<h3>app/package_b/fun_b.py</h3>\n\n<pre><code>from app.package_a.fun_a import print_a\ndef print_b():\n print 'This is a function in dir package_b'\n print 'going to call a function in dir package_a'\n print '-'*30\n print_a()\n</code></pre>\n\n<h3>main.py</h3>\n\n<pre><code>from app.package_b import fun_b\nfun_b.print_b()\n</code></pre>\n\n<p>if you run <code>$ python main.py</code> it returns:</p>\n\n<pre><code>This is a function in dir package_b\ngoing to call a function in dir package_a\n------------------------------\nThis is a function in dir package_a\n</code></pre>\n\n<ul>\n<li>main.py does: <code>from app.package_b import fun_b</code> </li>\n<li>fun_b.py does <code>from app.package_a.fun_a import print_a</code></li>\n</ul>\n\n<p>so file in folder <code>package_b</code> used file in folder <code>package_a</code>, which is what you want. Right??</p>\n"
},
{
"answer_id": 30736316,
"author": "LondonRob",
"author_id": 2071807,
"author_profile": "https://Stackoverflow.com/users/2071807",
"pm_score": 3,
"selected": false,
"text": "<p>As @EvgeniSergeev says in the comments to the OP, you can import code from a <code>.py</code> file at an arbitrary location with:</p>\n\n<pre><code>import imp\n\nfoo = imp.load_source('module.name', '/path/to/file.py')\nfoo.MyClass()\n</code></pre>\n\n<p>This is taken from <a href=\"https://stackoverflow.com/a/67692/2071807\">this SO answer</a>.</p>\n"
},
{
"answer_id": 35338828,
"author": "Роман Арсеньев",
"author_id": 5774201,
"author_profile": "https://Stackoverflow.com/users/5774201",
"pm_score": 6,
"selected": false,
"text": "<p>This is solved 100%:</p>\n\n<ul>\n<li>app/\n\n<ul>\n<li>main.py</li>\n</ul></li>\n<li>settings/\n\n<ul>\n<li>local_setings.py</li>\n</ul></li>\n</ul>\n\n<p>Import settings/local_setting.py in app/main.py:</p>\n\n<p>main.py:</p>\n\n<pre><code>import sys\nsys.path.insert(0, \"../settings\")\n\n\ntry:\n from local_settings import *\nexcept ImportError:\n print('No Import')\n</code></pre>\n"
},
{
"answer_id": 60846688,
"author": "Giorgos Myrianthous",
"author_id": 7131757,
"author_profile": "https://Stackoverflow.com/users/7131757",
"pm_score": 1,
"selected": false,
"text": "<p>You have to append the module’s path to <code>PYTHONPATH</code>: </p>\n\n<pre><code>export PYTHONPATH=\"${PYTHONPATH}:/path/to/your/module/\"\n</code></pre>\n"
},
{
"answer_id": 70163621,
"author": "Rohit Kumar J",
"author_id": 14376181,
"author_profile": "https://Stackoverflow.com/users/14376181",
"pm_score": 0,
"selected": false,
"text": "<p>This method queries and auto populates the path:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\nimport inspect\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nos.sys.path.insert(1, parentdir)\n# print("currentdir = ", currentdir)\n# print("parentdir=", parentdir)\n</code></pre>\n"
},
{
"answer_id": 71315540,
"author": "F.M.F.",
"author_id": 4858818,
"author_profile": "https://Stackoverflow.com/users/4858818",
"pm_score": 0,
"selected": false,
"text": "<p>A hacky way to do it is to append the current directory to the PATH at runtime as follows:</p>\n<pre><code>import pathlib \nimport sys\nsys.path.append(pathlib.Path(__file__).parent.resolve())\nimport file_to_import # the actual intended import\n</code></pre>\n<p>In contrast to another solution for this question this uses <code>pathlib</code> instead of <code>os.path</code>.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3497/"
]
| Imagine this directory structure:
```
app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
```
I'm coding `mod1`, and I need to import something from `mod2`. How should I do it?
I tried `from ..sub2 import mod2` but I'm getting an "Attempted relative import in non-package".
I googled around but found only "`sys.path` manipulation" hacks. Isn't there a clean way?
---
Edit: all my `__init__.py`'s are currently empty
Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (`sub1`, `subX`, etc.).
Edit3: The behaviour I'm looking for is the same as described in [PEP 366](http://www.python.org/dev/peps/pep-0366/) (thanks John B) | Everyone seems to want to tell you what you should be doing rather than just answering the question.
The problem is that you're running the module as '\_\_main\_\_' by passing the mod1.py as an argument to the interpreter.
From [PEP 328](http://www.python.org/dev/peps/pep-0328/):
>
> Relative imports use a module's \_\_name\_\_ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '\_\_main\_\_') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
>
>
>
In Python 2.6, they're adding the ability to reference modules relative to the main module. [PEP 366](http://python.org/dev/peps/pep-0366/) describes the change.
**Update**: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch. |
72,899 | <p>How do I sort a list of dictionaries by a specific key's value? Given:</p>
<pre><code>[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
</code></pre>
<p>When sorted by <code>name</code>, it should become:</p>
<pre><code>[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
</code></pre>
| [
{
"answer_id": 72950,
"author": "Matej",
"author_id": 11457,
"author_profile": "https://Stackoverflow.com/users/11457",
"pm_score": 5,
"selected": false,
"text": "<p>You have to implement your own comparison function that will compare the dictionaries by values of name keys. See <a href=\"http://wiki.python.org/moin/HowTo/Sorting\" rel=\"noreferrer\">Sorting Mini-HOW TO from PythonInfo Wiki</a></p>\n"
},
{
"answer_id": 73019,
"author": "Bartosz Radaczyński",
"author_id": 985,
"author_profile": "https://Stackoverflow.com/users/985",
"pm_score": 5,
"selected": false,
"text": "<p>I guess you've meant:</p>\n\n<pre><code>[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]\n</code></pre>\n\n<p>This would be sorted like this:</p>\n\n<pre><code>sorted(l,cmp=lambda x,y: cmp(x['name'],y['name']))\n</code></pre>\n"
},
{
"answer_id": 73044,
"author": "pjz",
"author_id": 8002,
"author_profile": "https://Stackoverflow.com/users/8002",
"pm_score": 7,
"selected": false,
"text": "<pre><code>my_list = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]\n\nmy_list.sort(lambda x,y : cmp(x['name'], y['name']))\n</code></pre>\n<p><code>my_list</code> will now be what you want.</p>\n<p>Or better:</p>\n<p>Since Python 2.4, there's a <code>key</code> argument is both more efficient and neater:</p>\n<pre><code>my_list = sorted(my_list, key=lambda k: k['name'])\n</code></pre>\n<p>...the lambda is, IMO, easier to understand than <code>operator.itemgetter</code>, but your mileage may vary.</p>\n"
},
{
"answer_id": 73050,
"author": "Mario F",
"author_id": 3785,
"author_profile": "https://Stackoverflow.com/users/3785",
"pm_score": 13,
"selected": true,
"text": "<p>The <a href=\"https://docs.python.org/library/functions.html#sorted\" rel=\"noreferrer\"><code>sorted()</code></a> function takes a <code>key=</code> parameter</p>\n<pre><code>newlist = sorted(list_to_be_sorted, key=lambda d: d['name']) \n</code></pre>\n<p>Alternatively, you can use <a href=\"https://docs.python.org/library/operator.html#operator.itemgetter\" rel=\"noreferrer\"><code>operator.itemgetter</code></a> instead of defining the function yourself</p>\n<pre><code>from operator import itemgetter\nnewlist = sorted(list_to_be_sorted, key=itemgetter('name')) \n</code></pre>\n<p>For completeness, add <code>reverse=True</code> to sort in descending order</p>\n<pre><code>newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)\n</code></pre>\n"
},
{
"answer_id": 73098,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 5,
"selected": false,
"text": "<pre><code>import operator\na_list_of_dicts.sort(key=operator.itemgetter('name'))\n</code></pre>\n\n<p>'key' is used to sort by an arbitrary value and 'itemgetter' sets that value to each item's 'name' attribute.</p>\n"
},
{
"answer_id": 73186,
"author": "Owen",
"author_id": 12592,
"author_profile": "https://Stackoverflow.com/users/12592",
"pm_score": 5,
"selected": false,
"text": "<p>You could use a custom comparison function, or you could pass in a function that calculates a custom sort key. That's usually more efficient as the key is only calculated once per item, while the comparison function would be called many more times.</p>\n\n<p>You could do it this way:</p>\n\n<pre><code>def mykey(adict): return adict['name']\nx = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age':10}]\nsorted(x, key=mykey)\n</code></pre>\n\n<p>But the standard library contains a generic routine for getting items of arbitrary objects: <code>itemgetter</code>. So try this instead:</p>\n\n<pre><code>from operator import itemgetter\nx = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age':10}]\nsorted(x, key=itemgetter('name'))\n</code></pre>\n"
},
{
"answer_id": 73465,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "<pre><code>import operator\n</code></pre>\n\n<p>To sort the list of dictionaries by key='name':</p>\n\n<pre><code>list_of_dicts.sort(key=operator.itemgetter('name'))\n</code></pre>\n\n<p>To sort the list of dictionaries by key='age':</p>\n\n<pre><code>list_of_dicts.sort(key=operator.itemgetter('age'))\n</code></pre>\n"
},
{
"answer_id": 2858683,
"author": "Dologan",
"author_id": 222135,
"author_profile": "https://Stackoverflow.com/users/222135",
"pm_score": 6,
"selected": false,
"text": "<p>If you want to sort the list by multiple keys, you can do the following:</p>\n<pre><code>my_list = [{'name':'Homer', 'age':39}, {'name':'Milhouse', 'age':10}, {'name':'Bart', 'age':10} ]\nsortedlist = sorted(my_list , key=lambda elem: "%02d %s" % (elem['age'], elem['name']))\n</code></pre>\n<p>It is rather hackish, since it relies on converting the values into a single string representation for comparison, but it works as expected for numbers including negative ones (although you will need to format your string appropriately with zero paddings if you are using numbers).</p>\n"
},
{
"answer_id": 16772049,
"author": "kiriloff",
"author_id": 1141493,
"author_profile": "https://Stackoverflow.com/users/1141493",
"pm_score": 5,
"selected": false,
"text": "<p>Using the <a href=\"https://en.wikipedia.org/wiki/Schwartzian_transform\" rel=\"noreferrer\">Schwartzian transform</a> from Perl,</p>\n<pre><code>py = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]\n</code></pre>\n<p>do</p>\n<pre><code>sort_on = "name"\ndecorated = [(dict_[sort_on], dict_) for dict_ in py]\ndecorated.sort()\nresult = [dict_ for (key, dict_) in decorated]\n</code></pre>\n<p>gives</p>\n<pre><code>>>> result\n[{'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]\n</code></pre>\n<p>More on the Perl Schwartzian transform:</p>\n<blockquote>\n<p>In computer science, the Schwartzian transform is a Perl programming\nidiom used to improve the efficiency of sorting a list of items. This\nidiom is appropriate for comparison-based sorting when the ordering is\nactually based on the ordering of a certain property (the key) of the\nelements, where computing that property is an intensive operation that\nshould be performed a minimal number of times. The Schwartzian\nTransform is notable in that it does not use named temporary arrays.</p>\n</blockquote>\n"
},
{
"answer_id": 23102554,
"author": "Shank_Transformer",
"author_id": 2819862,
"author_profile": "https://Stackoverflow.com/users/2819862",
"pm_score": 4,
"selected": false,
"text": "<p>Let's say I have a dictionary <code>D</code> with the elements below. To sort, just use the key argument in <code>sorted</code> to pass a custom function as below:</p>\n<pre><code>D = {'eggs': 3, 'ham': 1, 'spam': 2}\ndef get_count(tuple):\n return tuple[1]\n\nsorted(D.items(), key = get_count, reverse=True)\n# Or\nsorted(D.items(), key = lambda x: x[1], reverse=True) # Avoiding get_count function call\n</code></pre>\n<p>Check <a href=\"https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions\" rel=\"nofollow noreferrer\">this</a> out.</p>\n"
},
{
"answer_id": 28094888,
"author": "vvladymyrov",
"author_id": 1296661,
"author_profile": "https://Stackoverflow.com/users/1296661",
"pm_score": 4,
"selected": false,
"text": "<p>Here is the alternative general solution - it sorts elements of a dict by keys and values.</p>\n<p>The advantage of it - no need to specify keys, and it would still work if some keys are missing in some of dictionaries.</p>\n<pre><code>def sort_key_func(item):\n """ Helper function used to sort list of dicts\n\n :param item: dict\n :return: sorted list of tuples (k, v)\n """\n pairs = []\n for k, v in item.items():\n pairs.append((k, v))\n return sorted(pairs)\nsorted(A, key=sort_key_func)\n</code></pre>\n"
},
{
"answer_id": 39281050,
"author": "abby sobh",
"author_id": 3135363,
"author_profile": "https://Stackoverflow.com/users/3135363",
"pm_score": 4,
"selected": false,
"text": "<p>Using the <a href=\"https://en.wikipedia.org/wiki/Pandas_%28software%29\" rel=\"noreferrer\">Pandas</a> package is another method, though its runtime at large scale is much slower than the more traditional methods proposed by others:</p>\n<pre><code>import pandas as pd\n\nlistOfDicts = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]\ndf = pd.DataFrame(listOfDicts)\ndf = df.sort_values('name')\nsorted_listOfDicts = df.T.to_dict().values()\n</code></pre>\n<p>Here are some benchmark values for a tiny list and a large (100k+) list of dicts:</p>\n<pre><code>setup_large = "listOfDicts = [];\\\n[listOfDicts.extend(({'name':'Homer', 'age':39}, {'name':'Bart', 'age':10})) for _ in range(50000)];\\\nfrom operator import itemgetter;import pandas as pd;\\\ndf = pd.DataFrame(listOfDicts);"\n\nsetup_small = "listOfDicts = [];\\\nlistOfDicts.extend(({'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}));\\\nfrom operator import itemgetter;import pandas as pd;\\\ndf = pd.DataFrame(listOfDicts);"\n\nmethod1 = "newlist = sorted(listOfDicts, key=lambda k: k['name'])"\nmethod2 = "newlist = sorted(listOfDicts, key=itemgetter('name')) "\nmethod3 = "df = df.sort_values('name');\\\nsorted_listOfDicts = df.T.to_dict().values()"\n\nimport timeit\nt = timeit.Timer(method1, setup_small)\nprint('Small Method LC: ' + str(t.timeit(100)))\nt = timeit.Timer(method2, setup_small)\nprint('Small Method LC2: ' + str(t.timeit(100)))\nt = timeit.Timer(method3, setup_small)\nprint('Small Method Pandas: ' + str(t.timeit(100)))\n\nt = timeit.Timer(method1, setup_large)\nprint('Large Method LC: ' + str(t.timeit(100)))\nt = timeit.Timer(method2, setup_large)\nprint('Large Method LC2: ' + str(t.timeit(100)))\nt = timeit.Timer(method3, setup_large)\nprint('Large Method Pandas: ' + str(t.timeit(1)))\n\n#Small Method LC: 0.000163078308105\n#Small Method LC2: 0.000134944915771\n#Small Method Pandas: 0.0712950229645\n#Large Method LC: 0.0321750640869\n#Large Method LC2: 0.0206089019775\n#Large Method Pandas: 5.81405615807\n</code></pre>\n"
},
{
"answer_id": 42855105,
"author": "forzagreen",
"author_id": 3495031,
"author_profile": "https://Stackoverflow.com/users/3495031",
"pm_score": 6,
"selected": false,
"text": "<pre><code>a = [{'name':'Homer', 'age':39}, ...]\n\n# This changes the list a\na.sort(key=lambda k : k['name'])\n\n# This returns a new list (a is not modified)\nsorted(a, key=lambda k : k['name']) \n</code></pre>\n"
},
{
"answer_id": 45094029,
"author": "uingtea",
"author_id": 4082344,
"author_profile": "https://Stackoverflow.com/users/4082344",
"pm_score": 4,
"selected": false,
"text": "<p>Sometimes we need to use <code>lower()</code>. For example,</p>\n<pre><code>lists = [{'name':'Homer', 'age':39},\n {'name':'Bart', 'age':10},\n {'name':'abby', 'age':9}]\n\nlists = sorted(lists, key=lambda k: k['name'])\nprint(lists)\n# [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}, {'name':'abby', 'age':9}]\n\nlists = sorted(lists, key=lambda k: k['name'].lower())\nprint(lists)\n# [ {'name':'abby', 'age':9}, {'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]\n</code></pre>\n"
},
{
"answer_id": 47892332,
"author": "srikavineehari",
"author_id": 8709791,
"author_profile": "https://Stackoverflow.com/users/8709791",
"pm_score": 4,
"selected": false,
"text": "<p>If you do not need the original <code>list</code> of <code>dictionaries</code>, you could modify it in-place with <code>sort()</code> method using a custom key function.</p>\n\n<p>Key function:</p>\n\n<pre><code>def get_name(d):\n \"\"\" Return the value of a key in a dictionary. \"\"\"\n\n return d[\"name\"]\n</code></pre>\n\n<p>The <code>list</code> to be sorted:</p>\n\n<pre><code>data_one = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]\n</code></pre>\n\n<p>Sorting it in-place:</p>\n\n<pre><code>data_one.sort(key=get_name)\n</code></pre>\n\n<p>If you need the original <code>list</code>, call the <code>sorted()</code> function passing it the <code>list</code> and the key function, then assign the returned sorted <code>list</code> to a new variable:</p>\n\n<pre><code>data_two = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]\nnew_data = sorted(data_two, key=get_name)\n</code></pre>\n\n<p>Printing <code>data_one</code> and <code>new_data</code>.</p>\n\n<pre><code>>>> print(data_one)\n[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]\n>>> print(new_data)\n[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]\n</code></pre>\n"
},
{
"answer_id": 58179903,
"author": "Bejür",
"author_id": 7933218,
"author_profile": "https://Stackoverflow.com/users/7933218",
"pm_score": 4,
"selected": false,
"text": "<p>I have been a big fan of a filter with lambda. However, it is not best option if you consider time complexity.</p>\n<h3>First option</h3>\n<pre><code>sorted_list = sorted(list_to_sort, key= lambda x: x['name'])\n# Returns list of values\n</code></pre>\n<h3>Second option</h3>\n<pre><code>list_to_sort.sort(key=operator.itemgetter('name'))\n# Edits the list, and does not return a new list\n</code></pre>\n<h3>Fast comparison of execution times</h3>\n<pre><code># First option\npython3.6 -m timeit -s "list_to_sort = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}, {'name':'Faaa', 'age':57}, {'name':'Errr', 'age':20}]" -s "sorted_l=[]" "sorted_l = sorted(list_to_sort, key=lambda e: e['name'])"\n</code></pre>\n<blockquote>\n<p>1000000 loops, best of 3: 0.736 µsec per loop</p>\n</blockquote>\n<pre><code># Second option\npython3.6 -m timeit -s "list_to_sort = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}, {'name':'Faaa', 'age':57}, {'name':'Errr', 'age':20}]" -s "sorted_l=[]" -s "import operator" "list_to_sort.sort(key=operator.itemgetter('name'))"\n</code></pre>\n<blockquote>\n<p>1000000 loops, best of 3: 0.438 µsec per loop</p>\n</blockquote>\n"
},
{
"answer_id": 59802559,
"author": "swac",
"author_id": 10452855,
"author_profile": "https://Stackoverflow.com/users/10452855",
"pm_score": 3,
"selected": false,
"text": "<p>If performance is a concern, I would use <code>operator.itemgetter</code> instead of <code>lambda</code> as built-in functions perform faster than hand-crafted functions. The <code>itemgetter</code> function seems to perform approximately 20% faster than <code>lambda</code> based on my testing.</p>\n<p>From <a href=\"https://wiki.python.org/moin/PythonSpeed\" rel=\"noreferrer\">https://wiki.python.org/moin/PythonSpeed</a>:</p>\n<blockquote>\n<p>Likewise, the builtin functions run faster than hand-built equivalents. For example, map(operator.add, v1, v2) is faster than map(lambda x,y: x+y, v1, v2).</p>\n</blockquote>\n<p>Here is a comparison of sorting speed using <code>lambda</code> vs <code>itemgetter</code>.</p>\n<pre><code>import random\nimport operator\n\n# Create a list of 100 dicts with random 8-letter names and random ages from 0 to 100.\nl = [{'name': ''.join(random.choices(string.ascii_lowercase, k=8)), 'age': random.randint(0, 100)} for i in range(100)]\n\n# Test the performance with a lambda function sorting on name\n%timeit sorted(l, key=lambda x: x['name'])\n13 µs ± 388 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n# Test the performance with itemgetter sorting on name\n%timeit sorted(l, key=operator.itemgetter('name'))\n10.7 µs ± 38.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n# Check that each technique produces the same sort order\nsorted(l, key=lambda x: x['name']) == sorted(l, key=operator.itemgetter('name'))\nTrue\n</code></pre>\n<p>Both techniques sort the list in the same order (verified by execution of the final statement in the code block), but the first one is a little faster.</p>\n"
},
{
"answer_id": 69072597,
"author": "Tms91",
"author_id": 7658051,
"author_profile": "https://Stackoverflow.com/users/7658051",
"pm_score": 1,
"selected": false,
"text": "<p>As indicated by @Claudiu to @monojohnny in comment section of <a href=\"https://stackoverflow.com/a/73465/7658051\">this answer</a>,<br> given:</p>\n<pre><code>list_to_be_sorted = [\n {'name':'Homer', 'age':39}, \n {'name':'Milhouse', 'age':10}, \n {'name':'Bart', 'age':10} \n ]\n</code></pre>\n<p>to sort the list of dictionaries by key <code>'age'</code>, <code>'name'</code>\n<br>(like in SQL statement <code>ORDER BY age, name</code>), you can use:</p>\n<pre><code>newlist = sorted( list_to_be_sorted, key=lambda k: (k['age'], k['name']) )\n</code></pre>\n<p>or, likewise</p>\n<pre><code>import operator\nnewlist = sorted( list_to_be_sorted, key=operator.itemgetter('age','name') )\n</code></pre>\n<p><code>print(newlist)</code></p>\n<blockquote>\n<p>[{'name': 'Bart', 'age': 10},<br> {'name': 'Milhouse', 'age': 10},<br>\n{'name': 'Homer', 'age': 39}]</p>\n</blockquote>\n"
},
{
"answer_id": 72939809,
"author": "alex",
"author_id": 4444742,
"author_profile": "https://Stackoverflow.com/users/4444742",
"pm_score": 0,
"selected": false,
"text": "<p>sorting by multiple columns, while in descending order on some of them:\nthe cmps array is global to the cmp function, containing field names and inv == -1 for desc 1 for asc</p>\n<pre><code>def cmpfun(a, b):\n for (name, inv) in cmps:\n res = cmp(a[name], b[name])\n if res != 0:\n return res * inv\n return 0\n\ndata = [\n dict(name='alice', age=10), \n dict(name='baruch', age=9), \n dict(name='alice', age=11),\n]\n\nall_cmps = [\n [('name', 1), ('age', -1)], \n [('name', 1), ('age', 1)], \n [('name', -1), ('age', 1)],]\n\nprint 'data:', data\nfor cmps in all_cmps: print 'sort:', cmps; print sorted(data, cmpfun)\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12398/"
]
| How do I sort a list of dictionaries by a specific key's value? Given:
```
[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
```
When sorted by `name`, it should become:
```
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
``` | The [`sorted()`](https://docs.python.org/library/functions.html#sorted) function takes a `key=` parameter
```
newlist = sorted(list_to_be_sorted, key=lambda d: d['name'])
```
Alternatively, you can use [`operator.itemgetter`](https://docs.python.org/library/operator.html#operator.itemgetter) instead of defining the function yourself
```
from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
```
For completeness, add `reverse=True` to sort in descending order
```
newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)
``` |
72,913 | <p>If I have an IEnumerator variable is it possible to have a lambda function that takes it, advances it with MoveNext() and returns the Current value every single time its called?</p>
| [
{
"answer_id": 72963,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": 1,
"selected": false,
"text": "<p>A Lambda expression can contain complex statements, so you can do the following:</p>\n\n<pre><code>Func<IEnumerator, object> f = ie => { ie.MoveNext(); return ie.Current; };\n</code></pre>\n"
},
{
"answer_id": 73007,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 3,
"selected": true,
"text": "<pre><code>e => e.MoveNext() ? e.Current : null\n</code></pre>\n\n<p>This will advance the enumerator and return the current value, and return null when the enumeration is complete.</p>\n"
},
{
"answer_id": 73041,
"author": "fryguybob",
"author_id": 4592,
"author_profile": "https://Stackoverflow.com/users/4592",
"pm_score": 0,
"selected": false,
"text": "<p>Is this what you are looking for?</p>\n\n<pre><code>List<string> strings = new List<string>()\n{\n \"Hello\", \"I\", \"am\", \"a\", \"list\", \"of\", \"strings.\"\n};\nIEnumerator<string> e = strings.GetEnumerator();\nFunc<string> f = () => e.MoveNext() ? e.Current : null;\nfor (; ; )\n{\n string str = f();\n if (str == null)\n break;\n\n Console.Write(str + \" \");\n}\n</code></pre>\n\n<p>The point of an <code>IEnumerator</code> is that you already get syntactic sugar to deal with it:</p>\n\n<pre><code>foreach (string str in strings)\n Console.Write(str + \" \");\n</code></pre>\n\n<p>Even handling the enumerator directly looks cleaner in this case:</p>\n\n<pre><code>while (e.MoveNext())\n Console.Write(e.Current + \" \");\n</code></pre>\n"
},
{
"answer_id": 73058,
"author": "Nathan Baulch",
"author_id": 8799,
"author_profile": "https://Stackoverflow.com/users/8799",
"pm_score": 0,
"selected": false,
"text": "<p>Extending on Abe's solution, you can also use closures to hold a reference to the enumerator:</p>\n\n<pre><code>var iter = ((IEnumerable<char>)\"hello\").GetEnumerator();\n\n//with closure\n{\n Func<object> f =\n () =>\n {\n iter.MoveNext();\n return iter.Current;\n };\n Console.WriteLine(f());\n Console.WriteLine(f());\n}\n\n//without closure\n{\n Func<IEnumerator, object> f =\n ie =>\n {\n ie.MoveNext();\n return ie.Current;\n };\n Console.WriteLine(f(iter));\n Console.WriteLine(f(iter));\n}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
]
| If I have an IEnumerator variable is it possible to have a lambda function that takes it, advances it with MoveNext() and returns the Current value every single time its called? | ```
e => e.MoveNext() ? e.Current : null
```
This will advance the enumerator and return the current value, and return null when the enumeration is complete. |
72,921 | <p>I am just starting to learn javascript, so I don't have the skills to figure out what I assume is a trivial problem.</p>
<p>I'm working with a Wordpress blog that serves as a FAQ for our community and I am trying to pull together some tools to make managing the comments easier. <a href="https://stackoverflow.com/users/4465/levik">Internet Duct Tape's Greasemonkey tools, like Comment Ninja</a>, are helpful for most of it, but I want to be able to get a list of all the IP addresses that we're getting comments from in order to track trends and so forth.</p>
<p>I just want to be able to select a bunch of text on the comments page and click a bookmarklet (<a href="https://stackoverflow.com/users/8119/jacob">http://bookmarklets.com</a>) in Firefox that pops up a window listing all the IP addresses found in the selection.</p>
<p><strong>Update:</strong></p>
<p>I kind of combined a the answers from <a href="https://stackoverflow.com/users/4465/levik">levik</a> and <a href="https://stackoverflow.com/users/8119/jacob">Jacob</a> to come up with this:</p>
<pre><code>javascript:ipAddresses=document.getSelection().match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g).join("<br>");newWindow=window.open('', 'IP Addresses in Selection', 'innerWidth=200,innerHeight=300,scrollbars');newWindow.document.write(ipAddresses)
</code></pre>
<p>The difference is that instead of an <em>alert</em> message, as in levik's answer, I open a new window similar to Jacob's answer. The <em>alert</em> doesn't provide scroll bars which can be a problem for pages with many IP addresses. However, I needed the list to be vertical, unlike Jacob's solution, so I used the hint from levik's to make a <em><br></em> for the join instead of levik's <em>\n</em>. </p>
<p>Thanks for all the help, guys.</p>
| [
{
"answer_id": 72981,
"author": "Dr. Bob",
"author_id": 12182,
"author_profile": "https://Stackoverflow.com/users/12182",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://javascript.about.com/library/blip.htm\" rel=\"nofollow noreferrer\">Here</a> is a good article on obtaining the IP address of your visitors. You could display this in addition to their comment if you wanted or include it as a label or field in your page so you can reference it later.</p>\n"
},
{
"answer_id": 73031,
"author": "jtimberman",
"author_id": 7672,
"author_profile": "https://Stackoverflow.com/users/7672",
"pm_score": 1,
"selected": false,
"text": "<p>Use a regular expression to detect the IP address. A couple examples:</p>\n\n<pre><code>/\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/\n/^([1-9][0-9]{0,2})+\\.([1-9][0-9]{0,2})+\\.([1-9][0-9]{0,2})+\\.([1-9][0-9]{0,2})+$/\n</code></pre>\n"
},
{
"answer_id": 73723,
"author": "levik",
"author_id": 4465,
"author_profile": "https://Stackoverflow.com/users/4465",
"pm_score": 3,
"selected": true,
"text": "<p>In Firefox, you could do something like this:</p>\n\n<pre><code>javascript:alert(\n document.getSelection().match(/\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/g)\n .join(\"\\n\"))\n</code></pre>\n\n<p>How this works:</p>\n\n<ul>\n<li>Gets the selection text from the browser (\"document.getSelection()\" in FF, in IE it would be \"document.selection.createRange().text\")</li>\n<li>Applies a regular expression to march the IP addresses (as suggested by Muerr) - this results in an array of strings.</li>\n<li>Joins this array into one string separated by return characters</li>\n<li>Alerts that string</li>\n</ul>\n\n<p>The way you get the selection is a little different on IE, but the principle is the same. To get it to be cross-browser, you'd need to check which method is available. You could also do more complicated output (like create a floating DIV and insert all the IPs into it).</p>\n"
},
{
"answer_id": 74377,
"author": "Jacob",
"author_id": 8119,
"author_profile": "https://Stackoverflow.com/users/8119",
"pm_score": 1,
"selected": false,
"text": "<h2>As a bookmarklet</h2>\n<pre><code>javascript:document.write(document.getSelection().match(/\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/g))\n</code></pre>\n<p>Just create a new bookmark and paste that javascript in</p>\n<h2>How to do it in Ubiquity</h2>\n<pre><code>CmdUtils.CreateCommand({\n name: "findip",\n preview: function( pblock ) {\n var msg = 'IP Addresses Found<br/><br/> ';\n ips = CmdUtils.getHtmlSelection().match(/\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/g);\n if(ips){\n msg += ips.join("<br/>\\n");\n }else{\n msg += 'None';\n }\n pblock.innerHTML = msg;\n },\n\n execute: function() {\n ips = CmdUtils.getHtmlSelection().match(/\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/g);\n if(ips){\n CmdUtils.setSelection(ips.join("<br/>\\n"));\n }\n }\n})\n</code></pre>\n"
},
{
"answer_id": 74387,
"author": "jtimberman",
"author_id": 7672,
"author_profile": "https://Stackoverflow.com/users/7672",
"pm_score": 0,
"selected": false,
"text": "<p>Have a look at the <a href=\"https://www.squarefree.com/bookmarklets/pagedata.html#rot13_selection\" rel=\"nofollow noreferrer\" title=\"rot13 bookmarklet\">rot13 bookmarklet</a> for an example of selecting text and performing an action (in this case substitution) when the bookmarklet is clicked.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12419/"
]
| I am just starting to learn javascript, so I don't have the skills to figure out what I assume is a trivial problem.
I'm working with a Wordpress blog that serves as a FAQ for our community and I am trying to pull together some tools to make managing the comments easier. [Internet Duct Tape's Greasemonkey tools, like Comment Ninja](https://stackoverflow.com/users/4465/levik), are helpful for most of it, but I want to be able to get a list of all the IP addresses that we're getting comments from in order to track trends and so forth.
I just want to be able to select a bunch of text on the comments page and click a bookmarklet ([http://bookmarklets.com](https://stackoverflow.com/users/8119/jacob)) in Firefox that pops up a window listing all the IP addresses found in the selection.
**Update:**
I kind of combined a the answers from [levik](https://stackoverflow.com/users/4465/levik) and [Jacob](https://stackoverflow.com/users/8119/jacob) to come up with this:
```
javascript:ipAddresses=document.getSelection().match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g).join("<br>");newWindow=window.open('', 'IP Addresses in Selection', 'innerWidth=200,innerHeight=300,scrollbars');newWindow.document.write(ipAddresses)
```
The difference is that instead of an *alert* message, as in levik's answer, I open a new window similar to Jacob's answer. The *alert* doesn't provide scroll bars which can be a problem for pages with many IP addresses. However, I needed the list to be vertical, unlike Jacob's solution, so I used the hint from levik's to make a for the join instead of levik's *\n*.
Thanks for all the help, guys. | In Firefox, you could do something like this:
```
javascript:alert(
document.getSelection().match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g)
.join("\n"))
```
How this works:
* Gets the selection text from the browser ("document.getSelection()" in FF, in IE it would be "document.selection.createRange().text")
* Applies a regular expression to march the IP addresses (as suggested by Muerr) - this results in an array of strings.
* Joins this array into one string separated by return characters
* Alerts that string
The way you get the selection is a little different on IE, but the principle is the same. To get it to be cross-browser, you'd need to check which method is available. You could also do more complicated output (like create a floating DIV and insert all the IPs into it). |
72,936 | <pre>
kt@rails-ubuntu:~/rails/ledger/releases/20080820144914/.git/hooks$ ls -al
ls: cannot access post-commit: No such file or directory
ls: cannot access update: No such file or directory
ls: cannot access post-update: No such file or directory
ls: cannot access commit-msg: No such file or directory
ls: cannot access pre-rebase: No such file or directory
ls: cannot access post-receive: No such file or directory
ls: cannot access pre-applypatch: No such file or directory
ls: cannot access pre-commit: No such file or directory
total 8
drwxrwxr-x 2 kt kt 4096 2008-09-09 18:10 .
drwxrwxr-x 4 kt kt 4096 2008-09-09 18:10 ..
-????????? ? ? ? ? ? commit-msg
-????????? ? ? ? ? ? post-commit
-????????? ? ? ? ? ? post-receive
-????????? ? ? ? ? ? post-update
-????????? ? ? ? ? ? pre-applypatch
-????????? ? ? ? ? ? pre-commit
-????????? ? ? ? ? ? pre-rebase
-????????? ? ? ? ? ? update
</pre>
| [
{
"answer_id": 72988,
"author": "raldi",
"author_id": 7598,
"author_profile": "https://Stackoverflow.com/users/7598",
"pm_score": 4,
"selected": true,
"text": "<p>First off, here's your question, nicely formatted (surround it in < pre > tags to get this):</p>\n\n<pre>kt@rails-ubuntu:~/rails/ledger/releases/20080820144914/.git/hooks$ ls -al\nls: cannot access post-commit: No such file or directory\nls: cannot access update: No such file or directory\nls: cannot access post-update: No such file or directory\n[snip]</pre>\n\n<p>Anyway, you need to boot up in single-user mode and run fsck. If you can't reboot right now, just move the directory to /tmp and forget about it.</p>\n"
},
{
"answer_id": 73013,
"author": "David Precious",
"author_id": 4040,
"author_profile": "https://Stackoverflow.com/users/4040",
"pm_score": 1,
"selected": false,
"text": "<p>(a) Looks like you have some kind of filesystem problems; I'd recommend you run fsck and see if it finds anything</p>\n\n<p>(b) Really not a programming-related question, so off-topic here.</p>\n"
},
{
"answer_id": 8263727,
"author": "James EJ",
"author_id": 600525,
"author_profile": "https://Stackoverflow.com/users/600525",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem caused by Aptana Studio working with rails more than once.\n The long term solution was to avoid using aptana to create files.</p>\n"
},
{
"answer_id": 23014728,
"author": "iOSAndroidWindowsMobileAppsDev",
"author_id": 1611779,
"author_profile": "https://Stackoverflow.com/users/1611779",
"pm_score": 0,
"selected": false,
"text": "<p>I ran into this problem and tried everything. Surprisingly the solution is very simple. Dude, this is what you do:\nUsing GUI and not the terminal\n1. Move all other files in that folder to a different one with a different name\n2. Move the containing directory which should have only the problematic file to trash\n3 Empty trash</p>\n\n<p>and yes, it is that simple</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12417/"
]
| ```
kt@rails-ubuntu:~/rails/ledger/releases/20080820144914/.git/hooks$ ls -al
ls: cannot access post-commit: No such file or directory
ls: cannot access update: No such file or directory
ls: cannot access post-update: No such file or directory
ls: cannot access commit-msg: No such file or directory
ls: cannot access pre-rebase: No such file or directory
ls: cannot access post-receive: No such file or directory
ls: cannot access pre-applypatch: No such file or directory
ls: cannot access pre-commit: No such file or directory
total 8
drwxrwxr-x 2 kt kt 4096 2008-09-09 18:10 .
drwxrwxr-x 4 kt kt 4096 2008-09-09 18:10 ..
-????????? ? ? ? ? ? commit-msg
-????????? ? ? ? ? ? post-commit
-????????? ? ? ? ? ? post-receive
-????????? ? ? ? ? ? post-update
-????????? ? ? ? ? ? pre-applypatch
-????????? ? ? ? ? ? pre-commit
-????????? ? ? ? ? ? pre-rebase
-????????? ? ? ? ? ? update
``` | First off, here's your question, nicely formatted (surround it in < pre > tags to get this):
```
kt@rails-ubuntu:~/rails/ledger/releases/20080820144914/.git/hooks$ ls -al
ls: cannot access post-commit: No such file or directory
ls: cannot access update: No such file or directory
ls: cannot access post-update: No such file or directory
[snip]
```
Anyway, you need to boot up in single-user mode and run fsck. If you can't reboot right now, just move the directory to /tmp and forget about it. |
72,943 | <p>Is it possible to launch a new window in JavaScript using the window.Open function, then set the focus to that tab?</p>
<p>Here's what I'm doing today:
<code></p>
<pre>
var winRef = window.open(outUrl,wName,'left='+ wX +',top=' + wY + ',height=' + wH + ',width=' + wW + args);
try {
// Not all window types support the focus() property.
winRef.focus();
}
catch (exception) {
}
</pre>
<p></code></p>
<p>The window opens, but the new tab doesn't receive focus.</p>
| [
{
"answer_id": 72971,
"author": "jtimberman",
"author_id": 7672,
"author_profile": "https://Stackoverflow.com/users/7672",
"pm_score": 1,
"selected": false,
"text": "<p>As a user, I never want applications (or tabs) to take focus unless I specifically requested it. I have gone to great lengths to prevent tabs in my browser (Firefox) from taking focus for this reason. </p>\n"
},
{
"answer_id": 72997,
"author": "Guido",
"author_id": 12388,
"author_profile": "https://Stackoverflow.com/users/12388",
"pm_score": 3,
"selected": true,
"text": "<p>Jay,</p>\n\n<p>You are seeing designed behavior. To limit opportunities for malicious behavior, scripts running in tabbed windows cannot affect other tabs.</p>\n\n<p>For more information, please see Tabbed Browsing for Developers at <a href=\"http://msdn.microsoft.com/en-us/library/ms537636.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms537636.aspx</a> :</p>\n\n<p>\"The ability to open multiple documents within the same browser window has certain practical and security implications [...] Active tabs (tabs with focus) cannot be affected by scripts that run in inactive or background tabs.\"</p>\n\n<p>BR.</p>\n"
},
{
"answer_id": 73005,
"author": "Erratic",
"author_id": 2246765,
"author_profile": "https://Stackoverflow.com/users/2246765",
"pm_score": 1,
"selected": false,
"text": "<p>I'm reasonably certain you can't shift focus to another tab.</p>\n\n<p>My understanding is this is done to somewhat limit pop ups and other malicious content from stealing the users focus. </p>\n"
},
{
"answer_id": 78119,
"author": "Brendan Kidwell",
"author_id": 13958,
"author_profile": "https://Stackoverflow.com/users/13958",
"pm_score": 1,
"selected": false,
"text": "<p>If the other \"tab\" is part of your application (and not content from another site) perhaps you should include it in a popup div on top of your main content instead of in a separate window; that way you can always control focusing it, deactivating the content under it (for modal dialogs), hiding it, etc.</p>\n"
},
{
"answer_id": 547019,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>As a user, shouldn't I be able to control how this operates?</p>\n\n<p>What if there is an application that would be enhanced by this feature that I want to run - shouldn't I be able to grant a domain that privilege?</p>\n\n<p>Just a thought.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/733/"
]
| Is it possible to launch a new window in JavaScript using the window.Open function, then set the focus to that tab?
Here's what I'm doing today:
```
var winRef = window.open(outUrl,wName,'left='+ wX +',top=' + wY + ',height=' + wH + ',width=' + wW + args);
try {
// Not all window types support the focus() property.
winRef.focus();
}
catch (exception) {
}
```
The window opens, but the new tab doesn't receive focus. | Jay,
You are seeing designed behavior. To limit opportunities for malicious behavior, scripts running in tabbed windows cannot affect other tabs.
For more information, please see Tabbed Browsing for Developers at <http://msdn.microsoft.com/en-us/library/ms537636.aspx> :
"The ability to open multiple documents within the same browser window has certain practical and security implications [...] Active tabs (tabs with focus) cannot be affected by scripts that run in inactive or background tabs."
BR. |
72,945 | <p>Using Django's built in models, how would one create a triple-join between three models.</p>
<p>For example:</p>
<ul>
<li>Users, Roles, and Events are the models.</li>
<li>Users have many Roles, and Roles many Users. (ManyToMany)</li>
<li>Events have many Users, and Users many Events. (ManyToMany)</li>
<li>But for any given Event, any User may have only one Role.</li>
</ul>
<p>How can this be represented in the model?</p>
| [
{
"answer_id": 73153,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 2,
"selected": false,
"text": "<p>I'd recommend just creating an entirely separate model for this.</p>\n\n<pre><code>class Assignment(Model):\n user = ForeignKey(User)\n role = ForeignKey(Role)\n event = ForeignKey(Event)\n</code></pre>\n\n<p>This lets you do all the usual model stuff, such as</p>\n\n<pre><code>user.assignment_set.filter(role__name=\"Chaperon\")\nrole.assignment_set.filter(event__name=\"Silly Walkathon\")\n</code></pre>\n\n<p>The only thing left is to enforce your one-role-per-user-per-event restriction. You can do this in the Assignment class by either overriding the save method (<a href=\"http://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods\" rel=\"nofollow noreferrer\">http://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods</a>) or using signals (<a href=\"http://docs.djangoproject.com/en/dev/topics/signals/\" rel=\"nofollow noreferrer\">http://docs.djangoproject.com/en/dev/topics/signals/</a>)</p>\n"
},
{
"answer_id": 76221,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 0,
"selected": false,
"text": "<p>I'd model Role as an association class between Users and Roles, thus,</p>\n\n<pre><code>class User(models.Model):\n ...\n\nclass Event(models.Model):\n ...\n\nclass Role(models.Model):\n user = models.ForeignKey(User)\n event = models.ForeignKey(Event)\n</code></pre>\n\n<p>And enforce the one role per user per event in either a manager or SQL constraints.</p>\n"
},
{
"answer_id": 77898,
"author": "zuber",
"author_id": 9812,
"author_profile": "https://Stackoverflow.com/users/9812",
"pm_score": 5,
"selected": true,
"text": "<p><strong>zacherates</strong> writes:</p>\n\n<blockquote>\n <p>I'd model Role as an association class between Users and Roles (...)</p>\n</blockquote>\n\n<p>I'd also reccomed this solution, but you can also make use of some syntactical sugar provided by Django: <a href=\"http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships\" rel=\"noreferrer\">ManyToMany relation with extra fields</a>.</p>\n\n<p>Example:</p>\n\n<pre><code>class User(models.Model):\n name = models.CharField(max_length=128)\n\nclass Event(models.Model):\n name = models.CharField(max_length=128)\n members = models.ManyToManyField(User, through='Role')\n\n def __unicode__(self):\n return self.name\n\nclass Role(models.Model):\n person = models.ForeignKey(User)\n group = models.ForeignKey(Event)\n date_joined = models.DateField()\n invite_reason = models.CharField(max_length=64)\n</code></pre>\n"
},
{
"answer_id": 16290256,
"author": "Brent Washburne",
"author_id": 584846,
"author_profile": "https://Stackoverflow.com/users/584846",
"pm_score": 0,
"selected": false,
"text": "<p>While trying to find a faster three-table join for my own Django models, I came across this question. By default, Django 1.1 uses INNER JOINs which can be slow on InnoDB. For a query like:</p>\n\n<pre><code>def event_users(event_name):\n return User.objects.filter(roles__events__name=event_name)\n</code></pre>\n\n<p>this might create the following SQL:</p>\n\n<pre><code>SELECT `user`.`id`, `user`.`name` FROM `user` INNER JOIN `roles` ON (`user`.`id` = `roles`.`user_id`) INNER JOIN `event` ON (`roles`.`event_id` = `event`.`id`) WHERE `event`.`name` = \"event_name\"\n</code></pre>\n\n<p>The INNER JOINs can be very slow compared with LEFT JOINs. An even faster query can be found under gimg1's answer: <a href=\"https://stackoverflow.com/questions/10257433/mysql-query-to-join-three-tables#10257569\">Mysql query to join three tables</a></p>\n\n<pre><code>SELECT `user`.`id`, `user`.`name` FROM `user`, `roles`, `event` WHERE `user`.`id` = `roles`.`user_id` AND `roles`.`event_id` = `event`.`id` AND `event`.`name` = \"event_name\"\n</code></pre>\n\n<p>However, you will need to use a custom SQL query: <a href=\"https://docs.djangoproject.com/en/dev/topics/db/sql/\" rel=\"nofollow noreferrer\">https://docs.djangoproject.com/en/dev/topics/db/sql/</a></p>\n\n<p>In this case, it would look something like:</p>\n\n<pre><code>from django.db import connection\ndef event_users(event_name):\n cursor = connection.cursor()\n cursor.execute('select U.name from user U, roles R, event E' \\\n ' where U.id=R.user_id and R.event_id=E.id and E.name=\"%s\"' % event_name)\n return [row[0] for row in cursor.fetchall()]\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8507/"
]
| Using Django's built in models, how would one create a triple-join between three models.
For example:
* Users, Roles, and Events are the models.
* Users have many Roles, and Roles many Users. (ManyToMany)
* Events have many Users, and Users many Events. (ManyToMany)
* But for any given Event, any User may have only one Role.
How can this be represented in the model? | **zacherates** writes:
>
> I'd model Role as an association class between Users and Roles (...)
>
>
>
I'd also reccomed this solution, but you can also make use of some syntactical sugar provided by Django: [ManyToMany relation with extra fields](http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships).
Example:
```
class User(models.Model):
name = models.CharField(max_length=128)
class Event(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(User, through='Role')
def __unicode__(self):
return self.name
class Role(models.Model):
person = models.ForeignKey(User)
group = models.ForeignKey(Event)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
``` |
72,994 | <p>I want to simulate a 'Web 2.0' Lightbox style UI technique in a <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="noreferrer">Windows Forms</a> application. That is, to draw attention to some foreground control by 'dimming' all other content in the client area of a window. </p>
<p>The obvious solution is to create a control that is simply a partially transparent rectangle that can be docked to the client area of a window and brought to the front of the Z-Order. It needs to act like a dirty pain of glass through which the other controls can still be seen (and therefore continue to paint themselves). Is this possible? </p>
<p>I've had a good hunt round and tried a few techniques myself but thus far have been unsuccessful.
If it is not possible, what would be another way to do it?</p>
<p>See: <a href="http://www.useit.com/alertbox/application-design.html" rel="noreferrer">http://www.useit.com/alertbox/application-design.html</a> (under the Lightbox section for a screenshot to illustrate what I mean.)</p>
| [
{
"answer_id": 73062,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>The forms themselves have the property <code>Opacity</code> that would be perfect, but I don't think most of the individual controls do. You'll have to owner-draw it.</p>\n"
},
{
"answer_id": 73065,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 1,
"selected": false,
"text": "<p>The big dimming rectangle is good.</p>\n\n<p>Another way to do it would be:</p>\n\n<p>Roll your own base Form class says a <code>MyLightboxAwareForm</code> class that would listen to a <code>LightboxEvent</code> from a <code>LightboxManager</code>. Then have all your forms inherit from <code>MyLightboxAwareForm</code>.</p>\n\n<p>On calling the <code>Show</code> method on any <code>Lightbox</code>, the <code>LightboxManager</code> would broadcast a <code>LightboxShown</code> event to all <code>MyLightboxAwareForm</code> instances and making them dim themselves.</p>\n\n<p>This has the advantage that normal Win32 forms functionality will continue to work such as taskbar-flashing of the form when you click on one of its modal dialogs or the management of mouseover/mousedown events would still work normally etc.</p>\n\n<p>And if you want the rectangle dimming style, you could just put the logic in MyLightboxAwareForm</p>\n"
},
{
"answer_id": 73146,
"author": "Miroslav Zadravec",
"author_id": 8239,
"author_profile": "https://Stackoverflow.com/users/8239",
"pm_score": 0,
"selected": false,
"text": "<p>Every form has \"Opacity\" property. Set it to 50% (or 0.5 from code) so will be half transparent. Remove borders and show it maximized before the form you want to have focus. You can change BackColor of the form or even set background image for different effects.</p>\n"
},
{
"answer_id": 73191,
"author": "Phil Wright",
"author_id": 6276,
"author_profile": "https://Stackoverflow.com/users/6276",
"pm_score": 4,
"selected": false,
"text": "<p>Can you do this in .NET/C#? </p>\n\n<p>Yes you certainly can but it takes a little bit of effort. I would recommend the following approach. Create a top level Form that has no border or titlebar area and then give make sure it draws no client area background by setting the TransparencyKey and BackColor to the same value. So you now have a window that draws nothing...</p>\n\n<pre><code>public class DarkenArea : Form\n{\n public DarkenArea()\n {\n FormBorderStyle = FormBorderStyle.None;\n SizeGripStyle = SizeGripStyle.Hide;\n StartPosition = FormStartPosition.Manual;\n MaximizeBox = false;\n MinimizeBox = false;\n ShowInTaskbar = false;\n BackColor = Color.Magenta;\n TransparencyKey = Color.Magenta;\n Opacity = 0.5f;\n }\n}\n</code></pre>\n\n<p>Create and position this DarkenArea window over the client area of your form. Then you need to be able to show the window without it taking the focus and so you will need to platform invoke in the following way to show without it becoming active...</p>\n\n<pre><code>public void ShowWithoutActivate()\n{\n // Show the window without activating it (i.e. do not take focus)\n PlatformInvoke.ShowWindow(this.Handle, (short)SW_SHOWNOACTIVATE);\n}\n</code></pre>\n\n<p>You need to make it actually draw something but exclude drawing in the area of the control you want to remain highlighted. So override the OnPaint handler and draw in black/blue or whatever you want but excluding the area you want to remain bright...</p>\n\n<pre><code>protected override void OnPaint(PaintEventArgs e)\n{\n base.OnPaint(e);\n // Do your painting here be exclude the area you want to be brighter\n}\n</code></pre>\n\n<p>Last you need to override the WndProc to prevent the mouse interacting with the window if the user tries something crazy like clicking on the darkened area. Something like this...</p>\n\n<pre><code>protected override void WndProc(ref Message m)\n{\n if (m.Msg == (int)WM_NCHITTEST)\n m.Result = (IntPtr)HTTRANSPARENT;\n else\n base.WndProc(ref m);\n}\n</code></pre>\n\n<p>That should be enough to get the desired effect. When you are ready to reverse the effect you dispose of the DarkenArea instance and carry on.</p>\n"
},
{
"answer_id": 169855,
"author": "ZeroBugBounce",
"author_id": 11314,
"author_profile": "https://Stackoverflow.com/users/11314",
"pm_score": 3,
"selected": false,
"text": "<p>This is a really cool idea - I will probably use it, so thanks. Anyway, my solution is really simple... open a new 50% opaque form over your current one and then custom draw a background image for that form with a rectangle matching the bounds of the control you want to highlight filled in the color of the transparency key.</p>\n\n<p>In my rough sample, I called this form the 'LBform' and the meat of it is this:</p>\n\n<pre><code>public Rectangle ControlBounds { get; set; }\nprivate void LBform_Load(object sender, EventArgs e)\n{\n Bitmap background = new Bitmap(this.Width, this.Height);\n Graphics g = Graphics.FromImage(background);\n g.FillRectangle(Brushes.Fuchsia, this.ControlBounds);\n\n g.Flush();\n\n this.BackgroundImage = background;\n this.Invalidate();\n}\n</code></pre>\n\n<p>Color.Fuchia is the TransparencyKey for this semi-opaque form, so you will be able to see through the rectangle drawn and interact with anything within it's bounds on the main form.</p>\n\n<p>In the experimental project I whipped up to try this, I used a UserControl dynamically added to the form, but you could just as easily use a control already on the form. In the main form (the one you are obscuring) I put the relevant code into a button click:</p>\n\n<pre><code>private void button1_Click(object sender, EventArgs e)\n{\n // setup user control:\n UserControl1 uc1 = new UserControl1();\n uc1.Left = (this.Width - uc1.Width) / 2;\n uc1.Top = (this.Height - uc1.Height) / 2;\n this.Controls.Add(uc1);\n uc1.BringToFront();\n\n // load the lightbox form:\n LBform lbform = new LBform();\n lbform.SetBounds(this.Left + 8, this.Top + 30, this.ClientRectangle.Width, this.ClientRectangle.Height);\n lbform.ControlBounds = uc1.Bounds;\n\n lbform.Owner = this;\n lbform.Show();\n}\n</code></pre>\n\n<p>Really basic stuff that you can do your own way if you like, but it's just adding the usercontrol, then setting the lightbox form over the main form and setting the bounds property to render the full transparency in the right place. Things like form dragging and closing the lightbox form and UserControl aren't handled in my quick sample. Oh and don't forget to dispose the Graphics instance - I left that out too (it's late, I'm really tired).</p>\n\n<p><a href=\"http://cid-12d219ccfc930f76.skydrive.live.com/self.aspx/Code/LightBox000.zip\" rel=\"noreferrer\">Here's my very did-it-in-20-minutes demo</a></p>\n"
},
{
"answer_id": 5757080,
"author": "Gad",
"author_id": 25152,
"author_profile": "https://Stackoverflow.com/users/25152",
"pm_score": 1,
"selected": false,
"text": "<p>Another solution that doesn't involve using a new Form :</p>\n\n<ul>\n<li>make a picture of your container (form / panel / whatever), </li>\n<li>change its opacity,</li>\n<li>display it in a new panel's background.</li>\n<li>Fill your container with that panel.</li>\n</ul>\n\n<p>And now the code... </p>\n\n<p>Let's say I have a UserControl called Frame to which I'll want to apply my lightbox effect:</p>\n\n<pre><code>public partial class Frame : UserControl\n{\n private Panel shadow = new Panel();\n private static float LIGHTBOX_OPACITY = 0.3f;\n\n public Frame()\n {\n InitializeComponent(); \n shadow.Dock = DockStyle.Fill;\n }\n\n public void ShowLightbox()\n {\n Bitmap bmp = new Bitmap(this.Width, this.Height);\n this.pnlContainer.DrawToBitmap(bmp, new Rectangle(0, 0, this.Width, this.Height));\n shadow.BackgroundImage = SetImgOpacity(bmp, LIGHTBOX_OPACITY );\n this.Controls.Add(shadow);\n shadow.BringToFront();\n }\n\n // http://www.geekpedia.com/code110_Set-Image-Opacity-Using-Csharp.html\n private Image SetImgOpacity(Image imgPic, float imgOpac)\n {\n Bitmap bmpPic = new Bitmap(imgPic.Width, imgPic.Height);\n Graphics gfxPic = Graphics.FromImage(bmpPic);\n ColorMatrix cmxPic = new ColorMatrix();\n cmxPic.Matrix33 = imgOpac;\n ImageAttributes iaPic = new ImageAttributes();\n iaPic.SetColorMatrix(cmxPic, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);\n gfxPic.DrawImage(imgPic, new Rectangle(0, 0, bmpPic.Width, bmpPic.Height), 0, 0, imgPic.Width, imgPic.Height, GraphicsUnit.Pixel, iaPic);\n gfxPic.Dispose();\n return bmpPic;\n }\n}\n</code></pre>\n\n<p>The advantages to using this technique are :</p>\n\n<ul>\n<li>You won't have to handle all of the mouse events</li>\n<li>You won't have to manage multiple forms to communicate with the lightbox elements</li>\n<li>No overriding of WndProc</li>\n<li>You'll be cool because you'll be the only one not to use forms to achieve this effect.</li>\n</ul>\n\n<p>Drawbacks are mainly that this technique is much slower because you have to process an entire image to correct each pixel point using the ColorMatrix.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6199/"
]
| I want to simulate a 'Web 2.0' Lightbox style UI technique in a [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) application. That is, to draw attention to some foreground control by 'dimming' all other content in the client area of a window.
The obvious solution is to create a control that is simply a partially transparent rectangle that can be docked to the client area of a window and brought to the front of the Z-Order. It needs to act like a dirty pain of glass through which the other controls can still be seen (and therefore continue to paint themselves). Is this possible?
I've had a good hunt round and tried a few techniques myself but thus far have been unsuccessful.
If it is not possible, what would be another way to do it?
See: <http://www.useit.com/alertbox/application-design.html> (under the Lightbox section for a screenshot to illustrate what I mean.) | Can you do this in .NET/C#?
Yes you certainly can but it takes a little bit of effort. I would recommend the following approach. Create a top level Form that has no border or titlebar area and then give make sure it draws no client area background by setting the TransparencyKey and BackColor to the same value. So you now have a window that draws nothing...
```
public class DarkenArea : Form
{
public DarkenArea()
{
FormBorderStyle = FormBorderStyle.None;
SizeGripStyle = SizeGripStyle.Hide;
StartPosition = FormStartPosition.Manual;
MaximizeBox = false;
MinimizeBox = false;
ShowInTaskbar = false;
BackColor = Color.Magenta;
TransparencyKey = Color.Magenta;
Opacity = 0.5f;
}
}
```
Create and position this DarkenArea window over the client area of your form. Then you need to be able to show the window without it taking the focus and so you will need to platform invoke in the following way to show without it becoming active...
```
public void ShowWithoutActivate()
{
// Show the window without activating it (i.e. do not take focus)
PlatformInvoke.ShowWindow(this.Handle, (short)SW_SHOWNOACTIVATE);
}
```
You need to make it actually draw something but exclude drawing in the area of the control you want to remain highlighted. So override the OnPaint handler and draw in black/blue or whatever you want but excluding the area you want to remain bright...
```
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// Do your painting here be exclude the area you want to be brighter
}
```
Last you need to override the WndProc to prevent the mouse interacting with the window if the user tries something crazy like clicking on the darkened area. Something like this...
```
protected override void WndProc(ref Message m)
{
if (m.Msg == (int)WM_NCHITTEST)
m.Result = (IntPtr)HTTRANSPARENT;
else
base.WndProc(ref m);
}
```
That should be enough to get the desired effect. When you are ready to reverse the effect you dispose of the DarkenArea instance and carry on. |
72,996 | <p>I am creating an installer in IzPack. It is quite large, and I have broken up my XML files appropriately using <xinclude> and <xfragment> tags. Unfortunately, IzPack does not combine them together when you build your installer. This requires you to package the files with the installer, which just won't work. </p>
<p>I was about to start writing a tool in Java to load the XML files and combine them, but I don't want to go reinventing the wheel. </p>
<p>Do the Java XML libraries provide native handling of xinclude? A google didn't seem to turn up much. </p>
<p>Not a big deal if I have to write this myself, just wanted to check with you guys. Thanks.</p>
<p>Format of XML for example purposes:
File1.xml</p>
<pre><code><?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>
<installation version="1.0">
<packs>
<pack name="Transaction Service" id="Transaction Service" required="no" >
<xinclude href="example/File2.xml" />
</pack>
</packs>
</code></pre>
<p>File2.xml</p>
<pre><code><xfragment>
<file src="..." />
</xfragment>
</code></pre>
<p>File2 does not need the standard XML header. The xml file is parsed at build time, because the resources it specifies are included in the installer. What isn't included is the actual XML information (order to write the files, where to put them etc.)</p>
<p>What I am looking to have produced:</p>
<pre><code><?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>
<installation version="1.0">
<packs>
<pack name="Transaction Service" id="Transaction Service" required="no" >
<file src="..." />
</pack>
</packs>
</code></pre>
<p>Thanks, I am going to start whipping it together in Java now, but hopefully someone has a simple answer. </p>
<p>Tim Reynolds</p>
| [
{
"answer_id": 73306,
"author": "Paul de Vrieze",
"author_id": 4100,
"author_profile": "https://Stackoverflow.com/users/4100",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure if java supports automatic xinclude. But you will have to use namespaces to make it work. So don't use <code><xinclude ....></code>, but use: </p>\n\n<pre><code><xi:xinclude xmlns:xi=\"http://www.w3.org/2001/XInclude\" href=\"example/File2.xml\" />\n</code></pre>\n\n<p>Normally the included file should still contain the xml header as well. There is no requirement for it to e.g. have the same encoding.</p>\n"
},
{
"answer_id": 74275,
"author": "Brian Agnew",
"author_id": 12960,
"author_profile": "https://Stackoverflow.com/users/12960",
"pm_score": 1,
"selected": false,
"text": "<p>If you can't get xinclude to work and you're using Ant, I'd recommend <a href=\"http://www.oopsconsultancy.com/software/xmltask\" rel=\"nofollow noreferrer\">XMLTask</a>, which is a plugin task for Ant. It'll do lots of clever stuff, including the one thing you're interested in - constructing a XML file out of fragments.</p>\n\n<p>e.g.</p>\n\n<pre><code><xmltask source=\"templatefile.xml\" dest=\"finalfile.xml\">\n <insert path=\"/packs/pack[1]\" position=\"under\" file=\"pack1.xml\"/>\n</xmltask>\n</code></pre>\n\n<p>(warning- the above is done from memory so please consult the documentation!).</p>\n\n<p>Note that in the above, the file <em>pack1.xm</em>l doesn't have to have a root node.</p>\n"
},
{
"answer_id": 534077,
"author": "mattwright",
"author_id": 33106,
"author_profile": "https://Stackoverflow.com/users/33106",
"pm_score": 0,
"selected": false,
"text": "<p>Apache Xerces, for example, should support Xinclude, but you will need to enable it.</p>\n\n<p><a href=\"http://xerces.apache.org/xerces2-j/faq-xinclude.html\" rel=\"nofollow noreferrer\">http://xerces.apache.org/xerces2-j/faq-xinclude.html</a></p>\n\n<pre><code>import javax.xml.parsers.SAXParserFactory;\n\nSAXParserFactory spf = SAXParserFactory.newInstance();\nspf.setNamespaceAware(true);\nspf.setXIncludeAware(true);\n</code></pre>\n\n<p>Their documentation also says you can enable it as a <a href=\"http://xerces.apache.org/xerces2-j/features.html#xinclude\" rel=\"nofollow noreferrer\">feature</a></p>\n"
},
{
"answer_id": 1302238,
"author": "denny",
"author_id": 159557,
"author_profile": "https://Stackoverflow.com/users/159557",
"pm_score": 0,
"selected": false,
"text": "<p>This works now:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"iso-8859-1\" standalone=\"yes\" ?>\n<installation version=\"1.0\">\n<packs> \n <pack name=\"Transaction Service\" id=\"Transaction Service\" required=\"no\" >\n <xi:include href=\"example/File2.xml\" xmlns:xi=\"http://www.w3.org/2001/XInclude\" />\n </pack>\n</packs>\n</code></pre>\n\n<p>example/File2.xml</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"iso-8859-1\" standalone=\"yes\" ?>\n<xfragment>\n <file src=\"...\" />\n</xfragment>\n</code></pre>\n"
},
{
"answer_id": 27536996,
"author": "matfud",
"author_id": 4372321,
"author_profile": "https://Stackoverflow.com/users/4372321",
"pm_score": 0,
"selected": false,
"text": "<p>Just for anyone who wants to know. IzPack used nanoXML to parse all config files. It does not have namespaces. And does not handle xml includes.</p>\n\n<p>To resolve an issue I had I added the \"xinclude\" etc (fragment/fallback) element to the parser stuff so that it that mostly followed the standards for x:include (notice the name difference?) One is correct and has a namespace. The other is a nasty hack that pretends to follow the standard without using namespaces.</p>\n\n<p>Anyway this is long ago and now IzPack uses a sane XML parser and understands if you do it correctly xi:include or whatever prefix you wish to use there are no problems. It is standard in decent xml parsers.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/72996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am creating an installer in IzPack. It is quite large, and I have broken up my XML files appropriately using <xinclude> and <xfragment> tags. Unfortunately, IzPack does not combine them together when you build your installer. This requires you to package the files with the installer, which just won't work.
I was about to start writing a tool in Java to load the XML files and combine them, but I don't want to go reinventing the wheel.
Do the Java XML libraries provide native handling of xinclude? A google didn't seem to turn up much.
Not a big deal if I have to write this myself, just wanted to check with you guys. Thanks.
Format of XML for example purposes:
File1.xml
```
<?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>
<installation version="1.0">
<packs>
<pack name="Transaction Service" id="Transaction Service" required="no" >
<xinclude href="example/File2.xml" />
</pack>
</packs>
```
File2.xml
```
<xfragment>
<file src="..." />
</xfragment>
```
File2 does not need the standard XML header. The xml file is parsed at build time, because the resources it specifies are included in the installer. What isn't included is the actual XML information (order to write the files, where to put them etc.)
What I am looking to have produced:
```
<?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>
<installation version="1.0">
<packs>
<pack name="Transaction Service" id="Transaction Service" required="no" >
<file src="..." />
</pack>
</packs>
```
Thanks, I am going to start whipping it together in Java now, but hopefully someone has a simple answer.
Tim Reynolds | If you can't get xinclude to work and you're using Ant, I'd recommend [XMLTask](http://www.oopsconsultancy.com/software/xmltask), which is a plugin task for Ant. It'll do lots of clever stuff, including the one thing you're interested in - constructing a XML file out of fragments.
e.g.
```
<xmltask source="templatefile.xml" dest="finalfile.xml">
<insert path="/packs/pack[1]" position="under" file="pack1.xml"/>
</xmltask>
```
(warning- the above is done from memory so please consult the documentation!).
Note that in the above, the file *pack1.xm*l doesn't have to have a root node. |
73,000 | <p>I have to write an applet that brings up a password dialog. The problem is that dialog is set to be always on top but when user clicks on IE window dialog gets hidden behind IE window nevertheless. And since dialog is modal and holds <strong>all</strong> IE threads IE pane does not refresh and dialog window is still painted on top of IE (but not refreshed). This behaviour confuses users (they <em>see</em> dialog on top of IE but it looks like it has hanged since it is not refreshe). </p>
<p>So I need a way to keep that dialog on top of everything. But any other solution to this problem would be nice. </p>
<p>Here's the code:</p>
<pre><code> PassDialog dialog = new PassDialog(parent);
/* do some non gui related initialization */
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
</code></pre>
<p>Resolution: As @shemnon noted I should make a window instead of (null, Frame, Applet) parent of modal dialog. So good way to initlialize parent was: </p>
<pre><code>parent = javax.swing.SwingUtilities.getWindowAncestor(theApplet);
</code></pre>
| [
{
"answer_id": 73214,
"author": "noah",
"author_id": 12034,
"author_profile": "https://Stackoverflow.com/users/12034",
"pm_score": 0,
"selected": false,
"text": "<p>You might try launching a modal from JavaScript using the JavaScript integration (see <a href=\"http://www.raditha.com/java/mayscript.php\" rel=\"nofollow noreferrer\">http://www.raditha.com/java/mayscript.php</a> for an example). </p>\n\n<p>The JavaScript you would need would be something like:</p>\n\n<pre><code>function getPassword() {\n return prompt(\"Enter Password\");\n}\n</code></pre>\n\n<p>And the Java would be:</p>\n\n<pre><code>password = jso.call(\"getPassword\", new String[0]);\n</code></pre>\n\n<p>Unfortunately that means giving up all hope of having a nice looking modal. Good luck!</p>\n"
},
{
"answer_id": 73525,
"author": "James A. N. Stauffer",
"author_id": 6770,
"author_profile": "https://Stackoverflow.com/users/6770",
"pm_score": 1,
"selected": false,
"text": "<p>Make a background Thread that calls toFront on the Dialog every 2 seconds.\nCode that we use (I hope I got everything):</p>\n\n<pre><code>class TestClass {\nprotected void toFrontTimer(JFrame frame) {\n try {\n bringToFrontTimer = new java.util.Timer();\n bringToFrontTask = new BringToFrontTask(frame);\n bringToFrontTimer.schedule( bringToFrontTask, 300, 300);\n } catch (Throwable t) {\n t.printStackTrace();\n }\n}\n\nclass BringToFrontTask extends TimerTask {\n private Frame frame;\n public BringToFrontTask(Frame frame) {\n this.frame = frame;\n }\n public void run()\n {\n if(count < 2) {\n frame.toFront();\n } else {\n cancel();\n }\n count ++;\n }\n private int count = 0;\n}\n\npublic void cleanup() {\n if(bringToFrontTask != null) {\n bringToFrontTask.cancel();\n bringToFrontTask = null;\n }\n if(bringToFrontTimer != null) {\n bringToFrontTimer = null;\n }\n}\n\njava.util.Timer bringToFrontTimer = null;\njava.util.TimerTask bringToFrontTask = null;\n}\n</code></pre>\n"
},
{
"answer_id": 73615,
"author": "Joel Anair",
"author_id": 7441,
"author_profile": "https://Stackoverflow.com/users/7441",
"pm_score": 1,
"selected": false,
"text": "<p>This is a shot in the dark as I'm not familiar with applets, but you could take a look at IE's built-in window.showModalDialog method. It's fairly easy to use. Maybe a combination of this and Noah's suggestion?</p>\n"
},
{
"answer_id": 93914,
"author": "shemnon",
"author_id": 8020,
"author_profile": "https://Stackoverflow.com/users/8020",
"pm_score": 2,
"selected": true,
"text": "<p>What argument are you using for the parent?</p>\n\n<p>You may have better luck if you use the parent of the Applet.</p>\n\n<pre><code>javax.swing.SwingUtilities.getWindowAncestor(theApplet)\n</code></pre>\n\n<p>Using the getWindowAncestor will skip the applet parents (getRoot(component) will return applets). In at least some versions of Java there was a Frame that was equivalent to the IE window. YMMV.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7918/"
]
| I have to write an applet that brings up a password dialog. The problem is that dialog is set to be always on top but when user clicks on IE window dialog gets hidden behind IE window nevertheless. And since dialog is modal and holds **all** IE threads IE pane does not refresh and dialog window is still painted on top of IE (but not refreshed). This behaviour confuses users (they *see* dialog on top of IE but it looks like it has hanged since it is not refreshe).
So I need a way to keep that dialog on top of everything. But any other solution to this problem would be nice.
Here's the code:
```
PassDialog dialog = new PassDialog(parent);
/* do some non gui related initialization */
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
```
Resolution: As @shemnon noted I should make a window instead of (null, Frame, Applet) parent of modal dialog. So good way to initlialize parent was:
```
parent = javax.swing.SwingUtilities.getWindowAncestor(theApplet);
``` | What argument are you using for the parent?
You may have better luck if you use the parent of the Applet.
```
javax.swing.SwingUtilities.getWindowAncestor(theApplet)
```
Using the getWindowAncestor will skip the applet parents (getRoot(component) will return applets). In at least some versions of Java there was a Frame that was equivalent to the IE window. YMMV. |
73,024 | <p>This is from an example accompanying the agsXMPP .Net assembly. I've read up on delegates, but am not sure how that fits in with this line of code (which waits for the logon to occur, and then sends a message. I guess what I'm looking for is an understanding of why <code>delegate(0)</code> accomplishes this, in the kind of simple terms I can understand.</p>
<pre><code>xmpp.OnLogin += delegate(object o) {
xmpp.Send(new Message(new Jid(JID_RECEIVER),
MessageType.chat,
"Hello, how are you?"));
};
</code></pre>
| [
{
"answer_id": 73040,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": 0,
"selected": false,
"text": "<p>That is creating an anonymous function. This feature was introduced in C# 2.0</p>\n"
},
{
"answer_id": 73066,
"author": "André Chalella",
"author_id": 4850,
"author_profile": "https://Stackoverflow.com/users/4850",
"pm_score": 0,
"selected": false,
"text": "<p>It serves as an anonymous method, so you don't need to declare it somewhere else. It's very useful.</p>\n\n<p>What it does in that case is to attach that method to the list of actions that are triggered because of the <code>onLogin</code> event.</p>\n"
},
{
"answer_id": 73069,
"author": "juan",
"author_id": 1782,
"author_profile": "https://Stackoverflow.com/users/1782",
"pm_score": 2,
"selected": false,
"text": "<p>It's exactly the same as</p>\n\n<pre><code>xmpp.OnLogin += EventHandler(MyMethod);\n</code></pre>\n\n<p>Where MyMethod is</p>\n\n<pre><code>public void MyMethod(object o) \n{ \n xmpp.Send(new Message(new Jid(JID_RECEIVER), MessageType.chat, \"Hello, how are you?\")); \n}\n</code></pre>\n"
},
{
"answer_id": 73083,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": 2,
"selected": true,
"text": "<p>The <code>delegate(object o){..}</code> tells the compiler to package up whatever is inside the brackets as an object to be executed later, in this case when <code>OnLogin</code> is fired. Without the <code>delegate()</code> statement, the compiler would think you are tying to execute an action in the middle of an assignemnt statement and give you errors.</p>\n"
},
{
"answer_id": 73088,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 0,
"selected": false,
"text": "<p>Agreed with Abe, this is an anonymous method. An anonymous method is just that -- a method without a name, which can be supplied as a parameter argument.</p>\n\n<p>Obviously the OnLogin object is an Event; using an += operator ensures that the method specified by the anonymous delegate above is executed whenever the OnLogin event is raised.</p>\n"
},
{
"answer_id": 73092,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 0,
"selected": false,
"text": "<p>Basically, the code inside the {} will run when the \"OnLogin\" event of the xmpp event is fired. Based on the name, I'd guess that event fires at some point during the login process.</p>\n\n<p>The syntax:</p>\n\n<pre><code>delegate(object o) { statements; }\n</code></pre>\n\n<p>is a called an anonymous method. The code in your question would be equivilent to this:</p>\n\n<pre><code>public class MyClass\n{\n private XMPPObjectType xmpp;\n public void Main()\n {\n xmpp.OnLogin += MyMethod;\n }\n private void MyMethod(object o)\n {\n xmpp.Send(new Message(new Jid(JID_RECEIVER), MessageType.chat, \"Hello, how are you?\"));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 73103,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>You are subscribing to the OnLogin event in xmpp.</p>\n\n<p>This means that when xmpp fires this event, the code inside the anonymous delegate will fire. Its an elegant way to have callbacks.</p>\n\n<p>In Xmpp, something like this is going on:</p>\n\n<pre><code> // Check to see if we should fire the login event\n // ALso check to see if anything is subscribed to OnLogin \n // (It will be null otherwise)\n if (loggedIn && OnLogin != null)\n {\n // Anyone subscribed will now receive the event.\n OnLogin(this);\n }\n</code></pre>\n"
},
{
"answer_id": 73137,
"author": "Remi Despres-Smyth",
"author_id": 8169,
"author_profile": "https://Stackoverflow.com/users/8169",
"pm_score": 2,
"selected": false,
"text": "<p>As Abe noted, this code is creating an anonymous function. This:</p>\n\n<pre><code>\nxmpp.OnLogin += delegate(object o) \n { \n xmpp.Send(\n new Message(new Jid(JID_RECEIVER), MessageType.chat, \"Hello, how are you?\")); \n };\n</code></pre>\n\n<p>would have been accomplished as follows in older versions of .Net (I've excluded class declarations and such, and just kept the essential elements):</p>\n\n<pre><code>\ndelegate void OnLoginEventHandler(object o);\n\npublic void MyLoginEventHandler(object o)\n{\n xmpp.Send(\n new Message(new Jid(JID_RECEIVER), MessageType.chat, \"Hello, how are you?\")); \n}\n\n[...]\n\nxmpp.OnLogin += new OnLoginEventHandler(MyLoginEventHandler);\n</code></pre>\n\n<p>What you're doing in either case is associating a method of yours to run when the xmpp OnLogin event is fired.</p>\n"
},
{
"answer_id": 73254,
"author": "Romain Verdier",
"author_id": 4687,
"author_profile": "https://Stackoverflow.com/users/4687",
"pm_score": 2,
"selected": false,
"text": "<p><code>OnLogin</code> on xmpp is probably an event declared like this :</p>\n\n<pre><code>public event LoginEventHandler OnLogin;\n</code></pre>\n\n<p>where <code>LoginEventHandler</code> is as delegate type probably declared as :</p>\n\n<pre><code>public delegate void LoginEventHandler(Object o);\n</code></pre>\n\n<p>That means that in order to subscribe to the event, you need to provide a method (or an <a href=\"http://msdn.microsoft.com/en-us/library/0yw3tz5k(VS.80).aspx\" rel=\"nofollow noreferrer\">anonymous method</a> / <a href=\"http://msdn.microsoft.com/en-us/library/bb397687.aspx\" rel=\"nofollow noreferrer\">lambda expression</a>) which match the <code>LoginEventHandler</code> delegate signature.</p>\n\n<p>In your example, you pass an anonymous method using the <code>delegate</code> keyword:</p>\n\n<pre><code>xmpp.OnLogin += delegate(object o)\n { \n xmpp.Send(new Message(new Jid(JID_RECEIVER), \n MessageType.chat,\n \"Hello, how are you?\")); \n };\n</code></pre>\n\n<p>The anonymous method matches the delegate signature expected by the <code>OnLogin</code> event (void return type + one object argument). You could also remove the <code>object o</code> parameter leveraging the <a href=\"http://msdn.microsoft.com/en-us/library/ms173174(VS.80).aspx\" rel=\"nofollow noreferrer\">contravariance</a>, since it is not used inside the anonymous method body.</p>\n\n<pre><code>xmpp.OnLogin += delegate\n { \n xmpp.Send(new Message(new Jid(JID_RECEIVER), \n MessageType.chat,\n \"Hello, how are you?\")); \n };\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7574/"
]
| This is from an example accompanying the agsXMPP .Net assembly. I've read up on delegates, but am not sure how that fits in with this line of code (which waits for the logon to occur, and then sends a message. I guess what I'm looking for is an understanding of why `delegate(0)` accomplishes this, in the kind of simple terms I can understand.
```
xmpp.OnLogin += delegate(object o) {
xmpp.Send(new Message(new Jid(JID_RECEIVER),
MessageType.chat,
"Hello, how are you?"));
};
``` | The `delegate(object o){..}` tells the compiler to package up whatever is inside the brackets as an object to be executed later, in this case when `OnLogin` is fired. Without the `delegate()` statement, the compiler would think you are tying to execute an action in the middle of an assignemnt statement and give you errors. |
73,029 | <p>I try to use the Forms-Based authentication within an embedded Jetty 6.1.7 project.</p>
<p>That's why I need to serve servlets and html (login.html) under the same context
to make authentication work. I don't want to secure the hole application since
different context should need different roles. The jetty javadoc states that a
ContextHandlerCollection can handle different handlers for one context but I don't
get it to work. My sample ignoring the authentication stuff will not work, why?</p>
<pre><code>ContextHandlerCollection contexts = new ContextHandlerCollection();
// serve html
Context ctxADocs= new Context(contexts,"/ctxA",Context.SESSIONS);
ctxADocs.setResourceBase("d:\\tmp\\ctxA");
ServletHolder ctxADocHolder= new ServletHolder();
ctxADocHolder.setInitParameter("dirAllowed", "false");
ctxADocHolder.setServlet(new DefaultServlet());
ctxADocs.addServlet(ctxADocHolder, "/");
// serve a sample servlet
Context ctxA = new Context(contexts,"/ctxA",Context.SESSIONS);
ctxA.addServlet(new ServletHolder(new SessionDump()), "/sda");
ctxA.addServlet(new ServletHolder(new DefaultServlet()), "/");
contexts.setHandlers(new Handler[]{ctxA, ctxADocs});
// end of snippet
</code></pre>
<p>Any helpful thought is welcome!</p>
<p>Thanks.</p>
<p>Okami</p>
| [
{
"answer_id": 91072,
"author": "Eduard Wirch",
"author_id": 17428,
"author_profile": "https://Stackoverflow.com/users/17428",
"pm_score": 1,
"selected": false,
"text": "<p>Use the web application descriptor:</p>\n\n<p>Paste this in to your web.xml:</p>\n\n<pre><code><login-config>\n <auth-method>BASIC</auth-method>\n</login-config>\n<security-role>\n <role-name>MySiteRole</role-name>\n</security-role>\n\n<security-constraint>\n <display-name>ProtectEverything</display-name>\n <web-resource-collection>\n <web-resource-name>ProtectEverything</web-resource-name>\n <url-pattern>*.*</url-pattern>\n <url-pattern>/*</url-pattern>\n </web-resource-collection>\n <auth-constraint>\n <role-name>MySiteRole</role-name>\n </auth-constraint>\n</security-constraint>\n\n<security-constraint>\n <web-resource-collection>\n <web-resource-name>ExcludeLoginPage</web-resource-name>\n <url-pattern>/login.html</url-pattern>\n </web-resource-collection>\n <user-data-constraint>\n <transport-guarantee>NONE</transport-guarantee>\n </user-data-constraint>\n</security-constraint>\n</code></pre>\n\n<p>Without authentication this will hide everything but the login.html.</p>\n"
},
{
"answer_id": 114336,
"author": "Okami",
"author_id": 11450,
"author_profile": "https://Stackoverflow.com/users/11450",
"pm_score": 2,
"selected": false,
"text": "<p>Finally I got it right, solution is to use latest jetty 6.1.12 rc2.\nI didn't check out what they changed - I'm just happy that it works now.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11450/"
]
| I try to use the Forms-Based authentication within an embedded Jetty 6.1.7 project.
That's why I need to serve servlets and html (login.html) under the same context
to make authentication work. I don't want to secure the hole application since
different context should need different roles. The jetty javadoc states that a
ContextHandlerCollection can handle different handlers for one context but I don't
get it to work. My sample ignoring the authentication stuff will not work, why?
```
ContextHandlerCollection contexts = new ContextHandlerCollection();
// serve html
Context ctxADocs= new Context(contexts,"/ctxA",Context.SESSIONS);
ctxADocs.setResourceBase("d:\\tmp\\ctxA");
ServletHolder ctxADocHolder= new ServletHolder();
ctxADocHolder.setInitParameter("dirAllowed", "false");
ctxADocHolder.setServlet(new DefaultServlet());
ctxADocs.addServlet(ctxADocHolder, "/");
// serve a sample servlet
Context ctxA = new Context(contexts,"/ctxA",Context.SESSIONS);
ctxA.addServlet(new ServletHolder(new SessionDump()), "/sda");
ctxA.addServlet(new ServletHolder(new DefaultServlet()), "/");
contexts.setHandlers(new Handler[]{ctxA, ctxADocs});
// end of snippet
```
Any helpful thought is welcome!
Thanks.
Okami | Finally I got it right, solution is to use latest jetty 6.1.12 rc2.
I didn't check out what they changed - I'm just happy that it works now. |
73,032 | <p>I'd really like to handle this without monkey-patching but I haven't been able to find another option yet.</p>
<p>I have an array (in Ruby) that I need to sort by multiple conditions. I know how to use the sort method and I've used the trick on sorting using an array of options to sort by multiple conditions. However, in this case I need the first condition to sort ascending and the second to sort descending. For example:</p>
<pre><code>ordered_list = [[1, 2], [1, 1], [2, 1]]
</code></pre>
<p>Any suggestions?</p>
<p>Edit: Just realized I should mention that I can't easily compare the first and second values (I'm actually working with object attributes here). So for a simple example it's more like:</p>
<pre><code>ordered_list = [[1, "b"], [1, "a"], [2, "a"]]
</code></pre>
| [
{
"answer_id": 73090,
"author": "Brian Phillips",
"author_id": 7230,
"author_profile": "https://Stackoverflow.com/users/7230",
"pm_score": 6,
"selected": true,
"text": "<p>How about:</p>\n\n<pre>\n<code>\nordered_list = [[1, \"b\"], [1, \"a\"], [2, \"a\"]]\nordered_list.sort! do |a,b|\n [a[0],b[1]] <=> [b[0], a[1]]\nend\n</code>\n</pre>\n"
},
{
"answer_id": 73496,
"author": "glenn mcdonald",
"author_id": 7919,
"author_profile": "https://Stackoverflow.com/users/7919",
"pm_score": 2,
"selected": false,
"text": "<p>I had this same basic problem, and solved it by adding this:</p>\n\n<pre><code>class Inverter\n attr_reader :o\n\n def initialize(o)\n @o = o\n end\n\n def <=>(other)\n if @o.is && other.o.is\n -(@o <=> other.o)\n else\n @o <=> other.o\n end\n end\nend\n</code></pre>\n\n<p>This is a wrapper that simply inverts the <=> function, which then allows you to do things like this:</p>\n\n<pre><code>your_objects.sort_by {|y| [y.prop1,Inverter.new(y.prop2)]}\n</code></pre>\n"
},
{
"answer_id": 76148,
"author": "mislav",
"author_id": 11687,
"author_profile": "https://Stackoverflow.com/users/11687",
"pm_score": 2,
"selected": false,
"text": "<p><code>Enumerable#multisort</code> is a generic solution that can be applied to arrays of <strong>any size</strong>, not just those with 2 items. Arguments are booleans that indicate whether a specific field should be sorted ascending or descending (usage below):</p>\n\n<pre><code>items = [\n [3, \"Britney\"],\n [1, \"Corin\"],\n [2, \"Cody\"],\n [5, \"Adam\"],\n [1, \"Sally\"],\n [2, \"Zack\"],\n [5, \"Betty\"]\n]\n\nmodule Enumerable\n def multisort(*args)\n sort do |a, b|\n i, res = -1, 0\n res = a[i] <=> b[i] until !res.zero? or (i+=1) == a.size\n args[i] == false ? -res : res\n end\n end\nend\n\nitems.multisort(true, false)\n# => [[1, \"Sally\"], [1, \"Corin\"], [2, \"Zack\"], [2, \"Cody\"], [3, \"Britney\"], [5, \"Betty\"], [5, \"Adam\"]]\nitems.multisort(false, true)\n# => [[5, \"Adam\"], [5, \"Betty\"], [3, \"Britney\"], [2, \"Cody\"], [2, \"Zack\"], [1, \"Corin\"], [1, \"Sally\"]]\n</code></pre>\n"
},
{
"answer_id": 3275140,
"author": "Alex Fortuna",
"author_id": 243424,
"author_profile": "https://Stackoverflow.com/users/243424",
"pm_score": 2,
"selected": false,
"text": "<p>I've been using Glenn's recipe for quite a while now. Tired of copying code from project to project over and over again, I've decided to make it a gem:</p>\n\n<p><a href=\"http://github.com/dadooda/invert\" rel=\"nofollow noreferrer\">http://github.com/dadooda/invert</a></p>\n"
},
{
"answer_id": 11320778,
"author": "TwoByteHero",
"author_id": 1311787,
"author_profile": "https://Stackoverflow.com/users/1311787",
"pm_score": 3,
"selected": false,
"text": "<p>I was having a nightmare of a time trying to figure out how to reverse sort a specific attribute but normally sort the other two. Just a note about the sorting for those that come along after this and are confused by the |a,b| block syntax. You cannot use the <code>{|a,b| a.blah <=> b.blah}</code> block style with <code>sort_by!</code> or <code>sort_by</code>. It must be used with <code>sort!</code> or <code>sort</code>. Also, as indicated previously by the other posters swap <code>a</code> and <code>b</code> across the comparison operator <code><=></code> to reverse the sort order. Like this:</p>\n\n<p>To sort by blah and craw normally, but sort by bleu in reverse order do this:</p>\n\n<pre><code>something.sort!{|a,b| [a.blah, b.bleu, a.craw] <=> [b.blah, a.bleu, b.craw]}\n</code></pre>\n\n<p>It is also possible to use the <code>-</code> sign with <code>sort_by</code> or <code>sort_by!</code> to do a reverse sort on numerals (as far as I am aware it only works on numbers so don't try it with strings as it just errors and kills the page). </p>\n\n<p>Assume <code>a.craw</code> is an integer. For example:</p>\n\n<pre><code>something.sort_by!{|a| [a.blah, -a.craw, a.bleu]}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3230/"
]
| I'd really like to handle this without monkey-patching but I haven't been able to find another option yet.
I have an array (in Ruby) that I need to sort by multiple conditions. I know how to use the sort method and I've used the trick on sorting using an array of options to sort by multiple conditions. However, in this case I need the first condition to sort ascending and the second to sort descending. For example:
```
ordered_list = [[1, 2], [1, 1], [2, 1]]
```
Any suggestions?
Edit: Just realized I should mention that I can't easily compare the first and second values (I'm actually working with object attributes here). So for a simple example it's more like:
```
ordered_list = [[1, "b"], [1, "a"], [2, "a"]]
``` | How about:
```
ordered_list = [[1, "b"], [1, "a"], [2, "a"]]
ordered_list.sort! do |a,b|
[a[0],b[1]] <=> [b[0], a[1]]
end
``` |
73,037 | <p>This is a 3 part question regarding embedded RegEx into SQL statements. </p>
<ol>
<li><p>How do you embed a RegEx expression into an Oracle PL/SQL
select statement that will parse out
the “DELINQUENT” string in the text
string shown below?</p></li>
<li><p>What is the performance impact if used within a
mission critical business
transaction?</p></li>
<li><p>Since embedding regex
into SQL was introduced in Oracle
10g and SQL Server 2005, is it
considered a recommended practice?</p></li>
</ol>
<hr>
<p>Dear Larry :</p>
<p>Thank you for using ABC's alert service.</p>
<p>ABC has detected a change in the status of one of your products in the state of KS. Please review the
information below to determine if this status change was intended.</p>
<p>ENTITY NAME: Oracle Systems, LLC</p>
<p>PREVIOUS STATUS: --</p>
<p>CURRENT STATUS: DELINQUENT</p>
<p>As a reminder, you may contact your the ABC Team for assistance in correcting any delinquencies or, if needed, reinstating
the service. Alternatively, if the system does not intend to continue to engage this state, please notify ABC
so that we can discontinue our services.</p>
<p>Kind regards,</p>
<p>Service Team 1
ABC</p>
<p>--PLEASE DO NOT REPLY TO THIS EMAIL. IT IS NOT A MONITORED EMAIL ACCOUNT.--</p>
<p>Notice: ABC Corporation cannot independently verify the timeliness, accuracy, or completeness of the public information
maintained by the responsible government agency or other sources of data upon which these alerts are based.</p>
| [
{
"answer_id": 73084,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 0,
"selected": false,
"text": "<p>Why not just use INSTR (for Oracle) or CHARINDEX (for SQL Server) combined with SUBSTRING? Seems a bit more straightforward (and portable, since it's supported in older versions).</p>\n\n<p><a href=\"http://www.techonthenet.com/oracle/functions/instr.php\" rel=\"nofollow noreferrer\">http://www.techonthenet.com/oracle/functions/instr.php</a> and <a href=\"http://www.adp-gmbh.ch/ora/sql/substr.html\" rel=\"nofollow noreferrer\">http://www.adp-gmbh.ch/ora/sql/substr.html</a></p>\n\n<p><a href=\"http://www.databasejournal.com/features/mssql/article.php/3071531\" rel=\"nofollow noreferrer\">http://www.databasejournal.com/features/mssql/article.php/3071531</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms187748.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms187748.aspx</a></p>\n"
},
{
"answer_id": 73336,
"author": "Gary Russo",
"author_id": 3048,
"author_profile": "https://Stackoverflow.com/users/3048",
"pm_score": 0,
"selected": false,
"text": "<p>INSTR and CHARINDEX are great alternative approaches but I'd like to explore the benefits of embedding Regex.</p>\n"
},
{
"answer_id": 74827,
"author": "WIDBA",
"author_id": 10868,
"author_profile": "https://Stackoverflow.com/users/10868",
"pm_score": 0,
"selected": false,
"text": "<p>In MS SQL you can use LIKE which has some \"pattern matching\" in it. I would guess Oracle has something similar. Its not Regex, but has some of the matching capabilities. (Note: its not particularly fast).. Fulltext searching could also be an option (again MS SQL) (probably a much faster way in the context of a good sized database)</p>\n"
},
{
"answer_id": 78318,
"author": "Sergey Stadnik",
"author_id": 10557,
"author_profile": "https://Stackoverflow.com/users/10557",
"pm_score": 2,
"selected": true,
"text": "<p>Why would you need regular expressions here?\nINSTR and SUBSTR will do the job perfectly.</p>\n\n<p>But if you convinced you need Regex'es you can use:</p>\n\n<p><a href=\"http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions129.htm#i1239887\" rel=\"nofollow noreferrer\">REGEXP_INSTR</a><br>\n<a href=\"http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions130.htm#i1305521\" rel=\"nofollow noreferrer\">REGEXP_REPLACE</a><br>\n<a href=\"http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions131.htm#i1239858\" rel=\"nofollow noreferrer\">REGEXP_SUBSTR</a> </p>\n\n<p>(only available in Oracle 10g and up)</p>\n\n<pre><code>SELECT emp_id, text\n FROM employee_comment\n WHERE REGEXP_LIKE(text,'...-....');\n</code></pre>\n"
},
{
"answer_id": 152118,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 1,
"selected": false,
"text": "<p>If I recall correctly, it is possible to write a UDF in c#/vb for SQL Server. \nHere's a link, though possibly not the best: <a href=\"http://www.novicksoftware.com/coding-in-sql/Vol3/cis-v3-N13-dot-net-clr-in-sql-server.htm\" rel=\"nofollow noreferrer\">http://www.novicksoftware.com/coding-in-sql/Vol3/cis-v3-N13-dot-net-clr-in-sql-server.htm</a></p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3048/"
]
| This is a 3 part question regarding embedded RegEx into SQL statements.
1. How do you embed a RegEx expression into an Oracle PL/SQL
select statement that will parse out
the “DELINQUENT” string in the text
string shown below?
2. What is the performance impact if used within a
mission critical business
transaction?
3. Since embedding regex
into SQL was introduced in Oracle
10g and SQL Server 2005, is it
considered a recommended practice?
---
Dear Larry :
Thank you for using ABC's alert service.
ABC has detected a change in the status of one of your products in the state of KS. Please review the
information below to determine if this status change was intended.
ENTITY NAME: Oracle Systems, LLC
PREVIOUS STATUS: --
CURRENT STATUS: DELINQUENT
As a reminder, you may contact your the ABC Team for assistance in correcting any delinquencies or, if needed, reinstating
the service. Alternatively, if the system does not intend to continue to engage this state, please notify ABC
so that we can discontinue our services.
Kind regards,
Service Team 1
ABC
--PLEASE DO NOT REPLY TO THIS EMAIL. IT IS NOT A MONITORED EMAIL ACCOUNT.--
Notice: ABC Corporation cannot independently verify the timeliness, accuracy, or completeness of the public information
maintained by the responsible government agency or other sources of data upon which these alerts are based. | Why would you need regular expressions here?
INSTR and SUBSTR will do the job perfectly.
But if you convinced you need Regex'es you can use:
[REGEXP\_INSTR](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions129.htm#i1239887)
[REGEXP\_REPLACE](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions130.htm#i1305521)
[REGEXP\_SUBSTR](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions131.htm#i1239858)
(only available in Oracle 10g and up)
```
SELECT emp_id, text
FROM employee_comment
WHERE REGEXP_LIKE(text,'...-....');
``` |
73,039 | <p>In my web application there is a process that queries data from all over the web, filters it, and saves it to the database. As you can imagine this process takes some time. My current solution is to increase the page timeout and give an AJAX progress bar to the user while it loads. This is a problem for two reasons - 1) it still takes to long and the user must wait 2) it sometimes still times out.</p>
<p>I've dabbled in threading the process and have read I should async post it to a web service ("Fire and forget").</p>
<p>Some references I've read:<br>
- <a href="http://msdn.microsoft.com/en-us/library/ms978607.aspx#diforwc-ap02_plag_howtomultithread" rel="nofollow noreferrer">MSDN</a><br>
- <a href="http://aspalliance.com/329" rel="nofollow noreferrer">Fire and Forget</a></p>
<p>So my question is - what is the best method?</p>
<p>UPDATE: After the user inputs their data I would like to redirect them to the results page that incrementally updates as the process is running in the background.</p>
| [
{
"answer_id": 73082,
"author": "kemiller2002",
"author_id": 1942,
"author_profile": "https://Stackoverflow.com/users/1942",
"pm_score": 1,
"selected": false,
"text": "<p>I ran into this exact problem at my last job. The best way I found was to fire off an asychronous process, and notify the user when it's done (email or something else). Making them wait that long is going to be problematic because of timeouts and wasted productivity for them. Having them wait for a progress bar can give them false sense of security that they can cancel the process when they close the browser which may not be the case depending on how you set up the system. </p>\n"
},
{
"answer_id": 73148,
"author": "ahin4114",
"author_id": 11579,
"author_profile": "https://Stackoverflow.com/users/11579",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li>How are you querying the remote data?</li>\n<li>How often does it change?</li>\n<li>Are the results something that could be cached for a period of time?</li>\n<li>How long a period of time are we actually talking about here?</li>\n</ol>\n\n<p>The 'best method' is likely to depend in some way on the answers to these questions...</p>\n"
},
{
"answer_id": 73170,
"author": "wile.e.coyote",
"author_id": 12542,
"author_profile": "https://Stackoverflow.com/users/12542",
"pm_score": 2,
"selected": false,
"text": "<p>We had a similar issue and solved it by starting the work via an asychronous web service call (which meant that the user did not have to wait for the work to finish). The web service then started a SQL Job which performed the work and periodically updated a table with the status of the work. We provided a UI which allowed the user to query the table.</p>\n"
},
{
"answer_id": 73171,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can create another thread and store a reference to the thread in the session or application state, depending on wether the thread can run only once per website, or once per user session.<br />\nYou can then redirect the user to a page where he can monitor the threads progress. You can set the page to refresh automatically, or display a refresh button to the user.<br />\nUpon completion of the thread, you can send an email to the user.</p>\n"
},
{
"answer_id": 73177,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 0,
"selected": false,
"text": "<p>My solution to this, has been an out of band service that does these and caches them in db.</p>\n\n<p>When the person asks for something the first time, they get a bit of a wait, and then it shows up but if they refresh, its immediate, and then, because its int he db, its now part of the hourly update for the next 24 hours from the last request.</p>\n"
},
{
"answer_id": 73428,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 4,
"selected": true,
"text": "<p>To avoid excessive architecture astronomy, I often <a href=\"http://encosia.com/2007/10/03/easy-incremental-status-updates-for-long-requests/\" rel=\"nofollow noreferrer\">use a hidden iframe to call the long running process and stream back progress information</a>. Coupled with something like <a href=\"http://www.bram.us/demo/projects/jsprogressbarhandler/\" rel=\"nofollow noreferrer\">jsProgressBarHandler</a>, you can pretty easily create great out-of-band progress indication for longer tasks where a generic progress animation doesn't cut it.</p>\n\n<p>In your specific situation, you may want to use one LongRunningProcess.aspx call per task, to avoid those page timeouts. </p>\n\n<p>For example, call LongRunningProcess.aspx?taskID=1 to kick it off and then at the end of that task, emit a </p>\n\n<pre><code>document.location = \"LongRunningProcess.aspx?taskID=2\". \n</code></pre>\n\n<p>Ad nauseum.</p>\n"
},
{
"answer_id": 73485,
"author": "tbone",
"author_id": 8678,
"author_profile": "https://Stackoverflow.com/users/8678",
"pm_score": 0,
"selected": false,
"text": "<p>Add the job, with its relevant parameters, to a job queue table. Then, write a windows service that will pick up these jobs and process them, save the results to an appropriate location, and email the requester with a link to the results. It is also a nice touch to give some sort of a UI so the user can check the status of their job(s).</p>\n\n<p>This way is much better than launching a seperate thread or increasing the timeout, especially if your application is larger and needs to scale, as you can simply add multiple servers to process jobs if necessary.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12442/"
]
| In my web application there is a process that queries data from all over the web, filters it, and saves it to the database. As you can imagine this process takes some time. My current solution is to increase the page timeout and give an AJAX progress bar to the user while it loads. This is a problem for two reasons - 1) it still takes to long and the user must wait 2) it sometimes still times out.
I've dabbled in threading the process and have read I should async post it to a web service ("Fire and forget").
Some references I've read:
- [MSDN](http://msdn.microsoft.com/en-us/library/ms978607.aspx#diforwc-ap02_plag_howtomultithread)
- [Fire and Forget](http://aspalliance.com/329)
So my question is - what is the best method?
UPDATE: After the user inputs their data I would like to redirect them to the results page that incrementally updates as the process is running in the background. | To avoid excessive architecture astronomy, I often [use a hidden iframe to call the long running process and stream back progress information](http://encosia.com/2007/10/03/easy-incremental-status-updates-for-long-requests/). Coupled with something like [jsProgressBarHandler](http://www.bram.us/demo/projects/jsprogressbarhandler/), you can pretty easily create great out-of-band progress indication for longer tasks where a generic progress animation doesn't cut it.
In your specific situation, you may want to use one LongRunningProcess.aspx call per task, to avoid those page timeouts.
For example, call LongRunningProcess.aspx?taskID=1 to kick it off and then at the end of that task, emit a
```
document.location = "LongRunningProcess.aspx?taskID=2".
```
Ad nauseum. |
73,051 | <p>I need to run a stored procedure from a C# application.</p>
<p>I use the following code to do so:</p>
<pre><code>Process sqlcmdCall = new Process();
sqlcmdCall.StartInfo.FileName = "sqlcmd.exe";
sqlcmdCall.StartInfo.Arguments = "-S localhost\\SQLEXPRESS -d some_db -Q \":EXIT(sp_test)\""
sqlcmdCall.Start();
sqlcmdCall.WaitForExit();
</code></pre>
<p>From the sqlcmdCall object after the call completes, I currently get an ExitCode of -100 for success and of 1 for failure (i.e. missing parameter, stored proc does not exist, etc...).</p>
<p>How can I customize these return codes?</p>
<p>H.</p>
| [
{
"answer_id": 73108,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<p>If you are trying to call a stored procedure from c# you would want to use ADO.Net instead of the calling sqlcmd via the command line. Look at <code>SqlConnection</code> and <code>SqlCommand</code> in the <code>System.Data.SqlClient</code> namespace.</p>\n\n<p>Once you are calling the stored procedure via <code>SqlCommand</code> you will be able to catch an exception raised by the stored procedure as well we reading the return value of the procedure if you need to.</p>\n"
},
{
"answer_id": 73193,
"author": "Ron Savage",
"author_id": 12476,
"author_profile": "https://Stackoverflow.com/users/12476",
"pm_score": 2,
"selected": false,
"text": "<p>I have a small VB.Net app that executes system commands like that. To capture error or success conditions I define regular expressions to match the error text output from the command and I capture the output like this:</p>\n\n<pre><code> myprocess.Start()\n procReader = myprocess.StandardOutput()\n\n While (Not procReader.EndOfStream)\n procLine = procReader.ReadLine()\n\n If (MatchesRegEx(errRegEx, procLine)) Then\n writeDebug(\"Error reg ex: [\" + errorRegEx + \"] has matched: [\" + procLine + \"] setting hasError to true.\")\n\n Me.hasError = True\n End If\n\n writeLog(procLine)\n End While\n\n procReader.Close()\n\n myprocess.WaitForExit(CInt(waitTime))\n</code></pre>\n\n<p>That way I can capture specific errors and also log all the output from the command in case I run across an unexpected error.</p>\n"
},
{
"answer_id": 77400,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 0,
"selected": false,
"text": "<p>Even with windows authentication you can still use <code>SqlCommand</code> and <code>SqlConnection</code> to execute, and you don't have to re-invent the wheel for exception handling.</p>\n\n<p>A simple connection configuration and a single <code>SqlCommand</code> can execute it without issue.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12525/"
]
| I need to run a stored procedure from a C# application.
I use the following code to do so:
```
Process sqlcmdCall = new Process();
sqlcmdCall.StartInfo.FileName = "sqlcmd.exe";
sqlcmdCall.StartInfo.Arguments = "-S localhost\\SQLEXPRESS -d some_db -Q \":EXIT(sp_test)\""
sqlcmdCall.Start();
sqlcmdCall.WaitForExit();
```
From the sqlcmdCall object after the call completes, I currently get an ExitCode of -100 for success and of 1 for failure (i.e. missing parameter, stored proc does not exist, etc...).
How can I customize these return codes?
H. | If you are trying to call a stored procedure from c# you would want to use ADO.Net instead of the calling sqlcmd via the command line. Look at `SqlConnection` and `SqlCommand` in the `System.Data.SqlClient` namespace.
Once you are calling the stored procedure via `SqlCommand` you will be able to catch an exception raised by the stored procedure as well we reading the return value of the procedure if you need to. |
73,063 | <p>In Visual Studio 2005-2015 it is possible to find all lines containing certain references and display them in a "Find Results" window.</p>
<p>Now that these result lines are displayed, is there any keyboard shortcut that would allow adding debug breakpoints to all of them?</p>
| [
{
"answer_id": 73120,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 2,
"selected": false,
"text": "<p>If you can search for the word exactly, you can use a pair of keyboard shortcuts to do it quickly.</p>\n\n<p>Tools -> Options -> Enviroment -> Keyboard</p>\n\n<ul>\n<li>Edit.GoToFindResults1NextLocation</li>\n<li>EditorContextMenus.CodeWindow.Breakpoint.InsertBreakpoint</li>\n</ul>\n\n<p>Assign them to Control+Alt+F11 and F10 and you can go through all the results very quickly. I haven't found a shortcut for going to the next reference however.</p>\n"
},
{
"answer_id": 249501,
"author": "Jeff Hillman",
"author_id": 3950,
"author_profile": "https://Stackoverflow.com/users/3950",
"pm_score": 5,
"selected": true,
"text": "<p><strong><em>This answer does not work for Visual Studio 2015 or later. A more recent answer can be found <a href=\"https://stackoverflow.com/questions/38061627/how-do-i-add-debug-breakpoints-to-lines-displayed-in-a-find-results-window-in?rq=1\">here</a>.</em></strong></p>\n\n<p>You can do this fairly easily with a Visual Studio macro. Within Visual Studio, hit Alt-F11 to open the Macro IDE and add a new module by right-clicking on MyMacros and selecting Add|Add Module...</p>\n\n<p>Paste the following in the source editor:</p>\n\n<pre><code>Imports System\nImports System.IO\nImports System.Text.RegularExpressions\nImports EnvDTE\nImports EnvDTE80\nImports EnvDTE90\nImports System.Diagnostics\n\nPublic Module CustomMacros\n Sub BreakpointFindResults()\n Dim findResultsWindow As Window = DTE.Windows.Item(Constants.vsWindowKindFindResults1)\n\n Dim selection As TextSelection\n selection = findResultsWindow.Selection\n selection.SelectAll()\n\n Dim findResultsReader As New StringReader(selection.Text)\n Dim findResult As String = findResultsReader.ReadLine()\n\n Dim findResultRegex As New Regex(\"(?<Path>.*?)\\((?<LineNumber>\\d+)\\):\")\n\n While Not findResult Is Nothing\n Dim findResultMatch As Match = findResultRegex.Match(findResult)\n\n If findResultMatch.Success Then\n Dim path As String = findResultMatch.Groups.Item(\"Path\").Value\n Dim lineNumber As Integer = Integer.Parse(findResultMatch.Groups.Item(\"LineNumber\").Value)\n\n Try\n DTE.Debugger.Breakpoints.Add(\"\", path, lineNumber)\n Catch ex As Exception\n ' breakpoints can't be added everywhere\n End Try\n End If\n\n findResult = findResultsReader.ReadLine()\n End While\n End Sub\nEnd Module\n</code></pre>\n\n<p>This example uses the results in the \"Find Results 1\" window; you might want to create an individual shortcut for each result window.</p>\n\n<p>You can create a keyboard shortcut by going to Tools|Options... and selecting <strong>Keyboard</strong> under the <strong>Environment</strong> section in the navigation on the left. Select your macro and assign any shortcut you like. </p>\n\n<p>You can also add your macro to a menu or toolbar by going to Tools|Customize... and selecting the <strong>Macros</strong> section in the navigation on the left. Once you locate your macro in the list, you can drag it to any menu or toolbar, where it its text or icon can be customized to whatever you want.</p>\n"
},
{
"answer_id": 797454,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I needed something similar to disable all breakpoints and place a breakpoint on every \"Catch ex as Exception\". However, I expanded this a little so it will place a breakpoint at every occurance of the string you have selected. All you need to do with this is highlight the string you want to have a breakpoint on and run the macro. </p>\n\n<pre><code> Sub BreakPointAtString()\n\n Try\n DTE.ExecuteCommand(\"Debug.DisableAllBreakpoints\")\n Catch ex As Exception\n\n End Try\n\n Dim tsSelection As String = DTE.ActiveDocument.Selection.text\n DTE.ActiveDocument.Selection.selectall()\n Dim AllText As String = DTE.ActiveDocument.Selection.Text\n\n Dim findResultsReader As New StringReader(AllText)\n Dim findResult As String = findResultsReader.ReadLine()\n Dim lineNum As Integer = 1\n\n Do Until findResultsReader.Peek = -1\n lineNum += 1\n findResult = findResultsReader.ReadLine()\n If Trim(findResult) = Trim(tsSelection) Then\n DTE.ActiveDocument.Selection.GotoLine(lineNum)\n DTE.ExecuteCommand(\"Debug.ToggleBreakpoint\")\n End If\n Loop\n\nEnd Sub\n</code></pre>\n\n<p>Hope it works for you :)</p>\n"
},
{
"answer_id": 1631799,
"author": "Dmytro",
"author_id": 194487,
"author_profile": "https://Stackoverflow.com/users/194487",
"pm_score": 1,
"selected": false,
"text": "<p>Paul, thanks a lot, but I have the following error (message box), may be I need to restart my PC:</p>\n\n<pre><code>Error\n---------------------------\nError HRESULT E_FAIL has been returned from a call to a COM component.\n---------------------------\nOK \n---------------------------\n</code></pre>\n\n<p>I would propose the following solution that's very simple but it works for me</p>\n\n<pre><code>Sub BreakPointsFromSearch()\n Dim n As Integer = InputBox(\"Enter the number of search results\")\n\n For i = 1 To n\n DTE.ExecuteCommand(\"Edit.GoToNextLocation\")\n DTE.ExecuteCommand(\"Debug.ToggleBreakpoint\") \n Next\nEnd Sub\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12113/"
]
| In Visual Studio 2005-2015 it is possible to find all lines containing certain references and display them in a "Find Results" window.
Now that these result lines are displayed, is there any keyboard shortcut that would allow adding debug breakpoints to all of them? | ***This answer does not work for Visual Studio 2015 or later. A more recent answer can be found [here](https://stackoverflow.com/questions/38061627/how-do-i-add-debug-breakpoints-to-lines-displayed-in-a-find-results-window-in?rq=1).***
You can do this fairly easily with a Visual Studio macro. Within Visual Studio, hit Alt-F11 to open the Macro IDE and add a new module by right-clicking on MyMacros and selecting Add|Add Module...
Paste the following in the source editor:
```
Imports System
Imports System.IO
Imports System.Text.RegularExpressions
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Public Module CustomMacros
Sub BreakpointFindResults()
Dim findResultsWindow As Window = DTE.Windows.Item(Constants.vsWindowKindFindResults1)
Dim selection As TextSelection
selection = findResultsWindow.Selection
selection.SelectAll()
Dim findResultsReader As New StringReader(selection.Text)
Dim findResult As String = findResultsReader.ReadLine()
Dim findResultRegex As New Regex("(?<Path>.*?)\((?<LineNumber>\d+)\):")
While Not findResult Is Nothing
Dim findResultMatch As Match = findResultRegex.Match(findResult)
If findResultMatch.Success Then
Dim path As String = findResultMatch.Groups.Item("Path").Value
Dim lineNumber As Integer = Integer.Parse(findResultMatch.Groups.Item("LineNumber").Value)
Try
DTE.Debugger.Breakpoints.Add("", path, lineNumber)
Catch ex As Exception
' breakpoints can't be added everywhere
End Try
End If
findResult = findResultsReader.ReadLine()
End While
End Sub
End Module
```
This example uses the results in the "Find Results 1" window; you might want to create an individual shortcut for each result window.
You can create a keyboard shortcut by going to Tools|Options... and selecting **Keyboard** under the **Environment** section in the navigation on the left. Select your macro and assign any shortcut you like.
You can also add your macro to a menu or toolbar by going to Tools|Customize... and selecting the **Macros** section in the navigation on the left. Once you locate your macro in the list, you can drag it to any menu or toolbar, where it its text or icon can be customized to whatever you want. |
73,110 | <p>For a System.Windows.Forms.TextBox with Multiline=True, I'd like to only show the scrollbars when the text doesn't fit.</p>
<p>This is a readonly textbox used only for display. It's a TextBox so that users can copy the text out. Is there anything built-in to support auto show of scrollbars? If not, should I be using a different control? Or do I need to hook TextChanged and manually check for overflow (if so, how to tell if the text fits?)</p>
<hr/>
<p>Not having any luck with various combinations of WordWrap and Scrollbars settings. I'd like to have no scrollbars initially and have each appear dynamically only if the text doesn't fit in the given direction.</p>
<hr/>
<p>@nobugz, thanks, that works when WordWrap is disabled. I'd prefer not to disable wordwrap, but it's the lesser of two evils.</p>
<hr/>
<p>@André Neves, good point, and I would go that way if it was user-editable. I agree that consistency is the cardinal rule for UI intuitiveness.</p>
| [
{
"answer_id": 73173,
"author": "André Chalella",
"author_id": 4850,
"author_profile": "https://Stackoverflow.com/users/4850",
"pm_score": 3,
"selected": false,
"text": "<p>I also made some experiments, and found that the vertical bar will always show if you enable it, and the horizontal bar always shows as long as it's enabled and <code>WordWrap == false</code>.</p>\n\n<p>I think you're not going to get exactly what you want here. However, I believe that users would like better Windows' default behavior than the one you're trying to force. If I were using your app, I probably would be bothered if my textbox real-estate suddenly shrinked just because it needs to accomodate an unexpected scrollbar because I gave it too much text!</p>\n\n<p>Perhaps it would be a good idea just to let your application follow Windows' look and feel.</p>\n"
},
{
"answer_id": 89428,
"author": "Hans Passant",
"author_id": 17034,
"author_profile": "https://Stackoverflow.com/users/17034",
"pm_score": 5,
"selected": true,
"text": "<p>Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form. It's not quite perfect but ought to work for you.</p>\n\n<pre><code>using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\npublic class MyTextBox : TextBox {\n private bool mScrollbars;\n public MyTextBox() {\n this.Multiline = true;\n this.ReadOnly = true;\n }\n private void checkForScrollbars() {\n bool scroll = false;\n int cnt = this.Lines.Length;\n if (cnt > 1) {\n int pos0 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(0)).Y;\n if (pos0 >= 32768) pos0 -= 65536;\n int pos1 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(1)).Y;\n if (pos1 >= 32768) pos1 -= 65536;\n int h = pos1 - pos0;\n scroll = cnt * h > (this.ClientSize.Height - 6); // 6 = padding\n }\n if (scroll != mScrollbars) {\n mScrollbars = scroll;\n this.ScrollBars = scroll ? ScrollBars.Vertical : ScrollBars.None;\n }\n }\n\n protected override void OnTextChanged(EventArgs e) {\n checkForScrollbars();\n base.OnTextChanged(e);\n }\n\n protected override void OnClientSizeChanged(EventArgs e) {\n checkForScrollbars();\n base.OnClientSizeChanged(e);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 612234,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>I came across this question when I wanted to solve the same problem. </p>\n\n<p>The easiest way to do it is to change to System.Windows.Forms.RichTextBox. The ScrollBars property in this case can be left to the default value of RichTextBoxScrollBars.Both, which indicates \"Display both a horizontal and a vertical scroll bar when needed.\" It would be nice if this functionality were provided on TextBox.</p>\n"
},
{
"answer_id": 666731,
"author": "yagni",
"author_id": 80525,
"author_profile": "https://Stackoverflow.com/users/80525",
"pm_score": 3,
"selected": false,
"text": "<p>There's an extremely subtle bug in nobugz's solution that results in a heap corruption, but only if you're using AppendText() to update the TextBox.</p>\n\n<p>Setting the ScrollBars property from OnTextChanged will cause the Win32 window (handle) to be destroyed and recreated. But OnTextChanged is called from the bowels of the Win32 edit control (EditML_InsertText), which immediately thereafter expects the internal state of that Win32 edit control to be unchanged. Unfortunately, since the window is recreated, that internal state has been freed by the OS, resulting in an access violation.</p>\n\n<p>So the moral of the story is: don't use AppendText() if you're going to use nobugz's solution.</p>\n"
},
{
"answer_id": 4147348,
"author": "b8adamson",
"author_id": 215954,
"author_profile": "https://Stackoverflow.com/users/215954",
"pm_score": 2,
"selected": false,
"text": "<p>I had some success with the code below.</p>\n\n<pre><code> public partial class MyTextBox : TextBox\n {\n private bool mShowScrollBar = false;\n\n public MyTextBox()\n {\n InitializeComponent();\n\n checkForScrollbars();\n }\n\n private void checkForScrollbars()\n {\n bool showScrollBar = false;\n int padding = (this.BorderStyle == BorderStyle.Fixed3D) ? 14 : 10;\n\n using (Graphics g = this.CreateGraphics())\n {\n // Calcualte the size of the text area.\n SizeF textArea = g.MeasureString(this.Text,\n this.Font,\n this.Bounds.Width - padding);\n\n if (this.Text.EndsWith(Environment.NewLine))\n {\n // Include the height of a trailing new line in the height calculation \n textArea.Height += g.MeasureString(\"A\", this.Font).Height;\n }\n\n // Show the vertical ScrollBar if the text area\n // is taller than the control.\n showScrollBar = (Math.Ceiling(textArea.Height) >= (this.Bounds.Height - padding));\n\n if (showScrollBar != mShowScrollBar)\n {\n mShowScrollBar = showScrollBar;\n this.ScrollBars = showScrollBar ? ScrollBars.Vertical : ScrollBars.None;\n }\n }\n }\n\n protected override void OnTextChanged(EventArgs e)\n {\n checkForScrollbars();\n base.OnTextChanged(e);\n }\n\n protected override void OnResize(EventArgs e)\n {\n checkForScrollbars();\n base.OnResize(e);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 25197797,
"author": "Michael Csikos",
"author_id": 1484559,
"author_profile": "https://Stackoverflow.com/users/1484559",
"pm_score": 0,
"selected": false,
"text": "<p>What Aidan describes is almost exactly the UI scenario I am facing. As the text box is read only, I don't need it to respond to TextChanged. And I'd prefer the auto-scroll recalculation to be delayed so it's not firing dozens of times per second while a window is being resized.</p>\n\n<p>For most UIs, text boxes with both vertical and horizontal scroll bars are, well, evil, so I'm only interested in vertical scroll bars here.</p>\n\n<p>I also found that MeasureString produced a height that was actually bigger than what was required. Using the text box's PreferredHeight with no border as the line height gives a better result.</p>\n\n<p>The following seems to work pretty well, with or without a border, and it works with WordWrap on.</p>\n\n<p>Simply call AutoScrollVertically() when you need it, and optionally specify recalculateOnResize.</p>\n\n<pre><code>public class TextBoxAutoScroll : TextBox\n{\n public void AutoScrollVertically(bool recalculateOnResize = false)\n {\n SuspendLayout();\n\n if (recalculateOnResize)\n {\n Resize -= OnResize;\n Resize += OnResize;\n }\n\n float linesHeight = 0;\n var borderStyle = BorderStyle;\n\n BorderStyle = BorderStyle.None;\n\n int textHeight = PreferredHeight;\n\n try\n {\n using (var graphics = CreateGraphics())\n {\n foreach (var text in Lines)\n {\n var textArea = graphics.MeasureString(text, Font);\n\n if (textArea.Width < Width)\n linesHeight += textHeight;\n else\n {\n var numLines = (float)Math.Ceiling(textArea.Width / Width);\n\n linesHeight += textHeight * numLines;\n }\n }\n }\n\n if (linesHeight > Height)\n ScrollBars = ScrollBars.Vertical;\n else\n ScrollBars = ScrollBars.None;\n }\n catch (Exception ex)\n {\n System.Diagnostics.Debug.WriteLine(ex);\n }\n finally\n {\n BorderStyle = borderStyle;\n\n ResumeLayout();\n }\n }\n\n private void OnResize(object sender, EventArgs e)\n {\n m_timerResize.Stop();\n\n m_timerResize.Tick -= OnDelayedResize;\n m_timerResize.Tick += OnDelayedResize;\n m_timerResize.Interval = 475;\n\n m_timerResize.Start();\n }\n\n Timer m_timerResize = new Timer();\n\n private void OnDelayedResize(object sender, EventArgs e)\n {\n m_timerResize.Stop();\n\n Resize -= OnResize;\n\n AutoScrollVertically();\n\n Resize += OnResize;\n }\n}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1042/"
]
| For a System.Windows.Forms.TextBox with Multiline=True, I'd like to only show the scrollbars when the text doesn't fit.
This is a readonly textbox used only for display. It's a TextBox so that users can copy the text out. Is there anything built-in to support auto show of scrollbars? If not, should I be using a different control? Or do I need to hook TextChanged and manually check for overflow (if so, how to tell if the text fits?)
---
Not having any luck with various combinations of WordWrap and Scrollbars settings. I'd like to have no scrollbars initially and have each appear dynamically only if the text doesn't fit in the given direction.
---
@nobugz, thanks, that works when WordWrap is disabled. I'd prefer not to disable wordwrap, but it's the lesser of two evils.
---
@André Neves, good point, and I would go that way if it was user-editable. I agree that consistency is the cardinal rule for UI intuitiveness. | Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form. It's not quite perfect but ought to work for you.
```
using System;
using System.Drawing;
using System.Windows.Forms;
public class MyTextBox : TextBox {
private bool mScrollbars;
public MyTextBox() {
this.Multiline = true;
this.ReadOnly = true;
}
private void checkForScrollbars() {
bool scroll = false;
int cnt = this.Lines.Length;
if (cnt > 1) {
int pos0 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(0)).Y;
if (pos0 >= 32768) pos0 -= 65536;
int pos1 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(1)).Y;
if (pos1 >= 32768) pos1 -= 65536;
int h = pos1 - pos0;
scroll = cnt * h > (this.ClientSize.Height - 6); // 6 = padding
}
if (scroll != mScrollbars) {
mScrollbars = scroll;
this.ScrollBars = scroll ? ScrollBars.Vertical : ScrollBars.None;
}
}
protected override void OnTextChanged(EventArgs e) {
checkForScrollbars();
base.OnTextChanged(e);
}
protected override void OnClientSizeChanged(EventArgs e) {
checkForScrollbars();
base.OnClientSizeChanged(e);
}
}
``` |
73,117 | <p>I wanted to "emulate" a popular flash game, Chrontron, in C++ and needed some help getting started. (NOTE: Not for release, just practicing for myself)</p>
<pre>
Basics:
Player has a time machine. On each iteration of using the time machine, a parallel state
is created, co-existing with a previous state. One of the states must complete all the
objectives of the level before ending the stage. In addition, all the stages must be able
to end the stage normally, without causing a state paradox (wherein they should have
been able to finish the stage normally but, due to the interactions of another state,
were not).
</pre>
<p>So, that sort of explains how the game works. You should play it a bit to really
understand what my problem is. <br /></p>
<p>I'm thinking a good way to solve this would be to use linked lists to store each state,
which will probably either be a hash map, based on time, or a linked list that iterates
based on time. I'm still unsure.<br /></p>
<p>ACTUAL QUESTION:</p>
<p>Now that I have some rough specs, I need some help deciding on which data structures to use for this, and why. Also, I want to know what Graphics API/Layer I should use to do this: SDL, OpenGL, or DirectX (my current choice is SDL). And how would I go about implementing parallel states? With parallel threads?</p>
<p>EDIT (To clarify more):<br />
OS -- Windows (since this is a hobby project, may do this in Linux later)<br />
Graphics -- 2D
Language -- C++ (must be C++ -- this is practice for a course next semester)</p>
<p>Q-Unanswered: SDL : OpenGL : Direct X <br />
Q-Answered: Avoid Parallel Processing <br />
Q-Answered: Use STL to implement time-step actions.<br /></p>
<pre>
So far from what people have said, I should:
1. Use STL to store actions.
2. Iterate through actions based on time-step.
3. Forget parallel processing -- period. (But I'd still like some pointers as to how it
could be used and in what cases it should be used, since this is for practice).
</pre>
<p>Appending to the question, I've mostly used C#, PHP, and Java before so I wouldn't describe myself as a hotshot programmer. What C++ specific knowledge would help make this project easier for me? (ie. Vectors?)</p>
| [
{
"answer_id": 73152,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 1,
"selected": false,
"text": "<p>I have played this game before. I don't necessarily think parallel processing is the way to go. You have shared objects in the game (levers, boxes, elevators, etc) that will need to be shared between processes, possibly with every delta, thereby reducing the effectiveness of the parallelism.</p>\n\n<p>I would personally just keep a list of actions, then for each subsequent iteration start interleaving them together. For example, if the list is in the format of <[iteration.action]> then the 3rd time thru would execute actions 1.1, 2.1, 3.1, 1.2, 2.2, 3.3, etc.</p>\n"
},
{
"answer_id": 73160,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 0,
"selected": false,
"text": "<p>After briefly glossing over the description, I think you have the right idea, I would have a state object that holds the state data, and place this into a linked list...I don't think you need parallel threads...</p>\n\n<p>as far as the graphics API, I have only used opengl, and can say that it is pretty powerful and has a good C / C++ API, opengl would also be more cross platform as you can use the messa library on *Nix computers. </p>\n"
},
{
"answer_id": 73178,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>A very interesting game idea. I think you are right that parrellel computing would be benefical to this design, but no more then any other high resource program. </p>\n\n<p>The question is a bit ambigous. I see that you are going to write this in C++ but what OS are you coding it for? Do you intend on it being cross platform and what kind of graphics would you like, ie 3D, 2D, high end, web based.</p>\n\n<p>So basically we need a lot more information.</p>\n"
},
{
"answer_id": 73265,
"author": "enigmatic",
"author_id": 443575,
"author_profile": "https://Stackoverflow.com/users/443575",
"pm_score": 0,
"selected": false,
"text": "<p>Parallel processing isn't the answer. You should simply \"record\" the players actions then play them back for the \"previous actions\"</p>\n\n<p>So you create a vector (singly linked list) of vectors that holds the actions. Simply store the frame number that the action was taken (or the delta) and complete that action on the \"dummy bot\" that represents the player during that particular instance. You simply loop through the states and trigger them one after another.</p>\n\n<p>You get a side effect of easily \"breaking\" the game when a state paradox happens simply because the next action fails.</p>\n"
},
{
"answer_id": 73328,
"author": "Iain",
"author_id": 11911,
"author_profile": "https://Stackoverflow.com/users/11911",
"pm_score": 0,
"selected": false,
"text": "<p>Unless you're desperate to use C++ for your own education, you should definitely look at <a href=\"http://creators.xna.com\" rel=\"nofollow noreferrer\">XNA</a> for your game & graphics framework (it uses C#). It's completely free, it does a lot of things for you, and soon you'll be able to sell your game on Xbox Live.</p>\n\n<p>To answer your main question, nothing that you can already do in Flash would ever need to use more than one thread. Just store a list of positions in an array and loop through with a different offset for each robot.</p>\n"
},
{
"answer_id": 73353,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 3,
"selected": false,
"text": "<p>This sounds very similar to <a href=\"http://braid-game.com\" rel=\"noreferrer\">Braid</a>. You really don't want parallel processing for this - parallel programming is <b>hard</b>, and for something like this, performance should not be an issue.</p>\n\n<p>Since the game state vector will grow very quickly (probably on the order of several kilobytes per second, depending on the frame rate and how much data you store), you don't want a linked list, which has a lot of overhead in terms of space (and can introduce big performance penalties due to cache misses if it is laid out poorly). For each parallel timeline, you want a vector data structure. You can store each parallel timeline in a linked list. Each timeline knows at what time it began.</p>\n\n<p>To run the game, you iterate through all active timelines and perform one frame's worth of actions from each of them in lockstep. No need for parallel processing.</p>\n"
},
{
"answer_id": 73537,
"author": "Andreas Magnusson",
"author_id": 5811,
"author_profile": "https://Stackoverflow.com/users/5811",
"pm_score": 4,
"selected": true,
"text": "<p>What you should do is first to read and understand the \"fixed time-step\" game loop (Here's a good explanation: <a href=\"http://www.gaffer.org/game-physics/fix-your-timestep\" rel=\"nofollow noreferrer\">http://www.gaffer.org/game-physics/fix-your-timestep</a>).</p>\n\n<p>Then what you do is to keep a list of list of pairs of frame counter and action. STL example:</p>\n\n<pre class=\"lang-c++ prettyprint-override\"><code>std::list<std::list<std::pair<unsigned long, Action> > > state;\n</code></pre>\n\n<p>Or maybe a vector of lists of pairs. To create the state, for every action (player interaction) you store the frame number and what action is performed, most likely you'd get the best results if action simply was \"key <X> pressed\" or \"key <X> released\":</p>\n\n<pre class=\"lang-c++ prettyprint-override\"><code>state.back().push_back(std::make_pair(currentFrame, VK_LEFT | KEY_PRESSED));\n</code></pre>\n\n<p>To play back the previous states, you'd have to reset the frame counter every time the player activates the time machine and then iterate through the state list for each previous state and see if any matches the current frame. If there is, perform the action for that state.\nTo optimize you could keep a list of iterators to where you are in each previous state-list. Here's some <em>pseudo-code</em> for that:</p>\n\n<pre class=\"lang-c++ prettyprint-override\"><code>typedef std::list<std::pair<unsigned long, Action> > StateList;\nstd::list<StateList::iterator> stateIteratorList;\n//\nforeach(it in stateIteratorList)\n{\n if(it->first == currentFrame)\n {\n performAction(it->second);\n ++it;\n }\n}\n</code></pre>\n\n<p>I hope you get the idea...</p>\n\n<p>Separate threads would simply complicate the matter greatly, this way you get the same result every time, which you cannot guarantee by using separate threads (can't really see how that would be implemented) or a non-fixed time-step game loop.</p>\n\n<p>When it comes to graphics API, I'd go with SDL as it's probably the easiest thing to get you started. You can always use OpenGL from SDL later on if you want to go 3D.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6128/"
]
| I wanted to "emulate" a popular flash game, Chrontron, in C++ and needed some help getting started. (NOTE: Not for release, just practicing for myself)
```
Basics:
Player has a time machine. On each iteration of using the time machine, a parallel state
is created, co-existing with a previous state. One of the states must complete all the
objectives of the level before ending the stage. In addition, all the stages must be able
to end the stage normally, without causing a state paradox (wherein they should have
been able to finish the stage normally but, due to the interactions of another state,
were not).
```
So, that sort of explains how the game works. You should play it a bit to really
understand what my problem is.
I'm thinking a good way to solve this would be to use linked lists to store each state,
which will probably either be a hash map, based on time, or a linked list that iterates
based on time. I'm still unsure.
ACTUAL QUESTION:
Now that I have some rough specs, I need some help deciding on which data structures to use for this, and why. Also, I want to know what Graphics API/Layer I should use to do this: SDL, OpenGL, or DirectX (my current choice is SDL). And how would I go about implementing parallel states? With parallel threads?
EDIT (To clarify more):
OS -- Windows (since this is a hobby project, may do this in Linux later)
Graphics -- 2D
Language -- C++ (must be C++ -- this is practice for a course next semester)
Q-Unanswered: SDL : OpenGL : Direct X
Q-Answered: Avoid Parallel Processing
Q-Answered: Use STL to implement time-step actions.
```
So far from what people have said, I should:
1. Use STL to store actions.
2. Iterate through actions based on time-step.
3. Forget parallel processing -- period. (But I'd still like some pointers as to how it
could be used and in what cases it should be used, since this is for practice).
```
Appending to the question, I've mostly used C#, PHP, and Java before so I wouldn't describe myself as a hotshot programmer. What C++ specific knowledge would help make this project easier for me? (ie. Vectors?) | What you should do is first to read and understand the "fixed time-step" game loop (Here's a good explanation: <http://www.gaffer.org/game-physics/fix-your-timestep>).
Then what you do is to keep a list of list of pairs of frame counter and action. STL example:
```c++
std::list<std::list<std::pair<unsigned long, Action> > > state;
```
Or maybe a vector of lists of pairs. To create the state, for every action (player interaction) you store the frame number and what action is performed, most likely you'd get the best results if action simply was "key <X> pressed" or "key <X> released":
```c++
state.back().push_back(std::make_pair(currentFrame, VK_LEFT | KEY_PRESSED));
```
To play back the previous states, you'd have to reset the frame counter every time the player activates the time machine and then iterate through the state list for each previous state and see if any matches the current frame. If there is, perform the action for that state.
To optimize you could keep a list of iterators to where you are in each previous state-list. Here's some *pseudo-code* for that:
```c++
typedef std::list<std::pair<unsigned long, Action> > StateList;
std::list<StateList::iterator> stateIteratorList;
//
foreach(it in stateIteratorList)
{
if(it->first == currentFrame)
{
performAction(it->second);
++it;
}
}
```
I hope you get the idea...
Separate threads would simply complicate the matter greatly, this way you get the same result every time, which you cannot guarantee by using separate threads (can't really see how that would be implemented) or a non-fixed time-step game loop.
When it comes to graphics API, I'd go with SDL as it's probably the easiest thing to get you started. You can always use OpenGL from SDL later on if you want to go 3D. |
73,123 | <p>Is it possible to use .htaccess to process all six digit URLs by sending them to a script, but handle every other invalid URL as an error 404?</p>
<p>For example:</p>
<pre><code>http://mywebsite.com/132483
</code></pre>
<p>would be sent to:</p>
<pre><code>http://mywebsite.com/scriptname.php?no=132483
</code></pre>
<p>but</p>
<pre><code>http://mywebsite.com/132483a or
http://mywebsite.com/asdf
</code></pre>
<p>would be handled as a 404 error.</p>
<p>I presently have this working via a custom PHP 404 script but it's kind of kludgy. Seems to me that .htaccess might be a more elegant solution, but I haven't been able to figure out if it's even possible.</p>
| [
{
"answer_id": 73141,
"author": "Frank Wiles",
"author_id": 12568,
"author_profile": "https://Stackoverflow.com/users/12568",
"pm_score": 0,
"selected": false,
"text": "<p>Yes it's possible with mod_rewrite. There are tons of good mod_rewrite tutorials online a quick Google search should turn up your answer in no time. </p>\n\n<p>Basically what you're going to want to do is ensure that the regular expression you use is just looking for digits and no other characters and to ensure the length is 6. Then you'll redirect to scriptname.?no= with the number you captured. </p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 73184,
"author": "Adam Hopkinson",
"author_id": 12280,
"author_profile": "https://Stackoverflow.com/users/12280",
"pm_score": 4,
"selected": false,
"text": "<p>In your htaccess file, put the following</p>\n\n<pre><code>RewriteEngine On\nRewriteRule ^([0-9]{6})$ /scriptname.php?no=$1 [L]\n</code></pre>\n\n<p>The first line turns the mod_rewrite engine on. The () brackets put the contents into $1 - successive () would populate $2, $3... and so on. The [0-9]{6} says look for a string precisely 6 characters long containing only characters 0-9.</p>\n\n<p>The [L] at the end makes this the last rule - if it applies, rule processing will stop.</p>\n\n<p>Oh, the ^ and $ mark the start and end of the incoming uri.</p>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 73315,
"author": "daniels",
"author_id": 9789,
"author_profile": "https://Stackoverflow.com/users/9789",
"pm_score": 3,
"selected": true,
"text": "<pre><code><IfModule mod_rewrite.c>\n RewriteEngine on\n RewriteRule ^([0-9]{6})$ scriptname.php?no=$1 [L]\n</IfModule>\n</code></pre>\n\n<p>To preserve the clean URL </p>\n\n<pre><code>http://mywebsite.com/132483\n</code></pre>\n\n<p>while serving scriptname.php use only [L]. \nUsing [R=301] will redirect you to your scriptname.php?no=xxx</p>\n\n<p>You may find this useful <a href=\"http://www.addedbytes.com/download/mod_rewrite-cheat-sheet-v2/pdf/\" rel=\"nofollow noreferrer\">http://www.addedbytes.com/download/mod_rewrite-cheat-sheet-v2/pdf/</a> </p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12513/"
]
| Is it possible to use .htaccess to process all six digit URLs by sending them to a script, but handle every other invalid URL as an error 404?
For example:
```
http://mywebsite.com/132483
```
would be sent to:
```
http://mywebsite.com/scriptname.php?no=132483
```
but
```
http://mywebsite.com/132483a or
http://mywebsite.com/asdf
```
would be handled as a 404 error.
I presently have this working via a custom PHP 404 script but it's kind of kludgy. Seems to me that .htaccess might be a more elegant solution, but I haven't been able to figure out if it's even possible. | ```
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^([0-9]{6})$ scriptname.php?no=$1 [L]
</IfModule>
```
To preserve the clean URL
```
http://mywebsite.com/132483
```
while serving scriptname.php use only [L].
Using [R=301] will redirect you to your scriptname.php?no=xxx
You may find this useful <http://www.addedbytes.com/download/mod_rewrite-cheat-sheet-v2/pdf/> |
73,128 | <p>We just started running in to an odd problem with a FileSystemWatcher where the call to Dispose() appears to be hanging. This is code that has been working without any problems for a while but we just upgraded to .NET3.5 SP1 so I'm trying to find out if anyone else has seen this behavior. Here is the code that creates the FileSystemWatcher: </p>
<pre><code>if (this.fileWatcher == null)
{
this.fileWatcher = new FileSystemWatcher();
}
this.fileWatcher.BeginInit();
this.fileWatcher.IncludeSubdirectories = true;
this.fileWatcher.Path = project.Directory;
this.fileWatcher.EnableRaisingEvents = true;
this.fileWatcher.NotifyFilter = NotifyFilters.Attributes;
this.fileWatcher.Changed += delegate(object s, FileSystemEventArgs args)
{
FileWatcherFileChanged(args);
};
this.fileWatcher.EndInit();
</code></pre>
<p>The way this is being used is to update the state image of a TreeNode object (adjusted slightly to remove business specific information):</p>
<pre><code>private void FileWatcherFileChanged(FileSystemEventArgs args)
{
if (this.TreeView != null)
{
if (this.TreeView.InvokeRequired)
{
FileWatcherFileChangedCallback d = new FileWatcherFileChangedCallback(FileWatcherFileChanged);
this.TreeView.Invoke(d, new object[]
{
args
});
}
else
{
switch (args.ChangeType)
{
case WatcherChangeTypes.Changed:
if (String.CompareOrdinal(this.project.FullName, args.FullPath) == 0)
{
this.StateImageKey = GetStateImageKey();
}
else
{
projectItemTreeNode.StateImageKey = GetStateImageKey();
}
break;
}
}
}
}
</code></pre>
<p>Is there something we're missing or is this an anomoly from .NET3.5 SP1?</p>
| [
{
"answer_id": 73192,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 4,
"selected": true,
"text": "<p>Just a thought... Any chance there's a deadlock issue here?</p>\n\n<p>You're calling TreeView.Invoke, which is a blocking call. If a filesystem change happens just as you're clicking whatever button causes the FileSystemWatcher.Dispose() call, your FileWatcherFileChanged method will get called on a background thread and call TreeView.Invoke, which will block until your form thread can process the Invoke request. However, your form thread would be calling FileSystemWatcher.Dispose(), which probably doesn't return until all pending change requests are processed.</p>\n\n<p>Try changing the .Invoke to .BeginInvoke and see if that helps. That may help point you in the right direction.</p>\n\n<p>Of course, it could also be a .NET 3.5SP1 issue. I'm just speculating here based on the code you provided.</p>\n"
},
{
"answer_id": 88377,
"author": "Jamie Penney",
"author_id": 68230,
"author_profile": "https://Stackoverflow.com/users/68230",
"pm_score": 1,
"selected": false,
"text": "<p>We are also having this issue. Our application runs on .Net 2.0 but is compiled by VS 2008 SP1. I have .NET 3.5 SP1 installed as well. I've got no idea why this happens either, it doesn't look like a deadlock issue on our end as no other threads are running at this point (it is during application shutdown).</p>\n"
},
{
"answer_id": 153922,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 2,
"selected": false,
"text": "<p>Scott, we've occasionally seen issues with control.Invoke in .NET 2. Try switching to control.BeginInvoke and see if that helps. </p>\n\n<p>Doing that will allow the FileSystemWatcher thread to return immediately. I suspect your issue is somehow that the control.Invoke is blocking, thus causing the FileSystemWatcher to freeze upon dispose.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1559/"
]
| We just started running in to an odd problem with a FileSystemWatcher where the call to Dispose() appears to be hanging. This is code that has been working without any problems for a while but we just upgraded to .NET3.5 SP1 so I'm trying to find out if anyone else has seen this behavior. Here is the code that creates the FileSystemWatcher:
```
if (this.fileWatcher == null)
{
this.fileWatcher = new FileSystemWatcher();
}
this.fileWatcher.BeginInit();
this.fileWatcher.IncludeSubdirectories = true;
this.fileWatcher.Path = project.Directory;
this.fileWatcher.EnableRaisingEvents = true;
this.fileWatcher.NotifyFilter = NotifyFilters.Attributes;
this.fileWatcher.Changed += delegate(object s, FileSystemEventArgs args)
{
FileWatcherFileChanged(args);
};
this.fileWatcher.EndInit();
```
The way this is being used is to update the state image of a TreeNode object (adjusted slightly to remove business specific information):
```
private void FileWatcherFileChanged(FileSystemEventArgs args)
{
if (this.TreeView != null)
{
if (this.TreeView.InvokeRequired)
{
FileWatcherFileChangedCallback d = new FileWatcherFileChangedCallback(FileWatcherFileChanged);
this.TreeView.Invoke(d, new object[]
{
args
});
}
else
{
switch (args.ChangeType)
{
case WatcherChangeTypes.Changed:
if (String.CompareOrdinal(this.project.FullName, args.FullPath) == 0)
{
this.StateImageKey = GetStateImageKey();
}
else
{
projectItemTreeNode.StateImageKey = GetStateImageKey();
}
break;
}
}
}
}
```
Is there something we're missing or is this an anomoly from .NET3.5 SP1? | Just a thought... Any chance there's a deadlock issue here?
You're calling TreeView.Invoke, which is a blocking call. If a filesystem change happens just as you're clicking whatever button causes the FileSystemWatcher.Dispose() call, your FileWatcherFileChanged method will get called on a background thread and call TreeView.Invoke, which will block until your form thread can process the Invoke request. However, your form thread would be calling FileSystemWatcher.Dispose(), which probably doesn't return until all pending change requests are processed.
Try changing the .Invoke to .BeginInvoke and see if that helps. That may help point you in the right direction.
Of course, it could also be a .NET 3.5SP1 issue. I'm just speculating here based on the code you provided. |
73,134 | <p>I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allocated by casting array <code>new</code> thus:</p>
<pre class="lang-cpp prettyprint-override"><code>STRUCT* pStruct = (STRUCT*)new BYTE[sizeof(STRUCT) + nPaddingSize];
</code></pre>
<p>Later on however the memory is freed using a <code>delete</code> call:</p>
<pre class="lang-cpp prettyprint-override"><code>delete pStruct;
</code></pre>
<p>Will this mix of array <code>new[]</code> and non-array <code>delete</code> cause a memory leak or would it depend on the compiler? Would I be better off changing this code to use <code>malloc</code> and <code>free</code> instead?</p>
| [
{
"answer_id": 73157,
"author": "Fire Lancer",
"author_id": 6266,
"author_profile": "https://Stackoverflow.com/users/6266",
"pm_score": 0,
"selected": false,
"text": "<p>Yes that may, since your allocating with new[] but deallocating with delelte, yes malloc/free is safer here, but in c++ you should not use them since they won't handle (de)constructors.</p>\n\n<p>Also your code will call the deconstructor, but not the constructor. For some structs this may cause a memory leak (if the constructor allocated further memory, eg for a string)</p>\n\n<p>Better would be to do it correctly, as this will also correctly call any constructors and deconstructors</p>\n\n<pre><code>STRUCT* pStruct = new STRUCT;\n...\ndelete pStruct;\n</code></pre>\n"
},
{
"answer_id": 73163,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 5,
"selected": true,
"text": "<p>Technically I believe it could cause a problem with mismatched allocators, though in practice I don't know of any compiler that would not do the right thing with this example.</p>\n\n<p>More importantly if <code>STRUCT</code> where to have (or ever be given) a destructor then it would invoke the destructor without having invoked the corresponding constructor.</p>\n\n<p>Of course, if you know where pStruct came from why not just cast it on delete to match the allocation:</p>\n\n<pre><code>delete [] (BYTE*) pStruct;\n</code></pre>\n"
},
{
"answer_id": 73189,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 0,
"selected": false,
"text": "<p>You'd could cast back to a BYTE * and the delete:</p>\n\n<pre><code>delete[] (BYTE*)pStruct;\n</code></pre>\n"
},
{
"answer_id": 73201,
"author": "slicedlime",
"author_id": 11230,
"author_profile": "https://Stackoverflow.com/users/11230",
"pm_score": 3,
"selected": false,
"text": "<p>The behaviour of the code is undefined. You may be lucky (or not) and it may work with your compiler, but really that's not correct code. There's two problems with it:</p>\n\n<ol>\n<li>The <code>delete</code> should be an array <code>delete []</code>.</li>\n<li>The <code>delete</code> should be called on a pointer to the same type as the type allocated.</li>\n</ol>\n\n<p>So to be entirely correct, you want to be doing something like this:</p>\n\n<pre><code>delete [] (BYTE*)(pStruct);\n</code></pre>\n"
},
{
"answer_id": 73219,
"author": "Serge",
"author_id": 1007,
"author_profile": "https://Stackoverflow.com/users/1007",
"pm_score": -1,
"selected": false,
"text": "<p>Rob Walker <a href=\"https://stackoverflow.com/questions/73134/will-this-c-code-cause-a-memory-leak-casting-vector-new#73163\">reply</a> is good.</p>\n\n<p>Just small addition, if you don't have any constructor or/and distructors, so you basically need allocate and free a chunk of raw memory, consider using free/malloc pair.</p>\n"
},
{
"answer_id": 73225,
"author": "QBziZ",
"author_id": 11572,
"author_profile": "https://Stackoverflow.com/users/11572",
"pm_score": 0,
"selected": false,
"text": "<p>It's always best to keep acquisition/release of any resource as balanced as possible.\nAlthough leaking or not is hard to say in this case. It depends on the compiler's implementation of the vector (de)allocation.</p>\n\n<pre><code>BYTE * pBytes = new BYTE [sizeof(STRUCT) + nPaddingSize];\n\nSTRUCT* pStruct = reinterpret_cast< STRUCT* > ( pBytes ) ;\n\n // do stuff with pStruct\n\ndelete [] pBytes ;\n</code></pre>\n"
},
{
"answer_id": 73233,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You're sort of mixing C and C++ ways of doing things. Why allocate more than the size of a STRUCT? Why not just \"new STRUCT\"? If you must do this then it might be clearer to use malloc and free in this case, since then you or other programmers might be a little less likely to make assumptions about the types and sizes of the allocated objects.</p>\n"
},
{
"answer_id": 73295,
"author": "Len Holgate",
"author_id": 7925,
"author_profile": "https://Stackoverflow.com/users/7925",
"pm_score": 3,
"selected": false,
"text": "<p>Yes it will cause a memory leak.</p>\n\n<p>See this except from C++ Gotchas: <a href=\"http://www.informit.com/articles/article.aspx?p=30642\" rel=\"nofollow noreferrer\"><a href=\"http://www.informit.com/articles/article.aspx?p=30642\" rel=\"nofollow noreferrer\">http://www.informit.com/articles/article.aspx?p=30642</a></a> for why.</p>\n\n<p>Raymond Chen has an explanation of how vector <code>new</code> and <code>delete</code> differ from the scalar versions under the covers for the Microsoft compiler... Here: \n<a href=\"http://blogs.msdn.com/oldnewthing/archive/2004/02/03/66660.aspx\" rel=\"nofollow noreferrer\"><a href=\"http://blogs.msdn.com/oldnewthing/archive/2004/02/03/66660.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/oldnewthing/archive/2004/02/03/66660.aspx</a></a> </p>\n\n<p>IMHO you should fix the delete to:</p>\n\n<pre><code>delete [] pStruct;\n</code></pre>\n\n<p>rather than switching to <code>malloc</code>/<code>free</code>, if only because it's a simpler change to make without making mistakes ;)</p>\n\n<p>And, of course, the simpler to make change that I show above is wrong due to the casting in the original allocation, it should be </p>\n\n<pre><code>delete [] reinterpret_cast<BYTE *>(pStruct);\n</code></pre>\n\n<p>so, I guess it's probably as easy to switch to <code>malloc</code>/<code>free</code> after all ;)</p>\n"
},
{
"answer_id": 73332,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Len: the problem with that is that pStruct is a STRUCT*, but the memory allocated is actually a BYTE[] of some unknown size. So delete[] pStruct will not de-allocate all of the allocated memory.</p>\n"
},
{
"answer_id": 73368,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 0,
"selected": false,
"text": "<p>Use operator new and delete:</p>\n\n<pre><code>struct STRUCT\n{\n void *operator new (size_t)\n {\n return new char [sizeof(STRUCT) + nPaddingSize];\n }\n\n void operator delete (void *memory)\n {\n delete [] reinterpret_cast <char *> (memory);\n }\n};\n\nvoid main()\n{\n STRUCT *s = new STRUCT;\n delete s;\n}\n</code></pre>\n"
},
{
"answer_id": 73420,
"author": "ben",
"author_id": 4607,
"author_profile": "https://Stackoverflow.com/users/4607",
"pm_score": 2,
"selected": false,
"text": "<p>The C++ standard clearly states:</p>\n\n<pre><code>delete-expression:\n ::opt delete cast-expression\n ::opt delete [ ] cast-expression\n</code></pre>\n\n<blockquote>\n <p>The first alternative is for non-array objects, and the second is for arrays. The operand shall have a pointer type, or a class type having a single conversion function (12.3.2) to a pointer type. The result has type void.</p>\n \n <p>In the first alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object [...] If not, the behavior is undefined.</p>\n</blockquote>\n\n<p>The value of the operand in <code>delete pStruct</code> is a pointer to an array of <code>char</code>, independent of its static type (<code>STRUCT*</code>). Therefore, any discussion of memory leaks is quite pointless, because the code is ill-formed, and a C++ compiler is not required to produce a sensible executable in this case.</p>\n\n<p>It could leak memory, it could not, or it could do anything up to crashing your system. Indeed, a C++ implementation with which I tested your code aborts the program execution at the point of the delete expression.</p>\n"
},
{
"answer_id": 73718,
"author": "Matt Cruikshank",
"author_id": 8643,
"author_profile": "https://Stackoverflow.com/users/8643",
"pm_score": 3,
"selected": false,
"text": "<p>I personally think you'd be better off using <code>std::vector</code> to manage your memory, so you don't need the <code>delete</code>.</p>\n\n<pre><code>std::vector<BYTE> backing(sizeof(STRUCT) + nPaddingSize);\nSTRUCT* pStruct = (STRUCT*)(&backing[0]);\n</code></pre>\n\n<p>Once backing leaves scope, your <code>pStruct</code> is no longer valid.</p>\n\n<p>Or, you can use:</p>\n\n<pre><code>boost::scoped_array<BYTE> backing(new BYTE[sizeof(STRUCT) + nPaddingSize]);\nSTRUCT* pStruct = (STRUCT*)backing.get();\n</code></pre>\n\n<p>Or <code>boost::shared_array</code> if you need to move ownership around.</p>\n"
},
{
"answer_id": 74170,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "<p>If you <em>really</em> must do this sort of thing, you should probably call operator <code>new</code> directly:</p>\n\n<pre><code>STRUCT* pStruct = operator new(sizeof(STRUCT) + nPaddingSize);\n</code></pre>\n\n<p>I believe calling it this way avoids calling constructors/destructors.</p>\n"
},
{
"answer_id": 74232,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 1,
"selected": false,
"text": "<p>I am currently unable to vote, but <a href=\"https://stackoverflow.com/questions/73134/will-this-c-code-cause-a-memory-leak-casting-vector-new#73201\">slicedlime's answer</a> is preferable to <a href=\"https://stackoverflow.com/questions/73134/will-this-c-code-cause-a-memory-leak-casting-vector-new#73163\">Rob Walker's answer</a>, since the problem has nothing to do with allocators or whether or not the STRUCT has a destructor.</p>\n\n<p>Also note that the example code does not necessarily result in a memory leak - it's undefined behavior. Pretty much anything could happen (from nothing bad to a crash far, far away).</p>\n\n<p>The example code results in undefined behavior, plain and simple. slicedlime's answer is direct and to the point (with the caveat that the word 'vector' should be changed to 'array' since vectors are an STL thing).</p>\n\n<p>This kind of stuff is covered pretty well in the C++ FAQ (Sections 16.12, 16.13, and 16.14):</p>\n\n<p><a href=\"http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.12\" rel=\"nofollow noreferrer\">http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.12</a></p>\n"
},
{
"answer_id": 74236,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 2,
"selected": false,
"text": "<p>As highlighted in other posts:</p>\n\n<p>1) Calls to new/delete allocate memory and may call constructors/destructors (C++ '03 5.3.4/5.3.5)</p>\n\n<p>2) Mixing array/non-array versions of <code>new</code> and <code>delete</code> is undefined behaviour. (C++ '03 5.3.5/4)</p>\n\n<p>Looking at the source it appears that someone did a search and replace for <code>malloc</code> and <code>free</code> and the above is the result. C++ does have a direct replacement for these functions, and that is to call the allocation functions for <code>new</code> and <code>delete</code> directly:</p>\n\n<pre><code>STRUCT* pStruct = (STRUCT*)::operator new (sizeof(STRUCT) + nPaddingSize);\n// ...\npStruct->~STRUCT (); // Call STRUCT destructor\n::operator delete (pStruct);\n</code></pre>\n\n<p>If the constructor for STRUCT should be called, then you could consider allocating the memory and then use placement <code>new</code>:</p>\n\n<pre><code>BYTE * pByteData = new BYTE[sizeof(STRUCT) + nPaddingSize];\nSTRUCT * pStruct = new (pByteData) STRUCT ();\n// ...\npStruct->~STRUCT ();\ndelete[] pByteData;\n</code></pre>\n"
},
{
"answer_id": 74361,
"author": "Eric",
"author_id": 12937,
"author_profile": "https://Stackoverflow.com/users/12937",
"pm_score": 0,
"selected": false,
"text": "<p>I think the is no memory leak.</p>\n\n<pre><code>STRUCT* pStruct = (STRUCT*)new BYTE [sizeof(STRUCT) + nPaddingSize];\n</code></pre>\n\n<p>This gets translated into a memory allocation call within the operating system upon which a pointer to that memory is returned. At the time memory is allocated, the size of <code>sizeof(STRUCT)</code> and the size of <code>nPaddingSize</code> would be known in order to fulfill any memory allocation requests against the underlying operating system.</p>\n\n<p>So the memory that is allocated is \"recorded\" in the operating system's global memory allocation tables. Memory tables are indexed by their pointers. So in the corresponding call to delete, all memory that was originally allocated is free. (memory fragmentation a popular subject in this realm as well).</p>\n\n<p>You see, the C/C++ compiler is not managing memory, the underlying operating system is.</p>\n\n<p>I agree there are cleaner methods but the OP did say this was legacy code.</p>\n\n<p>In short, I don't see a memory leak as the accepted answer believes there to be one.</p>\n"
},
{
"answer_id": 74411,
"author": "Assaf Lavie",
"author_id": 11208,
"author_profile": "https://Stackoverflow.com/users/11208",
"pm_score": 1,
"selected": false,
"text": "<p>It's an array delete ([]) you're referring to, not a vector delete.\nA vector is std::vector, and it takes care of deletion of its elements.</p>\n"
},
{
"answer_id": 75945,
"author": "Matt Cruikshank",
"author_id": 8643,
"author_profile": "https://Stackoverflow.com/users/8643",
"pm_score": -1,
"selected": false,
"text": "<p>ericmayo.myopenid.com is so wrong, that someone with enough reputation should downvote him.</p>\n\n<p>The C or C++ runtime libraries are managing the heap which is given to it in blocks by the Operating System, somewhat like you indicate, Eric. But it <em>is</em> the responsibility of the developer to indicate to the compiler which runtime calls should be made to free memory, and possibly destruct the objects that are there. Vector delete (aka delete[]) is necessary in this case, in order for the C++ runtime to leave the heap in a valid state. The fact that when the PROCESS terminates, the OS is smart enough to deallocate the underlying memory blocks is not something that developers should rely on. This would be like never calling delete at all.</p>\n"
},
{
"answer_id": 79620,
"author": "Eric",
"author_id": 12937,
"author_profile": "https://Stackoverflow.com/users/12937",
"pm_score": 0,
"selected": false,
"text": "<p>@Matt Cruikshank \nYou should pay attention and read what I wrote again because I never suggested not calling delete[] and just let the OS clean up. And you're wrong about the C++ run-time libraries managing the heap. If that were the case then C++ would not be portable as is today and a crashing application would never get cleaned up by the OS. (acknowledging there are OS specific run-times that make C/C++ appear non-portable). I challenge you to find stdlib.h in the Linux sources from kernel.org. The new keyword in C++ actually is talking to the same memory management routines as malloc.</p>\n\n<p>The C++ run-time libraries make OS system calls and it's the OS that manages the heaps. You are partly correct in that the run-time libraries indicate when to release the memory however, they don't actually walk any heap tables directly. In other words, the runtime you link against does not add code to your application to walk heaps to allocate or deallocate. This is the case in Windows, Linux, Solaris, AIX, etc... It's also the reason you won't fine malloc in any Linux's kernel source nor will you find stdlib.h in Linux source. Understand these modern operating system have virtual memory managers that complicates things a bit further.</p>\n\n<p>Ever wonder why you can make a call to malloc for 2G of RAM on a 1G box and still get back a valid memory pointer?</p>\n\n<p>Memory management on x86 processors is managed within Kernel space using three tables. PAM (Page Allocation Table), PD (Page Directories) and PT (Page Tables). This is at the hardware level I'm speaking of. One of the things the OS memory manager does, not your C++ application, is to find out how much physical memory is installed on the box during boot with help of BIOS calls. The OS also handles exceptions such as when you try to access memory your application does not have rights too. (GPF General Protection Fault).</p>\n\n<p>It may be that we are saying the same thing Matt, but I think you may be confusing the under hood functionality a bit. I use to maintain a C/C++ compiler for a living...</p>\n"
},
{
"answer_id": 83972,
"author": "Matt Cruikshank",
"author_id": 8643,
"author_profile": "https://Stackoverflow.com/users/8643",
"pm_score": 0,
"selected": false,
"text": "<p>@ericmayo - cripes. Well, experimenting with VS2005, I can't get an honest leak out of scalar delete on memory that was made by vector new. I guess the compiler behavior is \"undefined\" here, is about the best defense I can muster.</p>\n\n<p>You've got to admit though, it's a really lousy practice to do what the original poster said.</p>\n\n<blockquote>\n <p>If that were the case then C++ would\n not be portable as is today and a\n crashing application would never get\n cleaned up by the OS.</p>\n</blockquote>\n\n<p>This logic doesn't really hold, though. My assertion is that a compiler's runtime can manage the memory within the memory blocks that the OS returns to it. This is how most virtual machines work, so your argument against portability in this case don't make much sense.</p>\n"
},
{
"answer_id": 84335,
"author": "Eric",
"author_id": 12937,
"author_profile": "https://Stackoverflow.com/users/12937",
"pm_score": 0,
"selected": false,
"text": "<p>@Matt Cruikshank</p>\n\n<p>\"Well, experimenting with VS2005, I can't get an honest leak out of scalar delete on memory that was made by vector new. I guess the compiler behavior is \"undefined\" here, is about the best defense I can muster.\"</p>\n\n<p>I disagree that it's a compiler behavior or even a compiler issue. The 'new' keyword gets compiled and linked, as you pointed out, to run-time libraries. Those run-time libraries handle the memory management calls to the OS in a OS independent consistent syntax and those run-time libraries are responsible for making malloc and new work consistently between OSes such as Linux, Windows, Solaris, AIX, etc.... This is the reason I mentioned the portability argument; an attempt to prove to you that the run-time does not actually manage memory either. </p>\n\n<p>The OS manages memory. </p>\n\n<p>The run-time libs interface to the OS.. On Windows, this is the virtual memory manager DLLs. This is why stdlib.h is implemented within the GLIB-C libraries and not the Linux kernel source; if GLIB-C is used on other OSes, it's implementation of malloc changes to make the correct OS calls. In VS, Borland, etc.. you will never find any libraries that ship with their compilers that actually manage memory either. You will, however, find OS specific definitions for malloc.</p>\n\n<p>Since we have the source to Linux, you can go look at how malloc is implemented there. You will see that malloc is actually implemented in the GCC compiler which, in turn, basically makes two Linux system calls into the kernel to allocate memory. Never, malloc itself, actually managing memory!</p>\n\n<p>And don't take it from me. Read the source code to Linux OS or you can see what K&R say about it... Here is a PDF link to the K&R on C.</p>\n\n<p><a href=\"http://www.oberon2005.ru/paper/kr_c.pdf\" rel=\"nofollow noreferrer\">http://www.oberon2005.ru/paper/kr_c.pdf</a></p>\n\n<p>See near end of Page 149:\n\"Calls to malloc and free may occur in any order; malloc calls\nupon the operating system to obtain more memory as necessary. These routines illustrate some of the considerations involved in writing machine-dependent code in a relatively machineindependent way, and also show a real-life application of structures, unions and typedef.\"</p>\n\n<p>\"You've got to admit though, it's a really lousy practice to do what the original poster said.\"</p>\n\n<p>Oh, I don't disagree there. My point was that the original poster's code was not conducive of a memory leak. That's all I was saying. I didn't chime in on the best practice side of things. Since the code is calling delete, the memory is getting free up.</p>\n\n<p>I agree, in your defense, if the original poster's code never exited or never made it to the delete call, that the code could have a memory leak but since he states that later on he sees the delete getting called. \"Later on however the memory is freed using a delete call:\"</p>\n\n<p>Moreover, my reason for responding as I did was due to the OP's comment \"variable length structures (TAPI), where the structure size will depend on variable length strings\"</p>\n\n<p>That comment sounded like he was questioning the dynamic nature of the allocations against the cast being made and was consequentially wondering if that would cause a memory leak. I was reading between the lines if you will ;).</p>\n"
},
{
"answer_id": 84503,
"author": "KPexEA",
"author_id": 13676,
"author_profile": "https://Stackoverflow.com/users/13676",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to the excellent answers above, I would also like to add:</p>\n\n<p>If your code runs on linux or if you can compile it on linux then I would suggest running it through <a href=\"http://valgrind.org/\" rel=\"nofollow noreferrer\">Valgrind</a>. It is an excellent tool, among the myriad of useful warnings it produces it also will tell you when you allocate memory as an array and then free it as a non-array ( and vice-versa ).</p>\n"
},
{
"answer_id": 85021,
"author": "Matt Cruikshank",
"author_id": 8643,
"author_profile": "https://Stackoverflow.com/users/8643",
"pm_score": 2,
"selected": false,
"text": "<p>@eric - Thanks for the comments. You keep saying something though, that drives me nuts:</p>\n\n<blockquote>\n <p>Those run-time libraries handle the\n memory management calls to the OS in a\n OS independent consistent syntax and\n those run-time libraries are\n responsible for making malloc and new\n work consistently between OSes such as\n Linux, Windows, Solaris, AIX, etc....</p>\n</blockquote>\n\n<p>This is not true. The compiler writer provides the implementation of the std libraries, for instance, and they are absolutely free to implement those in an OS <strong>dependent</strong> way. They're free, for instance, to make one giant call to malloc, and then manage memory within the block however they wish.</p>\n\n<p>Compatibility is provided because the API of std, etc. is the same - not because the run-time libraries all turn around and call the exact same OS calls.</p>\n"
},
{
"answer_id": 108454,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 2,
"selected": false,
"text": "<p>The various possible uses of the keywords new and delete seem to create a fair amount of confusion. There are always two stages to constructing dynamic objects in C++: the allocation of the raw memory and the construction of the new object in the allocated memory area. On the other side of the object lifetime there is the destruction of the object and the deallocation of the memory location where the object resided.</p>\n\n<p>Frequently these two steps are performed by a single C++ statement.</p>\n\n<pre><code>MyObject* ObjPtr = new MyObject;\n\n//...\n\ndelete MyObject;\n</code></pre>\n\n<p>Instead of the above you can use the C++ raw memory allocation functions <code>operator new</code> and <code>operator delete</code> and explicit construction (via placement <code>new</code>) and destruction to perform the equivalent steps.</p>\n\n<pre><code>void* MemoryPtr = ::operator new( sizeof(MyObject) );\nMyObject* ObjPtr = new (MemoryPtr) MyObject;\n\n// ...\n\nObjPtr->~MyObject();\n::operator delete( MemoryPtr );\n</code></pre>\n\n<p>Notice how there is no casting involved, and only one type of object is constructed in the allocated memory area. Using something like <code>new char[N]</code> as a way to allocate raw memory is technically incorrect as, logically, <code>char</code> objects are created in the newly allocated memory. I don't know of any situation where it doesn't 'just work' but it blurs the distinction between raw memory allocation and object creation so I advise against it.</p>\n\n<p>In this particular case, there is no gain to be had by separating out the two steps of <code>delete</code> but you do need to manually control the initial allocation. The above code works in the 'everything working' scenario but it will leak the raw memory in the case where the constructor of <code>MyObject</code> throws an exception. While this could be caught and solved with an exception handler at the point of allocation it is probably neater to provide a custom operator new so that the complete construction can be handled by a placement new expression.</p>\n\n<pre><code>class MyObject\n{\n void* operator new( std::size_t rqsize, std::size_t padding )\n {\n return ::operator new( rqsize + padding );\n }\n\n // Usual (non-placement) delete\n // We need to define this as our placement operator delete\n // function happens to have one of the allowed signatures for\n // a non-placement operator delete\n void operator delete( void* p )\n {\n ::operator delete( p );\n }\n\n // Placement operator delete\n void operator delete( void* p, std::size_t )\n {\n ::operator delete( p );\n }\n};\n</code></pre>\n\n<p>There are a couple of subtle points here. We define a class placement new so that we can allocate enough memory for the class instance plus some user specifiable padding. Because we do this we need to provide a matching placement delete so that if the memory allocation succeeds but the construction fails, the allocated memory is automatically deallocated. Unfortunately, the signature for our placement delete matches one of the two allowed signatures for non-placement delete so we need to provide the other form of non-placement delete so that our real placement delete is treated as a placement delete. (We could have got around this by adding an extra dummy parameter to both our placement new and placement delete, but this would have required extra work at all the calling sites.)</p>\n\n<pre><code>// Called in one step like so:\nMyObject* ObjectPtr = new (padding) MyObject;\n</code></pre>\n\n<p>Using a single new expression we are now guaranteed that memory won't leak if any part of the new expression throws.</p>\n\n<p>At the other end of the object lifetime, because we defined operator delete (even if we hadn't, the memory for the object originally came from global operator new in any case), the following is the correct way to destroy the dynamically created object.</p>\n\n<pre><code>delete ObjectPtr;\n</code></pre>\n\n<p>Summary!</p>\n\n<ol>\n<li><p>Look no casts! <code>operator new</code> and <code>operator delete</code> deal with raw memory, placement new can construct objects in raw memory. An explicit cast from a <code>void*</code> to an object pointer is usually a sign of something logically wrong, even if it does 'just work'.</p></li>\n<li><p>We've completely ignored new[] and delete[]. These variable size objects will not work in arrays in any case.</p></li>\n<li><p>Placement new allows a new expression not to leak, the new expression still evaluates to a pointer to an object that needs destroying and memory that needs deallocating. Use of some type of smart pointer may help prevent other types of leak. On the plus side we've let a plain <code>delete</code> be the correct way to do this so most standard smart pointers will work.</p></li>\n</ol>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
]
| I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allocated by casting array `new` thus:
```cpp
STRUCT* pStruct = (STRUCT*)new BYTE[sizeof(STRUCT) + nPaddingSize];
```
Later on however the memory is freed using a `delete` call:
```cpp
delete pStruct;
```
Will this mix of array `new[]` and non-array `delete` cause a memory leak or would it depend on the compiler? Would I be better off changing this code to use `malloc` and `free` instead? | Technically I believe it could cause a problem with mismatched allocators, though in practice I don't know of any compiler that would not do the right thing with this example.
More importantly if `STRUCT` where to have (or ever be given) a destructor then it would invoke the destructor without having invoked the corresponding constructor.
Of course, if you know where pStruct came from why not just cast it on delete to match the allocation:
```
delete [] (BYTE*) pStruct;
``` |
73,162 | <p>Is there an API call in .NET or a native DLL that I can use to create similar behaviour as Windows Live Messenger when a response comes from someone I chat with?</p>
| [
{
"answer_id": 73203,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": 2,
"selected": false,
"text": "<p>The FlashWindowEx Win32 API is the call used to do this. The documentation for it is at:\n<a href=\"http://msdn.microsoft.com/en-us/library/ms679347(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms679347(VS.85).aspx</a></p>\n"
},
{
"answer_id": 73208,
"author": "nathaniel",
"author_id": 11947,
"author_profile": "https://Stackoverflow.com/users/11947",
"pm_score": 2,
"selected": false,
"text": "<pre><code>HWND hHandle = FindWindow(NULL,\"YourApplicationName\");\nFLASHWINFO pf;\npf.cbSize = sizeof(FLASHWINFO);\npf.hwnd = hHandle;\npf.dwFlags = FLASHW_TIMER|FLASHW_TRAY; // (or FLASHW_ALL to flash and if it is not minimized)\npf.uCount = 8;\npf.dwTimeout = 75;\n\nFlashWindowEx(&pf);\n</code></pre>\n\n<p>Stolen from experts-exchange member gtokas.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms679347%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">FlashWindowEx</a>.</p>\n"
},
{
"answer_id": 73209,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 0,
"selected": false,
"text": "<p>I believe you're looking for <a href=\"http://msdn.microsoft.com/en-us/library/ms633539.aspx\" rel=\"nofollow noreferrer\"><code>SetForegroundWindow</code></a>.</p>\n"
},
{
"answer_id": 73287,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 2,
"selected": false,
"text": "<p>From a Raymond Chen blog entry: </p>\n\n<blockquote>\n <p><strong><a href=\"http://blogs.msdn.com/oldnewthing/archive/2008/05/12/8490184.aspx\" rel=\"nofollow noreferrer\">How do I flash my window caption and taskbar button manually?</a></strong></p>\n \n <p>How do I flash my window caption and\n taskbar button manually? Commenter\n Jonathan Scheepers wonders about those\n programs that flash their taskbar\n button indefinitely, overriding the\n default flash count set by\n SysteParametersInfo(SPI_SETFOREGROUNDFLASHCOUNT).</p>\n \n <p>The FlashWindowEx function and its\n simpler precursor FlashWindow let a\n program flash its window caption and\n taskbar button manually. The window\n manager flashes the caption\n automatically (and Explorer follows\n the caption by flashing the taskbar\n button) if a program calls\n SetForegroundWindow when it doesn't\n have permission to take foreground,\n and it is that automatic flashing that\n the SPI_SETFOREGROUNDFLASHCOUNT\n setting controls.</p>\n \n <p>For illustration purposes, I'll\n demonstrate flashing the caption\n manually. This is generally speaking\n not recommended, but since you asked,\n I'll show you how. And then promise\n you won't do it.</p>\n \n <p>Start with the scratch program and\n make this simple change:</p>\n\n<pre><code>void\nOnSize(HWND hwnd, UINT state, int cx, int cy)\n{\n if (state == SIZE_MINIMIZED) {\n FLASHWINFO fwi = { sizeof(fwi), hwnd,\n FLASHW_TIMERNOFG | FLASHW_ALL };\n FlashWindowEx(&fwi);\n }\n}\n</code></pre>\n \n <p>Compile and run this program, then\n minimize it. When you do, its taskbar\n button flashes indefinitely until you\n click on it. The program responds to\n being minimzed by calling the\n FlashWindowEx function asking for\n everything possible (currently the\n caption and taskbar button) to be\n flashed until the window comes to the\n foreground.</p>\n \n <p>Other members of the FLASHWINFO\n structure let you customize the\n flashing behavior further, such as\n controlling the flash frequency and\n the number of flashes. and if you\n really want to take control, you can\n use FLASHW_ALL and FLASHW_STOP to turn\n your caption and taskbar button on and\n off exactly the way you want it. (Who\n knows, maybe you want to send a\n message in Morse code.)</p>\n \n <p>Published Monday, May 12, 2008 7:00 AM\n by oldnewthing Filed under: Code</p>\n</blockquote>\n"
},
{
"answer_id": 73383,
"author": "dummy",
"author_id": 6297,
"author_profile": "https://Stackoverflow.com/users/6297",
"pm_score": 6,
"selected": true,
"text": "<p>FlashWindowEx is the way to go. See <a href=\"http://msdn.microsoft.com/en-us/library/ms679347%28VS.85%29.aspx\" rel=\"noreferrer\">here for MSDN documentation</a></p>\n\n<pre><code>[DllImport(\"user32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool FlashWindowEx(ref FLASHWINFO pwfi);\n\n[StructLayout(LayoutKind.Sequential)]\npublic struct FLASHWINFO\n{\n public UInt32 cbSize;\n public IntPtr hwnd;\n public UInt32 dwFlags;\n public UInt32 uCount;\n public UInt32 dwTimeout;\n}\n\npublic const UInt32 FLASHW_ALL = 3; \n</code></pre>\n\n<p>Calling the Function:</p>\n\n<pre><code>FLASHWINFO fInfo = new FLASHWINFO();\n\nfInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));\nfInfo.hwnd = hWnd;\nfInfo.dwFlags = FLASHW_ALL;\nfInfo.uCount = UInt32.MaxValue;\nfInfo.dwTimeout = 0;\n\nFlashWindowEx(ref fInfo);\n</code></pre>\n\n<p>This was shamelessly plugged from <a href=\"http://pinvoke.net/default.aspx/user32/FlashWindowEx.html\" rel=\"noreferrer\">Pinvoke.net</a></p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6896/"
]
| Is there an API call in .NET or a native DLL that I can use to create similar behaviour as Windows Live Messenger when a response comes from someone I chat with? | FlashWindowEx is the way to go. See [here for MSDN documentation](http://msdn.microsoft.com/en-us/library/ms679347%28VS.85%29.aspx)
```
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool FlashWindowEx(ref FLASHWINFO pwfi);
[StructLayout(LayoutKind.Sequential)]
public struct FLASHWINFO
{
public UInt32 cbSize;
public IntPtr hwnd;
public UInt32 dwFlags;
public UInt32 uCount;
public UInt32 dwTimeout;
}
public const UInt32 FLASHW_ALL = 3;
```
Calling the Function:
```
FLASHWINFO fInfo = new FLASHWINFO();
fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));
fInfo.hwnd = hWnd;
fInfo.dwFlags = FLASHW_ALL;
fInfo.uCount = UInt32.MaxValue;
fInfo.dwTimeout = 0;
FlashWindowEx(ref fInfo);
```
This was shamelessly plugged from [Pinvoke.net](http://pinvoke.net/default.aspx/user32/FlashWindowEx.html) |
73,198 | <p>When using Linq to SQL and stored procedures, the class generated to describe the proc's result set uses char properties to represent char(1) columns in the SQL proc. I'd rather these be strings - is there any easy way to make this happen?</p>
| [
{
"answer_id": 73237,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": -1,
"selected": false,
"text": "<p>Not sure why you'd want to do that. The underlying data type can't store more than one char, by representing it as a string variable you introduce the need to check lengths before committing to the db, where as if you leave it as is you can just call ToString() on the char to get a string</p>\n"
},
{
"answer_id": 73812,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 0,
"selected": false,
"text": "<pre><code>var whatever =\n from x in something\n select new { yourString = Char.ToString(x.theChar); }\n</code></pre>\n"
},
{
"answer_id": 73976,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": true,
"text": "<p>You could modify the {database}.designer.cs file. I don't have one handy to check, but I believe it's fairly straight forward --- you'll just have to plow through a lot of code, and remember to re-apply the change if you ever regenerate it.</p>\n\n<p>Alternately, you could create your own class and handle it in the select. For example, given the LINQ generated class:</p>\n\n<pre><code>class MyTable\n{ int MyNum {get; set;}\n int YourNum {get; set;}\n char OneChar {get; set;}\n}\n</code></pre>\n\n<p>you could easily create: </p>\n\n<pre><code>class MyFixedTable\n{ int MyNum {get; set;}\n int YourNum {get; set;}\n string OneChar {get; set;}\n public MyFixedTable(MyTable t)\n {\n this,MyNum = t.MyNum;\n this.YourNum = t.YourNum;\n this.OneChar = new string(t.OneChar, 1);\n }\n}\n</code></pre>\n\n<p>Then instead of writing:</p>\n\n<pre><code>var q = from t in db.MyTable\n select t;\n</code></pre>\n\n<p>write</p>\n\n<pre><code>var q = from t in db.MyTable\n select new MyFixTable(t);\n</code></pre>\n"
},
{
"answer_id": 173294,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": 0,
"selected": false,
"text": "<p>Just go to the designer window and change the type to string. I do it all the time, as I find Strings to be easier to use than Char in my code.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12260/"
]
| When using Linq to SQL and stored procedures, the class generated to describe the proc's result set uses char properties to represent char(1) columns in the SQL proc. I'd rather these be strings - is there any easy way to make this happen? | You could modify the {database}.designer.cs file. I don't have one handy to check, but I believe it's fairly straight forward --- you'll just have to plow through a lot of code, and remember to re-apply the change if you ever regenerate it.
Alternately, you could create your own class and handle it in the select. For example, given the LINQ generated class:
```
class MyTable
{ int MyNum {get; set;}
int YourNum {get; set;}
char OneChar {get; set;}
}
```
you could easily create:
```
class MyFixedTable
{ int MyNum {get; set;}
int YourNum {get; set;}
string OneChar {get; set;}
public MyFixedTable(MyTable t)
{
this,MyNum = t.MyNum;
this.YourNum = t.YourNum;
this.OneChar = new string(t.OneChar, 1);
}
}
```
Then instead of writing:
```
var q = from t in db.MyTable
select t;
```
write
```
var q = from t in db.MyTable
select new MyFixTable(t);
``` |
73,227 | <p>I get asked this question a lot and I thought I'd solicit some input on how to best describe the difference.</p>
| [
{
"answer_id": 73249,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": -1,
"selected": false,
"text": "<p>Well, the really oversimplified version is that a lambda is just shorthand for an anonymous function. A delegate can do a lot more than just anonymous functions: things like events, asynchronous calls, and multiple method chains.</p>\n"
},
{
"answer_id": 73255,
"author": "chessguy",
"author_id": 1908025,
"author_profile": "https://Stackoverflow.com/users/1908025",
"pm_score": 2,
"selected": false,
"text": "<p>I don't have a ton of experience with this, but the way I would describe it is that a delegate is a wrapper around any function, whereas a lambda expression is itself an anonymous function.</p>\n"
},
{
"answer_id": 73259,
"author": "Dan Shield",
"author_id": 4633,
"author_profile": "https://Stackoverflow.com/users/4633",
"pm_score": 4,
"selected": false,
"text": "<p>Delegates are equivalent to function pointers/method pointers/callbacks (take your pick), and lambdas are pretty much simplified anonymous functions. At least that's what I tell people.</p>\n"
},
{
"answer_id": 73271,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": 2,
"selected": false,
"text": "<p>lambdas are simply syntactic sugar on a delegate. The compiler ends up converting lambdas into delegates.</p>\n\n<p>These are the same, I believe:</p>\n\n<pre><code>Delegate delegate = x => \"hi!\";\nDelegate delegate = delegate(object x) { return \"hi\";};\n</code></pre>\n"
},
{
"answer_id": 73318,
"author": "Steve Cooper",
"author_id": 6722,
"author_profile": "https://Stackoverflow.com/users/6722",
"pm_score": 2,
"selected": false,
"text": "<p>A delegate is a function signature; something like </p>\n\n<pre><code>delegate string MyDelegate(int param1);\n</code></pre>\n\n<p>The delegate does not implement a body. </p>\n\n<p>The lambda is a function call that matches the signature of the delegate. For the above delegate, you might use any of;</p>\n\n<pre><code>(int i) => i.ToString();\n(int i) => \"ignored i\";\n(int i) => \"Step \" + i.ToString() + \" of 10\";\n</code></pre>\n\n<p>The <code>Delegate</code> type is badly named, though; creating an object of type <code>Delegate</code> actually creates a variable which can hold functions -- be they lambdas, static methods, or class methods.</p>\n"
},
{
"answer_id": 73367,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 2,
"selected": false,
"text": "<p>A delegate is always just basically a function pointer. A lambda can turn into a delegate, but it can also turn into a LINQ expression tree. For instance,</p>\n\n<pre><code>Func<int, int> f = x => x + 1;\nExpression<Func<int, int>> exprTree = x => x + 1;\n</code></pre>\n\n<p>The first line produces a delegate, while the second produces an expression tree.</p>\n"
},
{
"answer_id": 73384,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 1,
"selected": false,
"text": "<p>Delegates are really just structural typing for functions. You could do the same thing with nominal typing and implementing an anonymous class that implements an interface or abstract class, but that ends up being a lot of code when only one function is needed.</p>\n\n<p>Lambda comes from the idea of lambda calculus of Alonzo Church in the 1930s. It is an anonymous way of creating functions. They become especially useful for composing functions</p>\n\n<p>So while some might say lambda is syntactic sugar for delegates, I would says delegates are a bridge for easing people into lambdas in c#.</p>\n"
},
{
"answer_id": 73408,
"author": "Michael Meadows",
"author_id": 7643,
"author_profile": "https://Stackoverflow.com/users/7643",
"pm_score": 0,
"selected": false,
"text": "<p>Lambdas are simplified versions of delegates. They have some of the the properties of a <a href=\"http://en.wikipedia.org/wiki/Closure_(computer_science)\" rel=\"nofollow noreferrer\">closure</a> like anonymous delegates, but also allow you to use implied typing. A lambda like this:</p>\n\n<pre><code>something.Sort((x, y) => return x.CompareTo(y));\n</code></pre>\n\n<p>is a lot more concise than what you can do with a delegate:</p>\n\n<pre><code>something.Sort(sortMethod);\n...\n\nprivate int sortMethod(SomeType one, SomeType two)\n{\n one.CompareTo(two)\n}\n</code></pre>\n"
},
{
"answer_id": 73448,
"author": "Karg",
"author_id": 12685,
"author_profile": "https://Stackoverflow.com/users/12685",
"pm_score": 5,
"selected": false,
"text": "<p>One difference is that an anonymous delegate can omit parameters while a lambda must match the exact signature. Given:</p>\n\n<pre><code>public delegate string TestDelegate(int i);\n\npublic void Test(TestDelegate d)\n{}\n</code></pre>\n\n<p>you can call it in the following four ways (note that the second line has an anonymous delegate that does not have any parameters):</p>\n\n<pre><code>Test(delegate(int i) { return String.Empty; });\nTest(delegate { return String.Empty; });\nTest(i => String.Empty);\nTest(D);\n\nprivate string D(int i)\n{\n return String.Empty;\n}\n</code></pre>\n\n<p>You cannot pass in a lambda expression that has no parameters or a method that has no parameters. These are not allowed:</p>\n\n<pre><code>Test(() => String.Empty); //Not allowed, lambda must match signature\nTest(D2); //Not allowed, method must match signature\n\nprivate string D2()\n{\n return String.Empty;\n}\n</code></pre>\n"
},
{
"answer_id": 73819,
"author": "Chris Ammerman",
"author_id": 2729,
"author_profile": "https://Stackoverflow.com/users/2729",
"pm_score": 8,
"selected": true,
"text": "<p>They are actually two very different things. \"Delegate\" is actually the name for a variable that holds a reference to a method or a lambda, and a lambda is a method without a permanent name.</p>\n\n<p>Lambdas are very much like other methods, except for a couple subtle differences.</p>\n\n<ol>\n<li>A normal method is defined in a <a href=\"http://en.wikipedia.org/wiki/Statement_(programming)\" rel=\"noreferrer\">\"statement\"</a> and tied to a permanent name, whereas a lambda is defined \"on the fly\" in an <a href=\"http://en.wikipedia.org/wiki/Expression_(programming)\" rel=\"noreferrer\">\"expression\"</a> and has no permanent name.</li>\n<li>Some lambdas can be used with .NET expression trees, whereas methods cannot.</li>\n</ol>\n\n<p>A delegate is defined like this:</p>\n\n<pre><code>delegate Int32 BinaryIntOp(Int32 x, Int32 y);\n</code></pre>\n\n<p>A variable of type BinaryIntOp can have either a method or a labmda assigned to it, as long as the signature is the same: two Int32 arguments, and an Int32 return.</p>\n\n<p>A lambda might be defined like this:</p>\n\n<pre><code>BinaryIntOp sumOfSquares = (a, b) => a*a + b*b;\n</code></pre>\n\n<p>Another thing to note is that although the generic Func and Action types are often considered \"lambda types\", they are just like any other delegates. The nice thing about them is that they essentially define a name for any type of delegate you might need (up to 4 parameters, though you can certainly add more of your own). So if you are using a wide variety of delegate types, but none more than once, you can avoid cluttering your code with delegate declarations by using Func and Action.</p>\n\n<p>Here is an illustration of how Func and Action are \"not just for lambdas\":</p>\n\n<pre><code>Int32 DiffOfSquares(Int32 x, Int32 y)\n{\n return x*x - y*y;\n}\n\nFunc<Int32, Int32, Int32> funcPtr = DiffOfSquares;\n</code></pre>\n\n<p>Another useful thing to know is that delegate types (not methods themselves) with the same signature but different names will not be implicitly casted to each other. This includes the Func and Action delegates. However if the signature is identical, you can explicitly cast between them.</p>\n\n<p>Going the extra mile.... In C# functions are flexible, with the use of lambdas and delegates. But C# does not have \"first-class functions\". You can use a function's name assigned to a delegate variable to essentially create an object representing that function. But it's really a compiler trick. If you start a statement by writing the function name followed by a dot (i.e. try to do member access on the function itself) you'll find there are no members there to reference. Not even the ones from Object. This prevents the programmer from doing useful (and potentially dangerous of course) things such as adding extension methods that can be called on any function. The best you can do is extend the Delegate class itself, which is surely also useful, but not quite as much.</p>\n\n<p>Update: Also see <a href=\"https://stackoverflow.com/questions/73227/what-is-the-difference-between-lambdas-and-delegates-in-the-net-framework#73448\">Karg's answer</a> illustrating the difference between anonymous delegates vs. methods & lambdas.</p>\n\n<p>Update 2: <a href=\"https://stackoverflow.com/questions/73227/what-is-the-difference-between-lambdas-and-delegates-in-the-net-framework#74414\">James Hart</a> makes an important, though very technical, note that lambdas and delegates are not .NET entities (i.e. the CLR has no concept of a delegate or lambda), but rather they are framework and language constructs.</p>\n"
},
{
"answer_id": 74079,
"author": "Echostorm",
"author_id": 12862,
"author_profile": "https://Stackoverflow.com/users/12862",
"pm_score": 0,
"selected": false,
"text": "<p>Heres an example I put up awhile on my lame blog. Say you wanted to update a label from a worker thread. I've got 4 examples of how to update that label from 1 to 50 using delegates, anon delegates and 2 types of lambdas.</p>\n\n<pre><code> private void button2_Click(object sender, EventArgs e) \n { \n BackgroundWorker worker = new BackgroundWorker(); \n worker.DoWork += new DoWorkEventHandler(worker_DoWork); \n worker.RunWorkerAsync(); \n } \n\n private delegate void UpdateProgDelegate(int count); \n private void UpdateText(int count) \n { \n if (this.lblTest.InvokeRequired) \n { \n UpdateProgDelegate updateCallBack = new UpdateProgDelegate(UpdateText); \n this.Invoke(updateCallBack, new object[] { count }); \n } \n else \n { \n lblTest.Text = count.ToString(); \n } \n } \n\n void worker_DoWork(object sender, DoWorkEventArgs e) \n { \n /* Old Skool delegate usage. See above for delegate and method definitions */ \n for (int i = 0; i < 50; i++) \n { \n UpdateText(i); \n Thread.Sleep(50); \n } \n\n // Anonymous Method \n for (int i = 0; i < 50; i++) \n { \n lblTest.Invoke((MethodInvoker)(delegate() \n { \n lblTest.Text = i.ToString(); \n })); \n Thread.Sleep(50); \n } \n\n /* Lambda using the new Func delegate. This lets us take in an int and \n * return a string. The last parameter is the return type. so \n * So Func<int, string, double> would take in an int and a string \n * and return a double. count is our int parameter.*/ \n Func<int, string> UpdateProgress = (count) => lblTest.Text = count.ToString(); \n for (int i = 0; i < 50; i++) \n { \n lblTest.Invoke(UpdateProgress, i); \n Thread.Sleep(50); \n } \n\n /* Finally we have a totally inline Lambda using the Action delegate \n * Action is more or less the same as Func but it returns void. We could \n * use it with parameters if we wanted to like this: \n * Action<string> UpdateProgress = (count) => lblT…*/ \n for (int i = 0; i < 50; i++) \n { \n lblTest.Invoke((Action)(() => lblTest.Text = i.ToString())); \n Thread.Sleep(50); \n } \n }\n</code></pre>\n"
},
{
"answer_id": 74283,
"author": "Peter Ritchie",
"author_id": 5620,
"author_profile": "https://Stackoverflow.com/users/5620",
"pm_score": 2,
"selected": false,
"text": "<p>A delegate is a reference to a method with a particular parameter list and return type. It may or may not include an object.</p>\n\n<p>A lambda-expression is a form of anonymous function.</p>\n"
},
{
"answer_id": 74303,
"author": "justin.m.chase",
"author_id": 12958,
"author_profile": "https://Stackoverflow.com/users/12958",
"pm_score": 2,
"selected": false,
"text": "<p>A delegate is a Queue of function pointers, invoking a delegate may invoke multiple methods. A lambda is essentially an anonymous method declaration which may be interpreted by the compiler differently, depending on what context it is used as.</p>\n\n<p>You can get a delegate that points to the lambda expression as a method by casting it into a delegate, or if passing it in as a parameter to a method that expects a specific delegate type the compiler will cast it for you. Using it inside of a LINQ statement, the lambda will be translated by the compiler into an expression tree instead of simply a delegate.</p>\n\n<p>The difference really is that a lambda is a terse way to define a method inside of another expression, while a delegate is an actual object type.</p>\n"
},
{
"answer_id": 74414,
"author": "James Hart",
"author_id": 5755,
"author_profile": "https://Stackoverflow.com/users/5755",
"pm_score": 5,
"selected": false,
"text": "<p>The question is a little ambiguous, which explains the wide disparity in answers you're getting.</p>\n\n<p>You actually asked what the difference is between lambdas and delegates in the .NET framework; that might be one of a number of things. Are you asking:</p>\n\n<ul>\n<li><p>What is the difference between lambda expressions and anonymous delegates in the C# (or VB.NET) language?</p></li>\n<li><p>What is the difference between System.Linq.Expressions.LambdaExpression objects and System.Delegate objects in .NET 3.5?</p></li>\n<li><p>Or something somewhere between or around those extremes?</p></li>\n</ul>\n\n<p>Some people seem to be trying to give you the answer to the question 'what is the difference between C# Lambda expressions and .NET System.Delegate?', which doesn't make a whole lot of sense.</p>\n\n<p>The .NET framework does not in itself understand the concepts of anonymous delegates, lambda expressions, or closures - those are all things defined by language specifications. Think about how the C# compiler translates the definition of an anonymous method into a method on a generated class with member variables to hold closure state; to .NET, there's nothing anonymous about the delegate; it's just anonymous to the C# programmer writing it. That's equally true of a lambda expression assigned to a delegate type.</p>\n\n<p>What .NET <em>DOES</em> understand is the idea of a delegate - a type that describes a method signature, instances of which represent either bound calls to specific methods on specific objects, or unbound calls to a particular method on a particular type that can be invoked against any object of that type, where said method adheres to the said signature. Such types all inherit from System.Delegate.</p>\n\n<p>.NET 3.5 also introduces the System.Linq.Expressions namespace, which contains classes for describing code expressions - and which can also therefore represent bound or unbound calls to methods on particular types or objects. LambdaExpression instances can then be compiled into actual delegates (whereby a dynamic method based on the structure of the expression is codegenned, and a delegate pointer to it is returned).</p>\n\n<p>In C# you can produce instances of System.Expressions.Expression types by assigning a lambda expression to a variable of said type, which will produce the appropriate code to construct the expression at runtime.</p>\n\n<p>Of course, if you <em>were</em> asking what the difference is between lambda expressions and anonymous methods in C#, after all, then all this is pretty much irelevant, and in that case the primary difference is brevity, which leans towards anonymous delegates when you don't care about parameters and don't plan on returning a value, and towards lambdas when you want type inferenced parameters and return types.</p>\n\n<p>And lambda expressions support expression generation.</p>\n"
},
{
"answer_id": 6460111,
"author": "Philip Beber",
"author_id": 813016,
"author_profile": "https://Stackoverflow.com/users/813016",
"pm_score": 2,
"selected": false,
"text": "<p>It is pretty clear the question was meant to be \"what's the difference between lambdas and <strong>anonymous</strong> delegates?\" Out of all the answers here only one person got it right - the main difference is that lambdas can be used to create expression trees as well as delegates.</p>\n\n<p>You can read more on MSDN: <a href=\"http://msdn.microsoft.com/en-us/library/bb397687.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/bb397687.aspx</a></p>\n"
},
{
"answer_id": 27059973,
"author": "Olorin",
"author_id": 1581875,
"author_profile": "https://Stackoverflow.com/users/1581875",
"pm_score": 0,
"selected": false,
"text": "<p><em>I assume that your question concerns c# and not .NET, because of the ambiguity of your question, as .NET does not get alone - that is, without c# - comprehension of delegates and lambda expressions.</em></p>\n\n<p>A (<em>normal</em>, in opposition to so called <em>generic</em> delegates, <em>cf</em> later) delegate should be seen as a kind of c++ <code>typedef</code> of a function pointer type, for instance in c++ :</p>\n\n<pre><code>R (*thefunctionpointer) ( T ) ;\n</code></pre>\n\n<p>typedef's the type <code>thefunctionpointer</code> which is the type of pointers to a function taking an object of type <code>T</code> and returning an object of type <code>R</code>. You would use it like this :</p>\n\n<pre><code>thefunctionpointer = &thefunction ;\nR r = (*thefunctionpointer) ( t ) ; // where t is of type T\n</code></pre>\n\n<p>where <code>thefunction</code> would be a function taking a <code>T</code> and returning an <code>R</code>.</p>\n\n<p>In c# you would go for</p>\n\n<pre><code>delegate R thedelegate( T t ) ; // and yes, here the identifier t is needed\n</code></pre>\n\n<p>and you would use it like this :</p>\n\n<pre><code>thedelegate thedel = thefunction ;\nR r = thedel ( t ) ; // where t is of type T\n</code></pre>\n\n<p>where <code>thefunction</code> would be a function taking a <code>T</code> and returning an <code>R</code>. This is for delegates, so called normal delegates.</p>\n\n<p>Now, you also have generic delegates in c#, which are delegates that are generic, <em>i.e.</em> that are \"templated\" so to speak, using thereby a c++ expression. They are defined like this :</p>\n\n<pre><code>public delegate TResult Func<in T, out TResult>(T arg);\n</code></pre>\n\n<p>And you can used them like this :</p>\n\n<pre><code>Func<double, double> thefunctor = thefunction2; // call it a functor because it is\n // really as a functor that you should\n // \"see\" it\ndouble y = thefunctor(2.0);\n</code></pre>\n\n<p>where <code>thefunction2</code> is a function taking as argument and returning a <code>double</code>.</p>\n\n<p>Now imagine that instead of <code>thefunction2</code> I would like to use a \"function\" that is nowhere defined for now, by a statement, and that I will never use later. Then c# allows us to use the <em>expression</em> of this function. By expression I mean the \"mathematical\" (or functional, to stick to programs) expression of it, for instance : to a <code>double x</code> I will <em>associate</em> the <code>double</code> <code>x*x</code>. In maths you write this using <a href=\"https://math.stackexchange.com/questions/651205/regarding-the-notation-f-a-mapsto-b\">the \"\\mapsto\" latex symbol</a>. In c# the functional notation has been borrowed : <code>=></code>. For instance :</p>\n\n<pre><code>Func<double, double> thefunctor = ( (double x) => x * x ); // outer brackets are not\n // mandatory\n</code></pre>\n\n<p><code>(double x) => x * x</code> is an <a href=\"http://en.wikipedia.org/wiki/Expression_(computer_science)\" rel=\"nofollow noreferrer\"><em>expression</em></a>. It is not a type, whereas delegates (generic or not) are.</p>\n\n<p>Morality ? At end, what is a delegate (resp. generic delegate), if not a function pointer type (resp. wrapped+smart+generic function pointer type), huh ? Something else ! See <a href=\"http://blog.monstuff.com/archives/000037.html\" rel=\"nofollow noreferrer\">this</a> and <a href=\"http://msdn.microsoft.com/fr-fr/library/system.delegate%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\">that</a>.</p>\n"
},
{
"answer_id": 50314365,
"author": "Yogesh Prajapati",
"author_id": 4959238,
"author_profile": "https://Stackoverflow.com/users/4959238",
"pm_score": 1,
"selected": false,
"text": "<p>Some basic here.\n\"Delegate\" is actually the name for a variable that holds a reference to a method or a lambda</p>\n\n<p>This is a anonymous method - </p>\n\n<pre><code>(string testString) => { Console.WriteLine(testString); };\n</code></pre>\n\n<p>As anonymous method do not have any name we need a delegate in which we can assign both of these method or expression. For Ex.</p>\n\n<pre><code>delegate void PrintTestString(string testString); // declare a delegate\n\nPrintTestString print = (string testString) => { Console.WriteLine(testString); }; \nprint();\n</code></pre>\n\n<hr>\n\n<p>Same with the lambda expression. Usually we need delegate to use them</p>\n\n<pre><code>s => s.Age > someValue && s.Age < someValue // will return true/false\n</code></pre>\n\n<p>We can use a func delegate to use this expression.</p>\n\n<pre><code>Func< Student,bool> checkStudentAge = s => s.Age > someValue && s.Age < someValue ;\n\nbool result = checkStudentAge ( Student Object);\n</code></pre>\n"
},
{
"answer_id": 67167690,
"author": "Ievgen Martynov",
"author_id": 927030,
"author_profile": "https://Stackoverflow.com/users/927030",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Short version:</strong></p>\n<p>A delegate is a <strong>type</strong> that represents references to methods. C# <strong>lambda</strong> expression is a syntax to create <strong>delegates</strong> or <strong>expression trees</strong>.</p>\n<p><strong>Kinda long version:</strong></p>\n<p>Delegate is not "the name for a variable" as it's said in the accepted answer.</p>\n<p>A delegate is a <strong>type</strong> (literally a type, if you inspect IL, it's a class) that represents references to methods (<a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/\" rel=\"nofollow noreferrer\">learn.microsoft.com</a>).</p>\n<p><a href=\"https://i.stack.imgur.com/r0lPp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/r0lPp.png\" alt=\"enter image description here\" /></a></p>\n<p>This type could be initiated to associate its instance with any method with a compatible signature and return type.</p>\n<pre><code>namespace System\n{\n // define a type\n public delegate TResult Func<in T, out TResult>(T arg);\n}\n\n// method with the compatible signature\npublic static bool IsPositive(int int32)\n{\n return int32 > 0;\n}\n\n// initiated and associate\nFunc<int, bool> isPositive = new Func<int, bool>(IsPositive);\n</code></pre>\n<p>C# 2.0 introduced a syntactic sugar, anonymous method, enabling methods to be defined <strong>inline</strong>.</p>\n<pre><code>Func<int, bool> isPositive = delegate(int int32)\n{\n return int32 > 0;\n};\n</code></pre>\n<p>In C# 3.0+, the above anonymous method’s inline definition can be further simplified with lambda expression</p>\n<pre><code>Func<int, bool> isPositive = (int int32) =>\n{\n return int32 > 0;\n};\n</code></pre>\n<p>C# <strong>lambda</strong> expression is a syntax to create <strong>delegates</strong> or <strong>expression trees</strong>. I believe expression trees are not the topic of this question (<a href=\"https://www.youtube.com/playlist?list=PLRwVmtr-pp06SlwcsqhreZ2byuozdnPlg\" rel=\"nofollow noreferrer\">Jamie King about expression trees</a>).</p>\n<p>More could be found <a href=\"https://weblogs.asp.net/dixin/understanding-csharp-features-5-lambda-expression\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1538/"
]
| I get asked this question a lot and I thought I'd solicit some input on how to best describe the difference. | They are actually two very different things. "Delegate" is actually the name for a variable that holds a reference to a method or a lambda, and a lambda is a method without a permanent name.
Lambdas are very much like other methods, except for a couple subtle differences.
1. A normal method is defined in a ["statement"](http://en.wikipedia.org/wiki/Statement_(programming)) and tied to a permanent name, whereas a lambda is defined "on the fly" in an ["expression"](http://en.wikipedia.org/wiki/Expression_(programming)) and has no permanent name.
2. Some lambdas can be used with .NET expression trees, whereas methods cannot.
A delegate is defined like this:
```
delegate Int32 BinaryIntOp(Int32 x, Int32 y);
```
A variable of type BinaryIntOp can have either a method or a labmda assigned to it, as long as the signature is the same: two Int32 arguments, and an Int32 return.
A lambda might be defined like this:
```
BinaryIntOp sumOfSquares = (a, b) => a*a + b*b;
```
Another thing to note is that although the generic Func and Action types are often considered "lambda types", they are just like any other delegates. The nice thing about them is that they essentially define a name for any type of delegate you might need (up to 4 parameters, though you can certainly add more of your own). So if you are using a wide variety of delegate types, but none more than once, you can avoid cluttering your code with delegate declarations by using Func and Action.
Here is an illustration of how Func and Action are "not just for lambdas":
```
Int32 DiffOfSquares(Int32 x, Int32 y)
{
return x*x - y*y;
}
Func<Int32, Int32, Int32> funcPtr = DiffOfSquares;
```
Another useful thing to know is that delegate types (not methods themselves) with the same signature but different names will not be implicitly casted to each other. This includes the Func and Action delegates. However if the signature is identical, you can explicitly cast between them.
Going the extra mile.... In C# functions are flexible, with the use of lambdas and delegates. But C# does not have "first-class functions". You can use a function's name assigned to a delegate variable to essentially create an object representing that function. But it's really a compiler trick. If you start a statement by writing the function name followed by a dot (i.e. try to do member access on the function itself) you'll find there are no members there to reference. Not even the ones from Object. This prevents the programmer from doing useful (and potentially dangerous of course) things such as adding extension methods that can be called on any function. The best you can do is extend the Delegate class itself, which is surely also useful, but not quite as much.
Update: Also see [Karg's answer](https://stackoverflow.com/questions/73227/what-is-the-difference-between-lambdas-and-delegates-in-the-net-framework#73448) illustrating the difference between anonymous delegates vs. methods & lambdas.
Update 2: [James Hart](https://stackoverflow.com/questions/73227/what-is-the-difference-between-lambdas-and-delegates-in-the-net-framework#74414) makes an important, though very technical, note that lambdas and delegates are not .NET entities (i.e. the CLR has no concept of a delegate or lambda), but rather they are framework and language constructs. |
73,286 | <p>I created a C++ console app and just want to capture the cout/cerr statements in the Output Window within the Visual Studio 2005 IDE. I'm sure this is just a setting that I'm missing. Can anyone point me in the right direction?</p>
| [
{
"answer_id": 73363,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 3,
"selected": false,
"text": "<p>You can't do this.</p>\n\n<p>If you want to output to the debugger's output window, call OutputDebugString.</p>\n\n<p>I found <a href=\"http://www.flipcode.com/archives/Message_Box_ostream.shtml\" rel=\"noreferrer\">this implementation</a> of a 'teestream' which allows one output to go to multiple streams. You could implement a stream that sends data to OutputDebugString.</p>\n"
},
{
"answer_id": 73365,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Is this a case of the output screen just flashing and then dissapearing? if so you can keep it open by using cin as your last statement before return.</p>\n"
},
{
"answer_id": 74542,
"author": "ben",
"author_id": 4607,
"author_profile": "https://Stackoverflow.com/users/4607",
"pm_score": 3,
"selected": false,
"text": "<p>You can capture the output of cout like this, for example:</p>\n\n<pre><code>std::streambuf* old_rdbuf = std::cout.rdbuf();\nstd::stringbuf new_rdbuf;\n// replace default output buffer with string buffer\nstd::cout.rdbuf(&new_rdbuf);\n\n// write to new buffer, make sure to flush at the end\nstd::cout << \"hello, world\" << std::endl;\n\nstd::string s(new_rdbuf.str());\n// restore the default buffer before destroying the new one\nstd::cout.rdbuf(old_rdbuf);\n\n// show that the data actually went somewhere\nstd::cout << s.size() << \": \" << s;\n</code></pre>\n\n<p>Magicking it into the Visual Studio 2005 output window is left as an exercise to a Visual Studio 2005 plugin developer. But you could probably redirect it elsewhere, like a file or a custom window, perhaps by writing a custom streambuf class (see also boost.iostream).</p>\n"
},
{
"answer_id": 78699,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 2,
"selected": false,
"text": "<p>A combination of ben's answer and Mike Dimmick's: you would be implementing a stream_buf_ that ends up calling OutputDebugString. Maybe someone has done this already? Take a look at the two proposed Boost logging libraries.</p>\n"
},
{
"answer_id": 80782,
"author": "el2iot2",
"author_id": 8668,
"author_profile": "https://Stackoverflow.com/users/8668",
"pm_score": 0,
"selected": false,
"text": "<p>Also, depending on your intentions, and what libraries you are using, you may want to use the <a href=\"http://msdn.microsoft.com/en-us/library/4wyz8787(VS.80).aspx\" rel=\"nofollow noreferrer\">TRACE macro</a> (<a href=\"http://en.wikipedia.org/wiki/Microsoft_Foundation_Class_Library\" rel=\"nofollow noreferrer\">MFC</a>) or <a href=\"http://msdn.microsoft.com/en-us/library/6xkxyz08(VS.80).aspx\" rel=\"nofollow noreferrer\">ATLTRACE</a> (<a href=\"http://en.wikipedia.org/wiki/Active_Template_Library\" rel=\"nofollow noreferrer\">ATL</a>).</p>\n"
},
{
"answer_id": 6086817,
"author": "Yakov Galka",
"author_id": 277176,
"author_profile": "https://Stackoverflow.com/users/277176",
"pm_score": 4,
"selected": false,
"text": "<p>I've finally implemented this, so I want to share it with you:</p>\n\n<pre><code>#include <vector>\n#include <iostream>\n#include <windows.h>\n#include <boost/iostreams/stream.hpp>\n#include <boost/iostreams/tee.hpp>\n\nusing namespace std;\nnamespace io = boost::iostreams;\n\nstruct DebugSink\n{\n typedef char char_type;\n typedef io::sink_tag category;\n\n std::vector<char> _vec;\n\n std::streamsize write(const char *s, std::streamsize n)\n {\n _vec.assign(s, s+n);\n _vec.push_back(0); // we must null-terminate for WINAPI\n OutputDebugStringA(&_vec[0]);\n return n;\n }\n};\n\nint main()\n{\n typedef io::tee_device<DebugSink, std::streambuf> TeeDevice;\n TeeDevice device(DebugSink(), *cout.rdbuf());\n io::stream_buffer<TeeDevice> buf(device);\n cout.rdbuf(&buf);\n\n cout << \"hello world!\\n\";\n cout.flush(); // you may need to flush in some circumstances\n}\n</code></pre>\n\n<p><strong>BONUS TIP:</strong> If you write:</p>\n\n<pre><code>X:\\full\\file\\name.txt(10) : message\n</code></pre>\n\n<p>to the output window and then double-click on it, then Visual Studio will jump to the given file, line 10, and display the 'message' in status bar. It's <em>very</em> useful.</p>\n"
},
{
"answer_id": 57573500,
"author": "ejectamenta",
"author_id": 1740850,
"author_profile": "https://Stackoverflow.com/users/1740850",
"pm_score": 0,
"selected": false,
"text": "<p>Write to a std::ostringsteam and then TRACE that.</p>\n\n<pre><code>std::ostringstream oss;\n\noss << \"w:=\" << w << \" u=\" << u << \" vt=\" << vt << endl;\n\nTRACE(oss.str().data());\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1265473/"
]
| I created a C++ console app and just want to capture the cout/cerr statements in the Output Window within the Visual Studio 2005 IDE. I'm sure this is just a setting that I'm missing. Can anyone point me in the right direction? | I've finally implemented this, so I want to share it with you:
```
#include <vector>
#include <iostream>
#include <windows.h>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/tee.hpp>
using namespace std;
namespace io = boost::iostreams;
struct DebugSink
{
typedef char char_type;
typedef io::sink_tag category;
std::vector<char> _vec;
std::streamsize write(const char *s, std::streamsize n)
{
_vec.assign(s, s+n);
_vec.push_back(0); // we must null-terminate for WINAPI
OutputDebugStringA(&_vec[0]);
return n;
}
};
int main()
{
typedef io::tee_device<DebugSink, std::streambuf> TeeDevice;
TeeDevice device(DebugSink(), *cout.rdbuf());
io::stream_buffer<TeeDevice> buf(device);
cout.rdbuf(&buf);
cout << "hello world!\n";
cout.flush(); // you may need to flush in some circumstances
}
```
**BONUS TIP:** If you write:
```
X:\full\file\name.txt(10) : message
```
to the output window and then double-click on it, then Visual Studio will jump to the given file, line 10, and display the 'message' in status bar. It's *very* useful. |
73,308 | <p>I am trying to implement a request to an unreliable server. The request is a nice to have, but not 100% required for my perl script to successfully complete. The problem is that the server will occasionally deadlock (we're trying to figure out why) and the request will never succeed. Since the server thinks it is live, it keeps the socket connection open thus LWP::UserAgent's timeout value does us no good what-so-ever. What is the best way to enforce an absolute timeout on a request? </p>
<p>FYI, this is not an DNS problem. The deadlock has something to do with a massive number of updates hitting our Postgres database at the same time. For testing purposes, we've essentially put a while(1) {} line in the servers response handler. </p>
<p>Currently, the code looks like so:</p>
<pre><code>my $ua = LWP::UserAgent->new;
ua->timeout(5); $ua->cookie_jar({});
my $req = HTTP::Request->new(POST => "http://$host:$port/auth/login");
$req->content_type('application/x-www-form-urlencoded');
$req->content("login[user]=$username&login[password]=$password");
# This line never returns
$res = $ua->request($req);
</code></pre>
<p>I've tried using signals to trigger a timeout, but that does not seem to work. </p>
<pre><code>eval {
local $SIG{ALRM} = sub { die "alarm\n" };
alarm(1);
$res = $ua->request($req);
alarm(0);
};
# This never runs
print "here\n";
</code></pre>
<p>The final answer I'm going to use was proposed by someone offline, but I'll mention it here. For some reason, SigAction works while $SIG(ALRM) does not. Still not sure why, but this has been tested to work. Here are two working versions:</p>
<pre><code># Takes a LWP::UserAgent, and a HTTP::Request, returns a HTTP::Request
sub ua_request_with_timeout {
my $ua = $_[0];
my $req = $_[1];
# Get whatever timeout is set for LWP and use that to
# enforce a maximum timeout per request in case of server
# deadlock. (This has happened.)
use Sys::SigAction qw( timeout_call );
our $res = undef;
if( timeout_call( 5, sub {$res = $ua->request($req);}) ) {
return HTTP::Response->new( 408 ); #408 is the HTTP timeout
} else {
return $res;
}
}
sub ua_request_with_timeout2 {
print "ua_request_with_timeout\n";
my $ua = $_[0];
my $req = $_[1];
# Get whatever timeout is set for LWP and use that to
# enforce a maximum timeout per request in case of server
# deadlock. (This has happened.)
my $timeout_for_client = $ua->timeout() - 2;
our $socket_has_timedout = 0;
use POSIX;
sigaction SIGALRM, new POSIX::SigAction(
sub {
$socket_has_timedout = 1;
die "alarm timeout";
}
) or die "Error setting SIGALRM handler: $!\n";
my $res = undef;
eval {
alarm ($timeout_for_client);
$res = $ua->request($req);
alarm(0);
};
if ( $socket_has_timedout ) {
return HTTP::Response->new( 408 ); #408 is the HTTP timeout
} else {
return $res;
}
}
</code></pre>
| [
{
"answer_id": 73351,
"author": "Alex Fort",
"author_id": 12624,
"author_profile": "https://Stackoverflow.com/users/12624",
"pm_score": 0,
"selected": false,
"text": "<p>From what I understand, the timeout property doesn't take into account DNS timeouts. It's possible that you could make a DNS lookup separately, then make the request to the server if that works, with the correct timeout value set for the useragent.</p>\n\n<p>Is this a DNS problem with the server, or something else?</p>\n\n<p>EDIT: It could also be a problem with IO::Socket. Try updating your IO::Socket module, and see if that helps. I'm pretty sure there was a bug in there that was preventing LWP::UserAgent timeouts from working.</p>\n\n<p>Alex</p>\n"
},
{
"answer_id": 73374,
"author": "Stephen Deken",
"author_id": 7154,
"author_profile": "https://Stackoverflow.com/users/7154",
"pm_score": 5,
"selected": true,
"text": "<p>You might try <a href=\"http://search.cpan.org/%7Ebradfitz/LWPx-ParanoidAgent-1.02/lib/LWPx/ParanoidAgent.pm\" rel=\"noreferrer\">LWPx::ParanoidAgent</a>, a subclass of LWP::UserAgent which is more cautious about how it interacts with remote webservers.</p>\n<p>Among other things, it allows you to specify a global timeout. It was developed by Brad Fitzpatrick as part of the LiveJournal project.</p>\n"
},
{
"answer_id": 76379,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 1,
"selected": false,
"text": "<p>You can make your own timeout like this:</p>\n\n<pre><code>use LWP::UserAgent;\nuse IO::Pipe;\n\nmy $agent = new LWP::UserAgent;\n\nmy $finished = 0;\nmy $timeout = 5;\n\n$SIG{CHLD} = sub { wait, $finished = 1 };\n\nmy $pipe = new IO::Pipe;\nmy $pid = fork;\n\nif($pid == 0) {\n $pipe->writer;\n my $response = $agent->get(\"http://stackoverflow.com/\");\n $pipe->print($response->content);\n exit;\n}\n\n$pipe->reader;\n\nsleep($timeout);\n\nif($finished) {\n print \"Finished!\\n\";\n my $content = join('', $pipe->getlines);\n} \nelse {\n kill(9, $pid);\n print \"Timed out.\\n\";\n} \n</code></pre>\n"
},
{
"answer_id": 18542076,
"author": "Andrei Georgescu",
"author_id": 2734397,
"author_profile": "https://Stackoverflow.com/users/2734397",
"pm_score": 0,
"selected": false,
"text": "<p>The following generalization of one of the original answers also restores the alarm signal handler to the previous handler and adds a second call to alarm(0) in case the call in the eval clock throws a non alarm exception and we want to cancel the alarm. Further $@ inspection and handling can be added:</p>\n\n<pre><code>sub ua_request_with_timeout {\n my $ua = $_[0];\n my $request = $_[1];\n\n # Get whatever timeout is set for LWP and use that to \n # enforce a maximum timeout per request in case of server\n # deadlock. (This has happened.)`enter code here`\n my $timeout_for_client_sec = $ua->timeout();\n our $res_has_timedout = 0; \n\n use POSIX ':signal_h';\n\n my $newaction = POSIX::SigAction->new(\n sub { $res_has_timedout = 1; die \"web request timeout\"; },# the handler code ref\n POSIX::SigSet->new(SIGALRM),\n # not using (perl 5.8.2 and later) 'safe' switch or sa_flags\n ); \n\n my $oldaction = POSIX::SigAction->new();\n if(!sigaction(SIGALRM, $newaction, $oldaction)) {\n log('warn',\"Error setting SIGALRM handler: $!\");\n return $ua->request($request);\n } \n\n my $response = undef;\n eval {\n alarm ($timeout_for_client_sec);\n $response = $ua->request($request);\n alarm(0);\n }; \n\n alarm(0);# cancel alarm (if eval failed because of non alarm cause)\n if(!sigaction(SIGALRM, $oldaction )) {\n log('warn', \"Error resetting SIGALRM handler: $!\");\n }; \n\n if ( $res_has_timedout ) {\n log('warn', \"Timeout($timeout_for_client_sec sec) while waiting for a response from cred central\");\n return HTTP::Response->new(408); #408 is the HTTP timeout\n } else {\n return $response;\n }\n}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12628/"
]
| I am trying to implement a request to an unreliable server. The request is a nice to have, but not 100% required for my perl script to successfully complete. The problem is that the server will occasionally deadlock (we're trying to figure out why) and the request will never succeed. Since the server thinks it is live, it keeps the socket connection open thus LWP::UserAgent's timeout value does us no good what-so-ever. What is the best way to enforce an absolute timeout on a request?
FYI, this is not an DNS problem. The deadlock has something to do with a massive number of updates hitting our Postgres database at the same time. For testing purposes, we've essentially put a while(1) {} line in the servers response handler.
Currently, the code looks like so:
```
my $ua = LWP::UserAgent->new;
ua->timeout(5); $ua->cookie_jar({});
my $req = HTTP::Request->new(POST => "http://$host:$port/auth/login");
$req->content_type('application/x-www-form-urlencoded');
$req->content("login[user]=$username&login[password]=$password");
# This line never returns
$res = $ua->request($req);
```
I've tried using signals to trigger a timeout, but that does not seem to work.
```
eval {
local $SIG{ALRM} = sub { die "alarm\n" };
alarm(1);
$res = $ua->request($req);
alarm(0);
};
# This never runs
print "here\n";
```
The final answer I'm going to use was proposed by someone offline, but I'll mention it here. For some reason, SigAction works while $SIG(ALRM) does not. Still not sure why, but this has been tested to work. Here are two working versions:
```
# Takes a LWP::UserAgent, and a HTTP::Request, returns a HTTP::Request
sub ua_request_with_timeout {
my $ua = $_[0];
my $req = $_[1];
# Get whatever timeout is set for LWP and use that to
# enforce a maximum timeout per request in case of server
# deadlock. (This has happened.)
use Sys::SigAction qw( timeout_call );
our $res = undef;
if( timeout_call( 5, sub {$res = $ua->request($req);}) ) {
return HTTP::Response->new( 408 ); #408 is the HTTP timeout
} else {
return $res;
}
}
sub ua_request_with_timeout2 {
print "ua_request_with_timeout\n";
my $ua = $_[0];
my $req = $_[1];
# Get whatever timeout is set for LWP and use that to
# enforce a maximum timeout per request in case of server
# deadlock. (This has happened.)
my $timeout_for_client = $ua->timeout() - 2;
our $socket_has_timedout = 0;
use POSIX;
sigaction SIGALRM, new POSIX::SigAction(
sub {
$socket_has_timedout = 1;
die "alarm timeout";
}
) or die "Error setting SIGALRM handler: $!\n";
my $res = undef;
eval {
alarm ($timeout_for_client);
$res = $ua->request($req);
alarm(0);
};
if ( $socket_has_timedout ) {
return HTTP::Response->new( 408 ); #408 is the HTTP timeout
} else {
return $res;
}
}
``` | You might try [LWPx::ParanoidAgent](http://search.cpan.org/%7Ebradfitz/LWPx-ParanoidAgent-1.02/lib/LWPx/ParanoidAgent.pm), a subclass of LWP::UserAgent which is more cautious about how it interacts with remote webservers.
Among other things, it allows you to specify a global timeout. It was developed by Brad Fitzpatrick as part of the LiveJournal project. |
73,320 | <p>How do I set the column which has the header sort glyph, and its direction, in a .NET 2.0 WinForms ListView?</p>
<h2>Bump</h2>
<p>The listview is .net is not a managed control, it is a very thin wrapper around the Win32 ListView common control. It's not even a very good wrapper - it doesn't expose all the features of the real listview.</p>
<p>The Win32 listview common control supports drawing itself with themes. One of the themed elements is the header sort arrow. Windows Explorer's listview common control knows how to draw one of its columns with that theme element.</p>
<ul>
<li>does the Win32 listview support specifying which column has what sort order? </li>
<li>does the Win32 header control that the listview internally uses support specifying which column has what sort order? </li>
<li>does the win32 header control support custom drawing, so I can draw the header sort glyph myself?</li>
<li>does the win32 listview control support custom header drawing, so I can draw the header sort glyph myself?</li>
<li>does the .NET ListView control support custom header drawing, so I can draw the header sort glyph myself?</li>
</ul>
| [
{
"answer_id": 73331,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 1,
"selected": false,
"text": "<p>I use unicode arrow characters in the title of the column and make the header a linkbutton.</p>\n"
},
{
"answer_id": 2072955,
"author": "t0mm13b",
"author_id": 206367,
"author_profile": "https://Stackoverflow.com/users/206367",
"pm_score": 1,
"selected": false,
"text": "<p>There is a listview that I use that has that in-built into it. It's called <a href=\"http://www.codeproject.com/KB/list/XPTableListViewUpdate.aspx\" rel=\"nofollow noreferrer\">XPTable</a>..I am digging around my source code to find that helper class that will draw the glyph based on the sort order...This is the code that I have used <a href=\"http://www.codeproject.com/KB/list/lvsortmanager.aspx\" rel=\"nofollow noreferrer\">here</a>..</p>\n\n<p>Hope this helps,\nBest regards,\nTom.</p>\n"
},
{
"answer_id": 26857392,
"author": "IlPADlI",
"author_id": 2430943,
"author_profile": "https://Stackoverflow.com/users/2430943",
"pm_score": 1,
"selected": false,
"text": "<p>This article is helpful, uses SendMessage DllImport.</p>\n\n<p><a href=\"http://www.codeproject.com/Tips/734463/Sort-listview-Columns-and-Set-Sort-Arrow-Icon-on-C\" rel=\"nofollow\">http://www.codeproject.com/Tips/734463/Sort-listview-Columns-and-Set-Sort-Arrow-Icon-on-C</a></p>\n"
},
{
"answer_id": 36332488,
"author": "Adam",
"author_id": 5250659,
"author_profile": "https://Stackoverflow.com/users/5250659",
"pm_score": 2,
"selected": false,
"text": "<p>In case someone needs a quick solution (it draws up/down arrow at the beginning of column header text):</p>\n\n<p><strong>ListViewExtensions.cs:</strong></p>\n\n<pre><code>public static class ListViewExtensions\n{\n public static void DrawSortArrow(this ListView listView, SortOrder sortOrder, int colIndex)\n {\n string upArrow = \"▲ \";\n string downArrow = \"▼ \";\n\n foreach (ColumnHeader ch in listView.Columns)\n {\n if (ch.Text.Contains(upArrow))\n ch.Text = ch.Text.Replace(upArrow, string.Empty);\n else if (ch.Text.Contains(downArrow))\n ch.Text = ch.Text.Replace(downArrow, string.Empty);\n }\n\n if (sortOrder == SortOrder.Ascending)\n listView.Columns[colIndex].Text = listView.Columns[colIndex].Text.Insert(0, downArrow);\n else\n listView.Columns[colIndex].Text = listView.Columns[colIndex].Text.Insert(0, upArrow);\n }\n}\n</code></pre>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>private void lstOffers_ColumnClick(object sender, ColumnClickEventArgs e)\n{\n lstOffers.DrawSortArrow(SortOrder.Descending, e.Column);\n}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
]
| How do I set the column which has the header sort glyph, and its direction, in a .NET 2.0 WinForms ListView?
Bump
----
The listview is .net is not a managed control, it is a very thin wrapper around the Win32 ListView common control. It's not even a very good wrapper - it doesn't expose all the features of the real listview.
The Win32 listview common control supports drawing itself with themes. One of the themed elements is the header sort arrow. Windows Explorer's listview common control knows how to draw one of its columns with that theme element.
* does the Win32 listview support specifying which column has what sort order?
* does the Win32 header control that the listview internally uses support specifying which column has what sort order?
* does the win32 header control support custom drawing, so I can draw the header sort glyph myself?
* does the win32 listview control support custom header drawing, so I can draw the header sort glyph myself?
* does the .NET ListView control support custom header drawing, so I can draw the header sort glyph myself? | In case someone needs a quick solution (it draws up/down arrow at the beginning of column header text):
**ListViewExtensions.cs:**
```
public static class ListViewExtensions
{
public static void DrawSortArrow(this ListView listView, SortOrder sortOrder, int colIndex)
{
string upArrow = "▲ ";
string downArrow = "▼ ";
foreach (ColumnHeader ch in listView.Columns)
{
if (ch.Text.Contains(upArrow))
ch.Text = ch.Text.Replace(upArrow, string.Empty);
else if (ch.Text.Contains(downArrow))
ch.Text = ch.Text.Replace(downArrow, string.Empty);
}
if (sortOrder == SortOrder.Ascending)
listView.Columns[colIndex].Text = listView.Columns[colIndex].Text.Insert(0, downArrow);
else
listView.Columns[colIndex].Text = listView.Columns[colIndex].Text.Insert(0, upArrow);
}
}
```
**Usage:**
```
private void lstOffers_ColumnClick(object sender, ColumnClickEventArgs e)
{
lstOffers.DrawSortArrow(SortOrder.Descending, e.Column);
}
``` |
73,380 | <p>I'm running some c# .net pages with various gridviews. If I ever leave any of them alone in a web browser for an extended period of time (usually overnight), I get the following error when I click any element on the page.</p>
<p>I'm not really sure where to start dealing with the problem. I don't mind resetting the page if it's viewstate has expired, but throwing an error is unacceptable!</p>
<pre><code> Error: The state information is invalid for this page and might be corrupted.
Target: Void ThrowError(System.Exception, System.String, System.String, Boolean)
Data: System.Collections.ListDictionaryInternal
Inner: System.Web.UI.ViewStateException: Invalid viewstate. Client IP: 66.35.180.246 Port: 1799 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9) Gecko/2008052906 Firefox/3.0 ViewState: (**Very long Gibberish Omitted!**)
Offending URL: (**Omitted**)
Source: System.Web
Message: The state information is invalid for this page and might be corrupted.
Stack trace: at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.ClientScriptManager.EnsureEventValidationFieldLoaded() at System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) at System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) at System.Web.UI.WebControls.DropDownList.LoadPostData(String postDataKey, NameValueCollection postCollection) at System.Web.UI.WebControls.DropDownList.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) at System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
</code></pre>
| [
{
"answer_id": 73402,
"author": "MrHinsh - Martin Hinshelwood",
"author_id": 11799,
"author_profile": "https://Stackoverflow.com/users/11799",
"pm_score": 1,
"selected": false,
"text": "<p>You can remove this error completely by saving your view state to a database and only cleaning within the duration you need to. This also sygnificantly improves the performance of your pages even shen using relatively small viewstates.</p>\n\n<p>At the very least you can inherit from the Page class and add your own ViewStateLoad routen that check to see if it has expired and reloads the default state.</p>\n\n<p>Check <a href=\"http://www.codeproject.com/KB/viewstate/ViewStateProvider.aspx\" rel=\"nofollow noreferrer\">ViewState Provider - an implementation using Provider Model Design Pattern</a> for providing a custom Viewstate provider.</p>\n"
},
{
"answer_id": 73450,
"author": "Toby Mills",
"author_id": 12377,
"author_profile": "https://Stackoverflow.com/users/12377",
"pm_score": 0,
"selected": false,
"text": "<p>Alternatively if you know the time-out length then you could add a bit of javascript to the page which redirects the user to an alternative page if there has been no activity on the page after a preset period of time. You can then extend this to warn the customer that their session / page is about to expire and provide them with a means to extend it (e.g. javascript server call back).</p>\n"
},
{
"answer_id": 73463,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": 2,
"selected": false,
"text": "<p>That is odd as the ViewState is stored as a string in the webpage itself. So I do not see how an extended period of time would cause that error. Perhaps one or more objects on the page have been garbage collected or the application reset, so the viewstate is referencing old controls instead of the controls created when the application restarted. </p>\n\n<p>Whatever the case, I feel your pain, these errors are never pleasant to debug, and I have no easy answer as to how to find the problem other than perhaps studying <a href=\"http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx\" rel=\"nofollow noreferrer\">how ViewState works</a></p>\n"
},
{
"answer_id": 73757,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The above posts give you some answers on solving the problem. If just handling the ugly error in the interim is what you're looking for, custom errors are the easiest way to gracefully handle all your \"ugly yellow errors\"</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa479319.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa479319.aspx</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/h0hfz6fc.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/h0hfz6fc.aspx</a></p>\n"
},
{
"answer_id": 77377,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 0,
"selected": false,
"text": "<p>Another option is to add in a global error handler, that would capture the exception at the application level and redirect the user to a \"Session Elapsed\" page. </p>\n\n<p>If you want an idea of a general implementation of a global error handler, I have one available on my website, I can give you the code if needed - <a href=\"http://iowacomputergurus.com/free-products/asp.net-global-error-handler.aspx\" rel=\"nofollow noreferrer\">http://iowacomputergurus.com/free-products/asp.net-global-error-handler.aspx</a> </p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12382/"
]
| I'm running some c# .net pages with various gridviews. If I ever leave any of them alone in a web browser for an extended period of time (usually overnight), I get the following error when I click any element on the page.
I'm not really sure where to start dealing with the problem. I don't mind resetting the page if it's viewstate has expired, but throwing an error is unacceptable!
```
Error: The state information is invalid for this page and might be corrupted.
Target: Void ThrowError(System.Exception, System.String, System.String, Boolean)
Data: System.Collections.ListDictionaryInternal
Inner: System.Web.UI.ViewStateException: Invalid viewstate. Client IP: 66.35.180.246 Port: 1799 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9) Gecko/2008052906 Firefox/3.0 ViewState: (**Very long Gibberish Omitted!**)
Offending URL: (**Omitted**)
Source: System.Web
Message: The state information is invalid for this page and might be corrupted.
Stack trace: at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.ClientScriptManager.EnsureEventValidationFieldLoaded() at System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) at System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) at System.Web.UI.WebControls.DropDownList.LoadPostData(String postDataKey, NameValueCollection postCollection) at System.Web.UI.WebControls.DropDownList.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) at System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
``` | That is odd as the ViewState is stored as a string in the webpage itself. So I do not see how an extended period of time would cause that error. Perhaps one or more objects on the page have been garbage collected or the application reset, so the viewstate is referencing old controls instead of the controls created when the application restarted.
Whatever the case, I feel your pain, these errors are never pleasant to debug, and I have no easy answer as to how to find the problem other than perhaps studying [how ViewState works](http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx) |
73,385 | <p>Is there an easy way to convert a string from csv format into a string[] or list? </p>
<p>I can guarantee that there are no commas in the data.</p>
| [
{
"answer_id": 73390,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 0,
"selected": false,
"text": "<pre><code>CsvString.split(',');\n</code></pre>\n"
},
{
"answer_id": 73394,
"author": "Timothy Carter",
"author_id": 4660,
"author_profile": "https://Stackoverflow.com/users/4660",
"pm_score": 3,
"selected": true,
"text": "<pre>string[] splitString = origString.Split(',');</pre>\n\n<p><em>(Following comment not added by original answerer)</em>\n<strong>Please keep in mind that this answer addresses the SPECIFIC case where there are guaranteed to be NO commas in the data.</strong></p>\n"
},
{
"answer_id": 73404,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 0,
"selected": false,
"text": "<p>Get a string[] of all the lines: </p>\n\n<pre><code>string[] lines = System.IO.File.ReadAllLines(\"yourfile.csv\");\n</code></pre>\n\n<p>Then loop through and split those lines (this error prone because it doesn't check for commas in quote-delimited fields):</p>\n\n<pre><code>foreach (string line in lines)\n{\n string[] items = line.Split({','}};\n}\n</code></pre>\n"
},
{
"answer_id": 73414,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>string test = \"one,two,three\";\nstring[] okNow = test.Split(',');\n</code></pre>\n"
},
{
"answer_id": 73416,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 0,
"selected": false,
"text": "<pre><code>string s = \"1,2,3,4,5\";\n\nstring myStrings[] = s.Split({','}};\n</code></pre>\n\n<p>Note that Split() takes an <em>array</em> of characters to split on.</p>\n"
},
{
"answer_id": 73419,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 0,
"selected": false,
"text": "<pre><code>separationChar[] = {';'}; // or '\\t' ',' etc.\nvar strArray = strCSV.Split(separationChar);\n</code></pre>\n"
},
{
"answer_id": 73426,
"author": "Ryan Steckler",
"author_id": 12673,
"author_profile": "https://Stackoverflow.com/users/12673",
"pm_score": 0,
"selected": false,
"text": "<pre><code>string[] splitStrings = myCsv.Split(\",\".ToCharArray());\n</code></pre>\n"
},
{
"answer_id": 73460,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 3,
"selected": false,
"text": "<p>If you want robust CSV handling, check out <a href=\"http://www.filehelpers.com/\" rel=\"nofollow noreferrer\">FileHelpers</a></p>\n"
},
{
"answer_id": 73466,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 1,
"selected": false,
"text": "<p>There isn't a simple way to do this well, if you want to account for quoted elements with embedded commas, especially if they are mixed with non-quoted fields.</p>\n\n<p>You will also probably want to convert the lines to a dictionary, keyed by the column name.</p>\n\n<p>My code to do this is several hundred lines long.</p>\n\n<p>I think there are some examples on the web, open source projects, etc.</p>\n"
},
{
"answer_id": 73526,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 2,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>Regex rex = new Regex(\",(?=([^\\\"]*\\\"[^\\\"]*\\\")*(?![^\\\"]*\\\"))\");\nstring[] values = rex.Split( csvLine );\n</code></pre>\n\n<p>Source: <a href=\"http://weblogs.asp.net/prieck/archive/2004/01/16/59457.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/prieck/archive/2004/01/16/59457.aspx</a></p>\n"
},
{
"answer_id": 73557,
"author": "Sam",
"author_id": 9406,
"author_profile": "https://Stackoverflow.com/users/9406",
"pm_score": 0,
"selected": false,
"text": "<p>Some CSV files have double quotes around the values along with a comma. Therefore sometimes you can split on this string literal: \",\" </p>\n"
},
{
"answer_id": 73609,
"author": "claco",
"author_id": 91911,
"author_profile": "https://Stackoverflow.com/users/91911",
"pm_score": 0,
"selected": false,
"text": "<p><del>A Csv file with Quoted fields, is not a Csv file. Far more things (Excel) output without quotes rather than with quotes when you select \"Csv\" in a save as.</del></p>\n\n<p>If you want one you can use, free, or commit to, here's mine that also does IDataReader/Record. It also uses DataTable to define/convert/enforce columns and DbNull.</p>\n\n<p><a href=\"http://github.com/claco/csvdatareader/\" rel=\"nofollow noreferrer\">http://github.com/claco/csvdatareader/</a></p>\n\n<p>It doesn't do quotes.. yet. I just tossed it together a few days ago to scratch an itch.</p>\n\n<p>Forgotten Semicolon: Nice link. Thanks.\ncfeduke: Thanks for the tip to Microsoft.VisualBasic.FileIO.TextFieldParser. Going into CsvDataReader tonight.</p>\n"
},
{
"answer_id": 73639,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 4,
"selected": false,
"text": "<p>String.Split is just not going to cut it, but a Regex.Split may - Try this one:</p>\n\n<pre><code>using System.Text.RegularExpressions;\n\nstring[] line;\nline = Regex.Split( input, \",(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*(?![^\\\"]*\\\"))\");\n</code></pre>\n\n<p>Where 'input' is the csv line. This will handle quoted delimiters, and should give you back an array of strings representing each field in the line.</p>\n"
},
{
"answer_id": 73980,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 2,
"selected": false,
"text": "<p>You can take a look at using the Microsoft.VisualBasic assembly with the</p>\n\n<pre><code>Microsoft.VisualBasic.FileIO.TextFieldParser\n</code></pre>\n\n<p>It handles CSV (or any delimiter) with quotes. I've found it quite handy recently.</p>\n"
},
{
"answer_id": 74093,
"author": "Steve Cooper",
"author_id": 6722,
"author_profile": "https://Stackoverflow.com/users/6722",
"pm_score": 1,
"selected": false,
"text": "<p>Try this; </p>\n\n<pre><code>static IEnumerable<string> CsvParse(string input)\n{\n // null strings return a one-element enumeration containing null.\n if (input == null)\n {\n yield return null;\n yield break;\n }\n\n // we will 'eat' bits of the string until it's gone.\n String remaining = input;\n while (remaining.Length > 0)\n {\n\n if (remaining.StartsWith(\"\\\"\")) // deal with quotes\n {\n remaining = remaining.Substring(1); // pass over the initial quote.\n\n // find the end quote.\n int endQuotePosition = remaining.IndexOf(\"\\\"\");\n switch (endQuotePosition)\n {\n case -1:\n // unclosed quote.\n throw new ArgumentOutOfRangeException(\"Unclosed quote\");\n case 0:\n // the empty quote\n yield return \"\";\n remaining = remaining.Substring(2);\n break;\n default:\n string quote = remaining.Substring(0, endQuotePosition).Trim();\n remaining = remaining.Substring(endQuotePosition + 1);\n yield return quote;\n break;\n }\n }\n else // deal with commas\n {\n int nextComma = remaining.IndexOf(\",\");\n switch (nextComma)\n {\n case -1:\n // no more commas -- read to end\n yield return remaining.Trim();\n yield break;\n\n case 0:\n // the empty cell\n yield return \"\";\n remaining = remaining.Substring(1);\n break;\n\n default:\n // get everything until next comma\n string cell = remaining.Substring(0, nextComma).Trim();\n remaining = remaining.Substring(nextComma + 1);\n yield return cell;\n break;\n }\n }\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 80025,
"author": "claco",
"author_id": 91911,
"author_profile": "https://Stackoverflow.com/users/91911",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://github.com/claco/csvdatareader/\" rel=\"nofollow noreferrer\">http://github.com/claco/csvdatareader/</a> updated using TextFieldParser suggested by cfeduke.</p>\n\n<p>Just a few props away from exposing separators/trimspaces/type ig you just need code to steal.</p>\n"
},
{
"answer_id": 84639,
"author": "JohnOpincar",
"author_id": 16245,
"author_profile": "https://Stackoverflow.com/users/16245",
"pm_score": 0,
"selected": false,
"text": "<p>I was already splitting on tabs so this did the trick for me:</p>\n\n<pre><code>public static string CsvToTabDelimited(string line) {\n var ret = new StringBuilder(line.Length);\n bool inQuotes = false;\n for (int idx = 0; idx < line.Length; idx++) {\n if (line[idx] == '\"') {\n inQuotes = !inQuotes;\n } else {\n if (line[idx] == ',') {\n ret.Append(inQuotes ? ',' : '\\t');\n } else {\n ret.Append(line[idx]);\n }\n }\n }\n return ret.ToString();\n}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12653/"
]
| Is there an easy way to convert a string from csv format into a string[] or list?
I can guarantee that there are no commas in the data. | ```
string[] splitString = origString.Split(',');
```
*(Following comment not added by original answerer)*
**Please keep in mind that this answer addresses the SPECIFIC case where there are guaranteed to be NO commas in the data.** |
73,447 | <p>What's the most efficient way to convert the output of this function from a varbinary() to a a varchar()?</p>
| [
{
"answer_id": 73503,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 4,
"selected": true,
"text": "<p>How about this:</p>\n\n<pre><code>master.sys.fn_varbintohexstr(@binvalue)\n</code></pre>\n"
},
{
"answer_id": 887570,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>CONVERT(varchar, @binary)</p>\n"
},
{
"answer_id": 7979858,
"author": "Cheburek",
"author_id": 311108,
"author_profile": "https://Stackoverflow.com/users/311108",
"pm_score": 2,
"selected": false,
"text": "<p>For SQL Server 2008 use</p>\n\n<pre><code>CONVERT(varchar, @binary, 1)\n</code></pre>\n\n<p>1 - style 0x060D,\n2 - 060D</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-gb/library/ms187928.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-gb/library/ms187928.aspx</a></p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366182/"
]
| What's the most efficient way to convert the output of this function from a varbinary() to a a varchar()? | How about this:
```
master.sys.fn_varbintohexstr(@binvalue)
``` |
73,456 | <p>I have a weird problem with a dropdownbox selectedIndex always being set to 0 upon postback. I'm not accidentally rebinding it in my code. In fact I've placed a breakpoint at the very first line of the page_load event and the value is already set to zero. The dropdown is in the master page of my project, I don't know if that makes a difference. I'm not referencing the control in my content holder. </p>
<p>If I set my autoPostBack = 'true' the page works fine. I don't have to change any code and the selectedIndex is maintained. I have also tried setting enableViewState on and off and it doesn't make a difference. At this point I'm grasping at straws to figure out what's going on. I've never had this problem before.</p>
<p>Here is the code in my page_load event.</p>
<pre><code> If CartEstablished Then
txtCustNum.Visible = False
btnCustSearch.Visible = False
lblCustNum.Visible = True
ddlSalesType.Visible = False
lblSalesType.Visible = True
ddlTerms.Visible = False
lblTerms.Visible = True
lblTerms.Text = TermsDescription
Else
txtCustNum.Visible = True
btnCustSearch.Visible = True
lblCustNum.Visible = False
lblSalesType.Visible = False
ddlSalesType.Visible = True
lblTerms.Visible = False
ddlTerms.Visible = True
End If
If Page.IsPostBack Then
GetUIValues()
Else
LoadTermCodes()
End If
</code></pre>
<p>The LoadTermCodes is where I bind the dropdownlist that is causing me problems.</p>
| [
{
"answer_id": 73501,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": 1,
"selected": false,
"text": "<p>Are you sure you are doing a postback and not a refresh? It is hard to help you without more context into the problem or a chunk of the code.</p>\n"
},
{
"answer_id": 73543,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This may be barking up the wrong tree, but a couple of things that have bitten me in the past that left me scratching my head:</p>\n\n<ul>\n<li>Naming the input element a duplicated/reserved word (thinking \"name\", \"method\", \"reset\", etc.)</li>\n<li>having the form element physically outside of the form being submitted</li>\n</ul>\n\n<p>I find that when all the logical debugging turns up nothing, my own dumbness has created time-wasting \"mystery\" bugs like this on occasion.</p>\n"
},
{
"answer_id": 73627,
"author": "derek lawless",
"author_id": 400464,
"author_profile": "https://Stackoverflow.com/users/400464",
"pm_score": 0,
"selected": false,
"text": "<p>At what stage in the page lifecycle are you binding the dropdownlist? If you're binding in page_init it should work, if you're binding in page_load make sure you wrap a !IsPostBack around the binding commands.</p>\n\n<p>If you post the code in question it'd be easier to troubleshoot.</p>\n"
},
{
"answer_id": 74783,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": -1,
"selected": false,
"text": "<p>This may simply be a syntax error, but shouldn't</p>\n\n<pre><code> If Page.IsPostBack Then\n GetUIValues()\n Else\n</code></pre>\n\n<p>Look like this</p>\n\n<pre><code> If NOT Page.IsPostBack Then\n GetUIValues()\n Else\n</code></pre>\n"
},
{
"answer_id": 264776,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'm finding the same problem... in my case, the dropdownlist is filled by a javascript function after another dropdownlist onchange client event. On PageLoad, the 2nd dropdownlist has lost all its items and so its selectedIndex turns to 0. Is there any way of preventing this?</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/288/"
]
| I have a weird problem with a dropdownbox selectedIndex always being set to 0 upon postback. I'm not accidentally rebinding it in my code. In fact I've placed a breakpoint at the very first line of the page\_load event and the value is already set to zero. The dropdown is in the master page of my project, I don't know if that makes a difference. I'm not referencing the control in my content holder.
If I set my autoPostBack = 'true' the page works fine. I don't have to change any code and the selectedIndex is maintained. I have also tried setting enableViewState on and off and it doesn't make a difference. At this point I'm grasping at straws to figure out what's going on. I've never had this problem before.
Here is the code in my page\_load event.
```
If CartEstablished Then
txtCustNum.Visible = False
btnCustSearch.Visible = False
lblCustNum.Visible = True
ddlSalesType.Visible = False
lblSalesType.Visible = True
ddlTerms.Visible = False
lblTerms.Visible = True
lblTerms.Text = TermsDescription
Else
txtCustNum.Visible = True
btnCustSearch.Visible = True
lblCustNum.Visible = False
lblSalesType.Visible = False
ddlSalesType.Visible = True
lblTerms.Visible = False
ddlTerms.Visible = True
End If
If Page.IsPostBack Then
GetUIValues()
Else
LoadTermCodes()
End If
```
The LoadTermCodes is where I bind the dropdownlist that is causing me problems. | Are you sure you are doing a postback and not a refresh? It is hard to help you without more context into the problem or a chunk of the code. |
73,467 | <p>I've got a custom handler applied to a class (using the Policy Injection Application Block in entlib 4) and I would like to know whether the input method is a property when Invoke is called. Following is what my handler looks like.</p>
<pre><code>[ConfigurationElementType(typeof(MyCustomHandlerData))]
public class MyCustomHandler : ICallHandler
{
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
if (input.MethodBase.IsPublic && (input.MethodBase.Name.Contains("get_") || input.MethodBase.Name.Contains("set_")))
{
Console.WriteLine("MyCustomHandler Invoke called with input of {0}", input.MethodBase.Name);
}
return getNext().Invoke(input, getNext);
}
public int Order { get; set; }
}
</code></pre>
<p>As you can see from my code sample, the best way I've thought of so far is by parsing the method name. Isn't there a better way to do this?</p>
| [
{
"answer_id": 73747,
"author": "Fredrik Kalseth",
"author_id": 1710,
"author_profile": "https://Stackoverflow.com/users/1710",
"pm_score": 0,
"selected": false,
"text": "<p>You could check the IsSpecialName property; it will be true for property getters and setters. However, it will also be true for other special methods, like operator overloads.</p>\n"
},
{
"answer_id": 73779,
"author": "Nathan Baulch",
"author_id": 8799,
"author_profile": "https://Stackoverflow.com/users/8799",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not familiar with that application block, but assuming that MethodBase property is of type System.Reflection.MethodBase, you could take a look at the IsSpecialName property.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.isspecialname.aspx\" rel=\"nofollow noreferrer\">System.Reflection.MethodBase.IsSpecialName on MSDN</a></p>\n"
},
{
"answer_id": 73908,
"author": "ShuggyCoUk",
"author_id": 12748,
"author_profile": "https://Stackoverflow.com/users/12748",
"pm_score": 3,
"selected": true,
"text": "<p>You can also check IsSpecialName is true. this will be true in a property (amongst other things)</p>\n\n<p>At the il level the methods are exposed as follows (using Environment.ExitCode as example):</p>\n\n<pre><code>.method public hidebysig specialname static int32 get_ExitCode() cil managed\n.method public hidebysig specialname static void set_ExitCode(int32 'value') cil managed\n</code></pre>\n\n<p>If you wanted to get fancy you could verify after extracting the name that said property exists but to be honest </p>\n\n<pre><code>if (m.IsSpecialName && (m.Attributes & MethodAttributes.HideBySig) != 0)) \n</code></pre>\n\n<p>as well as starts with get_ or set_ then you should be good even for people using nasty names (faking the hidebysig is easy enough, faking the IsSpecialName would be very tricky)</p>\n\n<p>Nothing is guaranteed though. Someone could emit a class with a set_Foo method that looked just like a real set method but actually wasn't a set on a read only property.\nUnless you check whether the property CanRead/CanWrite as well.</p>\n\n<p>This strikes me as madness for you though you aren't expecting deliberate circumvention. \nA simple utility/extension method on MethodInfo which did this logic wouldn't be too hard and including IsSpecialName would almost certainly cover all your needs.</p>\n"
},
{
"answer_id": 24102577,
"author": "Paul Easter",
"author_id": 3583929,
"author_profile": "https://Stackoverflow.com/users/3583929",
"pm_score": 0,
"selected": false,
"text": "<p>A couple of you mentioned using the \"IsSpecialName\" property of the MethodBase type. While it is true that the will return true for property \"gets\" or \"sets\", it will also return true for operator overloads such as add_EventName or remove_EventName. So you will need to examine other attributes of the MethodBase instance to determine if its a property accessor. Unfortunately, if all you have is a reference to a MethodBase instance (which I believe is the case with intercepting behaviors in the Unity framework) there is not real \"clean\" way to determine if its a property setter or getter. The best way I've found is as follows:</p>\n\n<p>C#:</p>\n\n<pre><code>bool IsPropertySetter(MethodBase methodBase){\n return methodBase.IsSpecialName && methodBase.Name.StartsWith(\"set_\");\n}\n\nbool IsPropertyGetter(MethodBase methodBase){\n return methodBase.IsSpecialName && methodBase.Name.StartsWith(\"get_\");\n}\n</code></pre>\n\n<p>VB:</p>\n\n<pre><code> Private Function IsPropertySetter(methodBase As MethodBase) As Boolean\n\n Return methodBase.IsSpecialName AndAlso methodBase.Name.StartsWith(\"set_\")\n\n End Function\n\n Private Function IsPropertyGetter(methodBase As MethodBase) As Boolean\n\n Return methodBase.IsSpecialName AndAlso methodBase.Name.StartsWith(\"get_\")\n\n End Function\n</code></pre>\n"
},
{
"answer_id": 40128143,
"author": "Tomaz Stih",
"author_id": 6286989,
"author_profile": "https://Stackoverflow.com/users/6286989",
"pm_score": 0,
"selected": false,
"text": "<p>It is a bit late but other people will read this too. In addition to IsSpecialName and checking for the set_ prefix (operators have op_, event subscr./remov. has add_,remove_) you can check if method is a match to any of properties methods like this:</p>\n\n<pre><code> bool isProperty = method.ReflectedType.GetProperties().FirstOrDefault(p => \n p.GetGetMethod().GetHashCode() == method.GetHashCode() \n || p.GetSetMethod().GetHashCode() == method.GetHashCode())!=null;\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6542/"
]
| I've got a custom handler applied to a class (using the Policy Injection Application Block in entlib 4) and I would like to know whether the input method is a property when Invoke is called. Following is what my handler looks like.
```
[ConfigurationElementType(typeof(MyCustomHandlerData))]
public class MyCustomHandler : ICallHandler
{
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
if (input.MethodBase.IsPublic && (input.MethodBase.Name.Contains("get_") || input.MethodBase.Name.Contains("set_")))
{
Console.WriteLine("MyCustomHandler Invoke called with input of {0}", input.MethodBase.Name);
}
return getNext().Invoke(input, getNext);
}
public int Order { get; set; }
}
```
As you can see from my code sample, the best way I've thought of so far is by parsing the method name. Isn't there a better way to do this? | You can also check IsSpecialName is true. this will be true in a property (amongst other things)
At the il level the methods are exposed as follows (using Environment.ExitCode as example):
```
.method public hidebysig specialname static int32 get_ExitCode() cil managed
.method public hidebysig specialname static void set_ExitCode(int32 'value') cil managed
```
If you wanted to get fancy you could verify after extracting the name that said property exists but to be honest
```
if (m.IsSpecialName && (m.Attributes & MethodAttributes.HideBySig) != 0))
```
as well as starts with get\_ or set\_ then you should be good even for people using nasty names (faking the hidebysig is easy enough, faking the IsSpecialName would be very tricky)
Nothing is guaranteed though. Someone could emit a class with a set\_Foo method that looked just like a real set method but actually wasn't a set on a read only property.
Unless you check whether the property CanRead/CanWrite as well.
This strikes me as madness for you though you aren't expecting deliberate circumvention.
A simple utility/extension method on MethodInfo which did this logic wouldn't be too hard and including IsSpecialName would almost certainly cover all your needs. |
73,468 | <p>I'm coding the shutdown of a multithreaded server.If everything goes as it should all the threads exit by their own, but there's a small chance that a thread gets stuck.In this case it would be convenient to have a non-blocking join so I could do.</p>
<p><strong>Is there a way of doing a non-blocking pthread_join?
Some sort of timed join would be good too.</strong></p>
<p>something like this:</p>
<pre>
foreach thread do
nb_pthread_join();
if still running
pthread_cancel();
</pre>
<p>I can think more cases where a a non-bloking join would be useful.</p>
<p>As it seems there is no such a function so I have already coded a workaround, but it's not as simple as I would like.</p>
| [
{
"answer_id": 73481,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 0,
"selected": false,
"text": "<p>You could push a byte into a pipe opened as non-blocking to signal to the other thread when its done, then use a non-blocking read to check the status of the pipe.</p>\n"
},
{
"answer_id": 73535,
"author": "raldi",
"author_id": 7598,
"author_profile": "https://Stackoverflow.com/users/7598",
"pm_score": 1,
"selected": false,
"text": "<p>The answer really depends on why you want to do this. If you just want to clean up dead threads, for example, it's probably easiest just to have a \"dead thread cleaner\" thread that loops and joins.</p>\n"
},
{
"answer_id": 73821,
"author": "Srikanth",
"author_id": 7205,
"author_profile": "https://Stackoverflow.com/users/7205",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure what exactly you mean, but I'm assuming that what you really need is a wait and notify mechanism.</p>\n\n<p>In short, here's how it works: You wait for a condition to satisfy with a timeout. Your wait will be over if:</p>\n\n<ul>\n<li>The timeout occurs, or</li>\n<li>If the condition is satisfied.</li>\n</ul>\n\n<p>You can have this in a loop and add some more intelligence to your logic. The best resource I've found for this related to Pthreads is this tutorial:\nPOSIX Threads Programming (<a href=\"https://computing.llnl.gov/tutorials/pthreads/\" rel=\"nofollow noreferrer\">https://computing.llnl.gov/tutorials/pthreads/</a>).</p>\n\n<p>I'm also very surprised to see that there's no API for timed join in Pthreads.</p>\n"
},
{
"answer_id": 81050,
"author": "shodanex",
"author_id": 11589,
"author_profile": "https://Stackoverflow.com/users/11589",
"pm_score": 1,
"selected": false,
"text": "<p>There is no timed <code>pthread_join</code>, but if you are waiting for other thread blocked on conditions, you can use timed <code>pthread_cond_timed_wait</code> instead of <code>pthread_cond_wait</code></p>\n"
},
{
"answer_id": 81261,
"author": "dmityugov",
"author_id": 3232,
"author_profile": "https://Stackoverflow.com/users/3232",
"pm_score": 2,
"selected": false,
"text": "<p>If you're developing for QNX, you can use pthread_timedjoin() function.</p>\n\n<p>Otherwise, you can create a separate thread that will perform pthread_join() and alert the parent thread, by signalling a semaphore for example, that the child thread completes. This separate thread can return what is gets from pthread_join() to let the parent thread determine not only when the child completes but also what value it returns.</p>\n"
},
{
"answer_id": 83788,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 2,
"selected": true,
"text": "<p>As others have pointed out there is not a non-blocking pthread_join available in the standard pthread libraries.</p>\n\n<p>However, given your stated problem (trying to guarantee that all of your threads have exited on program shutdown) such a function is not needed. You can simply do this:</p>\n\n<pre><code>int killed_threads = 0;\nfor(i = 0; i < num_threads; i++) {\n int return = pthread_cancel(threads[i]);\n if(return != ESRCH)\n killed_threads++;\n}\nif(killed_threads)\n printf(\"%d threads did not shutdown properly\\n\", killed_threads)\nelse\n printf(\"All threads exited successfully\");\n</code></pre>\n\n<p>There is nothing wrong with calling pthread_cancel on all of your threads (terminated or not) so calling that for all of your threads will not block and will guarantee thread exit (clean or not).</p>\n\n<p>That should qualify as a 'simple' workaround.</p>\n"
},
{
"answer_id": 1244687,
"author": "yves Baumes",
"author_id": 83331,
"author_profile": "https://Stackoverflow.com/users/83331",
"pm_score": 5,
"selected": false,
"text": "<p>If you are running your application on Linux, you may be interested to know that:</p>\n\n<pre><code>int pthread_tryjoin_np(pthread_t thread, void **retval);\n\nint pthread_timedjoin_np(pthread_t thread, void **retval,\n const struct timespec *abstime);\n</code></pre>\n\n<p>Be careful, as the suffix suggests it, \"np\" means \"non-portable\". They are not POSIX standard, gnu extensions, useful though.</p>\n\n<p><a href=\"http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_tryjoin_np.3.html\" rel=\"noreferrer\">link to man page</a></p>\n"
},
{
"answer_id": 7535847,
"author": "David Schwartz",
"author_id": 721269,
"author_profile": "https://Stackoverflow.com/users/721269",
"pm_score": 4,
"selected": false,
"text": "<p>The 'pthread_join' mechanism is a convenience to be used if it happens to do exactly what you want. It doesn't do anything you couldn't do yourself, and where it's not exactly what you want, code exactly what you want.</p>\n\n<p>There is no real reason you should actually care whether a thread has terminated or not. What you care about is whether the work the thread was doing is completed. To tell that, have the thread do something to indicate that it is working. How you do that depends on what is ideal for your specific problem, which depends heavily on what the threads are doing.</p>\n\n<p>Start by changing your thinking. It's not a thread that gets stuck, it's what the thread was doing that gets stuck.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12661/"
]
| I'm coding the shutdown of a multithreaded server.If everything goes as it should all the threads exit by their own, but there's a small chance that a thread gets stuck.In this case it would be convenient to have a non-blocking join so I could do.
**Is there a way of doing a non-blocking pthread\_join?
Some sort of timed join would be good too.**
something like this:
```
foreach thread do
nb_pthread_join();
if still running
pthread_cancel();
```
I can think more cases where a a non-bloking join would be useful.
As it seems there is no such a function so I have already coded a workaround, but it's not as simple as I would like. | As others have pointed out there is not a non-blocking pthread\_join available in the standard pthread libraries.
However, given your stated problem (trying to guarantee that all of your threads have exited on program shutdown) such a function is not needed. You can simply do this:
```
int killed_threads = 0;
for(i = 0; i < num_threads; i++) {
int return = pthread_cancel(threads[i]);
if(return != ESRCH)
killed_threads++;
}
if(killed_threads)
printf("%d threads did not shutdown properly\n", killed_threads)
else
printf("All threads exited successfully");
```
There is nothing wrong with calling pthread\_cancel on all of your threads (terminated or not) so calling that for all of your threads will not block and will guarantee thread exit (clean or not).
That should qualify as a 'simple' workaround. |
73,471 | <p>I have an editable DataGridView with SelectionMode set to FullRowSelect (so the whole row is highlighted when the user clicks on any cell). However I would like the cell that currently has focus to be highlighted with a different back color (so the user can clearly see what cell they are about to edit). How can I do this (I do not want to change the SelectionMode)?</p>
| [
{
"answer_id": 73636,
"author": "Clinton Pierce",
"author_id": 8173,
"author_profile": "https://Stackoverflow.com/users/8173",
"pm_score": 0,
"selected": false,
"text": "<p>You want to use the DataGridView RowPostPaint method. Let the framework draw the row, and afterwards go back and color in the cell you're interested in.</p>\n\n<p>An example is here at <a href=\"http://msdn.microsoft.com/en-us/library/85kxk29c.aspx\" rel=\"nofollow noreferrer\">MSDN</a></p>\n"
},
{
"answer_id": 74256,
"author": "Phillip Wells",
"author_id": 3012,
"author_profile": "https://Stackoverflow.com/users/3012",
"pm_score": 4,
"selected": true,
"text": "<p>I figured out a better way of doing this, using the CellFormatting event:</p>\n\n<pre><code>Private Sub uxContacts_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles uxContacts.CellFormatting\n If uxContacts.CurrentCell IsNot Nothing Then\n If e.RowIndex = uxContacts.CurrentCell.RowIndex And e.ColumnIndex = uxContacts.CurrentCell.ColumnIndex Then\n e.CellStyle.SelectionBackColor = Color.SteelBlue\n Else\n e.CellStyle.SelectionBackColor = uxContacts.DefaultCellStyle.SelectionBackColor\n End If\n End If\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 11961408,
"author": "Henry Rodriguez",
"author_id": 8892051,
"author_profile": "https://Stackoverflow.com/users/8892051",
"pm_score": 0,
"selected": false,
"text": "<p>Try this, the OnMouseMove method:</p>\n\n<pre><code>Private Sub DataGridView1_CellMouseMove(sender As Object, e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseMove\n If e.RowIndex >= 0 Then\n DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Style.SelectionBackColor = Color.Red\n End If\nEnd Sub\n\nPrivate Sub DataGridView1_CellMouseLeave(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellMouseLeave\n If e.RowIndex >= 0 Then\n DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Style.SelectionBackColor = DataGridView1.DefaultCellStyle.SelectionBackColor\n End If\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 32944008,
"author": "Dennis Henry",
"author_id": 2790151,
"author_profile": "https://Stackoverflow.com/users/2790151",
"pm_score": 1,
"selected": false,
"text": "<p>For me <code>CellFormatting</code> does the Trick. I have a set of columns that one can Edit (that I made to appear in a different color) and this is the code I used:</p>\n\n<pre><code>Private Sub Util_CellFormatting(ByVal Sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles dgvUtil.CellFormatting\n If dgvUtil.CurrentCell IsNot Nothing Then\n If e.RowIndex = dgvUtil.CurrentCell.RowIndex And e.ColumnIndex = dgvUtil.CurrentCell.ColumnIndex And (dgvUtil.CurrentCell.ColumnIndex = 10 Or dgvUtil.CurrentCell.ColumnIndex = 11 Or dgvUtil.CurrentCell.ColumnIndex = 13) Then\n e.CellStyle.SelectionBackColor = Color.SteelBlue\n Else\n e.CellStyle.SelectionBackColor = dgvUtil.DefaultCellStyle.SelectionBackColor\n End If\n End If\nEnd Sub\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3012/"
]
| I have an editable DataGridView with SelectionMode set to FullRowSelect (so the whole row is highlighted when the user clicks on any cell). However I would like the cell that currently has focus to be highlighted with a different back color (so the user can clearly see what cell they are about to edit). How can I do this (I do not want to change the SelectionMode)? | I figured out a better way of doing this, using the CellFormatting event:
```
Private Sub uxContacts_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles uxContacts.CellFormatting
If uxContacts.CurrentCell IsNot Nothing Then
If e.RowIndex = uxContacts.CurrentCell.RowIndex And e.ColumnIndex = uxContacts.CurrentCell.ColumnIndex Then
e.CellStyle.SelectionBackColor = Color.SteelBlue
Else
e.CellStyle.SelectionBackColor = uxContacts.DefaultCellStyle.SelectionBackColor
End If
End If
End Sub
``` |
73,474 | <p>I am having a frequent problems with my web hosting (its shared)</p>
<p>I am not able to delete or change permission for a particular directory. The response is,</p>
<pre><code>Cannot delete. Directory may not be empty
</code></pre>
<p>I checked the permissions and it looks OK. There are 100's of files in this folder which I don't want. </p>
<p>I contacted my support and they solved it saying it was permission issue. But it reappeared. Any suggestions?</p>
<p>The server is Linux.</p>
| [
{
"answer_id": 73529,
"author": "Ram Prasad",
"author_id": 6361,
"author_profile": "https://Stackoverflow.com/users/6361",
"pm_score": 0,
"selected": false,
"text": "<p>This could also be because your FTP client might not be showing the hidden files (like cache, or any hiddn files that your application might create), while the hidden files are preventing you from deleting the directory. (though, in your case, I am not sure if this is the cause .. .it could be permission issue with your hosting provider.. Webserver running as another user (like apache or www) combined with your directories having global write perms).</p>\n"
},
{
"answer_id": 73549,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 3,
"selected": true,
"text": "<p>You can't <strong>rmdir</strong> a directory with files in it. You must first <strong>rm</strong> all files and subdirectories. Many times, the easiest solution is:</p>\n\n<pre><code>$ rm -rf old_directory\n</code></pre>\n\n<p>It's entirely possible that some of the files or subdirectories have permission limitations that might prevent them from being removed. Occasionally, this can be solved with:</p>\n\n<pre><code>$ chmod -R +w old_directory\n</code></pre>\n\n<p>But I suspect that's what your support people did earlier.</p>\n"
},
{
"answer_id": 73584,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 0,
"selected": false,
"text": "<p>I assume that's a response from an FTP server?</p>\n\n<p>Usually, a message from an FTP server really means it. If it says the directory is not empty, there might be certain files you cannot see that exists in the directory which maybe one of:</p>\n\n<ul>\n<li>Your PHP/JSP/ASP/whatever scripts may run under a different user account thus creating files which you may not be able to see/delete</li>\n<li>Is your hosting's web interface run under your FTP account? There might be conflicting permissions there if you manage some files from the web interface and then later via FTP.</li>\n<li>Hosting server/operating system files created unintentionally e.g. from the hosting's web interface</li>\n</ul>\n\n<p>If it comes from a script, write a one-time throw-away script that delete the files and that directory and then uploads and executes it.</p>\n\n<p>And just to be sure, some FTP server doesn't support direct directory deletion, you need all the files first, is that the case?</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12178/"
]
| I am having a frequent problems with my web hosting (its shared)
I am not able to delete or change permission for a particular directory. The response is,
```
Cannot delete. Directory may not be empty
```
I checked the permissions and it looks OK. There are 100's of files in this folder which I don't want.
I contacted my support and they solved it saying it was permission issue. But it reappeared. Any suggestions?
The server is Linux. | You can't **rmdir** a directory with files in it. You must first **rm** all files and subdirectories. Many times, the easiest solution is:
```
$ rm -rf old_directory
```
It's entirely possible that some of the files or subdirectories have permission limitations that might prevent them from being removed. Occasionally, this can be solved with:
```
$ chmod -R +w old_directory
```
But I suspect that's what your support people did earlier. |
73,476 | <p>We use SAX to parse XML because it does not require the entire XML document to be read into memory in order to parse a single value. I read many articles that insisted SAX can only be used to parse/decode XML and not create it. Is this true?</p>
| [
{
"answer_id": 73483,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 3,
"selected": true,
"text": "<p>No, it isn't true, you can encode XML to any Writer in Java using something similar to:</p>\n\n<pre><code>char[] ch;\nAttributesImpl atts = new AttributesImpl();\nWriter writer = new StringWriter();\nStreamResult streamResult = new StreamResult(writer);\nSAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();\n\n// SAX2.0 ContentHandler\nTransformerHandler transformerHandler = tf.newTransformerHandler();\n\nTransformer serializer = transformerHandler.getTransformer();\n\nserializer.setOutputProperty(OutputKeys.ENCODING, \"UTF-8\");\n// serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, \"nodes.dtd\");\nserializer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n\ntransformerHandler.setResult(streamResult);\n\ntransformerHandler.startDocument();\n\natts.clear();\n// atts.addAttribute(\"\", \"\", \"xmlns\", \"CDATA\", \"http://www.example.com/nodes\");\n// atts.addAttribute(\"\", \"\", \"xmlns:xsi\", \"CDATA\", \"http://www.w3.org/2001/XMLSchema-instance\");\n// atts.addAttribute(\"\", \"\", \"xsi:schemaLocation\", \"CDATA\", \"/nodes.xsd\");\ntransformerHandler.startElement(\"\", \"\", \"node_list\", atts);\n\n// displayName element\nif (displayName != null) {\n transformerHandler.startElement(\"\", \"\", \"display_name\", null);\n ch = displayName.toCharArray();\n transformerHandler.characters(ch, 0, ch.length);\n transformerHandler.endElement(\"\", \"\", \"display_name\");\n}\n\n// nodes element\ntransformerHandler.startElement(\"\", \"\", \"nodes\", null);\n\natts.clear();\natts.addAttribute(\"\", \"\", \"node_type\", \"CDATA\", \"sometype\");\ntransformerHandler.startElement(\"\", \"\", \"node\", atts);\n\nch = node.getValue().toCharArray();\ntransformerHandler.startElement(\"\", \"\", \"value\", null);\ntransformerHandler.characters(ch, 0, ch.length);\ntransformerHandler.endElement(\"\", \"\", \"value\");\n\ntransformerHandler.endElement(\"\", \"\", \"node\");\n\ntransformerHandler.endElement(\"\", \"\", \"nodes\");\n\ntransformerHandler.endElement(\"\", \"\", \"node_list\");\n\ntransformerHandler.endDocument();\n\nString xml = writer.toString();\n</code></pre>\n"
},
{
"answer_id": 73936,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 0,
"selected": false,
"text": "<p>The SAX handler interfaces were designed to be easy to implement. It's easy to write a class with similar (perhaps wrapping a SAX interface) to make it easy to call - chaining, remembering which element to close, easier attributes, etc.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9254/"
]
| We use SAX to parse XML because it does not require the entire XML document to be read into memory in order to parse a single value. I read many articles that insisted SAX can only be used to parse/decode XML and not create it. Is this true? | No, it isn't true, you can encode XML to any Writer in Java using something similar to:
```
char[] ch;
AttributesImpl atts = new AttributesImpl();
Writer writer = new StringWriter();
StreamResult streamResult = new StreamResult(writer);
SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
// SAX2.0 ContentHandler
TransformerHandler transformerHandler = tf.newTransformerHandler();
Transformer serializer = transformerHandler.getTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
// serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "nodes.dtd");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
transformerHandler.setResult(streamResult);
transformerHandler.startDocument();
atts.clear();
// atts.addAttribute("", "", "xmlns", "CDATA", "http://www.example.com/nodes");
// atts.addAttribute("", "", "xmlns:xsi", "CDATA", "http://www.w3.org/2001/XMLSchema-instance");
// atts.addAttribute("", "", "xsi:schemaLocation", "CDATA", "/nodes.xsd");
transformerHandler.startElement("", "", "node_list", atts);
// displayName element
if (displayName != null) {
transformerHandler.startElement("", "", "display_name", null);
ch = displayName.toCharArray();
transformerHandler.characters(ch, 0, ch.length);
transformerHandler.endElement("", "", "display_name");
}
// nodes element
transformerHandler.startElement("", "", "nodes", null);
atts.clear();
atts.addAttribute("", "", "node_type", "CDATA", "sometype");
transformerHandler.startElement("", "", "node", atts);
ch = node.getValue().toCharArray();
transformerHandler.startElement("", "", "value", null);
transformerHandler.characters(ch, 0, ch.length);
transformerHandler.endElement("", "", "value");
transformerHandler.endElement("", "", "node");
transformerHandler.endElement("", "", "nodes");
transformerHandler.endElement("", "", "node_list");
transformerHandler.endDocument();
String xml = writer.toString();
``` |
73,484 | <p>Basically I would like to find a way to ddo something like:</p>
<pre><code><asp:Label ID="lID" runat="server" AssociatedControlID="txtId" Text="<%# MyProperty %>"></asp:Label>
</code></pre>
<p>I know I could set it from code behind (writing lId.Text = MyProperty), but I'd prefer doing it in the markup and I just can't seem to find the solution.
(MyProperty is a string property)
cheers</p>
| [
{
"answer_id": 73507,
"author": "Akselsson",
"author_id": 8862,
"author_profile": "https://Stackoverflow.com/users/8862",
"pm_score": 0,
"selected": false,
"text": "<p>Call lID.Databind() from code-behind</p>\n"
},
{
"answer_id": 73513,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 2,
"selected": false,
"text": "<p>Leave the markup as is and make a call to Page.DataBind(); in your code behind.</p>\n"
},
{
"answer_id": 73558,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 2,
"selected": false,
"text": "<pre><code><asp:Label id=\"lID\" runat=\"server\"><%= MyProperty %></asp:Label>\n</code></pre>\n\n<p>since asp.net tags do not allow <% %> constructs, you cannot use Text=\"<%= MyProperty %>\".</p>\n"
},
{
"answer_id": 73585,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 0,
"selected": false,
"text": "<pre><code><div> <%=MyProperty\"%></div>\n</code></pre>\n"
},
{
"answer_id": 74054,
"author": "Mark S. Rasmussen",
"author_id": 12469,
"author_profile": "https://Stackoverflow.com/users/12469",
"pm_score": 4,
"selected": false,
"text": "<p>You can do </p>\n\n<pre><code><asp:Label runat=\"server\" Text='<%# MyProperty %>' />\n</code></pre>\n\n<p>And then a Page.DataBind() in the codebehind.</p>\n"
},
{
"answer_id": 75080,
"author": "Frederik Vig",
"author_id": 9819,
"author_profile": "https://Stackoverflow.com/users/9819",
"pm_score": 0,
"selected": false,
"text": "<p>When you use <%# MyProperty %> declaration you need to databind it, but when using <%= MyProperty %> you don't (which is similar to just writing Response.Write(MyProperty).</p>\n"
},
{
"answer_id": 75235,
"author": "mrflippy",
"author_id": 13292,
"author_profile": "https://Stackoverflow.com/users/13292",
"pm_score": 4,
"selected": true,
"text": "<p>Code expressions are an option as well. These can be used inside of quotes in ASP tags, unlike standard <%= %> tags.</p>\n\n<p>The general syntax is:</p>\n\n<pre><code><%$ resources: ResourceKey %>\n</code></pre>\n\n<p>There is a built-in expression for appSettings:</p>\n\n<pre><code><%$ appSettings: AppSettingsKey %>\n</code></pre>\n\n<p>More info on this here: <a href=\"http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx\" rel=\"noreferrer\">http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx</a></p>\n"
},
{
"answer_id": 2968964,
"author": "Brian",
"author_id": 357836,
"author_profile": "https://Stackoverflow.com/users/357836",
"pm_score": 0,
"selected": false,
"text": "<p>You can do this: </p>\n\n<pre><code><asp:Label ID=\"lblCurrentTime\" runat=\"server\">\n Last update: <%=DateTime.Now.ToString()%>\n</asp:Label>\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1613872/"
]
| Basically I would like to find a way to ddo something like:
```
<asp:Label ID="lID" runat="server" AssociatedControlID="txtId" Text="<%# MyProperty %>"></asp:Label>
```
I know I could set it from code behind (writing lId.Text = MyProperty), but I'd prefer doing it in the markup and I just can't seem to find the solution.
(MyProperty is a string property)
cheers | Code expressions are an option as well. These can be used inside of quotes in ASP tags, unlike standard <%= %> tags.
The general syntax is:
```
<%$ resources: ResourceKey %>
```
There is a built-in expression for appSettings:
```
<%$ appSettings: AppSettingsKey %>
```
More info on this here: <http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx> |
73,491 | <p>I'm trying to use maven2 to build an axis2 project. My project is configured as a parent project with AAR, WAR, and EAR modules. When I run the parent project's package goal, the console shows a successful build and all of the files are created. However the AAR file generated by AAR project is not included in the generated WAR project. The AAR project is listed as a dependency of WAR project. When I explicitly run the WAR's package goal, the AAR file is then included in the WAR file.</p>
<p>Why would the parent's package goal not include the necessary dependency while running the child's package goal does?</p>
<p>I'm using the maven-war-plugin v2.1-alpha-2 in my war project.</p>
<p>Parent POM:</p>
<pre><code><parent>
<groupId>companyId</groupId>
<artifactId>build</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.nationwide.nf</groupId>
<artifactId>parent</artifactId>
<packaging>pom</packaging>
<version>1.0.0-SNAPSHOT</version>
<modules>
<module>ws-war</module>
<module>ws-aar</module>
<module>ws-ear</module>
</modules>
</code></pre>
<p>AAR POM:</p>
<pre><code><parent>
<artifactId>parent</artifactId>
<groupId>companyId</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>companyId</groupId>
<artifactId>ws-aar</artifactId>
<version>1.0.0-SNAPSHOT</version>
<description/>
<packaging>aar</packaging>
<dependencies>...</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-wsdl2code-maven-plugin</artifactId>
<version>1.4</version>
<configuration>...</configuration>
<executions>
<execution>
<goals>
<goal>wsdl2code</goal>
</goals>
<id>axis2-gen-sources</id>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-aar-maven-plugin</artifactId>
<version>1.4</version>
<extensions>true</extensions>
<configuration>...</configuration>
</plugin>
</plugins>
</build>
</code></pre>
<p>WAR POM:</p>
<pre><code><parent>
<artifactId>parent</artifactId>
<groupId>companyId</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>companyId</groupId>
<artifactId>ws-war</artifactId>
<packaging>war</packaging>
<version>1.0.0-SNAPSHOT</version>
<description/>
<dependencies>
<dependency>
<groupId>companyId</groupId>
<artifactId>ws-aar</artifactId>
<type>aar</type>
<version>1.0.0-SNAPSHOT</version>
</dependency>
.
.
.
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1-alpha-2</version>
<configuration>
<warName>appName</warName>
</configuration>
</plugin>
</plugins>
</build>
</code></pre>
<p>Thanks,
Joe</p>
| [
{
"answer_id": 89868,
"author": "user11087",
"author_id": 11087,
"author_profile": "https://Stackoverflow.com/users/11087",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried using the \"type\" element in your dependencies? For example:</p>\n\n<pre><code><dependency>\n <groupId>group-a</groupId>\n <artifactId>artifact-b</artifactId>\n <version>1.0</version>\n <type>aar</type>\n</dependency>\n</code></pre>\n\n<p>Its hard to say for sure what your problem is without seeing your actual pom files.</p>\n\n<p>Update:</p>\n\n<p>What happens if, from the parent project, you run:</p>\n\n<pre><code> mvn clean install\n</code></pre>\n\n<ol>\n<li>Does \"install\" have any different behavior than \"package\" as far as your problem is concerned?</li>\n<li>Do you see the .aar file in your local maven repository (~/.m2/repository/com/mycompany/.../)?</li>\n</ol>\n\n<p>As a side note, i've never been very happy with the maven war plugin. I've always ended up using the maven assembly plugin. It just seems to work better and is more consistent. Also, make sure you are using the latest version of maven (2.0.9). I spent half a day fighting a similar problem which was fixed in the latest version.</p>\n"
},
{
"answer_id": 120938,
"author": "Joe",
"author_id": 5313,
"author_profile": "https://Stackoverflow.com/users/5313",
"pm_score": 3,
"selected": true,
"text": "<p>I was able to get my maven build working correctly by adding the following plugin to the ws-war pom file:</p>\n\n<pre><code> <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-dependency-plugin</artifactId>\n <executions>\n <execution>\n <phase>process-classes</phase>\n <goals>\n <goal>copy-dependencies</goal>\n </goals>\n <configuration>\n <outputDirectory>\n ${project.build.directory}/${project.build.finalName}/WEB-INF/services\n </outputDirectory>\n <includeArtifactIds>\n ws-aar\n </includeArtifactIds>\n </configuration>\n </execution>\n </executions>\n </plugin>\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5313/"
]
| I'm trying to use maven2 to build an axis2 project. My project is configured as a parent project with AAR, WAR, and EAR modules. When I run the parent project's package goal, the console shows a successful build and all of the files are created. However the AAR file generated by AAR project is not included in the generated WAR project. The AAR project is listed as a dependency of WAR project. When I explicitly run the WAR's package goal, the AAR file is then included in the WAR file.
Why would the parent's package goal not include the necessary dependency while running the child's package goal does?
I'm using the maven-war-plugin v2.1-alpha-2 in my war project.
Parent POM:
```
<parent>
<groupId>companyId</groupId>
<artifactId>build</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.nationwide.nf</groupId>
<artifactId>parent</artifactId>
<packaging>pom</packaging>
<version>1.0.0-SNAPSHOT</version>
<modules>
<module>ws-war</module>
<module>ws-aar</module>
<module>ws-ear</module>
</modules>
```
AAR POM:
```
<parent>
<artifactId>parent</artifactId>
<groupId>companyId</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>companyId</groupId>
<artifactId>ws-aar</artifactId>
<version>1.0.0-SNAPSHOT</version>
<description/>
<packaging>aar</packaging>
<dependencies>...</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-wsdl2code-maven-plugin</artifactId>
<version>1.4</version>
<configuration>...</configuration>
<executions>
<execution>
<goals>
<goal>wsdl2code</goal>
</goals>
<id>axis2-gen-sources</id>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-aar-maven-plugin</artifactId>
<version>1.4</version>
<extensions>true</extensions>
<configuration>...</configuration>
</plugin>
</plugins>
</build>
```
WAR POM:
```
<parent>
<artifactId>parent</artifactId>
<groupId>companyId</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>companyId</groupId>
<artifactId>ws-war</artifactId>
<packaging>war</packaging>
<version>1.0.0-SNAPSHOT</version>
<description/>
<dependencies>
<dependency>
<groupId>companyId</groupId>
<artifactId>ws-aar</artifactId>
<type>aar</type>
<version>1.0.0-SNAPSHOT</version>
</dependency>
.
.
.
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1-alpha-2</version>
<configuration>
<warName>appName</warName>
</configuration>
</plugin>
</plugins>
</build>
```
Thanks,
Joe | I was able to get my maven build working correctly by adding the following plugin to the ws-war pom file:
```
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>process-classes</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>
${project.build.directory}/${project.build.finalName}/WEB-INF/services
</outputDirectory>
<includeArtifactIds>
ws-aar
</includeArtifactIds>
</configuration>
</execution>
</executions>
</plugin>
``` |
73,518 | <p>In Windows XP:</p>
<p>How do you direct traffic to/from a particular site to a specific NIC?</p>
<p>For Instance: How do I say, all connections to stackoverflow.com should use my wireless connection, while all other sites will use my ethernet?</p>
| [
{
"answer_id": 73545,
"author": "Danimal",
"author_id": 2757,
"author_profile": "https://Stackoverflow.com/users/2757",
"pm_score": 1,
"selected": false,
"text": "<p>you should be able to do it using the route command. Route add (ip address) (netmask) (gateway) metric 1</p>\n"
},
{
"answer_id": 73613,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 3,
"selected": true,
"text": "<p>I'm not sure if there's an easier way, but one way would be to add a route to the IP(s) of stackoverflow.com that explicitly specifies your wireless connection, using a lower metric (cost) than your default route.</p>\n\n<p>Running nslookup www.stackoverflow.com shows only one IP: 67.199.15.132, so the syntax would be:</p>\n\n<pre>route -p add 67.199.15.132 [your wireless gateway] metric [lower metric than default route] IF [wireless interface]</pre>\n\n<p>See the route command for more info.</p>\n"
},
{
"answer_id": 73621,
"author": "Steve Moon",
"author_id": 3660,
"author_profile": "https://Stackoverflow.com/users/3660",
"pm_score": 1,
"selected": false,
"text": "<p>Modify your routing table so that specific hosts go through the desired interface. </p>\n\n<p>You need to have a 'default' route, which would either be your ethernet or wireless. But to direct traffic through the other interface, use the command line 'route' command to add a route to the specific IP address you're wanting to redirect.</p>\n\n<p>For example, stackoverflow.com has the IP address 67.199.15.132 (you can find this by using nslookup or pinging it). Issue a route add 67.199.15.132 mask 255.255.255.255 a.b.c.d IF e\nwhere a.b.c.d == the IP address of the router on the other end of your wireless interface, and e is the interface number (a 'route print' command will list each interface and it's interface number).</p>\n\n<p>If you add the '-p' flag to the route command the route will be persistent between reboots.</p>\n"
},
{
"answer_id": 73670,
"author": "Jay",
"author_id": 12479,
"author_profile": "https://Stackoverflow.com/users/12479",
"pm_score": 1,
"selected": false,
"text": "<p>Within XP, I have often found that by adding/modifying static routes, I can typically\naccomplish what I need in such cases. </p>\n\n<p>Of course, there are other 'high level' COTS tools/firewalls that might provide you a better interface.</p>\n\n<p>One caveat with modifying routes - VPN tunnels are not too happy about chnages in static routes once the VPN is set up so be sure to set it up at Windows boot up after the NICs are initialized through some scripting.</p>\n\n<p>Static routes- these will work fine, unless you are using a VPN tunnel.</p>\n\n<p>Windows 'route' help</p>\n\n<p>Manipulates network routing tables.</p>\n\n<p>ROUTE [-f] [-p] [command [destination]\n [MASK netmask] [gateway] [METRIC metric] [IF interface]</p>\n\n<p>-f Clears the routing tables of all gateway entries. If this is\n used in conjunction with one of the commands, the tables are\n cleared prior to running the command.\n -p When used with the ADD command, makes a route persistent across\n boots of the system. By default, routes are not preserved\n when the system is restarted. Ignored for all other commands,\n which always affect the appropriate persistent routes. This\n option is not supported in Windows 95.\n command One of these:\n PRINT Prints a route\n ADD Adds a route\n DELETE Deletes a route\n CHANGE Modifies an existing route</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2744/"
]
| In Windows XP:
How do you direct traffic to/from a particular site to a specific NIC?
For Instance: How do I say, all connections to stackoverflow.com should use my wireless connection, while all other sites will use my ethernet? | I'm not sure if there's an easier way, but one way would be to add a route to the IP(s) of stackoverflow.com that explicitly specifies your wireless connection, using a lower metric (cost) than your default route.
Running nslookup www.stackoverflow.com shows only one IP: 67.199.15.132, so the syntax would be:
```
route -p add 67.199.15.132 [your wireless gateway] metric [lower metric than default route] IF [wireless interface]
```
See the route command for more info. |
73,524 | <p>I have a list of addresses from a Database for which I'd like to put markers on a Yahoo Map. The <a href="http://developer.yahoo.com/maps/ajax/V3.8/index.html#YMap" rel="nofollow noreferrer"><code>addMarker()</code> method</a> on YMap takes a YGeoPoint, which requires a latitude and longitude. However, Yahoo Maps must know how to convert from addresses because <code>drawZoomAndCenter(LocationType,ZoomLevel)</code> can take an address. I could convert by using <code>drawZoomAndCenter()</code> then <code>getCenterLatLon()</code> but is there a better way, which doesn't require a draw?</p>
| [
{
"answer_id": 73625,
"author": "Paul Reiners",
"author_id": 7648,
"author_profile": "https://Stackoverflow.com/users/7648",
"pm_score": -1,
"selected": false,
"text": "<p>If you're working with U.S. addresses, you can use <a href=\"http://geocoder.us/\" rel=\"nofollow noreferrer\">geocoder.us</a>, which has <a href=\"http://geocoder.us/help/\" rel=\"nofollow noreferrer\">APIs</a>.</p>\n\n<p>Also, <em>Google Maps Hacks</em> has a hack, <a href=\"http://safari.oreilly.com/0596101619/googlemapshks-CHP-7-SECT-2\" rel=\"nofollow noreferrer\">\"Hack 62. Find the Latitude and Longitude of a Street Address\"</a>, for that.</p>\n"
},
{
"answer_id": 81551,
"author": "David Bick",
"author_id": 4914,
"author_profile": "https://Stackoverflow.com/users/4914",
"pm_score": 2,
"selected": true,
"text": "<p>You can ask the map object to do the geoCoding, and catch the callback:</p>\n\n<pre><code><script type=\"text/javascript\"> \nvar map = new YMap(document.getElementById('map'));\nmap.drawZoomAndCenter(\"Algeria\", 17);\n\nmap.geoCodeAddress(\"Cambridge, UK\");\n\nYEvent.Capture(map, EventsList.onEndGeoCode, function(geoCode) {\n if (geoCode.success)\n map.addOverlay(new YMarker(geoCode.GeoPoint));\n});\n</script>\n</code></pre>\n\n<p>One thing to beware of -- in this example the <code>drawAndZoom</code> call will itself make a geoCoding request, so you'll get the callback from that too. You might want to filter that out, or set the map's centre based on a GeoPoint.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5346/"
]
| I have a list of addresses from a Database for which I'd like to put markers on a Yahoo Map. The [`addMarker()` method](http://developer.yahoo.com/maps/ajax/V3.8/index.html#YMap) on YMap takes a YGeoPoint, which requires a latitude and longitude. However, Yahoo Maps must know how to convert from addresses because `drawZoomAndCenter(LocationType,ZoomLevel)` can take an address. I could convert by using `drawZoomAndCenter()` then `getCenterLatLon()` but is there a better way, which doesn't require a draw? | You can ask the map object to do the geoCoding, and catch the callback:
```
<script type="text/javascript">
var map = new YMap(document.getElementById('map'));
map.drawZoomAndCenter("Algeria", 17);
map.geoCodeAddress("Cambridge, UK");
YEvent.Capture(map, EventsList.onEndGeoCode, function(geoCode) {
if (geoCode.success)
map.addOverlay(new YMarker(geoCode.GeoPoint));
});
</script>
```
One thing to beware of -- in this example the `drawAndZoom` call will itself make a geoCoding request, so you'll get the callback from that too. You might want to filter that out, or set the map's centre based on a GeoPoint. |
73,542 | <p>I have an List and I'd like to wrap it into an IQueryable.</p>
<p>Is this possible?</p>
| [
{
"answer_id": 73563,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 8,
"selected": true,
"text": "<pre><code>List<int> list = new List<int>() { 1, 2, 3, 4, };\nIQueryable<int> query = list.AsQueryable();\n</code></pre>\n\n<p>If you don't see the <code>AsQueryable()</code> method, add a using statement for <code>System.Linq</code>.</p>\n"
},
{
"answer_id": 73564,
"author": "Chris Shaffer",
"author_id": 6744,
"author_profile": "https://Stackoverflow.com/users/6744",
"pm_score": 4,
"selected": false,
"text": "<p>Use the <code>AsQueryable<T>()</code> extension method.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11835/"
]
| I have an List and I'd like to wrap it into an IQueryable.
Is this possible? | ```
List<int> list = new List<int>() { 1, 2, 3, 4, };
IQueryable<int> query = list.AsQueryable();
```
If you don't see the `AsQueryable()` method, add a using statement for `System.Linq`. |
73,544 | <p>Anyone know of a good, hopefully free FTP class for use in .NET that can actually work behind an HTTP proxy or FTP gateway? The FtpWebRequest stuff in .NET is horrible at best, and I really don't want to roll my own here.</p>
| [
{
"answer_id": 73566,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": -1,
"selected": false,
"text": "<p>System.Net.WebClient can handle ftp urls, and it's a bit easier to work with. You can set credentials and proxy information with it, too.</p>\n"
},
{
"answer_id": 73630,
"author": "Jakub Šturc",
"author_id": 2361,
"author_profile": "https://Stackoverflow.com/users/2361",
"pm_score": 1,
"selected": false,
"text": "<p>I have no particular experience but <a href=\"http://sharptoolbox.com/\" rel=\"nofollow noreferrer\">sharptoolbox</a> offer <a href=\"http://sharptoolbox.com/search?ToolName%253dftp%2526Description%253dftp%2526Category%253d9d0e4330-f6ff-4ead-afd3-f77f1c06cdc8%2526Attribute%253d-800\" rel=\"nofollow noreferrer\">plenty implementations</a>.</p>\n"
},
{
"answer_id": 73637,
"author": "Juanma",
"author_id": 3730,
"author_profile": "https://Stackoverflow.com/users/3730",
"pm_score": 1,
"selected": false,
"text": "<p>You can give <a href=\"http://www.indyproject.org/index.en.aspx\" rel=\"nofollow noreferrer\" title=\"Indy.Sockets\">\"Indy.Sockets\"</a> a try. It can handle a lot of high level network protocols, including ftp.</p>\n"
},
{
"answer_id": 74165,
"author": "Brad Bruce",
"author_id": 5008,
"author_profile": "https://Stackoverflow.com/users/5008",
"pm_score": 1,
"selected": false,
"text": "<p>The best one I've run across is edtFTP.net <a href=\"http://www.enterprisedt.com/products/edtftpnet/overview.html\" rel=\"nofollow noreferrer\">http://www.enterprisedt.com/products/edtftpnet/overview.html</a> </p>\n\n<p>If offers flexibility you don't get in the built-in classes</p>\n"
},
{
"answer_id": 75069,
"author": "Kearns",
"author_id": 6500,
"author_profile": "https://Stackoverflow.com/users/6500",
"pm_score": 0,
"selected": false,
"text": "<p>I have used <a href=\"http://sourceforge.net/projects/dotnetftpclient/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/dotnetftpclient/</a> for quite a while now, and it does the job nicely. If you use a PASV connection, you shouldn't have any firewall issues. Not sure what an FTP gateway is, but I don't see how the HTTP Proxy would affect any FTP connection.</p>\n"
},
{
"answer_id": 2327985,
"author": "Martin Vobr",
"author_id": 16132,
"author_profile": "https://Stackoverflow.com/users/16132",
"pm_score": 2,
"selected": false,
"text": "<p>Our <a href=\"http://www.rebex.net/ftp.net/\" rel=\"nofollow noreferrer\">Rebex FTP</a> works with proxies just fine. Following code shows how to connect to the FTP using HTTP proxy (code is taken from <a href=\"http://www.rebex.net/ftp.net/tutorial-ftp.aspx#proxy\" rel=\"nofollow noreferrer\">FTP tutorial page</a>).</p>\n\n<pre><code>// initialize FTP client \nFtp client = new Ftp();\n\n// setup proxy details \nclient.Proxy.ProxyType = FtpProxyType.HttpConnect;\nclient.Proxy.Host = proxyHostname;\nclient.Proxy.Port = proxyPort;\n\n// add proxy username and password when needed \nclient.Proxy.UserName = proxyUsername;\nclient.Proxy.Password = proxyPassword;\n\n// connect, login \nclient.Connect(hostname, port);\nclient.Login(username, password);\n\n// do some work \n// ... \n\n// disconnect \nclient.Disconnect();\n</code></pre>\n\n<p>You can download the trial at <a href=\"http://www.rebex.net/ftp.net/download.aspx\" rel=\"nofollow noreferrer\">www.rebex.net/ftp.net/download.aspx</a></p>\n"
},
{
"answer_id": 2328113,
"author": "Rush Frisby",
"author_id": 266804,
"author_profile": "https://Stackoverflow.com/users/266804",
"pm_score": 0,
"selected": false,
"text": "<p>I used this in my project recently and it worked great.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/IP/ftplib.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/IP/ftplib.aspxt</a></p>\n"
},
{
"answer_id": 8060892,
"author": "Brady Moritz",
"author_id": 177242,
"author_profile": "https://Stackoverflow.com/users/177242",
"pm_score": 0,
"selected": false,
"text": "<p>.Net 4.0+ now includes an ftp client class- see this msdn link for more info. </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx</a></p>\n\n<p>I see options for even using PASV mode etc, so it appears to be fully functional (or so I hope). </p>\n"
},
{
"answer_id": 12266161,
"author": "freggel",
"author_id": 49788,
"author_profile": "https://Stackoverflow.com/users/49788",
"pm_score": 0,
"selected": false,
"text": "<p>I had a simalor issue, create an client for FTPS (explicit) communcation through a Socks4 proxy.</p>\n\n<p>After some searching and testing I found .NET library Starksoftftps.\n<a href=\"http://starksoftftps.codeplex.com/\" rel=\"nofollow\">http://starksoftftps.codeplex.com/</a></p>\n\n<p>Here is my code sample:</p>\n\n<pre><code>Socks4ProxyClient socks = new Socks4ProxyClient(\"socksproxyhost\",1010);\nFtpClient ftp = new FtpClient(\"ftpshost\",2010,FtpSecurityProtocol.Tls1Explicit);\nftp.Proxy = socks;\nftp.Open(\"userid\", \"******\");\nftp.PutFile(@\"C:\\519ec30a-ae15-4bd5-8bcd-94ef3ca49165.xml\");\nConsole.WriteLine(ftp.GetDirListAsText());\nftp.Close();\n</code></pre>\n"
},
{
"answer_id": 20353970,
"author": "A. 'Eradicator' Polyakov",
"author_id": 3061817,
"author_profile": "https://Stackoverflow.com/users/3061817",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my open source C# code that uploads file to FTP via HTTP proxy.</p>\n\n<pre><code>public bool UploadFile(string localFilePath, string remoteDirectory)\n{\n var fileName = Path.GetFileName(localFilePath);\n string content;\n using (var reader = new StreamReader(localFilePath))\n content = reader.ReadToEnd();\n\n var proxyAuthB64Str = Convert.ToBase64String(Encoding.ASCII.GetBytes(_proxyUserName + \":\" + _proxyPassword));\n var sendStr = \"PUT ftp://\" + _ftpLogin + \":\" + _ftpPassword\n + \"@\" + _ftpHost + remoteDirectory + fileName + \" HTTP/1.1\\n\"\n + \"Host: \" + _ftpHost + \"\\n\"\n + \"User-Agent: Mozilla/4.0 (compatible; Eradicator; dotNetClient)\\n\" + \"Proxy-Authorization: Basic \" + proxyAuthB64Str + \"\\n\"\n + \"Content-Type: application/octet-stream\\n\"\n + \"Content-Length: \" + content.Length + \"\\n\"\n + \"Connection: close\\n\\n\" + content;\n\n var sendBytes = Encoding.ASCII.GetBytes(sendStr);\n\n using (var proxySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))\n {\n proxySocket.Connect(_proxyHost, _proxyPort);\n if (!proxySocket.Connected)\n throw new SocketException();\n proxySocket.Send(sendBytes);\n\n const int recvSize = 65536;\n var recvBytes = new byte[recvSize];\n proxySocket.Receive(recvBytes, recvSize, SocketFlags.Partial);\n\n var responseFirstLine = new string(Encoding.ASCII.GetChars(recvBytes)).Split(\"\\n\".ToCharArray()).Take(1).ElementAt(0);\n var httpResponseCode = Regex.Replace(responseFirstLine, @\"HTTP/1\\.\\d (\\d+) (\\w+)\", \"$1\");\n var httpResponseDescription = Regex.Replace(responseFirstLine, @\"HTTP/1\\.\\d (\\d+) (\\w+)\", \"$2\");\n return httpResponseCode.StartsWith(\"2\");\n }\n return false;\n}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91911/"
]
| Anyone know of a good, hopefully free FTP class for use in .NET that can actually work behind an HTTP proxy or FTP gateway? The FtpWebRequest stuff in .NET is horrible at best, and I really don't want to roll my own here. | Our [Rebex FTP](http://www.rebex.net/ftp.net/) works with proxies just fine. Following code shows how to connect to the FTP using HTTP proxy (code is taken from [FTP tutorial page](http://www.rebex.net/ftp.net/tutorial-ftp.aspx#proxy)).
```
// initialize FTP client
Ftp client = new Ftp();
// setup proxy details
client.Proxy.ProxyType = FtpProxyType.HttpConnect;
client.Proxy.Host = proxyHostname;
client.Proxy.Port = proxyPort;
// add proxy username and password when needed
client.Proxy.UserName = proxyUsername;
client.Proxy.Password = proxyPassword;
// connect, login
client.Connect(hostname, port);
client.Login(username, password);
// do some work
// ...
// disconnect
client.Disconnect();
```
You can download the trial at [www.rebex.net/ftp.net/download.aspx](http://www.rebex.net/ftp.net/download.aspx) |
73,580 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/46663/how-do-you-send-email-from-a-java-app-using-gmail">How do you send email from a Java app using Gmail?</a> </p>
</blockquote>
<p>How do I send an SMTP Message from Java?</p>
| [
{
"answer_id": 73596,
"author": "Mason",
"author_id": 8973,
"author_profile": "https://Stackoverflow.com/users/8973",
"pm_score": 2,
"selected": false,
"text": "<p>See the <a href=\"http://www.oracle.com/technetwork/java/javamail/index.html\" rel=\"nofollow noreferrer\">JavaMail API</a> and associated javadocs.</p>\n"
},
{
"answer_id": 73599,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 2,
"selected": false,
"text": "<p>Please see this post </p>\n\n<p><a href=\"https://stackoverflow.com/questions/46663/how-do-you-send-email-from-a-java-app-using-gmail\">How can I send an email by Java application using GMail, Yahoo, or Hotmail?</a></p>\n\n<p>It is specific to gmail but you can substitute your smtp credentials.</p>\n"
},
{
"answer_id": 73600,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 2,
"selected": false,
"text": "<p>See the following tutorial at Java Practices.</p>\n\n<p><a href=\"http://www.javapractices.com/topic/TopicAction.do?Id=144\" rel=\"nofollow noreferrer\">http://www.javapractices.com/topic/TopicAction.do?Id=144</a></p>\n"
},
{
"answer_id": 73649,
"author": "tovare",
"author_id": 12677,
"author_profile": "https://Stackoverflow.com/users/12677",
"pm_score": 6,
"selected": true,
"text": "<p>Here's an example for Gmail smtp:</p>\n\n<pre><code>import java.io.*;\nimport java.net.InetAddress;\nimport java.util.Properties;\nimport java.util.Date;\n\nimport javax.mail.*;\n\nimport javax.mail.internet.*;\n\nimport com.sun.mail.smtp.*;\n\n\npublic class Distribution {\n\n public static void main(String args[]) throws Exception {\n Properties props = System.getProperties();\n props.put(\"mail.smtps.host\",\"smtp.gmail.com\");\n props.put(\"mail.smtps.auth\",\"true\");\n Session session = Session.getInstance(props, null);\n Message msg = new MimeMessage(session);\n msg.setFrom(new InternetAddress(\"[email protected]\"));;\n msg.setRecipients(Message.RecipientType.TO,\n InternetAddress.parse(\"[email protected]\", false));\n msg.setSubject(\"Heisann \"+System.currentTimeMillis());\n msg.setText(\"Med vennlig hilsennTov Are Jacobsen\");\n msg.setHeader(\"X-Mailer\", \"Tov Are's program\");\n msg.setSentDate(new Date());\n SMTPTransport t =\n (SMTPTransport)session.getTransport(\"smtps\");\n t.connect(\"smtp.gmail.com\", \"[email protected]\", \"<insert password here>\");\n t.sendMessage(msg, msg.getAllRecipients());\n System.out.println(\"Response: \" + t.getLastServerResponse());\n t.close();\n }\n}\n</code></pre>\n\n<p>Now, do it this way only if you would like to keep your project dependencies to a minimum, otherwise i can warmly recommend using classes from apache</p>\n\n<p><a href=\"http://commons.apache.org/email/\" rel=\"noreferrer\">http://commons.apache.org/email/</a> </p>\n\n<p>Regards</p>\n\n<p>Tov Are Jacobsen</p>\n"
},
{
"answer_id": 90001,
"author": "Brad at Kademi",
"author_id": 17025,
"author_profile": "https://Stackoverflow.com/users/17025",
"pm_score": 3,
"selected": false,
"text": "<p>Another way is to use aspirin (<a href=\"https://github.com/masukomi/aspirin\" rel=\"nofollow noreferrer\">https://github.com/masukomi/aspirin</a>) like this:</p>\n\n<pre><code>MailQue.queMail(MimeMessage message)\n</code></pre>\n\n<p>..after having constructed your mimemessage as above.</p>\n\n<p>Aspirin <strong>is</strong> an smtp 'server' so you don't have to configure it. But note that sending email to a broad set of recipients isnt as simple as it appears because of the many different spam filtering rules receiving mail servers and client applications apply. </p>\n"
},
{
"answer_id": 4578893,
"author": "user527619",
"author_id": 527619,
"author_profile": "https://Stackoverflow.com/users/527619",
"pm_score": 1,
"selected": false,
"text": "<pre><code>import javax.mail.*;\nimport javax.mail.internet.*;\nimport java.util.*; \n\npublic void postMail(String recipients[], String subject,\n String message , String from) throws MessagingException {\n\n //Set the host smtp address\n Properties props = new Properties();\n props.put(\"mail.smtp.host\", \"smtp.jcom.net\");\n\n // create some properties and get the default Session\n Session session = Session.getDefaultInstance(props, null);\n session.setDebug(false);\n\n // create a message\n Message msg = new MimeMessage(session);\n\n // set the from and to address\n InternetAddress addressFrom = new InternetAddress(from);\n msg.setFrom(addressFrom);\n\n InternetAddress[] addressTo = new InternetAddress[recipients.length]; \n for (int i = 0; i < recipients.length; i++) {\n addressTo[i] = new InternetAddress(recipients[i]);\n }\n msg.setRecipients(Message.RecipientType.TO, addressTo);\n\n // Optional : You can also set your custom headers in the Email if you Want\n msg.addHeader(\"MyHeaderName\", \"myHeaderValue\");\n\n // Setting the Subject and Content Type\n msg.setSubject(subject);\n msg.setContent(message, \"text/plain\");\n Transport.send(msg);\n}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
]
| >
> **Possible Duplicate:**
>
> [How do you send email from a Java app using Gmail?](https://stackoverflow.com/questions/46663/how-do-you-send-email-from-a-java-app-using-gmail)
>
>
>
How do I send an SMTP Message from Java? | Here's an example for Gmail smtp:
```
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;
import com.sun.mail.smtp.*;
public class Distribution {
public static void main(String args[]) throws Exception {
Properties props = System.getProperties();
props.put("mail.smtps.host","smtp.gmail.com");
props.put("mail.smtps.auth","true");
Session session = Session.getInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]"));;
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]", false));
msg.setSubject("Heisann "+System.currentTimeMillis());
msg.setText("Med vennlig hilsennTov Are Jacobsen");
msg.setHeader("X-Mailer", "Tov Are's program");
msg.setSentDate(new Date());
SMTPTransport t =
(SMTPTransport)session.getTransport("smtps");
t.connect("smtp.gmail.com", "[email protected]", "<insert password here>");
t.sendMessage(msg, msg.getAllRecipients());
System.out.println("Response: " + t.getLastServerResponse());
t.close();
}
}
```
Now, do it this way only if you would like to keep your project dependencies to a minimum, otherwise i can warmly recommend using classes from apache
<http://commons.apache.org/email/>
Regards
Tov Are Jacobsen |
73,628 | <p>If you have a JSF <code><h:commandLink></code> (which uses the <code>onclick</code> event of an <code><a></code> to submit the current form), how do you execute JavaScript (such as asking for delete confirmation) prior to the action being performed?</p>
| [
{
"answer_id": 73644,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 4,
"selected": true,
"text": "<pre><code><h:commandLink id=\"myCommandLink\" action=\"#{myPageCode.doDelete}\">\n <h:outputText value=\"#{msgs.deleteText}\" />\n</h:commandLink>\n<script type=\"text/javascript\">\nif (document.getElementById) {\n var commandLink = document.getElementById('<c:out value=\"${myPageCode.myCommandLinkClientId}\" />');\n if (commandLink && commandLink.onclick) {\n var commandLinkOnclick = commandLink.onclick;\n commandLink.onclick = function() {\n var result = confirm('Do you really want to <c:out value=\"${msgs.deleteText}\" />?');\n if (result) {\n return commandLinkOnclick();\n }\n return false;\n }\n }\n}\n</script>\n</code></pre>\n\n<p>Other Javascript actions (like validating form input etc) could be performed by replacing the call to <code>confirm()</code> with a call to another function.</p>\n"
},
{
"answer_id": 73800,
"author": "noah",
"author_id": 12034,
"author_profile": "https://Stackoverflow.com/users/12034",
"pm_score": 1,
"selected": false,
"text": "<p>You can still use onclick. The JSF <a href=\"http://java.sun.com/javaee/javaserverfaces/1.2/docs/renderkitdocs/HTML_BASIC/javax.faces.Commandjavax.faces.Link.html\" rel=\"nofollow noreferrer\">render kit specification</a> (see Encode Behavior) describes how the link should handle it. Here is the important part (what it renders for onclick):</p>\n\n<pre><code>var a=function(){/*your onclick*/}; var b=function(){/*JSF onclick*/}; return (a()==false) ? false : b();\n</code></pre>\n\n<p>So your function wont be passed the event object (which isn't reliable cross browser anyway), but returning true/false will short-circuit the submission.</p>\n"
},
{
"answer_id": 82125,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>In JSF 1.2 you can specify onclick events.</p>\n\n<p>Also, other libraries such as <a href=\"http://myfaces.apache.org/\" rel=\"nofollow noreferrer\">MyFaces</a> or <a href=\"http://www.icefaces.org\" rel=\"nofollow noreferrer\">IceFaces</a> implement the \"onclick\" handler.</p>\n\n<p>What you'd need to do then is simply:</p>\n\n<pre><code><h:commandLink action=\"#{bean.action}\" onclick=\"if(confirm('Are you sure?')) return false;\" />\n</code></pre>\n\n<p>Note: you can't just do <code>return confirm(...)</code> as this will block the rest of the JavaScript in the onClick event from happening, which would effectively stop your action from happening no matter what the user returned!</p>\n"
},
{
"answer_id": 82962,
"author": "Victor",
"author_id": 14514,
"author_profile": "https://Stackoverflow.com/users/14514",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to execute something before the form is posted, for confirmation for example, try the form event onSubmit. Something like:</p>\n\n<pre><code>myform.onsubmit = function(){confirm(\"really really sure?\")};\n</code></pre>\n"
},
{
"answer_id": 510671,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This never worked for me, </p>\n\n<pre><code> onclick=\"if(confirm('Are you sure?')) return false;\" />\n</code></pre>\n\n<p>but this did</p>\n\n<pre><code>onclick=\"if(confirm(\\\"Are you sure?\\\"))return true; else return false;\"\n</code></pre>\n"
},
{
"answer_id": 4542190,
"author": "iordan",
"author_id": 555424,
"author_profile": "https://Stackoverflow.com/users/555424",
"pm_score": 4,
"selected": false,
"text": "<p>Can be simplified like this</p>\n\n<pre><code>onclick=\"return confirm('Are you sure?');\"\n</code></pre>\n"
},
{
"answer_id": 4622401,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>var deleteClick;\nvar mess=\"xxx\";\nfunction assignDeleteClick(link) {\n if (link.onclick == confirmDelete) {\n return;\n }\n deleteClick = link.onclick;\n link.onclick = confirmDelete;\n}\n\n\nfunction confirmDelete() {\n var ans = confirm(mess);\n if (ans == true) {\n return deleteClick();\n } else {\n return false;\n }\n} \n</code></pre>\n\n<p>use this code for jsf 1.1.</p>\n"
},
{
"answer_id": 6113403,
"author": "Hanynowsky",
"author_id": 754756,
"author_profile": "https://Stackoverflow.com/users/754756",
"pm_score": 3,
"selected": false,
"text": "<p>This worked for me:</p>\n\n<pre><code><h:commandButton title=\"#{bundle.NewPatient}\" action=\"#{identifController.prepareCreate}\" \n id=\"newibutton\" \n onclick=\"if(confirm('#{bundle.NewPatient}?'))return true; else return false;\" \n value=\"#{bundle.NewPatient}\"/>\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9254/"
]
| If you have a JSF `<h:commandLink>` (which uses the `onclick` event of an `<a>` to submit the current form), how do you execute JavaScript (such as asking for delete confirmation) prior to the action being performed? | ```
<h:commandLink id="myCommandLink" action="#{myPageCode.doDelete}">
<h:outputText value="#{msgs.deleteText}" />
</h:commandLink>
<script type="text/javascript">
if (document.getElementById) {
var commandLink = document.getElementById('<c:out value="${myPageCode.myCommandLinkClientId}" />');
if (commandLink && commandLink.onclick) {
var commandLinkOnclick = commandLink.onclick;
commandLink.onclick = function() {
var result = confirm('Do you really want to <c:out value="${msgs.deleteText}" />?');
if (result) {
return commandLinkOnclick();
}
return false;
}
}
}
</script>
```
Other Javascript actions (like validating form input etc) could be performed by replacing the call to `confirm()` with a call to another function. |
73,629 | <p>I have a string that is like below.</p>
<pre><code>,liger, unicorn, snipe
</code></pre>
<p>in other languages I'm familiar with I can just do a string.trim(",") but how can I do that in c#?</p>
<p>Thanks.</p>
<hr>
<p><em>There's been a lot of back and forth about the StartTrim function. As several have pointed out, the StartTrim doesn't affect the primary variable. However, given the construction of the data vs the question, I'm torn as to which answer to accept. True the question only wants the first character trimmed off not the last (if anny), however, there would never be a "," at the end of the data. So, with that said, I'm going to accept the first answer that that said to use StartTrim assigned to a new variable.</em></p>
| [
{
"answer_id": 73650,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 0,
"selected": false,
"text": "<pre><code>if (s.StartsWith(\",\")) {\n s = s.Substring(1, s.Length - 1);\n}\n</code></pre>\n"
},
{
"answer_id": 73652,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 4,
"selected": false,
"text": "<pre><code>string s = \",liger, unicorn, snipe\";\ns.TrimStart(',');\n</code></pre>\n"
},
{
"answer_id": 73656,
"author": "Kieran Benton",
"author_id": 5777,
"author_profile": "https://Stackoverflow.com/users/5777",
"pm_score": 0,
"selected": false,
"text": "<pre><code>string t = \",liger, unicorn, snipe\".TrimStart(new char[] {','});\n</code></pre>\n"
},
{
"answer_id": 73658,
"author": "pilsetnieks",
"author_id": 6615,
"author_profile": "https://Stackoverflow.com/users/6615",
"pm_score": 0,
"selected": false,
"text": "<p>The same way as everywhere else: <a href=\"http://msdn.microsoft.com/en-us/library/d4tt83f9.aspx\" rel=\"nofollow noreferrer\">string.trim</a></p>\n"
},
{
"answer_id": 73660,
"author": "Matt Dawdy",
"author_id": 232,
"author_profile": "https://Stackoverflow.com/users/232",
"pm_score": 0,
"selected": false,
"text": "<pre><code> string s = \",liger, tiger\";\n\n if (s.Substring(0, 1) == \",\")\n s = s.Substring(1);\n</code></pre>\n"
},
{
"answer_id": 73665,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 0,
"selected": false,
"text": "<p>Did you mean trim all instances of \",\" in that string?</p>\n\n<p>In which case, you can do:</p>\n\n<pre><code>s = s.Replace(\",\", \"\");\n</code></pre>\n"
},
{
"answer_id": 73668,
"author": "Akselsson",
"author_id": 8862,
"author_profile": "https://Stackoverflow.com/users/8862",
"pm_score": 1,
"selected": false,
"text": "<p>\",liger, unicorn, snipe\".Trim(',') -> \"liger, unicor, snipe\"</p>\n"
},
{
"answer_id": 73671,
"author": "Magus",
"author_id": 2188,
"author_profile": "https://Stackoverflow.com/users/2188",
"pm_score": 1,
"selected": false,
"text": "<p>Try string.Trim(',') and see if that does what you want.</p>\n"
},
{
"answer_id": 73676,
"author": "Clinton Pierce",
"author_id": 8173,
"author_profile": "https://Stackoverflow.com/users/8173",
"pm_score": 0,
"selected": false,
"text": "<p>Just use Substring to ignore the first character (or assign it to another string);</p>\n\n<pre><code> string o = \",liger, unicorn, snipe\";\n string s = o.Substring(1);\n</code></pre>\n"
},
{
"answer_id": 73681,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 2,
"selected": false,
"text": "<p>.net strings can do Trim() and TrimStart(). Because it takes <code>params</code>, you can write:</p>\n\n<pre><code>\",liger, unicorn, snipe\".TrimStart(',')\n</code></pre>\n\n<p>and if you have more than one character to trim, you can write:</p>\n\n<pre><code>\",liger, unicorn, snipe\".TrimStart(\",; \".ToCharArray())\n</code></pre>\n"
},
{
"answer_id": 73708,
"author": "bentford",
"author_id": 946,
"author_profile": "https://Stackoverflow.com/users/946",
"pm_score": 0,
"selected": false,
"text": "<p>See: <a href=\"http://msdn.microsoft.com/en-us/library/d4tt83f9.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/d4tt83f9.aspx</a></p>\n\n<pre><code> string animals = \",liger, unicorn, snipe\";\n\n //trimmed will contain \"liger, unicorn, snipe\"\n string trimmed = word.Trim(',');\n</code></pre>\n"
},
{
"answer_id": 73734,
"author": "RickL",
"author_id": 7261,
"author_profile": "https://Stackoverflow.com/users/7261",
"pm_score": 5,
"selected": true,
"text": "<pre><code>string sample = \",liger, unicorn, snipe\";\nsample = sample.TrimStart(','); // to remove just the first comma\n</code></pre>\n\n<p>Or perhaps:</p>\n\n<pre><code>sample = sample.Trim().TrimStart(','); // to remove any whitespace and then the first comma\n</code></pre>\n"
},
{
"answer_id": 73749,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 1,
"selected": false,
"text": "<p>Note, the <em>original</em> string is left untouched, Trim will return you a new string:</p>\n\n<pre><code>string s1 = \",abc,d\";\nstring s2 = s1.TrimStart(\",\".ToCharArray());\nConsole.WriteLine(\"s1 = {0}\", s1);\nConsole.WriteLine(\"s2 = {0}\", s2);\n</code></pre>\n\n<p>prints:</p>\n\n<pre><code>s1 = ,abc,d\ns2 = abc,d\n</code></pre>\n"
},
{
"answer_id": 74536,
"author": "justin.m.chase",
"author_id": 12958,
"author_profile": "https://Stackoverflow.com/users/12958",
"pm_score": 2,
"selected": false,
"text": "<p>here is an easy way to not produce the leading comma to begin with:</p>\n\n<pre><code>string[] animals = { \"liger\", \"unicorn\", \"snipe\" };\nstring joined = string.Join(\", \", animals);\n</code></pre>\n"
},
{
"answer_id": 79881,
"author": "Wonko",
"author_id": 14842,
"author_profile": "https://Stackoverflow.com/users/14842",
"pm_score": 1,
"selected": false,
"text": "<pre><code>string s = ",liger, unicorn, snipe";\ns = s.TrimStart(',');\n</code></pre>\n<p>It's important to assign the result of TrimStart to a variable. As it says on the <a href=\"http://msdn.microsoft.com/en-us/library/system.string.trimstart.aspx\" rel=\"nofollow noreferrer\">TrimStart page</a>, "This method does not modify the value of the current instance. Instead, it returns a new string...".</p>\n<p>In .NET, strings don't change.</p>\n"
},
{
"answer_id": 80283,
"author": "abjbhat",
"author_id": 15048,
"author_profile": "https://Stackoverflow.com/users/15048",
"pm_score": 1,
"selected": false,
"text": "<p>you can use this </p>\n\n<p>,liger, unicorn, snipe\".TrimStart(',');</p>\n"
},
{
"answer_id": 80517,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 2,
"selected": false,
"text": "<p>string.TrimStart(',') will remove the comma, however you will have trouble with a split operation due to the space after the comma. \nBest to join just on the single comma or use </p>\n\n<blockquote>\n <p>Split(\", \".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);</p>\n</blockquote>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
]
| I have a string that is like below.
```
,liger, unicorn, snipe
```
in other languages I'm familiar with I can just do a string.trim(",") but how can I do that in c#?
Thanks.
---
*There's been a lot of back and forth about the StartTrim function. As several have pointed out, the StartTrim doesn't affect the primary variable. However, given the construction of the data vs the question, I'm torn as to which answer to accept. True the question only wants the first character trimmed off not the last (if anny), however, there would never be a "," at the end of the data. So, with that said, I'm going to accept the first answer that that said to use StartTrim assigned to a new variable.* | ```
string sample = ",liger, unicorn, snipe";
sample = sample.TrimStart(','); // to remove just the first comma
```
Or perhaps:
```
sample = sample.Trim().TrimStart(','); // to remove any whitespace and then the first comma
``` |
73,651 | <p>I'm failing at finding the commands I need to send to authenticate to a SMTP server using NTLM. </p>
<p>I think it goes something like:</p>
<pre><code>AUTH NTLM <bae64encode something>
334
<bae64encode something>
235
</code></pre>
| [
{
"answer_id": 82401,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 1,
"selected": false,
"text": "<p>Look for information about <strong>Apache</strong> and Siteminder as Apache is responsible for the HTTP transport stuff in Subversion</p>\n"
},
{
"answer_id": 812821,
"author": "Ram Prasad",
"author_id": 6361,
"author_profile": "https://Stackoverflow.com/users/6361",
"pm_score": 3,
"selected": true,
"text": "<p>SVN with Siteminder has been implemented and is working now. Since there is not much of information out there on this, I would like to post the overview of steps followed:</p>\n\n<ol>\n<li>Cookie based authentcation was disabled on Siteminder end</li>\n<li>HTTP AUTH was enabled (in Siteminder) and all webdav methods were added to policy server to be handled by SiteMinder</li>\n<li>Authentication was disabled on apache end (HTTP Auth) for SVN</li>\n</ol>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4580/"
]
| I'm failing at finding the commands I need to send to authenticate to a SMTP server using NTLM.
I think it goes something like:
```
AUTH NTLM <bae64encode something>
334
<bae64encode something>
235
``` | SVN with Siteminder has been implemented and is working now. Since there is not much of information out there on this, I would like to post the overview of steps followed:
1. Cookie based authentcation was disabled on Siteminder end
2. HTTP AUTH was enabled (in Siteminder) and all webdav methods were added to policy server to be handled by SiteMinder
3. Authentication was disabled on apache end (HTTP Auth) for SVN |
73,663 | <p>How do I exit a script early, like the <code>die()</code> command in PHP?</p>
| [
{
"answer_id": 73673,
"author": "pjz",
"author_id": 8002,
"author_profile": "https://Stackoverflow.com/users/8002",
"pm_score": 12,
"selected": true,
"text": "<pre><code>import sys\nsys.exit()\n</code></pre>\n<p>details from the <a href=\"https://docs.python.org/2/library/sys.html#sys.exit\" rel=\"noreferrer\"><code>sys</code> module documentation</a>:</p>\n<blockquote>\n<p><code>sys.<strong>exit</strong>([<em>arg</em>])</code></p>\n<p>Exit from Python. This is implemented by raising the\n<a href=\"https://docs.python.org/2/library/exceptions.html#SystemExit\" rel=\"noreferrer\" title=\"SystemExit\"><code>SystemExit</code></a> exception, so cleanup actions specified by finally clauses\nof <a href=\"https://docs.python.org/2/reference/compound_stmts.html#try\" rel=\"noreferrer\" title=\"try\"><code>try</code></a> statements are honored, and it is possible to intercept the\nexit attempt at an outer level.</p>\n<p>The optional argument <em>arg</em> can be an integer giving the exit status\n(defaulting to zero), or another type of object. If it is an integer,\nzero is considered “successful termination” and any nonzero value is\nconsidered “abnormal termination” by shells and the like. Most systems\nrequire it to be in the range 0-127, and produce undefined results\notherwise. Some systems have a convention for assigning specific\nmeanings to specific exit codes, but these are generally\nunderdeveloped; Unix programs generally use 2 for command line syntax\nerrors and 1 for all other kind of errors. If another type of object\nis passed, None is equivalent to passing zero, and any other object is\nprinted to <a href=\"https://docs.python.org/2/library/sys.html#sys.stderr\" rel=\"noreferrer\" title=\"sys.stderr\"><code>stderr</code></a> and results in an exit code of 1. In particular,\n<code>sys.exit("some error message")</code> is a quick way to exit a program when\nan error occurs.</p>\n<p>Since <a href=\"https://docs.python.org/2/library/constants.html#exit\" rel=\"noreferrer\" title=\"exit\"><code>exit()</code></a> ultimately “only” raises an exception, it will only exit\nthe process when called from the main thread, and the exception is not\nintercepted.</p>\n</blockquote>\n<p>Note that this is the 'nice' way to exit. @<a href=\"https://stackoverflow.com/questions/73663/terminating-a-python-script#76374\">glyphtwistedmatrix</a> below points out that if you want a 'hard exit', you can use <code>os._exit(*errorcode*)</code>, though it's likely os-specific to some extent (it might not take an errorcode under windows, for example), and it definitely is less friendly since it doesn't let the interpreter do any cleanup before the process dies. On the other hand, it <em>does</em> kill the entire process, including all running threads, while <code>sys.exit()</code> (as it says in the docs) only exits if called from the main thread, with no other threads running.</p>\n"
},
{
"answer_id": 73680,
"author": "Vhaerun",
"author_id": 11234,
"author_profile": "https://Stackoverflow.com/users/11234",
"pm_score": 7,
"selected": false,
"text": "<p>Another way is:</p>\n\n<pre><code>raise SystemExit\n</code></pre>\n"
},
{
"answer_id": 73695,
"author": "cleg",
"author_id": 29503,
"author_profile": "https://Stackoverflow.com/users/29503",
"pm_score": 5,
"selected": false,
"text": "<pre><code>from sys import exit\nexit()\n</code></pre>\n\n<p>As a parameter you can pass an exit code, which will be returned to OS. Default is 0.</p>\n"
},
{
"answer_id": 76374,
"author": "Glyph",
"author_id": 13564,
"author_profile": "https://Stackoverflow.com/users/13564",
"pm_score": 6,
"selected": false,
"text": "<p>While you should generally prefer <code>sys.exit</code> because it is more \"friendly\" to other code, all it actually does is raise an exception.</p>\n\n<p>If you are sure that you need to exit a process immediately, and you might be inside of some exception handler which would catch <code>SystemExit</code>, there is another function - <code>os._exit</code> - which terminates immediately at the C level and does not perform any of the normal tear-down of the interpreter; for example, hooks registered with the \"atexit\" module are not executed.</p>\n"
},
{
"answer_id": 14836329,
"author": "j.m.g.r",
"author_id": 2065348,
"author_profile": "https://Stackoverflow.com/users/2065348",
"pm_score": 9,
"selected": false,
"text": "<p>A simple way to terminate a Python script early is to use the built-in <code>quit()</code> function. There is no need to import any library, and it is efficient and simple.</p>\n\n<p>Example:</p>\n\n<pre><code>#do stuff\nif this == that:\n quit()\n</code></pre>\n"
},
{
"answer_id": 16150238,
"author": "Space cowboy",
"author_id": 1897240,
"author_profile": "https://Stackoverflow.com/users/1897240",
"pm_score": 7,
"selected": false,
"text": "<p>You can also use simply <code>exit()</code>.</p>\n\n<p>Keep in mind that <code>sys.exit()</code>, <code>exit()</code>, <code>quit()</code>, and <code>os._exit(0)</code> <strong>kill</strong> the Python interpreter. Therefore, if it appears in a script called from another script by <code>execfile()</code>, it stops execution of both scripts. </p>\n\n<p>See \"<a href=\"https://stackoverflow.com/a/1028632/1897240\">Stop execution of a script called with execfile</a>\" to avoid this.</p>\n"
},
{
"answer_id": 22504027,
"author": "Floggedhorse",
"author_id": 2428737,
"author_profile": "https://Stackoverflow.com/users/2428737",
"pm_score": 5,
"selected": false,
"text": "<p>I'm a total novice but surely this is cleaner and more controlled</p>\n\n<pre><code>def main():\n try:\n Answer = 1/0\n print Answer\n except:\n print 'Program terminated'\n return\n print 'You wont see this'\n\nif __name__ == '__main__': \n main()\n</code></pre>\n\n<p>...</p>\n\n<blockquote>\n <p>Program terminated</p>\n</blockquote>\n\n<p>than</p>\n\n<pre><code>import sys\ndef main():\n try:\n Answer = 1/0\n print Answer\n except:\n print 'Program terminated'\n sys.exit()\n print 'You wont see this'\n\nif __name__ == '__main__': \n main()\n</code></pre>\n\n<p>...</p>\n\n<blockquote>\n <blockquote>\n <p>Program terminated Traceback (most recent call last): File \"Z:\\Directory\\testdieprogram.py\", line 12, in \n main() File \"Z:\\Directory\\testdieprogram.py\", line 8, in main\n sys.exit() SystemExit</p>\n </blockquote>\n</blockquote>\n\n<p>Edit</p>\n\n<p>The point being that the program ends smoothly and peacefully, rather than <strong>\"I'VE STOPPED !!!!\"</strong></p>\n"
},
{
"answer_id": 40525942,
"author": "eaydin",
"author_id": 1278994,
"author_profile": "https://Stackoverflow.com/users/1278994",
"pm_score": 6,
"selected": false,
"text": "<p>I've just found out that when writing a multithreadded app, <code>raise SystemExit</code> and <code>sys.exit()</code> both kills only the running thread. On the other hand, <code>os._exit()</code> exits the whole process. This was discussed in \"<a href=\"https://stackoverflow.com/questions/905189/why-does-sys-exit-not-exit-when-called-inside-a-thread-in-python/5120178#5120178\">Why does sys.exit() not exit when called inside a thread in Python?</a>\".</p>\n\n<p>The example below has 2 threads. Kenny and Cartman. Cartman is supposed to live forever, but Kenny is called recursively and should die after 3 seconds. (recursive calling is not the best way, but I had other reasons)</p>\n\n<p>If we also want Cartman to die when Kenny dies, Kenny should go away with <code>os._exit</code>, otherwise, only Kenny will die and Cartman will live forever.</p>\n\n<pre><code>import threading\nimport time\nimport sys\nimport os\n\ndef kenny(num=0):\n if num > 3:\n # print(\"Kenny dies now...\")\n # raise SystemExit #Kenny will die, but Cartman will live forever\n # sys.exit(1) #Same as above\n\n print(\"Kenny dies and also kills Cartman!\")\n os._exit(1)\n while True:\n print(\"Kenny lives: {0}\".format(num))\n time.sleep(1)\n num += 1\n kenny(num)\n\ndef cartman():\n i = 0\n while True:\n print(\"Cartman lives: {0}\".format(i))\n i += 1\n time.sleep(1)\n\nif __name__ == '__main__':\n daemon_kenny = threading.Thread(name='kenny', target=kenny)\n daemon_cartman = threading.Thread(name='cartman', target=cartman)\n daemon_kenny.setDaemon(True)\n daemon_cartman.setDaemon(True)\n\n daemon_kenny.start()\n daemon_cartman.start()\n daemon_kenny.join()\n daemon_cartman.join()\n</code></pre>\n"
},
{
"answer_id": 41350119,
"author": "David C.",
"author_id": 6036809,
"author_profile": "https://Stackoverflow.com/users/6036809",
"pm_score": 4,
"selected": false,
"text": "<p>In Python 3.5, I tried to incorporate similar code without use of modules (e.g. sys, Biopy) other than what's built-in to stop the script and print an error message to my users. Here's my example:</p>\n\n<pre><code>## My example:\nif \"ATG\" in my_DNA: \n ## <Do something & proceed...>\nelse: \n print(\"Start codon is missing! Check your DNA sequence!\")\n exit() ## as most folks said above\n</code></pre>\n\n<p>Later on, I found it is more succinct to just throw an error:</p>\n\n<pre><code>## My example revised:\nif \"ATG\" in my_DNA: \n ## <Do something & proceed...>\nelse: \n raise ValueError(\"Start codon is missing! Check your DNA sequence!\")\n</code></pre>\n"
},
{
"answer_id": 60805367,
"author": "Matthew",
"author_id": 12898298,
"author_profile": "https://Stackoverflow.com/users/12898298",
"pm_score": 2,
"selected": false,
"text": "<p>My two cents.</p>\n\n<p>Python 3.8.1, Windows 10, 64-bit.</p>\n\n<p><code>sys.exit()</code> does not work directly for me.</p>\n\n<p>I have several nexted loops.</p>\n\n<p>First I declare a boolean variable, which I call <code>immediateExit</code>.</p>\n\n<p>So, in the beginning of the program code I write:</p>\n\n<pre><code>immediateExit = False\n</code></pre>\n\n<p>Then, starting from the most inner (nested) loop exception, I write:</p>\n\n<pre><code> immediateExit = True\n sys.exit('CSV file corrupted 0.')\n</code></pre>\n\n<p>Then I go into the immediate continuation of the outer loop, and before anything else being executed by the code, I write:</p>\n\n<pre><code> if immediateExit:\n sys.exit('CSV file corrupted 1.')\n</code></pre>\n\n<p>Depending on the complexity, sometimes the above statement needs to be repeated also in except sections, etc.</p>\n\n<pre><code> if immediateExit:\n sys.exit('CSV file corrupted 1.5.')\n</code></pre>\n\n<p>The custom message is for my personal debugging, as well, as the numbers are for the same purpose - to see where the script really exits. </p>\n\n<pre><code>'CSV file corrupted 1.5.'\n</code></pre>\n\n<p>In my particular case I am processing a CSV file, which I do not want the software to touch, if the software detects it is corrupted. Therefore for me it is very important to exit the whole Python script immediately after detecting the possible corruption.</p>\n\n<p>And following the gradual sys.exit-ing from all the loops I manage to do it.</p>\n\n<p>Full code: (some changes were needed because it is proprietory code for internal tasks):</p>\n\n<pre><code>immediateExit = False\nstart_date = '1994.01.01'\nend_date = '1994.01.04'\nresumedDate = end_date\n\n\nend_date_in_working_days = False\nwhile not end_date_in_working_days:\n try:\n end_day_position = working_days.index(end_date)\n\n end_date_in_working_days = True\n except ValueError: # try statement from end_date in workdays check\n print(current_date_and_time())\n end_date = input('>> {} is not in the list of working days. Change the date (YYYY.MM.DD): '.format(end_date))\n print('New end date: ', end_date, '\\n')\n continue\n\n\n csv_filename = 'test.csv'\n csv_headers = 'date,rate,brand\\n' # not real headers, this is just for example\n try:\n with open(csv_filename, 'r') as file:\n print('***\\nOld file {} found. Resuming the file by re-processing the last date lines.\\nThey shall be deleted and re-processed.\\n***\\n'.format(csv_filename))\n last_line = file.readlines()[-1]\n start_date = last_line.split(',')[0] # assigning the start date to be the last like date.\n resumedDate = start_date\n\n if last_line == csv_headers:\n pass\n elif start_date not in working_days:\n print('***\\n\\n{} file might be corrupted. Erase or edit the file to continue.\\n***'.format(csv_filename))\n immediateExit = True\n sys.exit('CSV file corrupted 0.')\n else:\n start_date = last_line.split(',')[0] # assigning the start date to be the last like date.\n print('\\nLast date:', start_date)\n file.seek(0) # setting the cursor at the beginnning of the file\n lines = file.readlines() # reading the file contents into a list\n count = 0 # nr. of lines with last date\n for line in lines: #cycling through the lines of the file\n if line.split(',')[0] == start_date: # cycle for counting the lines with last date in it.\n count = count + 1\n if immediateExit:\n sys.exit('CSV file corrupted 1.')\n for iter in range(count): # removing the lines with last date\n lines.pop()\n print('\\n{} lines removed from date: {} in {} file'.format(count, start_date, csv_filename))\n\n\n\n if immediateExit:\n sys.exit('CSV file corrupted 1.2.')\n with open(csv_filename, 'w') as file:\n print('\\nFile', csv_filename, 'open for writing')\n file.writelines(lines)\n\n print('\\nRemoving', count, 'lines from', csv_filename)\n\n fileExists = True\n\n except:\n if immediateExit:\n sys.exit('CSV file corrupted 1.5.')\n with open(csv_filename, 'w') as file:\n file.write(csv_headers)\n fileExists = False\n if immediateExit:\n sys.exit('CSV file corrupted 2.')\n\n</code></pre>\n"
},
{
"answer_id": 70811775,
"author": "Artyom Vancyan",
"author_id": 12755187,
"author_profile": "https://Stackoverflow.com/users/12755187",
"pm_score": 4,
"selected": false,
"text": "<h2>Problem</h2>\n<p>In my practice, there was even a case when it was necessary to kill an entire multiprocessor application from one of those processes.</p>\n<p>The following functions work well if your application uses the only main process. But no one of the following functions didn't work in my case as the application had many other alive processes.</p>\n<ul>\n<li><code>quit()</code></li>\n<li><code>exit(0)</code></li>\n<li><code>os._exit(0)</code></li>\n<li><code>sys.exit(0)</code></li>\n<li><code>os.kill(os.getppid(), 9)</code> - where <code>os.getppid()</code> is the <strong>pid</strong> of parent process</li>\n</ul>\n<p>The last one killed the main process and itself but the rest processes were still alive.</p>\n<h2>Solution</h2>\n<p>I had to kill it by external command and finally found the solution using <code>pkill</code>.</p>\n<pre><code>import os\n\n# This can be called even in process worker and will kill\n# whole application included correlated processes as well\nos.system(f"pkill -f {os.path.basename(__file__)}")\n</code></pre>\n"
},
{
"answer_id": 70824754,
"author": "ChanceMeteor515",
"author_id": 18007782,
"author_profile": "https://Stackoverflow.com/users/18007782",
"pm_score": 1,
"selected": false,
"text": "<p>Just put at the end of your code <code>quit()</code> and that should close a python script.</p>\n"
},
{
"answer_id": 72902963,
"author": "jimh",
"author_id": 3705490,
"author_profile": "https://Stackoverflow.com/users/3705490",
"pm_score": 2,
"selected": false,
"text": "<p>In Python 3.9, you can also use: <code>raise SystemExit("Because I said so")</code>.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
| How do I exit a script early, like the `die()` command in PHP? | ```
import sys
sys.exit()
```
details from the [`sys` module documentation](https://docs.python.org/2/library/sys.html#sys.exit):
>
> `sys.**exit**([*arg*])`
>
>
> Exit from Python. This is implemented by raising the
> [`SystemExit`](https://docs.python.org/2/library/exceptions.html#SystemExit "SystemExit") exception, so cleanup actions specified by finally clauses
> of [`try`](https://docs.python.org/2/reference/compound_stmts.html#try "try") statements are honored, and it is possible to intercept the
> exit attempt at an outer level.
>
>
> The optional argument *arg* can be an integer giving the exit status
> (defaulting to zero), or another type of object. If it is an integer,
> zero is considered “successful termination” and any nonzero value is
> considered “abnormal termination” by shells and the like. Most systems
> require it to be in the range 0-127, and produce undefined results
> otherwise. Some systems have a convention for assigning specific
> meanings to specific exit codes, but these are generally
> underdeveloped; Unix programs generally use 2 for command line syntax
> errors and 1 for all other kind of errors. If another type of object
> is passed, None is equivalent to passing zero, and any other object is
> printed to [`stderr`](https://docs.python.org/2/library/sys.html#sys.stderr "sys.stderr") and results in an exit code of 1. In particular,
> `sys.exit("some error message")` is a quick way to exit a program when
> an error occurs.
>
>
> Since [`exit()`](https://docs.python.org/2/library/constants.html#exit "exit") ultimately “only” raises an exception, it will only exit
> the process when called from the main thread, and the exception is not
> intercepted.
>
>
>
Note that this is the 'nice' way to exit. @[glyphtwistedmatrix](https://stackoverflow.com/questions/73663/terminating-a-python-script#76374) below points out that if you want a 'hard exit', you can use `os._exit(*errorcode*)`, though it's likely os-specific to some extent (it might not take an errorcode under windows, for example), and it definitely is less friendly since it doesn't let the interpreter do any cleanup before the process dies. On the other hand, it *does* kill the entire process, including all running threads, while `sys.exit()` (as it says in the docs) only exits if called from the main thread, with no other threads running. |
73,667 | <p>How can I start an interactive console for Perl, similar to the <code>irb</code> command for Ruby or <code>python</code> for Python?</p>
| [
{
"answer_id": 73685,
"author": "Brian Phillips",
"author_id": 7230,
"author_profile": "https://Stackoverflow.com/users/7230",
"pm_score": 3,
"selected": false,
"text": "<p><code>perl -d</code> is your friend:</p>\n\n<pre><code>% perl -de 0</code></pre>\n"
},
{
"answer_id": 73689,
"author": "Clinton Pierce",
"author_id": 8173,
"author_profile": "https://Stackoverflow.com/users/8173",
"pm_score": 4,
"selected": false,
"text": "<p>You can always just drop into the built-in debugger and run commands from there.</p>\n\n<pre><code> perl -d -e 1\n</code></pre>\n"
},
{
"answer_id": 73698,
"author": "Frank Wiles",
"author_id": 12568,
"author_profile": "https://Stackoverflow.com/users/12568",
"pm_score": 4,
"selected": false,
"text": "<p>There isn't an interactive console for Perl built in like Python does. You can however use the Perl Debugger to do debugging related things. You turn it on with the -d option, but you might want to check out 'man perldebug' to learn about it.</p>\n<p>After a bit of googling, there is a separate project that implements a Perl console which you can find at\n<a href=\"https://web.archive.org/web/20170726140417/http://www.sukria.net/perlconsole.html\" rel=\"nofollow noreferrer\">Perl Console - Perl code interactive evaluator with completion</a>.</p>\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 73703,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 9,
"selected": true,
"text": "<p>You can use the perl debugger on a trivial program, like so:</p>\n\n<pre><code>perl -de1\n</code></pre>\n\n<p>Alternatively there's <a href=\"http://search.cpan.org/~sukria/perlconsole-0.4/perlconsole\" rel=\"noreferrer\"><em>Alexis Sukrieh</em>'s Perl Console</a> application, but I haven't used it.</p>\n"
},
{
"answer_id": 73742,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 4,
"selected": false,
"text": "<p>I use the command line as a console:</p>\n\n<pre><code>$ perl -e 'print \"JAPH\\n\"'\n</code></pre>\n\n<p>Then I can use my <em>bash</em> history to get back old commands. This does not preserve state, however.</p>\n\n<p>This form is most useful when you want to test \"one little thing\" (like when answering Perl questions). Often, I find these commands get scraped verbatim into a shell script or makefile.</p>\n"
},
{
"answer_id": 73765,
"author": "shelfoo",
"author_id": 3444,
"author_profile": "https://Stackoverflow.com/users/3444",
"pm_score": 3,
"selected": false,
"text": "<p>You could look into psh here: <a href=\"http://gnp.github.io/psh/\" rel=\"noreferrer\">http://gnp.github.io/psh/</a></p>\n\n<p>It's a full on shell (you can use it in replacement of bash for example), but uses perl syntax.. so you can create methods on the fly etc.</p>\n"
},
{
"answer_id": 73780,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 3,
"selected": false,
"text": "<p>Perl doesn't have a console but the debugger can be used as one. At a command prompt, type <code>perl -de 1</code>. (The value "1" doesn't matter, it's just a valid statement that does nothing.)</p>\n<p>There are also a couple of options for a Perl shell:<br />\n<a href=\"https://web.archive.org/web/20120522111043/http://perldoc.perl.org/perlfaq3.html#Is-there-a-Perl-shell%3f\" rel=\"nofollow noreferrer\">Archived "perlfaq3" page which contain question "Is there Perl Shell?"</a></p>\n<p>For more information read <a href=\"https://perldoc.perl.org/perlfaq3\" rel=\"nofollow noreferrer\">perlfaq3</a> (current version).</p>\n"
},
{
"answer_id": 73868,
"author": "runrig",
"author_id": 10415,
"author_profile": "https://Stackoverflow.com/users/10415",
"pm_score": 1,
"selected": false,
"text": "<p>Also look for ptkdb on CPAN:\n<a href=\"http://search.cpan.org/search?query=ptkdb&mode=all\" rel=\"nofollow noreferrer\">http://search.cpan.org/search?query=ptkdb&mode=all</a></p>\n"
},
{
"answer_id": 73896,
"author": "amoore",
"author_id": 7573,
"author_profile": "https://Stackoverflow.com/users/7573",
"pm_score": 5,
"selected": false,
"text": "<p>I think you're asking about a REPL (Read, Evaluate, Print, Loop) interface to perl. There are a few ways to do this:</p>\n<ul>\n<li>Matt Trout has <a href=\"https://web.archive.org/web/20100921094613/http://chainsawblues.vox.com/library/post/a-perl-read-excute-print-loop-repl.html\" rel=\"nofollow noreferrer\">an article</a> that describes how to write one</li>\n<li>Adriano Ferreira <a href=\"https://web.archive.org/web/20150905151804/http://use.perl.org/use.perl.org/articlea9a7.html?sid=07/08/30/1729255\" rel=\"nofollow noreferrer\">has described some options</a></li>\n<li>and finally, you can hop on IRC at irc.perl.org and try out one of the eval bots in many of the popular channels. They will evaluate chunks of perl that you pass to them.</li>\n</ul>\n"
},
{
"answer_id": 74119,
"author": "Dave Rolsky",
"author_id": 9832,
"author_profile": "https://Stackoverflow.com/users/9832",
"pm_score": 6,
"selected": false,
"text": "<p>Not only did Matt Trout write an article about a REPL, he actually wrote one - <a href=\"http://search.cpan.org/dist/Devel-REPL\" rel=\"noreferrer\">Devel::REPL</a></p>\n\n<p>I've used it a bit and it works fairly well, and it's under active development.</p>\n\n<p>BTW, I have no idea why someone modded down the person who mentioned using \"perl -e\" from the console. This isn't really a REPL, true, but it's fantastically useful, and I use it all the time.</p>\n"
},
{
"answer_id": 76154,
"author": "raldi",
"author_id": 7598,
"author_profile": "https://Stackoverflow.com/users/7598",
"pm_score": 5,
"selected": false,
"text": "<p>I wrote a script I call \"psh\":</p>\n\n<pre><code>#! /usr/bin/perl\n\nwhile (<>) {\n chomp;\n my $result = eval;\n print \"$_ = $result\\n\";\n}\n</code></pre>\n\n<p>Whatever you type in, it evaluates in Perl:</p>\n\n<pre><code>> gmtime(2**30)\ngmtime(2**30) = Sat Jan 10 13:37:04 2004\n\n> $x = 'foo'\n$x = 'foo' = foo\n\n> $x =~ s/o/a/g\n$x =~ s/o/a/g = 2\n\n> $x\n$x = faa\n</code></pre>\n"
},
{
"answer_id": 80890,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>re.pl from Devel::REPL</p>\n"
},
{
"answer_id": 80900,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Sepia and PDE have also own REPLs (for GNU Emacs).</p>\n"
},
{
"answer_id": 90390,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>See also <a href=\"https://web.archive.org/web/20090109221511/http://blog.jrock.us/articles/Stylish%20REPL.pod\" rel=\"nofollow noreferrer\">Stylish REPL (for GNU Emacs)</a></p>\n"
},
{
"answer_id": 91565,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 3,
"selected": false,
"text": "<p>I always did:</p>\n\n<pre><code>rlwrap perl -wlne'eval;print$@if$@'\n</code></pre>\n\n<p>With 5.10, I've switched to:</p>\n\n<pre><code>rlwrap perl -wnE'say eval()//$@'\n</code></pre>\n\n<p>(rlwrap is optional)</p>\n"
},
{
"answer_id": 18843800,
"author": "KIM Taegyoon",
"author_id": 1941928,
"author_profile": "https://Stackoverflow.com/users/1941928",
"pm_score": 3,
"selected": false,
"text": "<p>Read-eval-print loop:</p>\n\n<pre><code>$ perl -e'while(<>){print eval,\"\\n\"}'\n</code></pre>\n"
},
{
"answer_id": 22840242,
"author": "Ján Sáreník",
"author_id": 1255163,
"author_profile": "https://Stackoverflow.com/users/1255163",
"pm_score": 5,
"selected": false,
"text": "<p>If you want history, use <a href=\"https://linux.die.net/man/1/rlwrap\" rel=\"noreferrer\">rlwrap</a>. This could be your <code>~/bin/ips</code> for example:</p>\n<pre><code>#!/bin/sh\necho 'This is Interactive Perl shell'\nrlwrap -A -pgreen -S"perl> " perl -wnE'say eval()//$@'\n</code></pre>\n<p>And this is how it looks like:</p>\n<pre><code>$ ips\nThis is Interactive Perl shell\nperl> 2**128\n3.40282366920938e+38\nperl> \n</code></pre>\n"
},
{
"answer_id": 28372724,
"author": "Eric Johnson",
"author_id": 58089,
"author_profile": "https://Stackoverflow.com/users/58089",
"pm_score": 4,
"selected": false,
"text": "<p>There are two popular Perl REPLs.</p>\n\n<ol>\n<li><a href=\"https://metacpan.org/pod/Devel::REPL\" rel=\"noreferrer\">Devel::REPL</a> is great.</li>\n<li>But IMO <a href=\"https://metacpan.org/pod/Reply\" rel=\"noreferrer\">Reply</a> is better. </li>\n</ol>\n"
},
{
"answer_id": 31283257,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 3,
"selected": false,
"text": "<p><sup>Update: I've since created a downloadable REPL - see <a href=\"https://stackoverflow.com/a/32798002/45375\">my other answer</a>.</sup></p>\n\n<p>With the benefit of hindsight:</p>\n\n<ul>\n<li>The <strong>third-party solutions</strong> mentioned among the existing answers are either <strong>cumbersome to install and/or do not work without non-trivial, non-obvious additional steps</strong> - some solutions appear to be at least half-abandoned.</li>\n<li><strong>A usable REPL needs the readline library for command-line-editing keyboard support and history support</strong> - ensuring this is a trouble spot for many third-party solutions.</li>\n<li>If you install CLI <strong><code>rlwrap</code>, which provides readline support to any command, you can combine it with a simple Perl command to create a usable REPL</strong>, and thus make do without third-party REPL solutions.\n\n<ul>\n<li>On OSX, you can install <code>rlwrap</code> via <a href=\"http://brew.sh\" rel=\"nofollow noreferrer\">Homebrew</a> with <code>brew install rlwrap</code>.</li>\n<li>Linux distros should offer <code>rlwrap</code> via their respective package managers; e.g., on Ubuntu, use <code>sudo apt-get install rlwrap</code>.</li>\n<li><strong>See <a href=\"https://stackoverflow.com/a/22840242/45375\">Ján Sáreník's answer</a> for said combination of <code>rlwrap</code> and a Perl command.</strong></li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p><strong>What you do NOT get</strong> with Ján's answer:</p>\n\n<ul>\n<li>auto-completion</li>\n<li>ability to enter multi-line statements</li>\n</ul>\n\n<p>The only third-party solution that offers these (with non-trivial installation + additional, non-obvious steps), is <strong><a href=\"https://github.com/gnp/psh\" rel=\"nofollow noreferrer\">psh</a></strong>, but:</p>\n\n<ul>\n<li><p>it hasn't seen activity in around 2.5 years</p></li>\n<li><p>its focus is different in that it aims to be a full-fledged <em>shell replacement</em>, and thus works like a traditional shell, which means that it doesn't automatically evaluate a command as a <em>Perl</em> statement, and requires an explicit output command such as <code>print</code> to print the result of an expression.</p></li>\n</ul>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/a/22840242/45375\">Ján Sáreník's answer</a> can be improved in one way:</p>\n\n<ul>\n<li>By default, it <strong>prints arrays/lists/hashtables as <em>scalars</em></strong>, i.e., only prints their <em>element count</em>, whereas it would be handy to enumerate their elements instead.</li>\n</ul>\n\n<p>If you install the <strong><code>Data::Printer</code></strong> module with <code>[sudo] cpan Data::Printer</code> as a one-time operation, you can load it into the REPL for use of the <strong><code>p()</code> function, to which you can pass lists/arrays/hashtables for enumeration.</strong></p>\n\n<p>Here's an <strong>alias named <code>iperl</code> with readline and <code>Data::Printer</code> support</strong>, which can you put in your POSIX-like shell's initialization file (e.g., <code>~/.bashrc</code>):</p>\n\n<pre><code>alias iperl='rlwrap -A -S \"iperl> \" perl -MData::Printer -wnE '\\''BEGIN { say \"# Use `p @<arrayOrList>` or `p %<hashTable>` to print arrays/lists/hashtables; e.g.: `p %ENV`\"; } say eval()//$@'\\'\n</code></pre>\n\n<p>E.g., you can then do the following to print all environment variables via hashtable <code>%ENV</code>:</p>\n\n<pre><code>$ iperl # start the REPL\niperl> p %ENV # print key-value pairs in hashtable %ENV\n</code></pre>\n\n<p>As with Ján's answer, the <em>scalar</em> result of an expression is <em>automatically</em> printed; e.g.:</p>\n\n<pre><code>iperl> 22 / 7 # automatically print scalar result of expression: 3.14285714285714\n</code></pre>\n"
},
{
"answer_id": 32798002,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 4,
"selected": false,
"text": "<p>I've created <a href=\"https://github.com/mklement0/perli\" rel=\"noreferrer\"><code>perli</code></a>, a <strong>Perl REPL</strong> that runs on <strong>Linux, macOS, and Windows</strong>.</p>\n\n<p>Its focus is automatic result printing, convenient documentation lookups, and easy\ninspection of regular-expression matches.<br>\nYou can see screenshots <a href=\"https://github.com/mklement0/perli#examples\" rel=\"noreferrer\">here</a>.</p>\n\n<p>It works <strong>stand-alone</strong> (has no dependencies other than Perl itself), but <strong>installation of <a href=\"https://github.com/hanslub42/rlwrap\" rel=\"noreferrer\"><code>rlwrap</code></a> is strongly recommended</strong> so as to support command-line editing, persistent command history, and tab-completion - read more <a href=\"https://github.com/mklement0/perli#supported-platforms-and-prerequisites\" rel=\"noreferrer\">here</a>.</p>\n\n<p><strong>Installation</strong></p>\n\n<ul>\n<li><p>If you happen to have Node.js installed:</p>\n\n<pre><code>npm install -g perli\n</code></pre></li>\n<li><p>Otherwise:</p>\n\n<ul>\n<li><p><em>Unix</em>-like platforms: Download <a href=\"https://raw.githubusercontent.com/mklement0/perli/stable/bin/perli\" rel=\"noreferrer\">this script</a> as <code>perli</code> to a folder in your system's path and make it executable with <code>chmod +x</code>.</p></li>\n<li><p><em>Windows</em>: Download the <a href=\"https://raw.githubusercontent.com/mklement0/perli/stable/bin/perli\" rel=\"noreferrer\">this script</a> as <code>perli.pl</code> (note the <code>.pl</code> extension) to a folder in your system's path.<br>\nIf you don't mind invoking Perli as <code>perli.pl</code>, you're all set.<br>\nOtherwise, create a batch file named <code>perli.cmd</code> in the same folder with the following content: <code>@%~dpn.pl %*</code>; this enables invocation as just <code>perli</code>.</p></li>\n</ul></li>\n</ul>\n"
},
{
"answer_id": 35815564,
"author": "gavenkoa",
"author_id": 173149,
"author_profile": "https://Stackoverflow.com/users/173149",
"pm_score": 2,
"selected": false,
"text": "<p>Under Debian/Ubuntu:</p>\n\n<pre><code>$ sudo apt-get install libdevel-repl-perl\n$ re.pl\n\n$ sudo apt-get install libapp-repl-perl\n$ iperl\n</code></pre>\n"
},
{
"answer_id": 37551820,
"author": "Davor Cubranic",
"author_id": 552683,
"author_profile": "https://Stackoverflow.com/users/552683",
"pm_score": 2,
"selected": false,
"text": "<p>Matt Trout's <a href=\"http://shadow.cat/blog/matt-s-trout/mstpan-17/\" rel=\"nofollow\">overview</a> lists five choices, from <code>perl -de 0</code> onwards, and he recommends <a href=\"https://metacpan.org/pod/Reply\" rel=\"nofollow\"><code>Reply</code></a>, if extensibility via plugins is important, or <code>tinyrepl</code> from <a href=\"https://metacpan.org/pod/Eval::WithLexicals\" rel=\"nofollow\"><code>Eval::WithLexicals</code></a>, for a minimal, pure-perl solution that includes readline support and lexical persistence.</p>\n"
},
{
"answer_id": 61923730,
"author": "Ross Attrill",
"author_id": 556644,
"author_profile": "https://Stackoverflow.com/users/556644",
"pm_score": 0,
"selected": false,
"text": "<p>You can do it online (like many things in life) here:</p>\n\n<p><a href=\"https://www.tutorialspoint.com/execute_perl_online.php\" rel=\"nofollow noreferrer\">https://www.tutorialspoint.com/execute_perl_online.php</a></p>\n"
},
{
"answer_id": 67925304,
"author": "HappyFace",
"author_id": 1410221,
"author_profile": "https://Stackoverflow.com/users/1410221",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>org-babel</code> in <code>emacs</code>; Open an <code>org-mode</code> file, i.e., <code>tmp.org</code>, and then you can do:</p>\n<pre><code>#+begin_src perl :results output\n@a = (1,5,9);\nprint ((join ", ", @a) . "\\n");\n$b = scalar @a;\nprint "$#a, $b\\n";\nprint "$#a, " . @a . "\\n";\nprint join ", ", 1..$#a; print "\\n";\nprint join ", ", @a[0..$#a]\n#+end_src\n</code></pre>\n<p>Pressing <code>CTRL-c CTRL-c</code> evals the block:</p>\n<pre><code>#+RESULTS:\n#+begin_example\n1, 5, 9\n2, 3\n2, 3\n1, 2\n1, 5, 9\n#+end_example\n</code></pre>\n<p>I am not sure what emacs config this needs to work, but I think you can just install <a href=\"https://github.com/hlissner/doom-emacs\" rel=\"nofollow noreferrer\">https://github.com/hlissner/doom-emacs</a> and enable its <code>perl</code> and <code>org-mode</code> modules.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5475/"
]
| How can I start an interactive console for Perl, similar to the `irb` command for Ruby or `python` for Python? | You can use the perl debugger on a trivial program, like so:
```
perl -de1
```
Alternatively there's [*Alexis Sukrieh*'s Perl Console](http://search.cpan.org/~sukria/perlconsole-0.4/perlconsole) application, but I haven't used it. |
73,686 | <pre><code>#include <iostream>
using namespace std;
int main()
{
double u = 0;
double w = -u;
cout << w << endl;
return 0;
}
</code></pre>
<p>Why does this great piece of code output <code>-0</code> and not <code>0</code>, as one would expect?</p>
| [
{
"answer_id": 73711,
"author": "foxxtrot",
"author_id": 10369,
"author_profile": "https://Stackoverflow.com/users/10369",
"pm_score": 5,
"selected": true,
"text": "<p>The IEEE 754 standard for floating-point numbers has the sign bit separate from the mantissa, which allows for zero to be negative. <a href=\"http://en.wikipedia.org/wiki/IEEE_754\" rel=\"nofollow noreferrer\">Wikipedia</a> should be able to help explain this.</p>\n"
},
{
"answer_id": 73717,
"author": "Clinton Pierce",
"author_id": 8173,
"author_profile": "https://Stackoverflow.com/users/8173",
"pm_score": 1,
"selected": false,
"text": "<p>Because \"negative zero\" is a valid number!</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/%E2%88%920_(number)\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/%E2%88%920_(number)</a></p>\n"
},
{
"answer_id": 73724,
"author": "Trent",
"author_id": 9083,
"author_profile": "https://Stackoverflow.com/users/9083",
"pm_score": 1,
"selected": false,
"text": "<p>Take a look at this article: <a href=\"http://en.wikipedia.org/wiki/Floating_point\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Floating_point</a>. Note that there is a sign bit, even if the value is zero.</p>\n"
},
{
"answer_id": 73728,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 2,
"selected": false,
"text": "<p>In IEEE floating point <code>0</code> and <code>-0</code> are both distinct values, from <a href=\"http://steve.hollasch.net/cgindex/coding/ieeefloat.html\" rel=\"nofollow noreferrer\">here</a> under \"Special Values\":</p>\n\n<blockquote>\n <p>Note that -0 and +0 are distinct\n values, though they both compare as\n equal.</p>\n</blockquote>\n"
},
{
"answer_id": 73740,
"author": "Drealmer",
"author_id": 12291,
"author_profile": "https://Stackoverflow.com/users/12291",
"pm_score": 2,
"selected": false,
"text": "<p>The IEEE 754 standard for floating point arithmetic makes a distinction between <code>+0</code> and <code>-0</code>, this can be used when dealing with very small numbers rounded to zero where the sign still has an importance.</p>\n"
},
{
"answer_id": 73743,
"author": "Saulius Valatka",
"author_id": 12790,
"author_profile": "https://Stackoverflow.com/users/12790",
"pm_score": 1,
"selected": false,
"text": "<p>Because a double can indeed have values -0, +0, -infinity, +infinity and NaN, which can be a result of various interesting expressions, like 0/0.</p>\n\n<p>Look <a href=\"http://en.wikipedia.org/wiki/%E2%88%920_(number)\" rel=\"nofollow noreferrer\">here</a> for more information.</p>\n"
},
{
"answer_id": 73814,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Because your expectations are wrong.</p>\n\n<p>IEEE requires that positive and negative zero be represented seperately.</p>\n\n<p>That is what you're seeing here.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6922/"
]
| ```
#include <iostream>
using namespace std;
int main()
{
double u = 0;
double w = -u;
cout << w << endl;
return 0;
}
```
Why does this great piece of code output `-0` and not `0`, as one would expect? | The IEEE 754 standard for floating-point numbers has the sign bit separate from the mantissa, which allows for zero to be negative. [Wikipedia](http://en.wikipedia.org/wiki/IEEE_754) should be able to help explain this. |
73,713 | <p>The following will cause infinite recursion on the == operator overload method</p>
<pre><code> Foo foo1 = null;
Foo foo2 = new Foo();
Assert.IsFalse(foo1 == foo2);
public static bool operator ==(Foo foo1, Foo foo2) {
if (foo1 == null) return foo2 == null;
return foo1.Equals(foo2);
}
</code></pre>
<p>How do I check for nulls?</p>
| [
{
"answer_id": 73729,
"author": "Andrew Jones",
"author_id": 12767,
"author_profile": "https://Stackoverflow.com/users/12767",
"pm_score": 4,
"selected": false,
"text": "<p>Cast to object in the overload method:</p>\n\n<pre><code>public static bool operator ==(Foo foo1, Foo foo2) {\n if ((object) foo1 == null) return (object) foo2 == null;\n return foo1.Equals(foo2);\n}\n</code></pre>\n"
},
{
"answer_id": 73732,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": 8,
"selected": true,
"text": "<p>Use <code>ReferenceEquals</code>:</p>\n\n<pre><code>Foo foo1 = null;\nFoo foo2 = new Foo();\nAssert.IsFalse(foo1 == foo2);\n\npublic static bool operator ==(Foo foo1, Foo foo2) {\n if (object.ReferenceEquals(null, foo1))\n return object.ReferenceEquals(null, foo2);\n return foo1.Equals(foo2);\n}\n</code></pre>\n"
},
{
"answer_id": 73744,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 2,
"selected": false,
"text": "<p>Try <code>Object.ReferenceEquals(foo1, null)</code></p>\n\n<p>Anyway, I wouldn't recommend overloading the <code>==</code>operator; it should be used for comparing references, and use <code>Equals</code> for \"semantic\" comparisons.</p>\n"
},
{
"answer_id": 73840,
"author": "Jon Adams",
"author_id": 2291,
"author_profile": "https://Stackoverflow.com/users/2291",
"pm_score": 3,
"selected": false,
"text": "<p>Use <code><a href=\"http://msdn.microsoft.com/en-us/library/system.object.referenceequals(VS.80).aspx\" rel=\"noreferrer\">ReferenceEquals</a></code>. From the <a href=\"http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/472d7dfe-9233-49d1-a545-de44069614b5/#ccef9e05-d609-4f01-9027-b84ea7f6a41d\" rel=\"noreferrer\">MSDN forums</a>:</p>\n\n<pre><code>public static bool operator ==(Foo foo1, Foo foo2) {\n if (ReferenceEquals(foo1, null)) return ReferenceEquals(foo2, null);\n if (ReferenceEquals(foo2, null)) return false;\n return foo1.field1 == foo2.field2;\n}\n</code></pre>\n"
},
{
"answer_id": 73915,
"author": "The Digital Gabeg",
"author_id": 12782,
"author_profile": "https://Stackoverflow.com/users/12782",
"pm_score": -1,
"selected": false,
"text": "<p>You can try to use an object property and catch the resulting NullReferenceException. If the property you try is inherited or overridden from Object, then this works for any class.</p>\n\n<pre><code>public static bool operator ==(Foo foo1, Foo foo2)\n{\n // check if the left parameter is null\n bool LeftNull = false;\n try { Type temp = a_left.GetType(); }\n catch { LeftNull = true; }\n\n // check if the right parameter is null\n bool RightNull = false;\n try { Type temp = a_right.GetType(); }\n catch { RightNull = true; }\n\n // null checking results\n if (LeftNull && RightNull) return true;\n else if (LeftNull || RightNull) return false;\n else return foo1.field1 == foo2.field2;\n}\n</code></pre>\n"
},
{
"answer_id": 81750,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 2,
"selected": false,
"text": "<p>If I have overridden <code>bool Equals(object obj)</code> and I want the operator <code>==</code> and <code>Foo.Equals(object obj)</code> to return the same value, I usually implement the <code>!=</code> operator like this:</p>\n<pre><code>public static bool operator ==(Foo foo1, Foo foo2) {\n return object.Equals(foo1, foo2);\n}\npublic static bool operator !=(Foo foo1, Foo foo2) {\n return !object.Equals(foo1, foo2);\n}\n</code></pre>\n<p>The operator <code>==</code> will then after doing all the null checks for me end up calling <code>foo1.Equals(foo2)</code> that I have overridden to do the actual check if the two are equal.</p>\n"
},
{
"answer_id": 13899647,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 1,
"selected": false,
"text": "<p>My approach is to do </p>\n\n<pre><code>(object)item == null\n</code></pre>\n\n<p>upon which I'm relying on <code>object</code>'s own equality operator which can't go wrong. Or a custom extension method (and an overload):</p>\n\n<pre><code>public static bool IsNull<T>(this T obj) where T : class\n{\n return (object)obj == null;\n}\n\npublic static bool IsNull<T>(this T? obj) where T : struct\n{\n return !obj.HasValue;\n}\n</code></pre>\n\n<p>or to handle more cases, may be:</p>\n\n<pre><code>public static bool IsNull<T>(this T obj) where T : class\n{\n return (object)obj == null || obj == DBNull.Value;\n}\n</code></pre>\n\n<p>The constraint prevents <code>IsNull</code> on value types. Now its as sweet as calling</p>\n\n<pre><code>object obj = new object();\nGuid? guid = null; \nbool b = obj.IsNull(); // false\nb = guid.IsNull(); // true\n2.IsNull(); // error\n</code></pre>\n\n<p>which means I have one consistent/not-error-prone style of checking for nulls throughout. I also have found <a href=\"https://stackoverflow.com/a/13899726/661933\"><code>(object)item == null</code> is very very very slightly faster than <code>Object.ReferenceEquals(item, null)</code></a>, but only if it matters (I'm currently working on something where I've to micro-optimize everything!).</p>\n\n<p>To see a complete guide on implementing equality checks, see <a href=\"https://stackoverflow.com/questions/104158/what-is-best-practice-for-comparing-two-instances-of-a-reference-type\">What is "Best Practice" For Comparing Two Instances of a Reference Type?</a></p>\n"
},
{
"answer_id": 40109060,
"author": "Basheer AL-MOMANI",
"author_id": 4251431,
"author_profile": "https://Stackoverflow.com/users/4251431",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>A common error in overloads of operator == is to use <code>(a == b)</code>, <code>(a ==null)</code>, or <code>(b == null)</code> to check for reference equality. This instead\n <strong>results in</strong> a call to the overloaded operator ==, causing an <code>infinite loop</code>. Use <code>ReferenceEquals</code> or cast the type to Object, to avoid the\n loop.</p>\n</blockquote>\n\n<p>check out this</p>\n\n<pre><code>// If both are null, or both are same instance, return true.\nif (System.Object.ReferenceEquals(a, b))// using ReferenceEquals\n{\n return true;\n}\n\n// If one is null, but not both, return false.\nif (((object)a == null) || ((object)b == null))// using casting the type to Object\n{\n return false;\n}\n</code></pre>\n\n<p>reference <a href=\"https://msdn.microsoft.com/ru-ru/library/ms173147(v=vs.80).aspx#Anchor_1\" rel=\"nofollow\">Guidelines for Overloading Equals() and Operator ==</a></p>\n"
},
{
"answer_id": 44376857,
"author": "jacekbe",
"author_id": 8116196,
"author_profile": "https://Stackoverflow.com/users/8116196",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using C# 7 or later you can use null constant pattern matching:</p>\n\n<pre><code>public static bool operator==(Foo foo1, Foo foo2)\n{\n if (foo1 is null)\n return foo2 is null;\n return foo1.Equals(foo2);\n}\n</code></pre>\n\n<p>This gives you slightly neater code than the one calling object.ReferenceEquals(foo1, null)</p>\n"
},
{
"answer_id": 45465996,
"author": "Zach Posten",
"author_id": 2517147,
"author_profile": "https://Stackoverflow.com/users/2517147",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://msdn.microsoft.com/en-us/library/w4hkze5k%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396\" rel=\"nofollow noreferrer\">The static <code>Equals(Object, Object)</code> method</a> indicates whether two objects, <code>objA</code> and <code>objB</code>, are equal. It also enables you to test objects whose value is <code>null</code> for equality. It compares <code>objA</code> and <code>objB</code> for equality as follows:</p>\n\n<ul>\n<li>It determines whether the two objects represent the same object reference. If they do, the method returns <code>true</code>. This test is equivalent to calling the <code>ReferenceEquals</code> method. In addition, if both <code>objA</code> and <code>objB</code> are <code>null</code>, the method returns <code>true</code>.</li>\n<li>It determines whether either <code>objA</code> or <code>objB</code> is <code>null</code>. If so, it returns <code>false</code>.\nIf the two objects do not represent the same object reference and neither is <code>null</code>, it calls <code>objA.Equals(objB)</code> and returns the result. This means that if <code>objA</code> overrides the <code>Object.Equals(Object)</code> method, this override is called.</li>\n</ul>\n\n<p>.</p>\n\n<pre><code>public static bool operator ==(Foo objA, Foo objB) {\n return Object.Equals(objA, objB);\n}\n</code></pre>\n"
},
{
"answer_id": 51354894,
"author": "CCondron",
"author_id": 602408,
"author_profile": "https://Stackoverflow.com/users/602408",
"pm_score": 0,
"selected": false,
"text": "<p>replying more to <a href=\"https://stackoverflow.com/questions/4219261/overriding-operator-how-to-compare-to-null\">overriding operator how to compare to null</a> that redirects here as a duplicate.</p>\n\n<p>In the cases where this is being done to support Value Objects, I find the new notation to handy, and like to ensure there is only one place where the comparison is made. Also leveraging Object.Equals(A, B) simplifies the null checks.</p>\n\n<p>This will overload ==, !=, Equals, and GetHashCode</p>\n\n<pre><code> public static bool operator !=(ValueObject self, ValueObject other) => !Equals(self, other);\n public static bool operator ==(ValueObject self, ValueObject other) => Equals(self, other);\n public override bool Equals(object other) => Equals(other as ValueObject );\n public bool Equals(ValueObject other) {\n return !(other is null) && \n // Value comparisons\n _value == other._value;\n }\n public override int GetHashCode() => _value.GetHashCode();\n</code></pre>\n\n<p>For more complicated objects add additional comparisons in Equals and a richer GetHashCode.</p>\n"
},
{
"answer_id": 54576557,
"author": "Reto Messerli",
"author_id": 9697734,
"author_profile": "https://Stackoverflow.com/users/9697734",
"pm_score": 2,
"selected": false,
"text": "<p>There is actually a simpler way of checking against <code>null</code> in this case:</p>\n\n<pre><code>if (foo is null)\n</code></pre>\n\n<p>That's it! </p>\n\n<p>This feature was introduced in C# 7</p>\n"
},
{
"answer_id": 58195524,
"author": "mr5",
"author_id": 2304737,
"author_profile": "https://Stackoverflow.com/users/2304737",
"pm_score": 0,
"selected": false,
"text": "<p>For a modern and condensed syntax:</p>\n\n<pre><code>public static bool operator ==(Foo x, Foo y)\n{\n return x is null ? y is null : x.Equals(y);\n}\n\npublic static bool operator !=(Foo x, Foo y)\n{\n return x is null ? !(y is null) : !x.Equals(y);\n}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12767/"
]
| The following will cause infinite recursion on the == operator overload method
```
Foo foo1 = null;
Foo foo2 = new Foo();
Assert.IsFalse(foo1 == foo2);
public static bool operator ==(Foo foo1, Foo foo2) {
if (foo1 == null) return foo2 == null;
return foo1.Equals(foo2);
}
```
How do I check for nulls? | Use `ReferenceEquals`:
```
Foo foo1 = null;
Foo foo2 = new Foo();
Assert.IsFalse(foo1 == foo2);
public static bool operator ==(Foo foo1, Foo foo2) {
if (object.ReferenceEquals(null, foo1))
return object.ReferenceEquals(null, foo2);
return foo1.Equals(foo2);
}
``` |
73,748 | <p>I have a dropdownlist with the autopostback set to true. I want the
user to confirm if they really want to change the value,
which on post back fires a server side event (selectedindexchanged).</p>
<p>I have tried adding an onchange attribute "return confirm('Please click OK to change. Otherwise click CANCEL?';") but it will not postback regardless of the confirm
result and the value in the list does not revert back if cancel
selected. </p>
<p>When I remove the onchange attribute from the DropdownList tag, the page does postback. It does not when the onchange attribute is added. Do I still need to wire the event handler (I'm on C# .Net 2.0 ).</p>
<p>Any leads will be helpful.</p>
<p>Thanks!</p>
| [
{
"answer_id": 73860,
"author": "Brian Liang",
"author_id": 5853,
"author_profile": "https://Stackoverflow.com/users/5853",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure your event is wired:</p>\n\n<pre><code>dropDown.SelectedIndexChanged += new EventHandler(dropDown_SelectedIndexChanged);\n</code></pre>\n\n<p>You can also apply a client-side attribute to return the confirmation. Set the index accordingly if cancelled.</p>\n\n<pre><code>dropDown.Attributes.Add(\"onchange\", \"javascript: return confirm('confirmation msg')\");\n</code></pre>\n"
},
{
"answer_id": 74027,
"author": "Craig",
"author_id": 2047,
"author_profile": "https://Stackoverflow.com/users/2047",
"pm_score": 3,
"selected": false,
"text": "<p>You can utilize the the CustomValidator control to \"validate\" dropdown by calling a javascript function in which you do the confirm():</p>\n\n<pre><code> <asp:DropDownList ID=\"TestDropDown\" runat=\"server\" AutoPostBack=\"true\" CausesValidation=\"true\"\n ValidationGroup=\"Group1\"\n OnSelectedIndexChanged=\"TestDropDown_SelectedIndexChanged\">\n <asp:ListItem Value=\"1\" Text=\"One\" />\n <asp:ListItem Value=\"2\" Text=\"Two\" />\n </asp:DropDownList>\n <script type=\"text/javascript\">\n function ConfirmDropDownValueChange(source, arguments) {\n arguments.IsValid = confirm(\"Are you sure?\");\n }\n </script>\n <asp:CustomValidator ID=\"ConfirmDropDownValidator\" runat=\"server\"\n ClientValidationFunction=\"ConfirmDropDownValueChange\" Display=\"Dynamic\" ValidationGroup=\"Group1\" />\n</code></pre>\n"
},
{
"answer_id": 74251,
"author": "Kyle B.",
"author_id": 6158,
"author_profile": "https://Stackoverflow.com/users/6158",
"pm_score": 4,
"selected": true,
"text": "<p>Have you tried to set the onChange event to a javascript function and then inside the function display the javascript alert and utilize the __doPostback function if it passes?</p>\n\n<p>i.e.</p>\n\n<pre><code> \ndrpControl.Attributes(\"onChange\") = \"DisplayConfirmation();\"\n\nfunction DisplayConfirmation() {\n if (confirm('Are you sure you want to do this?')) {\n __doPostback('drpControl','');\n }\n}\n</code></pre>\n"
},
{
"answer_id": 74289,
"author": "Billy Jo",
"author_id": 3447,
"author_profile": "https://Stackoverflow.com/users/3447",
"pm_score": 1,
"selected": false,
"text": "<p>Currently, you're always returning the result of the <code>confirm()</code>, so even if it returns <code>true</code>, you'll still stop execution of the event before the postback can fire. Your <code>onchange</code> should <code>return false;</code> only when the <code>confirm()</code> does, too, like this:</p>\n\n<pre><code>if (!confirm('Please click OK to change. Otherwise click CANCEL?')) return false;\n</code></pre>\n"
},
{
"answer_id": 74444,
"author": "Craig",
"author_id": 2047,
"author_profile": "https://Stackoverflow.com/users/2047",
"pm_score": 1,
"selected": false,
"text": "<p>Overriding the onchange attribute will not work if you have have AutoPostBack set to true because ASP.NET will always append the following to the end of your onchange script:</p>\n\n<pre><code>;setTimeout('__doPostBack(\\'YourDropDown\\',\\'\\')', 0)\n</code></pre>\n\n<p>If you set AutoPostBack to false, then overriding onchange with a \"confirm and __doPostBack\" type script (see above, err.. below) will work but you may have to manually create the __doPostBack function.</p>\n"
},
{
"answer_id": 2695583,
"author": "JCallico",
"author_id": 143195,
"author_profile": "https://Stackoverflow.com/users/143195",
"pm_score": 3,
"selected": false,
"text": "<p>The following works when the DropDownList is triggering partial postbacks:</p>\n\n<pre><code>// caching selected value at the time the control is clicked\nMyDropDownList.Attributes.Add(\n \"onclick\",\n \"this.currentvalue = this.value;\");\n\n// if the user chooses not to continue then restoring cached value and aborting by returning false\nMyDropDownList.Attributes.Add(\n \"onchange\",\n \"if (!confirm('Do you want to continue?')) {this.value = this.currentvalue; return false};\");\n</code></pre>\n"
},
{
"answer_id": 3301127,
"author": "NealB",
"author_id": 41114,
"author_profile": "https://Stackoverflow.com/users/41114",
"pm_score": 1,
"selected": false,
"text": "<pre><code>if (!confirm('Please click OK to change. Otherwise click CANCEL?')) return false;\n</code></pre>\n\n<p>Always returns so dropdownlist's OnSelectedIndexChanged event fires whether user clicks OK or CANCEL.</p>\n"
},
{
"answer_id": 16061689,
"author": "shailendra sharma",
"author_id": 2290912,
"author_profile": "https://Stackoverflow.com/users/2290912",
"pm_score": 0,
"selected": false,
"text": "<pre><code>&lt;asp:DropDownList runat=\"server\" ID=\"ddlShailendra\" AutoPostBack=\"True\" OnSelectedIndexChanged=\"ddlShailendra_SelectedIndexChanged\" onchange=\"javascript: { if(confirm('Click ok to prevent post back, Cancel to make a postback'))return true;} \" &gt;\n &lt;asp:ListItem Text=\"tes\" Value=\"1\" >&lt;/asp:ListItem&gt;\n &lt;asp:ListItem Text=\"test\" Value=\"-1\"&gt;&lt;/asp:ListItem&gt;\n &lt;/asp:DropDownList&gt;\n</code></pre>\n\n<p>Write the function inline and dont have a \"return\" for the condition in which you want a post back. This works and is as per the standards.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/262613/"
]
| I have a dropdownlist with the autopostback set to true. I want the
user to confirm if they really want to change the value,
which on post back fires a server side event (selectedindexchanged).
I have tried adding an onchange attribute "return confirm('Please click OK to change. Otherwise click CANCEL?';") but it will not postback regardless of the confirm
result and the value in the list does not revert back if cancel
selected.
When I remove the onchange attribute from the DropdownList tag, the page does postback. It does not when the onchange attribute is added. Do I still need to wire the event handler (I'm on C# .Net 2.0 ).
Any leads will be helpful.
Thanks! | Have you tried to set the onChange event to a javascript function and then inside the function display the javascript alert and utilize the \_\_doPostback function if it passes?
i.e.
```
drpControl.Attributes("onChange") = "DisplayConfirmation();"
function DisplayConfirmation() {
if (confirm('Are you sure you want to do this?')) {
__doPostback('drpControl','');
}
}
``` |
73,781 | <p>If I want to send mail not via SMTP, but rather via sendmail, is there a library for python that encapsulates this process?</p>
<p>Better yet, is there a good library that abstracts the whole 'sendmail -versus- smtp' choice?</p>
<p>I'll be running this script on a bunch of unix hosts, only some of which are listening on localhost:25; a few of these are part of embedded systems and can't be set up to accept SMTP.</p>
<p>As part of Good Practice, I'd really like to have the library take care of header injection vulnerabilities itself -- so just dumping a string to <code>popen('/usr/bin/sendmail', 'w')</code> is a little closer to the metal than I'd like.</p>
<p>If the answer is 'go write a library,' so be it ;-)</p>
| [
{
"answer_id": 73807,
"author": "tovare",
"author_id": 12677,
"author_profile": "https://Stackoverflow.com/users/12677",
"pm_score": 2,
"selected": false,
"text": "<p>It's quite common to just use the sendmail command from Python using os.popen</p>\n\n<p>Personally, for scripts i didn't write myself, I think just using the SMTP-protocol is better, since it wouldn't require installing say an sendmail clone to run on windows.</p>\n\n<p><a href=\"https://docs.python.org/library/smtplib.html\" rel=\"nofollow noreferrer\">https://docs.python.org/library/smtplib.html</a></p>\n"
},
{
"answer_id": 73811,
"author": "Frank Wiles",
"author_id": 12568,
"author_profile": "https://Stackoverflow.com/users/12568",
"pm_score": -1,
"selected": false,
"text": "<p>The easiest answer is the smtplib, you can find docs on it <a href=\"http://docs.python.org/lib/SMTP-example.html\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<p>All you need to do is configure your local sendmail to accept connection from localhost, which it probably already does by default. Sure, you're still using SMTP for the transfer, but it's the local sendmail, which is basically the same as using the commandline tool. </p>\n"
},
{
"answer_id": 73844,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 5,
"selected": false,
"text": "<p>This is a simple python function that uses the unix sendmail to deliver a mail.</p>\n\n<pre><code>def sendMail():\n sendmail_location = \"/usr/sbin/sendmail\" # sendmail location\n p = os.popen(\"%s -t\" % sendmail_location, \"w\")\n p.write(\"From: %s\\n\" % \"[email protected]\")\n p.write(\"To: %s\\n\" % \"[email protected]\")\n p.write(\"Subject: thesubject\\n\")\n p.write(\"\\n\") # blank line separating headers from body\n p.write(\"body of the mail\")\n status = p.close()\n if status != 0:\n print \"Sendmail exit status\", status\n</code></pre>\n"
},
{
"answer_id": 74084,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 8,
"selected": true,
"text": "<p>Header injection isn't a factor in how you send the mail, it's a factor in how you construct the mail. Check the <a href=\"https://docs.python.org/2/library/email.html\" rel=\"noreferrer\">email</a> package, construct the mail with that, serialise it, and send it to <code>/usr/sbin/sendmail</code> using the <a href=\"https://docs.python.org/2/library/subprocess.html\" rel=\"noreferrer\">subprocess</a> module:</p>\n<pre><code>import sys\nfrom email.mime.text import MIMEText\nfrom subprocess import Popen, PIPE\n\n\nmsg = MIMEText("Here is the body of my message")\nmsg["From"] = "[email protected]"\nmsg["To"] = "[email protected]"\nmsg["Subject"] = "This is the subject."\np = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)\n# Both Python 2.X and 3.X\np.communicate(msg.as_bytes() if sys.version_info >= (3,0) else msg.as_string()) \n\n# Python 2.X\np.communicate(msg.as_string())\n\n# Python 3.X\np.communicate(msg.as_bytes())\n</code></pre>\n"
},
{
"answer_id": 5545462,
"author": "amcgregor",
"author_id": 211827,
"author_profile": "https://Stackoverflow.com/users/211827",
"pm_score": 3,
"selected": false,
"text": "<p>This question is very old, but it's worthwhile to note that there is a message construction and e-mail delivery system called <a href=\"https://github.com/marrow/mailer\" rel=\"nofollow noreferrer\">Marrow Mailer</a> (previously TurboMail) which has been available since before this message was asked.</p>\n\n<p>It's now being ported to support Python 3 and updated as part of the <a href=\"https://github.com/marrow\" rel=\"nofollow noreferrer\">Marrow</a> suite.</p>\n"
},
{
"answer_id": 17345007,
"author": "elec3647",
"author_id": 1842416,
"author_profile": "https://Stackoverflow.com/users/1842416",
"pm_score": -1,
"selected": false,
"text": "<p>I was just searching around for the same thing and found a good example on the Python website: <a href=\"http://docs.python.org/2/library/email-examples.html\" rel=\"nofollow\">http://docs.python.org/2/library/email-examples.html</a></p>\n\n<p>From the site mentioned:</p>\n\n<pre><code># Import smtplib for the actual sending function\nimport smtplib\n\n# Import the email modules we'll need\nfrom email.mime.text import MIMEText\n\n# Open a plain text file for reading. For this example, assume that\n# the text file contains only ASCII characters.\nfp = open(textfile, 'rb')\n# Create a text/plain message\nmsg = MIMEText(fp.read())\nfp.close()\n\n# me == the sender's email address\n# you == the recipient's email address\nmsg['Subject'] = 'The contents of %s' % textfile\nmsg['From'] = me\nmsg['To'] = you\n\n# Send the message via our own SMTP server, but don't include the\n# envelope header.\ns = smtplib.SMTP('localhost')\ns.sendmail(me, [you], msg.as_string())\ns.quit()\n</code></pre>\n\n<p>Note that this requires that you have sendmail/mailx set up correctly to accept connections on \"localhost\". This works on my Mac, Ubuntu and Redhat servers by default, but you may want to double-check if you run into any issues.</p>\n"
},
{
"answer_id": 32673496,
"author": "MEI",
"author_id": 5351807,
"author_profile": "https://Stackoverflow.com/users/5351807",
"pm_score": 4,
"selected": false,
"text": "<p>Jim's answer did not work for me in Python 3.4. I had to add an additional <code>universal_newlines=True</code> argument to <code>subrocess.Popen()</code></p>\n\n<pre><code>from email.mime.text import MIMEText\nfrom subprocess import Popen, PIPE\n\nmsg = MIMEText(\"Here is the body of my message\")\nmsg[\"From\"] = \"[email protected]\"\nmsg[\"To\"] = \"[email protected]\"\nmsg[\"Subject\"] = \"This is the subject.\"\np = Popen([\"/usr/sbin/sendmail\", \"-t\", \"-oi\"], stdin=PIPE, universal_newlines=True)\np.communicate(msg.as_string())\n</code></pre>\n\n<p>Without the <code>universal_newlines=True</code> I get</p>\n\n<pre><code>TypeError: 'str' does not support the buffer interface\n</code></pre>\n"
},
{
"answer_id": 61923564,
"author": "Robin Stewart",
"author_id": 7488171,
"author_profile": "https://Stackoverflow.com/users/7488171",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Python 3.5+</strong> version:</p>\n\n<pre><code>import subprocess\nfrom email.message import EmailMessage\n\ndef sendEmail(from_addr, to_addrs, msg_subject, msg_body):\n msg = EmailMessage()\n msg.set_content(msg_body)\n msg['From'] = from_addr\n msg['To'] = to_addrs\n msg['Subject'] = msg_subject\n\n sendmail_location = \"/usr/sbin/sendmail\"\n subprocess.run([sendmail_location, \"-t\", \"-oi\"], input=msg.as_bytes())\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12779/"
]
| If I want to send mail not via SMTP, but rather via sendmail, is there a library for python that encapsulates this process?
Better yet, is there a good library that abstracts the whole 'sendmail -versus- smtp' choice?
I'll be running this script on a bunch of unix hosts, only some of which are listening on localhost:25; a few of these are part of embedded systems and can't be set up to accept SMTP.
As part of Good Practice, I'd really like to have the library take care of header injection vulnerabilities itself -- so just dumping a string to `popen('/usr/bin/sendmail', 'w')` is a little closer to the metal than I'd like.
If the answer is 'go write a library,' so be it ;-) | Header injection isn't a factor in how you send the mail, it's a factor in how you construct the mail. Check the [email](https://docs.python.org/2/library/email.html) package, construct the mail with that, serialise it, and send it to `/usr/sbin/sendmail` using the [subprocess](https://docs.python.org/2/library/subprocess.html) module:
```
import sys
from email.mime.text import MIMEText
from subprocess import Popen, PIPE
msg = MIMEText("Here is the body of my message")
msg["From"] = "[email protected]"
msg["To"] = "[email protected]"
msg["Subject"] = "This is the subject."
p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)
# Both Python 2.X and 3.X
p.communicate(msg.as_bytes() if sys.version_info >= (3,0) else msg.as_string())
# Python 2.X
p.communicate(msg.as_string())
# Python 3.X
p.communicate(msg.as_bytes())
``` |
73,785 | <p>I need to simply go through all the cells in a Excel Spreadsheet and check the values in the cells. The cells may contain text, numbers or be blank. I am not very familiar / comfortable working with the concept of 'Range'. Therefore, any sample codes would be greatly appreciated. (I did try to google it, but the code snippets I found didn't quite do what I needed)</p>
<p>Thank you.</p>
| [
{
"answer_id": 73891,
"author": "Martin08",
"author_id": 8203,
"author_profile": "https://Stackoverflow.com/users/8203",
"pm_score": 0,
"selected": false,
"text": "<p>In Excel VBA, this function will give you the content of any cell in any worksheet.</p>\n\n<pre><code>Function getCellContent(Byref ws As Worksheet, ByVal rowindex As Integer, ByVal colindex As Integer) as String\n getCellContent = CStr(ws.Cells(rowindex, colindex))\nEnd Function\n</code></pre>\n\n<p>So if you want to check the value of cells, just put the function in a loop, give it the reference to the worksheet you want and the row index and column index of the cell. Row index and column index both start from 1, meaning that cell A1 will be ws.Cells(1,1) and so on.</p>\n"
},
{
"answer_id": 73900,
"author": "betelgeuce",
"author_id": 366182,
"author_profile": "https://Stackoverflow.com/users/366182",
"pm_score": 4,
"selected": true,
"text": "<pre><code>Sub CheckValues1()\n Dim rwIndex As Integer\n Dim colIndex As Integer\n For rwIndex = 1 To 10\n For colIndex = 1 To 5\n If Cells(rwIndex, colIndex).Value <> 0 Then _\n Cells(rwIndex, colIndex).Value = 0\n Next colIndex\n Next rwIndex\nEnd Sub\n</code></pre>\n\n<p>Found this snippet on <a href=\"http://www.java2s.com/Code/VBA-Excel-Access-Word/Excel/Checksvaluesinarange10rowsby5columns.htm\" rel=\"noreferrer\">http://www.java2s.com/Code/VBA-Excel-Access-Word/Excel/Checksvaluesinarange10rowsby5columns.htm</a> It seems to be quite useful as a function to illustrate the means to check values in cells in an ordered fashion.</p>\n\n<p>Just imagine it as being a 2d Array of sorts and apply the same logic to loop through cells.</p>\n"
},
{
"answer_id": 73907,
"author": "theo",
"author_id": 7870,
"author_profile": "https://Stackoverflow.com/users/7870",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a For Each to iterate through all the cells in a defined range.</p>\n\n<pre><code>Public Sub IterateThroughRange()\n\nDim wb As Workbook\nDim ws As Worksheet\nDim rng As Range\nDim cell As Range\n\nSet wb = Application.Workbooks(1)\nSet ws = wb.Sheets(1)\nSet rng = ws.Range(\"A1\", \"C3\")\n\nFor Each cell In rng.Cells\n cell.Value = cell.Address\nNext cell\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 73912,
"author": "cori",
"author_id": 8151,
"author_profile": "https://Stackoverflow.com/users/8151",
"pm_score": 6,
"selected": false,
"text": "<p>If you only need to look at the cells that are in use you can use:</p>\n\n<pre><code>sub IterateCells()\n\n For Each Cell in ActiveSheet.UsedRange.Cells\n 'do some stuff\n Next\n\nEnd Sub\n</code></pre>\n\n<p>that will hit everything in the range from A1 to the last cell with data (the bottom right-most cell)</p>\n"
},
{
"answer_id": 73946,
"author": "TheXenocide",
"author_id": 8543,
"author_profile": "https://Stackoverflow.com/users/8543",
"pm_score": 1,
"selected": false,
"text": "<p>There are several methods to accomplish this, each of which has advantages and disadvantages; First and foremost, you're going to need to have an instance of a Worksheet object, Application.ActiveSheet works if you just want the one the user is looking at.</p>\n\n<p>The Worksheet object has three properties that can be used to access cell data (Cells, Rows, Columns) and a method that can be used to obtain a block of cell data, (get_Range).</p>\n\n<p>Ranges can be resized and such, but you may need to use the properties mentioned above to find out where the boundaries of your data are. The advantage to a Range becomes apparent when you are working with large amounts of data because VSTO add-ins are hosted outside the boundaries of the Excel application itself, so all calls to Excel have to be passed through a layer with overhead; obtaining a Range allows you to get/set all of the data you want in one call which can have huge performance benefits, but it requires you to use explicit details rather than iterating through each entry.</p>\n\n<p><a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=767501&SiteID=1\" rel=\"nofollow noreferrer\">This MSDN forum post</a> shows a VB.Net developer asking a question about getting the results of a Range as an array</p>\n"
},
{
"answer_id": 74006,
"author": "w4ik",
"author_id": 4232,
"author_profile": "https://Stackoverflow.com/users/4232",
"pm_score": 1,
"selected": false,
"text": "<p>You basically can loop over a Range</p>\n\n<p>Get a sheet</p>\n\n<pre><code>myWs = (Worksheet)MyWb.Worksheets[1];\n</code></pre>\n\n<p>Get the Range you're interested in If you really want to check every cell use Excel's limits </p>\n\n<blockquote>\n <p>The Excel 2007 \"Big Grid\" increases\n the maximum number of rows per\n worksheet from 65,536 to over 1\n million, and the number of columns\n from 256 (IV) to 16,384 (XFD).\n from here <a href=\"http://msdn.microsoft.com/en-us/library/aa730921.aspx#Office2007excelPerf_BigGridIncreasedLimitsExcel\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa730921.aspx#Office2007excelPerf_BigGridIncreasedLimitsExcel</a></p>\n</blockquote>\n\n<p>and then loop over the range</p>\n\n<pre><code> Range myBigRange = myWs.get_Range(\"A1\", \"A256\");\n\n string myValue;\n\n foreach(Range myCell in myBigRange )\n {\n myValue = myCell.Value2.ToString();\n }\n</code></pre>\n"
},
{
"answer_id": 74012,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>My VBA skills are a little rusty, but this is the general idea of what I'd do.<br>\nThe easiest way to do this would be to iterate through a loop for every column:</p>\n\n<pre><code>public sub CellProcessing()\non error goto errHandler\n\n dim MAX_ROW as Integer 'how many rows in the spreadsheet\n dim i as Integer\n dim cols as String\n\n for i = 1 to MAX_ROW\n 'perform checks on the cell here\n 'access the cell with Range(\"A\" & i) to get cell A1 where i = 1\n next i\n\nexitHandler:\n exit sub\nerrHandler:\n msgbox \"Error \" & err.Number & \": \" & err.Description\n resume exitHandler\nend sub\n</code></pre>\n\n<p>it seems that the color syntax highlighting doesn't like vba, but hopefully this will help somewhat (at least give you a starting point to work from).</p>\n\n<ul>\n<li>Brisketeer</li>\n</ul>\n"
},
{
"answer_id": 74209,
"author": "Cory Engebretson",
"author_id": 3406,
"author_profile": "https://Stackoverflow.com/users/3406",
"pm_score": 2,
"selected": false,
"text": "<p>For a VB or C# app, one way to do this is by using Office Interop. This depends on which version of Excel you're working with.</p>\n\n<p>For Excel 2003, this MSDN article is a good place to start.\n<a href=\"http://msdn.microsoft.com/en-us/library/aa537184(office.11).aspx\" rel=\"nofollow noreferrer\">Understanding the Excel Object Model from a Visual Studio 2005 Developer's Perspective </a></p>\n\n<p>You'll basically need to do the following:</p>\n\n<ul>\n<li>Start the Excel application.</li>\n<li>Open the Excel workbook.</li>\n<li>Retrieve the worksheet from the workbook by name or index.</li>\n<li>Iterate through all the Cells in the worksheet which were retrieved as a range.</li>\n<li>Sample (untested) code excerpt below for the last step.</li>\n</ul>\n\n<pre><code>\n Excel.Range allCellsRng;\n string lowerRightCell = \"IV65536\";\n allCellsRng = ws.get_Range(\"A1\", lowerRightCell).Cells;\n foreach (Range cell in allCellsRng)\n {\n if (null == cell.Value2 || isBlank(cell.Value2))\n {\n // Do something.\n }\n else if (isText(cell.Value2))\n {\n // Do something.\n }\n else if (isNumeric(cell.Value2))\n {\n // Do something.\n }\n }\n</code></pre>\n\n<p>For Excel 2007, try <a href=\"http://msdn.microsoft.com/en-us/library/bb979621.aspx\" rel=\"nofollow noreferrer\">this MSDN reference</a>.</p>\n"
},
{
"answer_id": 87577,
"author": "Jon Fournier",
"author_id": 5106,
"author_profile": "https://Stackoverflow.com/users/5106",
"pm_score": 3,
"selected": false,
"text": "<p>If you're just looking at values of cells you can store the values in an array of variant type. It seems that getting the value of an element in an array can be much faster than interacting with Excel, so you can see some difference in performance using an array of all cell values compared to repeatedly getting single cells.</p>\n\n<pre><code>Dim ValArray as Variant\nValArray = Range(\"A1:IV\" & Rows.Count).Value\n</code></pre>\n\n<p>Then you can get a cell value just by checking ValArray( row , column )</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5899/"
]
| I need to simply go through all the cells in a Excel Spreadsheet and check the values in the cells. The cells may contain text, numbers or be blank. I am not very familiar / comfortable working with the concept of 'Range'. Therefore, any sample codes would be greatly appreciated. (I did try to google it, but the code snippets I found didn't quite do what I needed)
Thank you. | ```
Sub CheckValues1()
Dim rwIndex As Integer
Dim colIndex As Integer
For rwIndex = 1 To 10
For colIndex = 1 To 5
If Cells(rwIndex, colIndex).Value <> 0 Then _
Cells(rwIndex, colIndex).Value = 0
Next colIndex
Next rwIndex
End Sub
```
Found this snippet on <http://www.java2s.com/Code/VBA-Excel-Access-Word/Excel/Checksvaluesinarange10rowsby5columns.htm> It seems to be quite useful as a function to illustrate the means to check values in cells in an ordered fashion.
Just imagine it as being a 2d Array of sorts and apply the same logic to loop through cells. |
73,797 | <p>How do I tell Subversion (svn) to treat a file as a binary file?</p>
| [
{
"answer_id": 73820,
"author": "Jan Krüger",
"author_id": 12471,
"author_profile": "https://Stackoverflow.com/users/12471",
"pm_score": 3,
"selected": false,
"text": "<p>For example:</p>\n\n<pre><code>svn propset svn:mime-type image/png foo.png\n</code></pre>\n"
},
{
"answer_id": 73830,
"author": "Adrian Petrescu",
"author_id": 12171,
"author_profile": "https://Stackoverflow.com/users/12171",
"pm_score": 2,
"selected": false,
"text": "<p>As per the <a href=\"http://subversion.apache.org/faq.html#binary-files\" rel=\"nofollow noreferrer\">Subversion FAQ</a>, you can use svn propset to change the <strong>svn:mime-type</strong> property to <strong>application/octet-stream</strong></p>\n"
},
{
"answer_id": 73832,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 2,
"selected": false,
"text": "<p>svn looks for a mime-type property, guessing it is text if it doesn't exist. You can explicity set this property, see <a href=\"http://svnbook.red-bean.com/en/1.5/svn.forcvs.binary-and-trans.html\" rel=\"nofollow noreferrer\">http://svnbook.red-bean.com/en/1.5/svn.forcvs.binary-and-trans.html</a></p>\n"
},
{
"answer_id": 73834,
"author": "KTamas",
"author_id": 6541,
"author_profile": "https://Stackoverflow.com/users/6541",
"pm_score": 4,
"selected": false,
"text": "<p>Basically, you have to set the mime type to octet-stream:</p>\n\n<pre><code>svn propset svn:mime-type application/octet-stream <filename>\n</code></pre>\n"
},
{
"answer_id": 73852,
"author": "Frank Wiles",
"author_id": 12568,
"author_profile": "https://Stackoverflow.com/users/12568",
"pm_score": 0,
"selected": false,
"text": "<p>It usually does this by default for you, but if it isn't you need to look into file properties and propset. </p>\n"
},
{
"answer_id": 73863,
"author": "Evil Andy",
"author_id": 4431,
"author_profile": "https://Stackoverflow.com/users/4431",
"pm_score": 4,
"selected": false,
"text": "<p>From page 367 of the <a href=\"http://svnbook.red-bean.com/en/1.5/svn-book.pdf\" rel=\"noreferrer\">Subversion book</a></p>\n\n<blockquote>\n <p>In the most general sense, Subversion handles binary files more gracefully than CVS does.\n Because CVS uses RCS, it can only store successive full copies of a changing binary file.\n Subversion, however, expresses differences between files using a binary differencing algorithm,\n regardless of whether they contain textual or binary data. That means all files are\n stored differentially (compressed) in the repository.</p>\n \n <p>CVS users have to mark binary files with -kb flags to prevent data from being garbled (due\n to keyword expansion and line-ending translations). They sometimes forget to do this.</p>\n \n <p>Subversion takes the more paranoid route. First, it never performs any kind of keyword or\n line-ending translation unless you explicitly ask it to do so (see the section called “Keyword\n Substitution” and the section called “End-of-Line Character Sequences” for more details).\n By default, Subversion treats all file data as literal byte strings, and files are always stored\n in the repository in an untranslated state.</p>\n \n <p>Second, Subversion maintains an internal notion of whether a file is “text” or “binary” data,\n but this notion is only extant in the working copy. During an svn update, Subversion will\n perform contextual merges on locally modified text files, but will not attempt to do so for\n binary files.</p>\n \n <p>To determine whether a contextual merge is possible, Subversion examines the\n svn:mime-type property. If the file has no svn:mime-type property, or has a MIME\n type that is textual (e.g., text/*), Subversion assumes it is text. Otherwise, Subversion\n assumes the file is binary. Subversion also helps users by running a binary-detection algorithm\n in the svn import and svn add commands. These commands will make a good\n guess and then (possibly) set a binary svn:mime-type property on the file being added.\n (If Subversion guesses wrong, the user can always remove or hand-edit the property.)</p>\n</blockquote>\n\n<p>Hand editing would be done by</p>\n\n<pre><code>svn propset svn:mime-type some/type filename.extension\n</code></pre>\n"
},
{
"answer_id": 73864,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 2,
"selected": false,
"text": "<p>If using tortoise svn in Windows, right click on the file and go to properties. Click on new and add a new property of type svn:mime-type. For the value put: application/octet-stream</p>\n"
},
{
"answer_id": 73924,
"author": "grammar31",
"author_id": 12815,
"author_profile": "https://Stackoverflow.com/users/12815",
"pm_score": 2,
"selected": false,
"text": "<p>Although Subversion tries to <a href=\"http://subversion.apache.org/faq.html#binary-files\" rel=\"nofollow noreferrer\">automatically detect</a> whether a file is binary or not, you can override the mime-type using <a href=\"http://svnbook.red-bean.com/en/1.0/re23.html\" rel=\"nofollow noreferrer\">svn propset</a>.\nFor example, <code>svn propset svn:mime-type application/octet-stream example.txt</code>. This will make your file act as a collection of bytes rather than a text file. See also, the svn manual on <a href=\"http://svnbook.red-bean.com/nightly/en/svn.advanced.props.file-portability.html#svn.advanced.props.special.mime-type\" rel=\"nofollow noreferrer\">File Portability</a>.</p>\n"
},
{
"answer_id": 74017,
"author": "stormlash",
"author_id": 12657,
"author_profile": "https://Stackoverflow.com/users/12657",
"pm_score": 7,
"selected": true,
"text": "<p>It is possible to manually identify a file located within a repository as <em>binary</em> by using:</p>\n\n<pre><code>svn propset svn:mime-type application/octet-stream <filename>\n</code></pre>\n\n<p>This is generally not necessary, as Subversion will attempt to determine whether a file is binary when the file is first added. If Subversion is incorrectly tagging a certain type as \"text\" when it should be treated as binary, it is possible to configure Subversion's <a href=\"http://svnbook.red-bean.com/nightly/en/svn.advanced.props.html#svn.advanced.props.auto\" rel=\"noreferrer\">auto-props feature</a> to automatically tag that file with a non-text MIME type. Regardless of the properties configured on the file, Subversion still stores the file in a binary format within the repository.</p>\n\n<p>If Subversion identifies the MIME type as a \"text\" type, it enables certain features which are not available on binary files, such as <em>svn diff</em> and <em>svn blame</em>. It also allows for automatic line ending conversion, which is configurable on a client-by-client basis.</p>\n\n<p>For more information, see <a href=\"http://subversion.apache.org/faq.html#binary-files\" rel=\"noreferrer\">How does Subversion handle binary files?</a></p>\n"
},
{
"answer_id": 11020623,
"author": "user1454388",
"author_id": 1454388,
"author_profile": "https://Stackoverflow.com/users/1454388",
"pm_score": 4,
"selected": false,
"text": "<p>If 'svn add' guesses the incorrect type and gives you an error like the following:</p>\n\n<pre><code>svn: E200009: File 'qt/examples/dialogs/configdialog/images/config.png' has inconsistent newlines\nsvn: E135000: Inconsistent line ending style\n</code></pre>\n\n<p>then the workaround is to add the file without properties and then set the properties in a second step:</p>\n\n<pre><code>svn add --no-auto-props qt/examples/dialogs/configdialog/images/config.png\nsvn propset svn:mime-type image/png qt/examples/dialogs/configdialog/images/config.png\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5222/"
]
| How do I tell Subversion (svn) to treat a file as a binary file? | It is possible to manually identify a file located within a repository as *binary* by using:
```
svn propset svn:mime-type application/octet-stream <filename>
```
This is generally not necessary, as Subversion will attempt to determine whether a file is binary when the file is first added. If Subversion is incorrectly tagging a certain type as "text" when it should be treated as binary, it is possible to configure Subversion's [auto-props feature](http://svnbook.red-bean.com/nightly/en/svn.advanced.props.html#svn.advanced.props.auto) to automatically tag that file with a non-text MIME type. Regardless of the properties configured on the file, Subversion still stores the file in a binary format within the repository.
If Subversion identifies the MIME type as a "text" type, it enables certain features which are not available on binary files, such as *svn diff* and *svn blame*. It also allows for automatic line ending conversion, which is configurable on a client-by-client basis.
For more information, see [How does Subversion handle binary files?](http://subversion.apache.org/faq.html#binary-files) |
73,833 | <p>I want to search for files containing DOS line endings with grep on Linux. Something like this:</p>
<pre class="lang-sh prettyprint-override"><code>grep -IUr --color '\r\n' .
</code></pre>
<p>The above seems to match for literal <code>rn</code> which is not what is desired.</p>
<p>The output of this will be piped through xargs into todos to convert crlf to lf like this</p>
<pre><code>grep -IUrl --color '^M' . | xargs -ifile fromdos 'file'
</code></pre>
| [
{
"answer_id": 73886,
"author": "pjz",
"author_id": 8002,
"author_profile": "https://Stackoverflow.com/users/8002",
"pm_score": 7,
"selected": false,
"text": "<p>Use <kbd>Ctrl</kbd>+<kbd>V</kbd>, <kbd>Ctrl</kbd>+<kbd>M</kbd> to enter a literal Carriage Return character into your grep string. So:</p>\n<pre><code>grep -IUr --color "^M"\n</code></pre>\n<p>will work - if the <code>^M</code> there is a literal CR that you input as I suggested.</p>\n<p>If you want the list of files, you want to add the <code>-l</code> option as well.</p>\n<p><strong>Explanation</strong></p>\n<ul>\n<li><code>-I</code> ignore binary files</li>\n<li><code>-U</code> prevents grep from stripping CR characters. By default it does this it if it decides it's a text file.</li>\n<li><code>-r</code> read all files under each directory recursively.</li>\n</ul>\n"
},
{
"answer_id": 73969,
"author": "Thomee",
"author_id": 12825,
"author_profile": "https://Stackoverflow.com/users/12825",
"pm_score": 9,
"selected": true,
"text": "<p>grep probably isn't the tool you want for this. It will print a line for every matching line in every file. Unless you want to, say, run todos 10 times on a 10 line file, grep isn't the best way to go about it. Using find to run file on every file in the tree then grepping through that for \"CRLF\" will get you one line of output for each file which has dos style line endings:</p>\n\n<pre><code>find . -not -type d -exec file \"{}\" \";\" | grep CRLF</code></pre>\n\n<p>will get you something like:</p>\n\n<pre><code>./1/dos1.txt: ASCII text, with CRLF line terminators\n./2/dos2.txt: ASCII text, with CRLF line terminators\n./dos.txt: ASCII text, with CRLF line terminators</code></pre>\n"
},
{
"answer_id": 74739,
"author": "Linulin",
"author_id": 12481,
"author_profile": "https://Stackoverflow.com/users/12481",
"pm_score": 4,
"selected": false,
"text": "<p>If your version of grep supports <strong>-P (--perl-regexp)</strong> option, then</p>\n\n<pre><code>grep -lUP '\\r$'\n</code></pre>\n\n<p>could be used.</p>\n"
},
{
"answer_id": 3184434,
"author": "yabt",
"author_id": 384287,
"author_profile": "https://Stackoverflow.com/users/384287",
"pm_score": 4,
"selected": false,
"text": "<pre><code># list files containing dos line endings (CRLF)\n\ncr=\"$(printf \"\\r\")\" # alternative to ctrl-V ctrl-M\n\ngrep -Ilsr \"${cr}$\" . \n\ngrep -Ilsr $'\\r$' . # yet another & even shorter alternative\n</code></pre>\n"
},
{
"answer_id": 3773573,
"author": "Peter Y",
"author_id": 455551,
"author_profile": "https://Stackoverflow.com/users/455551",
"pm_score": 2,
"selected": false,
"text": "<p>The query was search... I have a similar issue... somebody submitted mixed line\nendings into the version control, so now we have a bunch of files with <code>0x0d</code>\n<code>0x0d</code> <code>0x0a</code> line endings. Note that</p>\n\n<pre><code>grep -P '\\x0d\\x0a'\n</code></pre>\n\n<p>finds all lines, whereas</p>\n\n<pre><code>grep -P '\\x0d\\x0d\\x0a'\n</code></pre>\n\n<p>and</p>\n\n<pre><code>grep -P '\\x0d\\x0d'\n</code></pre>\n\n<p>finds no lines so there may be something \"else\" going on inside grep\nwhen it comes to line ending patterns... unfortunately for me!</p>\n"
},
{
"answer_id": 7715813,
"author": "MykennaC",
"author_id": 30818,
"author_profile": "https://Stackoverflow.com/users/30818",
"pm_score": 1,
"selected": false,
"text": "<p>If, like me, your minimalist unix doesn't include niceties like the <strong>file</strong> command, and backslashes in your <strong>grep</strong> expressions just don't cooperate, try this:</p>\n\n<pre><code>$ for file in `find . -type f` ; do\n> dump $file | cut -c9-50 | egrep -m1 -q ' 0d| 0d'\n> if [ $? -eq 0 ] ; then echo $file ; fi\n> done\n</code></pre>\n\n<p>Modifications you may want to make to the above include:</p>\n\n<ul>\n<li>tweak the <strong>find</strong> command to locate only the files you want to scan</li>\n<li>change the <strong>dump</strong> command to <strong>od</strong> or whatever file dump utility you have</li>\n<li>confirm that the <strong>cut</strong> command includes both a leading and trailing space as well as just the hexadecimal character output from the <strong>dump</strong> utility</li>\n<li>limit the <strong>dump</strong> output to the first 1000 characters or so for efficiency</li>\n</ul>\n\n<p>For example, something like this may work for you using <strong>od</strong> instead of <strong>dump</strong>:</p>\n\n<pre><code> od -t x2 -N 1000 $file | cut -c8- | egrep -m1 -q ' 0d| 0d|0d$'\n</code></pre>\n"
},
{
"answer_id": 13643222,
"author": "Zombo",
"author_id": 1002260,
"author_profile": "https://Stackoverflow.com/users/1002260",
"pm_score": 6,
"selected": false,
"text": "<p>Using RipGrep (depending on your shell, you might need to quote the last argument):</p>\n<pre><code>rg -l \\r\n</code></pre>\n<pre><code>-l, --files-with-matches\nOnly print the paths with at least one match.\n</code></pre>\n<p><a href=\"https://github.com/BurntSushi/ripgrep\" rel=\"nofollow noreferrer\">https://github.com/BurntSushi/ripgrep</a></p>\n"
},
{
"answer_id": 47165349,
"author": "Murali Krishna Parimi",
"author_id": 5943385,
"author_profile": "https://Stackoverflow.com/users/5943385",
"pm_score": 2,
"selected": false,
"text": "<p>You can use file command in unix. It gives you the character encoding of the file along with line terminators.</p>\n\n<pre><code>$ file myfile\nmyfile: ISO-8859 text, with CRLF line terminators\n$ file myfile | grep -ow CRLF\nCRLF \n</code></pre>\n"
},
{
"answer_id": 61631159,
"author": "dessert",
"author_id": 6164712,
"author_profile": "https://Stackoverflow.com/users/6164712",
"pm_score": 2,
"selected": false,
"text": "<p><code>dos2unix</code> has a file information option which can be used to show the files that would be converted:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>dos2unix -ic /path/to/file\n</code></pre>\n<p>To do that recursively you can use <code>bash</code>’s <code>globstar</code> option, which for the current shell is enabled with <code>shopt -s globstar</code>:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>dos2unix -ic ** # all files recursively\ndos2unix -ic **/file # files called “file” recursively\n</code></pre>\n<p>Alternatively you can use <code>find</code> for that:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>find -type f -exec dos2unix -ic {} + # all files recursively (ignoring directories)\nfind -name file -exec dos2unix -ic {} + # files called “file” recursively\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10245/"
]
| I want to search for files containing DOS line endings with grep on Linux. Something like this:
```sh
grep -IUr --color '\r\n' .
```
The above seems to match for literal `rn` which is not what is desired.
The output of this will be piped through xargs into todos to convert crlf to lf like this
```
grep -IUrl --color '^M' . | xargs -ifile fromdos 'file'
``` | grep probably isn't the tool you want for this. It will print a line for every matching line in every file. Unless you want to, say, run todos 10 times on a 10 line file, grep isn't the best way to go about it. Using find to run file on every file in the tree then grepping through that for "CRLF" will get you one line of output for each file which has dos style line endings:
```
find . -not -type d -exec file "{}" ";" | grep CRLF
```
will get you something like:
```
./1/dos1.txt: ASCII text, with CRLF line terminators
./2/dos2.txt: ASCII text, with CRLF line terminators
./dos.txt: ASCII text, with CRLF line terminators
``` |
73,885 | <p>How can I construct my ajaxSend call, this seems like the place to put it, to preview what is being passed back to the broker? also, can I stop the ajax call in ajaxSend?..so I can perfect my url string before dealing with errors from the broker?</p>
<p>This is the complete URL that, when passed to the broker, will return the JSON code I need:</p>
<pre><code>http://myServer/cgi-bin/broker?service=myService&program=myProgram&section=mySection&start=09/08/08&end=09/26/08
</code></pre>
<p>This is my $.post call (not sure it is creating the above url string)</p>
<pre><code>$(function() {
$("#submit").bind("click",
function() {
$.post({
url: "http://csewebprod/cgi-bin/broker" ,
datatype: "json",
data: {
'service' : myService,
'program' : myProgram,
'section' : mySection,
'start' : '09/08/08',
'end' : '09/26/08'
},
error: function(request){
$("#updateHTML").removeClass("hide") ;
$("#updateHTML").html(request.statusText);
},
success: function(request) {
$("#updateHTML").removeClass("hide") ;
$("#updateHTML").html(request) ;
}
}); // End post method
}); // End bind method
}); // End eventlistener
</code></pre>
<p>Thanks</p>
| [
{
"answer_id": 73916,
"author": "moswald",
"author_id": 8368,
"author_profile": "https://Stackoverflow.com/users/8368",
"pm_score": 3,
"selected": true,
"text": "<p>As far as I know, the only way to do that is to enter something (anything) on that line, then delete it. Or hit space and you'll never see it there until you return to that line.</p>\n\n<p>Once VS determines that you've edited a line of text, it won't automatically modify it for you (at least, not in that way that you've described).</p>\n"
},
{
"answer_id": 17349403,
"author": "John Smith",
"author_id": 2411533,
"author_profile": "https://Stackoverflow.com/users/2411533",
"pm_score": 1,
"selected": false,
"text": "<p>This is an annoyance to myself as well. Anytime the code is reformatted the blank lines are de-tabbed.\nYou might look at this: <a href=\"http://visualstudiogallery.msdn.microsoft.com/ac4d4d6b-b017-4a42-8f72-55f0ffe850d7\" rel=\"nofollow\">http://visualstudiogallery.msdn.microsoft.com/ac4d4d6b-b017-4a42-8f72-55f0ffe850d7</a> it's not exactly a solution but a step in the right direction</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
]
| How can I construct my ajaxSend call, this seems like the place to put it, to preview what is being passed back to the broker? also, can I stop the ajax call in ajaxSend?..so I can perfect my url string before dealing with errors from the broker?
This is the complete URL that, when passed to the broker, will return the JSON code I need:
```
http://myServer/cgi-bin/broker?service=myService&program=myProgram§ion=mySection&start=09/08/08&end=09/26/08
```
This is my $.post call (not sure it is creating the above url string)
```
$(function() {
$("#submit").bind("click",
function() {
$.post({
url: "http://csewebprod/cgi-bin/broker" ,
datatype: "json",
data: {
'service' : myService,
'program' : myProgram,
'section' : mySection,
'start' : '09/08/08',
'end' : '09/26/08'
},
error: function(request){
$("#updateHTML").removeClass("hide") ;
$("#updateHTML").html(request.statusText);
},
success: function(request) {
$("#updateHTML").removeClass("hide") ;
$("#updateHTML").html(request) ;
}
}); // End post method
}); // End bind method
}); // End eventlistener
```
Thanks | As far as I know, the only way to do that is to enter something (anything) on that line, then delete it. Or hit space and you'll never see it there until you return to that line.
Once VS determines that you've edited a line of text, it won't automatically modify it for you (at least, not in that way that you've described). |
73,892 | <p>How can I <strong>pre pend</strong> (insert at beginning of file) a file to all files of a type in folder and sub-folders using <code>Powershell</code>?</p>
<p>I need to add a standard header file to all <code>.cs</code> and was trying to use <code>Powershell</code> to do so, but while I was able to append it in a few lines of code I was stuck when trying to <strong>pre-pend</strong> it.</p>
| [
{
"answer_id": 74035,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 1,
"selected": false,
"text": "<p>Have no idea, but if you have the code to append just do it the other way round. Something like</p>\n\n<ol>\n<li>rename existing file,</li>\n<li>create an empty file named the same as above </li>\n<li>append header to new empty file,</li>\n<li>append renamed file to previous,</li>\n<li>delete renamed file</li>\n</ol>\n"
},
{
"answer_id": 74072,
"author": "Vhaerun",
"author_id": 11234,
"author_profile": "https://Stackoverflow.com/users/11234",
"pm_score": 1,
"selected": false,
"text": "<p>Algorithmically talking , you don't really need a temporary file :</p>\n\n<p>1)read the content of the file you need to modify</p>\n\n<p>2)modify the content ( as a string , assuming you have the content in a variable named content ) , like this : content = header + content</p>\n\n<p>3)seek to the beginning of the file , each language has a seek method or a seek equivalent</p>\n\n<p>4)write the new content</p>\n\n<p>5)truncate the file at the position returned by the file pointer</p>\n\n<p>There you have it,no temporary file. :)</p>\n"
},
{
"answer_id": 74073,
"author": "Mark Schill",
"author_id": 9482,
"author_profile": "https://Stackoverflow.com/users/9482",
"pm_score": 4,
"selected": true,
"text": "<p>Here is a very simple example to show you one of the ways it could be done.</p>\n\n<pre><code>$Content = \"This is your content`n\"\nGet-ChildItem *.cs | foreach-object { \n$FileContents = Get-Content -Path $_\nSet-Content -Path $_ -Value ($Content + $FileContents)\n}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11673/"
]
| How can I **pre pend** (insert at beginning of file) a file to all files of a type in folder and sub-folders using `Powershell`?
I need to add a standard header file to all `.cs` and was trying to use `Powershell` to do so, but while I was able to append it in a few lines of code I was stuck when trying to **pre-pend** it. | Here is a very simple example to show you one of the ways it could be done.
```
$Content = "This is your content`n"
Get-ChildItem *.cs | foreach-object {
$FileContents = Get-Content -Path $_
Set-Content -Path $_ -Value ($Content + $FileContents)
}
``` |
73,930 | <p>What do I need to add to my <code>.spec</code> file to create the desktop shortcut and assign an icon to the shortcut during install of my <code>.rpm</code>? If a script is required, an example would be very helpful.</p>
| [
{
"answer_id": 74003,
"author": "akdom",
"author_id": 145,
"author_profile": "https://Stackoverflow.com/users/145",
"pm_score": 3,
"selected": false,
"text": "<p>You use a .desktop file for icons under linux. Where to put the icon depends on what distribution and what desktop environment you are using. Since I'm currently running Gnome on Fedora 9, I will answer it in those terms.</p>\n<p>An example foo.desktop file would be:</p>\n<pre><code>[Desktop Entry]\nEncoding=UTF-8\nGenericName=Generic Piece Of Software\nName=FooBar\nExec=/usr/bin/foo.sh\nIcon=foo.png\nTerminal=false\nType=Application\nCategories=Qt;Gnome;Applications;\n</code></pre>\n<p>The .desktop file should under Fedora 9 Gnome be located in /usr/share/applications/ , you can run a locate on .desktop to figure out where you should put in on your distro. Gnome will generally look in the KDE icon directory to see if there are other icons there also....</p>\n<blockquote>\n<p>Encoding, Name and Exec should speak for themselves.</p>\n<ul>\n<li>Generic name == Brief Description of application.</li>\n<li>Icon == The image to display for the icon</li>\n<li>Terminal == Is this a terminal application, should I start it as one?</li>\n<li>Type == Type of program this is, can be used in placing the icon in a menu.</li>\n<li>Categories == This information is what is mainly used to place the icon in a given menu if an XML file to specify such is not present. The setup for menus is handled a little differently by everyone.</li>\n</ul>\n</blockquote>\n<p>There are more attributes you can set, but they aren't strictly necessary.</p>\n<p>The image file used sits somewhere in the bowels of the /usr/share/icons/ directory. You can parse through that to find all the wonders of how such things work, but the basics are that you pick the directory for the icon type (in my case gnome) and place the image within the appropriate directory (there is a scalable directory for .svg images, and specific sizes such as 48x48 for raster images. Under Gnome all images are generally .png).</p>\n"
},
{
"answer_id": 75904,
"author": "SpoonMeiser",
"author_id": 1577190,
"author_profile": "https://Stackoverflow.com/users/1577190",
"pm_score": 2,
"selected": false,
"text": "<p>akdom has given a fairly good answer, but doesn't do its relevance justice.</p>\n\n<p>Many common desktops, including Gnome, KDE and XFCE where relevant, implement the specifications laid out by <a href=\"http://www.freedesktop.org/\" rel=\"nofollow noreferrer\">freedesktop.org</a>. Among these, is the <a href=\"http://standards.freedesktop.org/desktop-entry-spec/latest/\" rel=\"nofollow noreferrer\">Desktop Entry Specification</a> which describes the format of files that define desktop icons, and <a href=\"http://standards.freedesktop.org/basedir-spec/latest/\" rel=\"nofollow noreferrer\">Desktop Base Directory Specification</a> that describes the locations that desktop environments should look to find these files.</p>\n\n<p>Your RPM needs to include a .desktop file, as specified by the <a href=\"http://standards.freedesktop.org/desktop-entry-spec/latest/\" rel=\"nofollow noreferrer\">Desktop Entry Specification</a>, and install it in the correct location as specified either by the <a href=\"http://standards.freedesktop.org/basedir-spec/latest/\" rel=\"nofollow noreferrer\">Desktop Base Directory Specification</a>, or in a distribution specific location (I imagine there will be aliases to use in the spec file for this location).</p>\n"
},
{
"answer_id": 36131913,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>To create a desktop icon to an application follow the two steps below.</p>\n\n<ol>\n<li><p>In an Editor create a new file.</p>\n\n<pre><code>gedit ~/.local/share/applications/NameYouWantForApplication.desktop\n</code></pre></li>\n<li><p>Place this section within the file and save it.</p>\n\n<pre><code>[Desktop Entry]\nType=Application\nEncoding=UTF-8\nName=JeremysPentaho\nComment=Whatever Comment You want\nExec=/home/[email protected]/Source/Pentaho/data-integration/spoon.sh\nIcon=/home/[email protected]/Source/Pentaho/data-integration/NameOfmyIconFile.jpg\nTerminal=false\n</code></pre></li>\n</ol>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| What do I need to add to my `.spec` file to create the desktop shortcut and assign an icon to the shortcut during install of my `.rpm`? If a script is required, an example would be very helpful. | You use a .desktop file for icons under linux. Where to put the icon depends on what distribution and what desktop environment you are using. Since I'm currently running Gnome on Fedora 9, I will answer it in those terms.
An example foo.desktop file would be:
```
[Desktop Entry]
Encoding=UTF-8
GenericName=Generic Piece Of Software
Name=FooBar
Exec=/usr/bin/foo.sh
Icon=foo.png
Terminal=false
Type=Application
Categories=Qt;Gnome;Applications;
```
The .desktop file should under Fedora 9 Gnome be located in /usr/share/applications/ , you can run a locate on .desktop to figure out where you should put in on your distro. Gnome will generally look in the KDE icon directory to see if there are other icons there also....
>
> Encoding, Name and Exec should speak for themselves.
>
>
> * Generic name == Brief Description of application.
> * Icon == The image to display for the icon
> * Terminal == Is this a terminal application, should I start it as one?
> * Type == Type of program this is, can be used in placing the icon in a menu.
> * Categories == This information is what is mainly used to place the icon in a given menu if an XML file to specify such is not present. The setup for menus is handled a little differently by everyone.
>
>
>
There are more attributes you can set, but they aren't strictly necessary.
The image file used sits somewhere in the bowels of the /usr/share/icons/ directory. You can parse through that to find all the wonders of how such things work, but the basics are that you pick the directory for the icon type (in my case gnome) and place the image within the appropriate directory (there is a scalable directory for .svg images, and specific sizes such as 48x48 for raster images. Under Gnome all images are generally .png). |
73,947 | <p>I'm talking about an action game with no upper score limit and no way to verify the score on the server by replaying moves etc. </p>
<p>What I really need is the strongest encryption possible in Flash/PHP, and a way to prevent people calling the PHP page other than through my Flash file. I have tried some simple methods in the past of making multiple calls for a single score and completing a checksum / fibonacci sequence etc, and also obfuscating the SWF with Amayeta SWF Encrypt, but they were all hacked eventually.</p>
<p>Thanks to StackOverflow responses I have now found some more info from Adobe - <a href="http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps_12.html" rel="noreferrer">http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps_12.html</a> and <a href="https://github.com/mikechambers/as3corelib" rel="noreferrer">https://github.com/mikechambers/as3corelib</a> - which I think I can use for the encryption. Not sure this will get me around CheatEngine though.</p>
<p>I need to know the best solutions for both AS2 and AS3, if they are different.</p>
<p>The main problems seem to be things like TamperData and LiveHTTP headers, but I understand there are more advanced hacking tools as well - like CheatEngine (thanks Mark Webster)</p>
| [
{
"answer_id": 74043,
"author": "Stephen Deken",
"author_id": 7154,
"author_profile": "https://Stackoverflow.com/users/7154",
"pm_score": 5,
"selected": false,
"text": "<p>You may be asking the wrong question. You seem focused on the methods people are using to game their way up the high score list, but blocking specific methods only goes so far. I have no experience with TamperData, so I can't speak to that.</p>\n\n<p>The question you should be asking is: \"How can I verify that submitted scores are valid and authentic?\" The specific way to do that is game-dependent. For very simple puzzle games, you might send over the score along with the specific starting state and the sequence of moves that resulted in the end state, and then re-run the game on the server side using the same moves. Confirm that the stated score is the same as the computed score and only accept the score if they match.</p>\n"
},
{
"answer_id": 74063,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 2,
"selected": false,
"text": "<p>Encrypting using a known (private) reversible key would be the simplest method. I'm not all up on AS so I'm not sure what sorts of encryption providers there are.</p>\n\n<p>But you could include variables like game-length (encrypted, again) and a click count.</p>\n\n<p>All things like this <em>can</em> be reverse engineered so consider throwing in a bunch of junk data to throw people off the scent.</p>\n\n<p>Edit: It might be worth chucking in some PHP sessions too. Start the session when they click start game and (as the comment to this post says) log the time. When they submit the score you can check they've actually got an open game and they're not submitting a score too soon or too large.</p>\n\n<p>It might be worth working out a scalar to see say what the maximum score is per second/minute of play.</p>\n\n<p>Neither of these things are uncircumventable but it'll help to have some logic not in the Flash where people can see it.</p>\n"
},
{
"answer_id": 74069,
"author": "Jan Krüger",
"author_id": 12471,
"author_profile": "https://Stackoverflow.com/users/12471",
"pm_score": 1,
"selected": false,
"text": "<p>Whenever your highscore system is based on the fact that the Flash application sends unencrpyted/unsigned highscore data via the network, that can be intercepted and manipulated/replayed. The answer follows from that: encrypt (decently!) or cryptographically sign highscore data. This, at least, makes it harder for people to crack your highscore system because they'll need to extract the secret key from your SWF file. Many people will probably give up right there. On the other hand, all it takes is a singly person to extract the key and post it somewhere.</p>\n\n<p>Real solutions involve more communication between the Flash application and the highscore database so that the latter can verify that a given score is somewhat realistic. This is probably complicated depending on what kind of game you've got.</p>\n"
},
{
"answer_id": 74128,
"author": "David Arno",
"author_id": 7122,
"author_profile": "https://Stackoverflow.com/users/7122",
"pm_score": 2,
"selected": false,
"text": "<p>There is no way to make it completely unhackable, as it is easy to decompile SWFs, and a skilled developer hacker could then trace through your code and work out how to bypass any encrypted system you might employ.</p>\n\n<p>If you simply want to stop kids cheating via the use of simple tools like TamperData though, then you could generate an encryption key that you pass to the SWF at startup. Then use something like <a href=\"http://code.google.com/p/as3crypto/\" rel=\"nofollow noreferrer\">http://code.google.com/p/as3crypto/</a> to encrypt the high score before passing it back to the PHP code. Then decrypt it at the server end before storing it in the database.</p>\n"
},
{
"answer_id": 74242,
"author": "Mark Webster",
"author_id": 7068,
"author_profile": "https://Stackoverflow.com/users/7068",
"pm_score": 1,
"selected": false,
"text": "<p>It's not really possible to achieve what you want. The internals of the Flash app are always partially accessible, especially when you know how to use things like <a href=\"http://www.cheatengine.org/\" rel=\"nofollow noreferrer\">CheatEngine</a>, meaning no matter how secure your website and browser<->server communications are, it is still going to be relatively simple to overcome.</p>\n"
},
{
"answer_id": 74448,
"author": "stormlash",
"author_id": 12657,
"author_profile": "https://Stackoverflow.com/users/12657",
"pm_score": 4,
"selected": false,
"text": "<p>An easy way to do this would be to provide a cryptographic hash of your highscore value along with the score it self. For example, when posting the results via HTTP GET:\n<strong><a href=\"http://example.com/highscores.php?score=500&checksum=0a16df3dc0301a36a34f9065c3ff8095\" rel=\"noreferrer\">http://example.com/highscores.php?score=500&checksum=0a16df3dc0301a36a34f9065c3ff8095</a></strong></p>\n\n<p>When calculating this checksum, a shared secret should be used; this secret should never be transmitted over the network, but should be hard coded within both the PHP backend and the flash frontend. The checksum above was created by prepending the string \"<strong>secret</strong>\" to the score \"<strong>500</strong>\", and running it through md5sum.</p>\n\n<p>Although this system will prevent a user from posting arbitrary scores, it does not prevent a \"replay attack\", where a user reposts a previously calculated score and hash combination. In the example above, a score of 500 would always produce the same hash string. Some of this risk can be mitigated by incorporating more information (such as a username, timestamp, or IP address) in the string which is to be hashed. Although this will not prevent the replay of data, it will insure that a set of data is only valid for a single user at a single time.</p>\n\n<p>To prevent <strong>any</strong> replay attacks from occurring, some type of challenge-response system will have to be created, such as the following:</p>\n\n<ol>\n<li>The flash game (\"the client\") performs an HTTP GET of <strong><a href=\"http://example.com/highscores.php\" rel=\"noreferrer\">http://example.com/highscores.php</a></strong> with no parameters. This page returns two values: a randomly generated <em>salt</em> value, and a cryptographic hash of that salt value combined with the shared secret. This salt value should be stored in a local database of pending queries, and should have a timestamp associated with it so that it can \"expire\" after perhaps one minute.</li>\n<li>The flash game combines the salt value with the shared secret and calculates a hash to verify that this matches the one provided by the server. This step is necessary to prevent tampering with salt values by users, as it verifies that the salt value was actually generated by the server.</li>\n<li>The flash game combines the salt value with the shared secret, high score value, and any other relevant information (nickname, ip, timestamp), and calculates a hash. It then sends this information back to the PHP backend via HTTP GET or POST, along with the salt value, high score, and other information.</li>\n<li>The server combines the information received in the same way as on the client, and calculates a hash to verify that this matches the one provided by the client. It then also verifies that the salt value is still valid as listed in the pending query list. If both these conditions are true, it writes the high score to the high score table and returns a signed \"success\" message to the client. It also removes the salt value from the pending query list.</li>\n</ol>\n\n<p><strong>Please keep in mind that the security of any of the above techniques is compromised if the shared secret is ever accessible to the user</strong></p>\n\n<p>As an alternative, some of this back-and-forth could be avoided by forcing the client to communicate with the server over HTTPS, and insuring that the client is preconfigured to trust only certificates signed by a specific certificate authority which you alone have access to.</p>\n"
},
{
"answer_id": 74505,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 2,
"selected": false,
"text": "<p>You are talking about what is called the \"client trust\" problem. Because the client (in this cash, a SWF running in a browser) is doing something it's designed to do. Save a high score.</p>\n\n<p>The problem is that you want to make sure that \"save score\" requests are coming from your flash movie, and not some arbitrary HTTP request. A possible solution for this is to encode a token generated by the server into the SWF at the time of request (using <a href=\"http://flasm.sourceforge.net/\" rel=\"nofollow noreferrer\">flasm</a>) that must accompany the request to save a high score. Once the server saves that score, the token is expired and can no longer be used for requests.</p>\n\n<p>The downside of this is that a user will only be able to submit one high score per load of the flash movie - you've have to force them to refresh/reload the SWF before they can play again for a new score.</p>\n"
},
{
"answer_id": 74841,
"author": "tqbf",
"author_id": 5674,
"author_profile": "https://Stackoverflow.com/users/5674",
"pm_score": 10,
"selected": true,
"text": "<p>This is a classic problem with Internet games and contests. Your Flash code works with users to decide a score for a game. But users aren't trusted, and the Flash code runs on the user's computer. You're SOL. There is nothing you can do to prevent an attacker from forging high scores:</p>\n\n<ul>\n<li><p>Flash is even easier to reverse engineer than you might think it is, since the bytecodes are well documented and describe a high-level language (Actionscript) --- when you publish a Flash game, you're publishing your source code, whether you know it or not.</p></li>\n<li><p>Attackers control the runtime memory of the Flash interpreter, so that anyone who knows how to use a programmable debugger can alter any variable (including the current score) at any time, or alter the program itself.</p></li>\n</ul>\n\n<p>The simplest possible attack against your system is to run the HTTP traffic for the game through a proxy, catch the high-score save, and replay it with a higher score.</p>\n\n<p>You can try to block this attack by binding each high score save to a single instance of the game, for instance by sending an encrypted token to the client at game startup, which might look like:</p>\n\n<pre><code>hex-encoding( AES(secret-key-stored-only-on-server, timestamp, user-id, random-number))\n</code></pre>\n\n<p>(You could also use a session cookie to the same effect).</p>\n\n<p>The game code echoes this token back to the server with the high-score save. But an attacker can still just launch the game again, get a token, and then immediately paste that token into a replayed high-score save. </p>\n\n<p>So next you feed not only a token or session cookie, but also a high-score-encrypting session key. This will be a 128 bit AES key, itself encrypted with a key hardcoded into the Flash game:</p>\n\n<pre><code>hex-encoding( AES(key-hardcoded-in-flash-game, random-128-bit-key))\n</code></pre>\n\n<p>Now before the game posts the high score, it decrypts the high-score-encrypting-session key, which it can do because you hardcoded the high-score-encrypting-session-key-decrypting-key into the Flash binary. You encrypt the high score with this decrypted key, along with the SHA1 hash of the high score:</p>\n\n<pre><code>hex-encoding( AES(random-128-bit-key-from-above, high-score, SHA1(high-score)))\n</code></pre>\n\n<p>The PHP code on the server checks the token to make sure the request came from a valid game instance, then decrypts the encrypted high score, checking to make sure the high-score matches the SHA1 of the high-score (if you skip this step, decryption will simply produce random, likely very high, high scores). </p>\n\n<p>So now the attacker decompiles your Flash code and quickly finds the AES code, which sticks out like a sore thumb, although even if it didn't it'd be tracked down in 15 minutes with a memory search and a tracer (\"I know my score for this game is 666, so let's find 666 in memory, then catch any operation that touches that value --- oh look, the high score encryption code!\"). With the session key, the attacker doesn't even have to run the Flash code; she grabs a game launch token and a session key and can send back an arbitrary high score.</p>\n\n<p>You're now at the point where most developers just give up --- give or take a couple months of messing with attackers by:</p>\n\n<ul>\n<li><p>Scrambling the AES keys with XOR operations</p></li>\n<li><p>Replacing key byte arrays with functions that calculate the key</p></li>\n<li><p>Scattering fake key encryptions and high score postings throughout the binary.</p></li>\n</ul>\n\n<p>This is all mostly a waste of time. It goes without saying, SSL isn't going to help you either; SSL can't protect you when one of the two SSL endpoints is evil.</p>\n\n<p>Here are some things that can actually reduce high score fraud:</p>\n\n<ul>\n<li><p>Require a login to play the game, have the login produce a session cookie, and don't allow multiple outstanding game launches on the same session, or multiple concurrent sessions for the same user.</p></li>\n<li><p>Reject high scores from game sessions that last less than the shortest real games ever played (for a more sophisticated approach, try \"quarantining\" high scores for game sessions that last less than 2 standard deviations below the mean game duration). Make sure you're tracking game durations serverside.</p></li>\n<li><p>Reject or quarantine high scores from logins that have only played the game once or twice, so that attackers have to produce a \"paper trail\" of reasonable looking game play for each login they create.</p></li>\n<li><p>\"Heartbeat\" scores during game play, so that your server sees the score growth over the lifetime of one game play. Reject high scores that don't follow reasonable score curves (for instance, jumping from 0 to 999999). </p></li>\n<li><p>\"Snapshot\" game state during game play (for instance, amount of ammunition, position in the level, etc), which you can later reconcile against recorded interim scores. You don't even have to have a way to detect anomalies in this data to start with; you just have to collect it, and then you can go back and analyze it if things look fishy.</p></li>\n<li><p>Disable the account of any user who fails one of your security checks (for instance, by ever submitting an encrypted high score that fails validation). </p></li>\n</ul>\n\n<p>Remember though that you're only deterring high score fraud here. There's <em>nothing</em> you can do to prevent if. If there's money on the line in your game, someone is going to defeat any system you come up with. The objective isn't to <em>stop</em> this attack; it's to make the attack more expensive than just getting really good at the game and beating it.</p>\n"
},
{
"answer_id": 79423,
"author": "DGM",
"author_id": 14253,
"author_profile": "https://Stackoverflow.com/users/14253",
"pm_score": 4,
"selected": false,
"text": "<p>I like what tpqf said, but rather than disabling an account when cheating is discovered, implement a honeypot so whenever they log in, they see their hacked scores and never suspect that they have been marked as a troll. Google for \"phpBB MOD Troll\" and you'll see an ingenious approach.</p>\n"
},
{
"answer_id": 413336,
"author": "Lucas Meijer",
"author_id": 47901,
"author_profile": "https://Stackoverflow.com/users/47901",
"pm_score": 2,
"selected": false,
"text": "<p>I usually include \"ghost data\" of the game session with the highscore entry. So if I'm making a racing game, I include the replay data. You often have the replay data already for replay functionality or ghost racing functionality (playing against your last race, or playing against the ghost of dude #14 on the leaderboard).</p>\n\n<p>Checking these is very manual labour, but if the goal is to verify if the top 10 entries in a contest are legit, this can be a useful addition to the arsenal of security measures others have pointed out already.</p>\n\n<p>If the goal is to keep highscores list online untill the end of time without anybody having to look at them, this won't bring you much.</p>\n"
},
{
"answer_id": 413794,
"author": "Scott Reynen",
"author_id": 10837,
"author_profile": "https://Stackoverflow.com/users/10837",
"pm_score": 2,
"selected": false,
"text": "<p>In my experience, this is best approached as a social engineering problem rather than a programming problem. Rather than focusing on making it impossible to cheat, focus on making it boring by removing the incentives to cheat. For example, if the main incentive is publicly visible high scores, simply putting a delay on when high scores are shown can significantly reduce cheating by removing the positive feedback loop for cheaters.</p>\n"
},
{
"answer_id": 2004006,
"author": "Vaughn",
"author_id": 243636,
"author_profile": "https://Stackoverflow.com/users/243636",
"pm_score": 2,
"selected": false,
"text": "<p>The way that a new popular arcade mod does it is that it sends data from the flash to php, back to flash (or reloads it), then back to php. This allows you to do anything you want to compare the data as well bypass post data/decryption hacks and the like. One way that it does this is by assigning 2 randomized values from php into the flash (which you cannot grab or see even if running a realtime flash data grabber), using a mathematical formula to add the score with the random values then checking it using the same formula to reverse it to see if the score matches it when it finally goes to the php at the end. These random values are never visible as well as it also times the transaction taking place and if it's any more than a couple seconds then it also flags it as cheating because it assumes you have stopped the send to try to figure out the randomized values or run the numbers through some type of cipher to return possible random values to compare with the score value.</p>\n\n<p>This seems like a pretty good solution if you ask me, does anybody see any issues with using this method? Or possible ways around it?</p>\n"
},
{
"answer_id": 7110508,
"author": "divillysausages",
"author_id": 639441,
"author_profile": "https://Stackoverflow.com/users/639441",
"pm_score": 2,
"selected": false,
"text": "<p>In the accepted answer tqbf mentions that you can just do a memory search for the score variable (\"My score is 666 so I look for the number 666 in memory\").</p>\n\n<p>There's a way around this. I have a class here: <a href=\"http://divillysausages.com/blog/safenumber_and_safeint\" rel=\"nofollow\">http://divillysausages.com/blog/safenumber_and_safeint</a></p>\n\n<p>Basically, you have an object to store your score. In the setter it multiplies the value that you pass it with a random number (+ and -), and in the getter you divide the saved value by the random multiplicator to get the original back. It's simple, but helps stop memory search.</p>\n\n<p>Also, check out the video from some of the guys behind the PushButton engine who talk about some of the different ways you can combat hacking: <a href=\"http://zaa.tv/2010/12/the-art-of-hacking-flash-games/\" rel=\"nofollow\">http://zaa.tv/2010/12/the-art-of-hacking-flash-games/</a>. They were the inspiration behind the class.</p>\n"
},
{
"answer_id": 8915028,
"author": "mathieu landry",
"author_id": 1062353,
"author_profile": "https://Stackoverflow.com/users/1062353",
"pm_score": 1,
"selected": false,
"text": "<p>I think the simplest way would be to make calls to a function like RegisterScore(score) each time the game registers a score to be added and then encode it, package it and send it to a php script as a string. The php script would know how to decode it properly. This would stop any calls straight to the php script as any tries to force a score would result in a decompression error.</p>\n"
},
{
"answer_id": 9590507,
"author": "hurturk",
"author_id": 1233686,
"author_profile": "https://Stackoverflow.com/users/1233686",
"pm_score": 2,
"selected": false,
"text": "<p>It is only possible by keeping the <strong>all game logic at server-side</strong> which also stores the score internally without knowledge of the user. For economical and scientific reasons, mankind can not apply this theory to all game types excluding turn-based. For e.g. keeping physics at server-side is computationally expensive and hard to get responsive as speed of hand. Even possible, while playing chess anyone can match AI chess gameplay to opponent. Therefore, better <strong>multiplayer games</strong> should also contain on-demand creativity.</p>\n"
},
{
"answer_id": 10725193,
"author": "zeller",
"author_id": 1413277,
"author_profile": "https://Stackoverflow.com/users/1413277",
"pm_score": 2,
"selected": false,
"text": "<p>You cannot trust any data the client returns. Validation needs to be performed on the server side. I'm not a game developer, but I do make business software. In both instances money can be involved and people will break client side obfuscation techniques.</p>\n\n<p>Maybe send data back to server periodically and do some validation. Don't focus on client code, even if that is where your applicaiton lives.</p>\n"
},
{
"answer_id": 17994553,
"author": "Chris Panayotoff",
"author_id": 1584898,
"author_profile": "https://Stackoverflow.com/users/1584898",
"pm_score": 2,
"selected": false,
"text": "<p>I made kind of workaround... I had a gave where scores incremented ( you always get +1 score ). First, I started to count from random num (let's say 14 ) and when I display the scores, just showed the scores var minus 14. This was so if the crackers are looking for example for 20, they won't find it ( it will be 34 in the memory ). Second, since I know what the next point should be... I used adobe crypto library, to create the hash of what the next point <strong>should be</strong>. When I have to increment the scores, I check if the hash of the incremented scores is equal to the hash is should be. If the cracker have changed the points in the memory, the hashes are not equal. I perform some server-side verification and when I got different points from game and from the PHP, I know that cheating were involved. Here is snippet ot my code ( I'm using Adobe Crypto libraty MD5 class and random cryptography salt. callPhp() is my server side validation )</p>\n\n<pre><code>private function addPoint(event:Event = null):void{\n trace(\"expectedHash: \" + expectedHash + \" || new hash: \" + MD5.hash( Number(SCORES + POINT).toString() + expectedHashSalt) );\n if(expectedHash == MD5.hash( Number(SCORES + POINT).toString() + expectedHashSalt)){\n SCORES +=POINT;\n callPhp();\n expectedHash = MD5.hash( Number(SCORES + POINT).toString() + expectedHashSalt);\n } else {\n //trace(\"cheat engine usage\");\n }\n }\n</code></pre>\n\n<p>Using this technique + SWF obfustication, I was able to stop the crackers. Also, when I'm sending the scores to the server-side, I use my own small, encryption / decryption function. Something like this (server side code not included, but you can see the algorithm and write it in PHP) :</p>\n\n<pre><code>package {\n\n import bassta.utils.Hash;\n\n public class ScoresEncoder {\n\n private static var ranChars:Array;\n private static var charsTable:Hash;\n\n public function ScoresEncoder() {\n\n }\n\n public static function init():void{\n\n ranChars = String(\"qwertyuiopasdfghjklzxcvbnm\").split(\"\")\n\n charsTable = new Hash({\n \"0\": \"x\",\n \"1\": \"f\",\n \"2\": \"q\",\n \"3\": \"z\",\n \"4\": \"a\",\n \"5\": \"o\",\n \"6\": \"n\",\n \"7\": \"p\",\n \"8\": \"w\",\n \"9\": \"y\"\n\n });\n\n }\n\n public static function encodeScore(_s:Number):String{\n\n var _fin:String = \"\";\n\n var scores:String = addLeadingZeros(_s);\n for(var i:uint = 0; i< scores.length; i++){\n //trace( scores.charAt(i) + \" - > \" + charsTable[ scores.charAt(i) ] );\n _fin += charsTable[ scores.charAt(i) ];\n }\n\n return _fin;\n\n }\n\n public static function decodeScore(_s:String):String{\n\n var _fin:String = \"\";\n\n var decoded:String = _s;\n\n for(var i:uint = 0; i< decoded.length; i++){\n //trace( decoded.charAt(i) + \" - > \" + charsTable.getKey( decoded.charAt(i) ) );\n _fin += charsTable.getKey( decoded.charAt(i) );\n }\n\n return _fin;\n\n }\n\n public static function encodeScoreRand(_s:Number):String{\n var _fin:String = \"\";\n\n _fin += generateRandomChars(10) + encodeScore(_s) + generateRandomChars(3)\n\n return _fin;\n }\n\n public static function decodeScoreRand(_s:String):Number{\n\n var decodedString:String = _s;\n var decoded:Number;\n\n decodedString = decodedString.substring(10,13); \n decodedString = decodeScore(decodedString);\n\n decoded = Number(decodedString);\n\n return decoded;\n }\n\n public static function generateRandomChars(_length:Number):String{\n\n var newRandChars:String = \"\";\n\n for(var i:uint = 0; i< _length; i++){\n newRandChars+= ranChars[ Math.ceil( Math.random()*ranChars.length-1 )];\n }\n\n return newRandChars;\n }\n\n private static function addLeadingZeros(_s:Number):String{\n\n var _fin:String;\n\n if(_s < 10 ){\n _fin = \"00\" + _s.toString();\n }\n\n if(_s >= 10 && _s < 99 ) {\n _fin = \"0\" + _s.toString();\n }\n\n if(_s >= 100 ) {\n _fin = _s.toString();\n } \n\n return _fin;\n }\n\n\n }//end\n}\n</code></pre>\n\n<p>Then I send the variable among with other fake-vars and it just get's lost among the way... It is a lot of work for just small flash game, but where prizes are involved some people just get greedy. If you need any help, write me a PM.</p>\n\n<p>Cheers, Ico</p>\n"
},
{
"answer_id": 23642533,
"author": "m1gu3l",
"author_id": 3243730,
"author_profile": "https://Stackoverflow.com/users/3243730",
"pm_score": 1,
"selected": false,
"text": "<p>It might be a good idea to communicate with backend via <a href=\"http://www.silexlabs.org/amfphp/\" rel=\"nofollow\">AMFPHP</a>. It should discourage at least the lazy ones from trying to push the results via browser console.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11911/"
]
| I'm talking about an action game with no upper score limit and no way to verify the score on the server by replaying moves etc.
What I really need is the strongest encryption possible in Flash/PHP, and a way to prevent people calling the PHP page other than through my Flash file. I have tried some simple methods in the past of making multiple calls for a single score and completing a checksum / fibonacci sequence etc, and also obfuscating the SWF with Amayeta SWF Encrypt, but they were all hacked eventually.
Thanks to StackOverflow responses I have now found some more info from Adobe - <http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps_12.html> and <https://github.com/mikechambers/as3corelib> - which I think I can use for the encryption. Not sure this will get me around CheatEngine though.
I need to know the best solutions for both AS2 and AS3, if they are different.
The main problems seem to be things like TamperData and LiveHTTP headers, but I understand there are more advanced hacking tools as well - like CheatEngine (thanks Mark Webster) | This is a classic problem with Internet games and contests. Your Flash code works with users to decide a score for a game. But users aren't trusted, and the Flash code runs on the user's computer. You're SOL. There is nothing you can do to prevent an attacker from forging high scores:
* Flash is even easier to reverse engineer than you might think it is, since the bytecodes are well documented and describe a high-level language (Actionscript) --- when you publish a Flash game, you're publishing your source code, whether you know it or not.
* Attackers control the runtime memory of the Flash interpreter, so that anyone who knows how to use a programmable debugger can alter any variable (including the current score) at any time, or alter the program itself.
The simplest possible attack against your system is to run the HTTP traffic for the game through a proxy, catch the high-score save, and replay it with a higher score.
You can try to block this attack by binding each high score save to a single instance of the game, for instance by sending an encrypted token to the client at game startup, which might look like:
```
hex-encoding( AES(secret-key-stored-only-on-server, timestamp, user-id, random-number))
```
(You could also use a session cookie to the same effect).
The game code echoes this token back to the server with the high-score save. But an attacker can still just launch the game again, get a token, and then immediately paste that token into a replayed high-score save.
So next you feed not only a token or session cookie, but also a high-score-encrypting session key. This will be a 128 bit AES key, itself encrypted with a key hardcoded into the Flash game:
```
hex-encoding( AES(key-hardcoded-in-flash-game, random-128-bit-key))
```
Now before the game posts the high score, it decrypts the high-score-encrypting-session key, which it can do because you hardcoded the high-score-encrypting-session-key-decrypting-key into the Flash binary. You encrypt the high score with this decrypted key, along with the SHA1 hash of the high score:
```
hex-encoding( AES(random-128-bit-key-from-above, high-score, SHA1(high-score)))
```
The PHP code on the server checks the token to make sure the request came from a valid game instance, then decrypts the encrypted high score, checking to make sure the high-score matches the SHA1 of the high-score (if you skip this step, decryption will simply produce random, likely very high, high scores).
So now the attacker decompiles your Flash code and quickly finds the AES code, which sticks out like a sore thumb, although even if it didn't it'd be tracked down in 15 minutes with a memory search and a tracer ("I know my score for this game is 666, so let's find 666 in memory, then catch any operation that touches that value --- oh look, the high score encryption code!"). With the session key, the attacker doesn't even have to run the Flash code; she grabs a game launch token and a session key and can send back an arbitrary high score.
You're now at the point where most developers just give up --- give or take a couple months of messing with attackers by:
* Scrambling the AES keys with XOR operations
* Replacing key byte arrays with functions that calculate the key
* Scattering fake key encryptions and high score postings throughout the binary.
This is all mostly a waste of time. It goes without saying, SSL isn't going to help you either; SSL can't protect you when one of the two SSL endpoints is evil.
Here are some things that can actually reduce high score fraud:
* Require a login to play the game, have the login produce a session cookie, and don't allow multiple outstanding game launches on the same session, or multiple concurrent sessions for the same user.
* Reject high scores from game sessions that last less than the shortest real games ever played (for a more sophisticated approach, try "quarantining" high scores for game sessions that last less than 2 standard deviations below the mean game duration). Make sure you're tracking game durations serverside.
* Reject or quarantine high scores from logins that have only played the game once or twice, so that attackers have to produce a "paper trail" of reasonable looking game play for each login they create.
* "Heartbeat" scores during game play, so that your server sees the score growth over the lifetime of one game play. Reject high scores that don't follow reasonable score curves (for instance, jumping from 0 to 999999).
* "Snapshot" game state during game play (for instance, amount of ammunition, position in the level, etc), which you can later reconcile against recorded interim scores. You don't even have to have a way to detect anomalies in this data to start with; you just have to collect it, and then you can go back and analyze it if things look fishy.
* Disable the account of any user who fails one of your security checks (for instance, by ever submitting an encrypted high score that fails validation).
Remember though that you're only deterring high score fraud here. There's *nothing* you can do to prevent if. If there's money on the line in your game, someone is going to defeat any system you come up with. The objective isn't to *stop* this attack; it's to make the attack more expensive than just getting really good at the game and beating it. |
73,958 | <p>In a shellscript, I'd like to set the IP of my box, run a command, then move to the next IP. The IPs are an entire C block.</p>
<p>The question is how do I set the IP of the box without editing a file? What command sets the IP on Slackware?</p>
<p>Thanks</p>
| [
{
"answer_id": 74039,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It should be something like: <code>ifconfig eth0 192.168.0.42 up</code></p>\n\n<p>Replace eth0 by the network interface of your network card, obviously adapt the ip address to your needs and the up is only necessary once, but doesn't hurt if you run it each time. </p>\n"
},
{
"answer_id": 74058,
"author": "tialaramex",
"author_id": 9654,
"author_profile": "https://Stackoverflow.com/users/9654",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know Slackware very well, I last used it over ten years ago. However, any mainstream Linux distribution should have either the 'ifconfig' program, or the 'ip' program or both. You will need to have root privilges, so either become root (e.g with su) or use the 'sudo' program if you know how. Let's do it with 'ip' first.</p>\n\n<pre><code>ip addr add 10.1.2.3 dev eth0\n</code></pre>\n\n<p>sets the device eth0 (usually the primary wired network adaptor) to have IP address 10.1.2.3. You can remove the address from this adaptor again when you're done with it...</p>\n\n<pre><code>ip addr del 10.1.2.3 dev eth0\n</code></pre>\n\n<p>ifconfig works a bit differently,</p>\n\n<pre><code>ifconfig eth0 10.1.2.3 netmask 255.255.255.0\n</code></pre>\n\n<p>again sets up device eth0, with IP address 10.1.2.3</p>\n\n<p>Depending on what you want these addresses for, you may also need to know how to set up a manual route, so that your IP packets actually get delivered wherever they're going.</p>\n"
},
{
"answer_id": 75221,
"author": "Thomee",
"author_id": 12825,
"author_profile": "https://Stackoverflow.com/users/12825",
"pm_score": 2,
"selected": false,
"text": "<p>As mentioned in other answers, you can use either the ifconfig command or the ip command. ip is a much more robust command, and I prefer to use it. A full script which loops through a full class C subnet adding the IP, doing stuff, then removing it follows. Note that it doesn't use .0 or .255, which are the network and broadcast addresses of the subnet. Also, when using the ip command to add or remove an address, it's good to include the mask width, as well (the /24 at the end of the address).</p>\n\n<pre><code>#!/bin/bash\nSUBNET=192.168.135.\nETH=eth0\n\nfor i in {1..254}\ndo\n ip addr add ${SUBNET}${i}/24 dev ${ETH}\n\n # do whatever you want here\n\n ip addr del ${SUBNET}${i}/24 dev ${ETH}\ndone</code></pre>\n"
},
{
"answer_id": 220745,
"author": "Eduardo",
"author_id": 9823,
"author_profile": "https://Stackoverflow.com/users/9823",
"pm_score": 0,
"selected": false,
"text": "<p>In one line, e.g.: ifconfig eth0 192.168.10.12 netmask 255.255.255.0</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| In a shellscript, I'd like to set the IP of my box, run a command, then move to the next IP. The IPs are an entire C block.
The question is how do I set the IP of the box without editing a file? What command sets the IP on Slackware?
Thanks | As mentioned in other answers, you can use either the ifconfig command or the ip command. ip is a much more robust command, and I prefer to use it. A full script which loops through a full class C subnet adding the IP, doing stuff, then removing it follows. Note that it doesn't use .0 or .255, which are the network and broadcast addresses of the subnet. Also, when using the ip command to add or remove an address, it's good to include the mask width, as well (the /24 at the end of the address).
```
#!/bin/bash
SUBNET=192.168.135.
ETH=eth0
for i in {1..254}
do
ip addr add ${SUBNET}${i}/24 dev ${ETH}
# do whatever you want here
ip addr del ${SUBNET}${i}/24 dev ${ETH}
done
``` |
73,960 | <p>In IE, the dropdown-list takes the same width as the dropbox (I hope I am making sense) whereas in Firefox the dropdown-list's width varies according to the content. </p>
<p>This basically means that I have to make sure that the dropbox is wide enough to display the longest selection possible. This makes my page look very ugly :(</p>
<p>Is there any workaround for this problem?
How can I use CSS to set different widths for dropbox and the dropdownlist?</p>
| [
{
"answer_id": 74062,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can add a style directly to the select element:</p>\n\n<p><code><select name=\"foo\" style=\"width: 200px\"></code></p>\n\n<p>So this select item will be 200 pixels wide.</p>\n\n<p>Alternatively you can apply a class or id to the element and reference it in a stylesheet</p>\n"
},
{
"answer_id": 74117,
"author": "pilsetnieks",
"author_id": 6615,
"author_profile": "https://Stackoverflow.com/users/6615",
"pm_score": 0,
"selected": false,
"text": "<p>So far there isn't one. Don't know about IE8 but it cannot be done in IE6 & IE7, unless you implement your own dropdown list functionality with javascript. There are examples how to do it on the web, though I don't see much benefit in duplicating existing functionality.</p>\n"
},
{
"answer_id": 74149,
"author": "Robert C. Barth",
"author_id": 9209,
"author_profile": "https://Stackoverflow.com/users/9209",
"pm_score": 3,
"selected": false,
"text": "<p>There is no way to do it in IE6/IE7/IE8. The control is drawn by the app and IE simply doesn't draw it that way. Your best bet is to implement your own drop-down via simple HTML/CSS/JavaScript if it's that important to have the the drop-down one width and the list another width.</p>\n"
},
{
"answer_id": 74550,
"author": "Sleep Deprivation Ninja",
"author_id": 13002,
"author_profile": "https://Stackoverflow.com/users/13002",
"pm_score": 4,
"selected": false,
"text": "<p>Creating your own drop down list is more of a pain than it's worth. You can use some JavaScript to make the IE drop down work.</p>\n\n<p>It uses a bit of the YUI library and a special extension for fixing IE select boxes.</p>\n\n<p>You will need to include the following and wrap your <code><select></code> elements in a <code><span class=\"select-box\"></code></p>\n\n<p>Put these before the body tag of your page:</p>\n\n<pre><code><script src=\"http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/yahoo_2.0.0-b3.js\" type=\"text/javascript\">\n</script>\n<script src=\"http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/event_2.0.0-b3.js\" type=\"text/javascript\">\n</script>\n<script src=\"http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/dom_2.0.2-b3.js\" type=\"text/javascript\">\n</script>\n<script src=\"ie-select-width-fix.js\" type=\"text/javascript\">\n</script>\n<script>\n// for each select box you want to affect, apply this:\nvar s1 = new YAHOO.Hack.FixIESelectWidth( 's1' ); // s1 is the ID of the select box you want to affect\n</script>\n</code></pre>\n\n<p>Post acceptance edit:</p>\n\n<p>You can also do this without the YUI library and Hack control. All you really need to do is put an onmouseover=\"this.style.width='auto'\" onmouseout=\"this.style.width='100px'\" (or whatever you want) on the select element. The YUI control gives it that nice animation but it's not necessary. This task can also be accomplished with jquery and other libraries (although, I haven't found explicit documentation for this)</p>\n\n<p>-- amendment to the edit:<br>\nIE has a problem with the onmouseout for select controls (it doesn't consider mouseover on options being a mouseover on the select). This makes using a mouseout very tricky. The first solution is the best I've found so far.</p>\n"
},
{
"answer_id": 714570,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>We have the same thing on an asp:dropdownlist:\n</p>\n\n<p>In Firefox(3.0.5) the dropdown is the width of the longest item in the dropdown, which is like 600 pixels wide or something like that.</p>\n"
},
{
"answer_id": 912435,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>In jQuery this works fairly well. Assume the dropdown has id=\"dropdown\".</p>\n\n<pre><code>$(document).ready(function(){\n\n $(\"#dropdown\").mousedown(function(){\n if($.browser.msie) {\n $(this).css(\"width\",\"auto\");\n }\n });\n $(\"#dropdown\").change(function(){\n if ($.browser.msie) {\n $(this).css(\"width\",\"175px\");\n }\n });\n\n});\n</code></pre>\n"
},
{
"answer_id": 1037055,
"author": "Tinus",
"author_id": 121290,
"author_profile": "https://Stackoverflow.com/users/121290",
"pm_score": 3,
"selected": false,
"text": "<p>@Thad you need to add a blur event handler as well</p>\n\n<pre><code>$(document).ready(function(){\n $(\"#dropdown\").mousedown(function(){\n if($.browser.msie) {\n $(this).css(\"width\",\"auto\");\n }\n });\n $(\"#dropdown\").change(function(){\n if ($.browser.msie) {\n $(this).css(\"width\",\"175px\");\n }\n });\n $(\"#dropdown\").blur(function(){\n if ($.browser.msie) {\n $(this).css(\"width\",\"175px\");\n }\n });\n});\n</code></pre>\n\n<p>However, this will still expand the selectbox on click, instead of just the elements. (and it seems to fail in IE6, but works perfectly in Chrome and IE7)</p>\n"
},
{
"answer_id": 1383840,
"author": "Justin Fisher",
"author_id": 169060,
"author_profile": "https://Stackoverflow.com/users/169060",
"pm_score": 3,
"selected": false,
"text": "<p>I used the following solution and it seems to work well in most situations.</p>\n\n<pre><code><style>\nselect{width:100px}\n</style>\n\n<html>\n<select onmousedown=\"if($.browser.msie){this.style.position='absolute';this.style.width='auto'}\" onblur=\"this.style.position='';this.style.width=''\">\n <option>One</option>\n <option>Two - A long option that gets cut off in IE</option>\n</select>\n</html>\n</code></pre>\n\n<hr>\n\n<p>Note: the <em>$.browser.msie</em> does require jquery.</p>\n"
},
{
"answer_id": 1568875,
"author": "bluwater2001",
"author_id": 175111,
"author_profile": "https://Stackoverflow.com/users/175111",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the simplest solution.</p>\n\n<p>Before I start, I must tell you dropdown select box will automatically expand in almost all the browsers except IE6. So, I would do a browser check (i.e., IE6) and write the following only to that browser. Here it goes. First check for the browser.</p>\n\n<p>The code will magically expands the dropdown select box. The only problem with the solution is onmouseover the dropdown will be expanded to 420px, and because the overflow = hidden we are hiding the expanded dropdown size and showing it as 170px; so, the arrow at the right side of the ddl will be hidden and cannot be seen. but the select box will be expanded to 420px; which is what we really want. Just try the code below for yourself and use it if you like it.</p>\n\n<pre><code>.ctrDropDown\n{\n width:420px; <%--this is the actual width of the dropdown list--%>\n}\n.ctrDropDownClick\n{\n width:420px; <%-- this the width of the dropdown select box.--%>\n}\n\n<div style=\"width:170px; overflow:hidden;\">\n<asp:DropDownList runat=\"server\" ID=\"ddlApplication\" onmouseout = \"this.className='ctrDropDown';\" onmouseover =\"this.className='ctrDropDownClick';\" class=\"ctrDropDown\" onBlur=\"this.className='ctrDropDown';\" onMouseDown=\"this.className='ctrDropDownClick';\" onChange=\"this.className='ctrDropDown';\"></asp:DropDownList>\n</div>\n</code></pre>\n\n<p>The above is the IE6 CSS. The common CSS for all other browsers should be as below.</p>\n\n<pre><code>.ctrDropDown\n{\n width:170px; <%--this is the actual width of the dropdown list--%>\n}\n.ctrDropDownClick\n{\n width:auto; <%-- this the width of the dropdown select box.--%>\n}\n</code></pre>\n"
},
{
"answer_id": 1873417,
"author": "Ybbest",
"author_id": 134579,
"author_profile": "https://Stackoverflow.com/users/134579",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://developer.yahoo.com/yui/examples/button/button-menu-select.html#\" rel=\"nofollow noreferrer\">http://developer.yahoo.com/yui/examples/button/button-menu-select.html#</a></p>\n"
},
{
"answer_id": 1875534,
"author": "cam",
"author_id": 228154,
"author_profile": "https://Stackoverflow.com/users/228154",
"pm_score": 2,
"selected": false,
"text": "<p>if you want a simple dropdown &/or flyout menu with no transition effects just use CSS... you can force IE6 to support :hover on all element using an .htc file (css3hover?) with behavior (IE6 only property) defined in the conditionally attached CSS file.</p>\n"
},
{
"answer_id": 2516571,
"author": "BalusC",
"author_id": 157882,
"author_profile": "https://Stackoverflow.com/users/157882",
"pm_score": 8,
"selected": true,
"text": "<p>Here's another <a href=\"http://jquery.com\" rel=\"noreferrer\">jQuery</a> based example. In contrary to all the other answers posted here, it takes all keyboard and mouse events into account, especially clicks:</p>\n\n<pre><code>if (!$.support.leadingWhitespace) { // if IE6/7/8\n $('select.wide')\n .bind('focus mouseover', function() { $(this).addClass('expand').removeClass('clicked'); })\n .bind('click', function() { $(this).toggleClass('clicked'); })\n .bind('mouseout', function() { if (!$(this).hasClass('clicked')) { $(this).removeClass('expand'); }})\n .bind('blur', function() { $(this).removeClass('expand clicked'); });\n}\n</code></pre>\n\n<p>Use it in combination with this piece of CSS:</p>\n\n<pre><code>select {\n width: 150px; /* Or whatever width you want. */\n}\nselect.expand {\n width: auto;\n}\n</code></pre>\n\n<p>All you need to do is to add the class <code>wide</code> to the dropdown element(s) in question.</p>\n\n<pre><code><select class=\"wide\">\n ...\n</select>\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/HnV9Q/\" rel=\"noreferrer\">Here is a jsfiddle example</a>. Hope this helps.</p>\n"
},
{
"answer_id": 2969250,
"author": "Sai",
"author_id": 337515,
"author_profile": "https://Stackoverflow.com/users/337515",
"pm_score": 4,
"selected": false,
"text": "<p>you could just try the following...</p>\n\n<pre><code> styleClass=\"someStyleWidth\"\n onmousedown=\"javascript:if(navigator.appName=='Microsoft Internet Explorer'){this.style.position='absolute';this.style.width='auto'}\" \n onblur=\"this.style.position='';this.style.width=''\"\n</code></pre>\n\n<p>I tried and it works for me. Nothing else is required.</p>\n"
},
{
"answer_id": 3048216,
"author": "lucien",
"author_id": 367610,
"author_profile": "https://Stackoverflow.com/users/367610",
"pm_score": 2,
"selected": false,
"text": "<p>check this out.. it's not perfect but it works and it's for IE only and doesn't affect FF. I used the regular javascript for onmousedown to establish IE only fix.. but the msie from jquery could be used as well in the onmousedown.. the main idea is the \"onchange\" and on blur to have the select box return to normal... decide you're own width for those. I needed 35%. </p>\n\n<pre><code>onmousedown=\"javascript:if(navigator.appName=='Microsoft Internet Explorer'){this.style.width='auto'}\" \nonchange=\"this.style.width='35%'\"\nonblur=\"this.style.width='35%'\"\n</code></pre>\n"
},
{
"answer_id": 3161181,
"author": "Hammad Tariq",
"author_id": 243354,
"author_profile": "https://Stackoverflow.com/users/243354",
"pm_score": 0,
"selected": false,
"text": "<p>The hedgerwow link (the YUI animation work-around) in the first best answer is broken, I guess the domain got expired. I copied the code before it got expired, so you can find it here (owner of code can let me know if I am breaching any copyrights by uploading it again)</p>\n\n<p><a href=\"http://ciitronian.com/blog/programming/yui-button-mimicking-native-select-dropdown-avoid-width-problem/\" rel=\"nofollow noreferrer\">http://ciitronian.com/blog/programming/yui-button-mimicking-native-select-dropdown-avoid-width-problem/</a></p>\n\n<p>On the same blog post I wrote about making an exact same SELECT element like the normal one using YUI Button menu. Have a look and let me know if this helps! </p>\n"
},
{
"answer_id": 3303191,
"author": "lhoess",
"author_id": 398403,
"author_profile": "https://Stackoverflow.com/users/398403",
"pm_score": 0,
"selected": false,
"text": "<p>This seems to work with IE6 and doesn't appear to break others. The other nice thing is that it changes the menu automatically as soon as you change your drop down selection.</p>\n\n<pre><code>$(document).ready(function(){\n $(\"#dropdown\").mouseover(function(){\n if($.browser.msie) {\n $(this).css(\"width\",\"auto\");\n }\n });\n $(\"#dropdown\").change(function(){\n if ($.browser.msie) {\n $(\"#dropdown\").trigger(\"mouseover\");\n }\n });\n\n});\n</code></pre>\n"
},
{
"answer_id": 3494994,
"author": "jbabey",
"author_id": 386152,
"author_profile": "https://Stackoverflow.com/users/386152",
"pm_score": 2,
"selected": false,
"text": "<p>BalusC's answer above works great, but there is a small fix I would add if the content of your dropdown has a smaller width than what you define in your CSS select.expand, add this to the mouseover bind:</p>\n\n<pre><code>.bind('mouseover', function() { $(this).addClass('expand').removeClass('clicked');\n if ($(this).width() < 300) // put your desired minwidth here\n {\n $(this).removeClass('expand');\n }})\n</code></pre>\n"
},
{
"answer_id": 3759984,
"author": "Ewen",
"author_id": 453874,
"author_profile": "https://Stackoverflow.com/users/453874",
"pm_score": 3,
"selected": false,
"text": "<p>If you use jQuery then try out this IE select width plugin:</p>\n\n<p><a href=\"http://www.jainaewen.com/files/javascript/jquery/ie-select-style/\" rel=\"noreferrer\">http://www.jainaewen.com/files/javascript/jquery/ie-select-style/</a></p>\n\n<p>Applying this plugin makes the select box in Internet Explorer appear to work as it would work in Firefox, Opera etc by allowing the option elements to open at full width without loosing the look and style of the fixed width. It also adds support for padding and borders on the select box in Internet Explorer 6 and 7.</p>\n"
},
{
"answer_id": 6389369,
"author": "Derrick",
"author_id": 265100,
"author_profile": "https://Stackoverflow.com/users/265100",
"pm_score": 2,
"selected": false,
"text": "<p>This is something l have done taking bits from other people's stuff.</p>\n\n<pre><code> $(document).ready(function () {\n if (document.all) {\n\n $('#<%=cboDisability.ClientID %>').mousedown(function () {\n $('#<%=cboDisability.ClientID %>').css({ 'width': 'auto' });\n });\n\n $('#<%=cboDisability.ClientID %>').blur(function () {\n $(this).css({ 'width': '208px' });\n });\n\n $('#<%=cboDisability.ClientID %>').change(function () {\n $('#<%=cboDisability.ClientID %>').css({ 'width': '208px' });\n });\n\n $('#<%=cboEthnicity.ClientID %>').mousedown(function () {\n $('#<%=cboEthnicity.ClientID %>').css({ 'width': 'auto' });\n });\n\n $('#<%=cboEthnicity.ClientID %>').blur(function () {\n $(this).css({ 'width': '208px' });\n });\n\n $('#<%=cboEthnicity.ClientID %>').change(function () {\n $('#<%=cboEthnicity.ClientID %>').css({ 'width': '208px' });\n });\n\n }\n });\n</code></pre>\n\n<p>where cboEthnicity and cboDisability are dropdowns with option text wider than the width of the select itself. </p>\n\n<p>As you can see, l have specified document.all as this only works in IE. Also, l encased the dropdowns within div elements like this:</p>\n\n<pre><code><div id=\"dvEthnicity\" style=\"width: 208px; overflow: hidden; position: relative; float: right;\"><asp:DropDownList CssClass=\"select\" ID=\"cboEthnicity\" runat=\"server\" DataTextField=\"description\" DataValueField=\"id\" Width=\"200px\"></asp:DropDownList></div>\n</code></pre>\n\n<p>This takes care of the other elements moving out of place when your dropdown expands. The only downside here is that the menulist visual disappears when you are selecting but returns as soon as you have selected.</p>\n\n<p>Hope this helps someone.</p>\n"
},
{
"answer_id": 7312042,
"author": "Federico Valido",
"author_id": 929457,
"author_profile": "https://Stackoverflow.com/users/929457",
"pm_score": 1,
"selected": false,
"text": "<p>The jquery BalusC's solution improved by me. Used also: Brad Robertson's <a href=\"http://doctype.com/ie7-width-overrides-minwidth-select\" rel=\"nofollow\">comment here</a>.</p>\n\n<p>Just put this in a .js, use the wide class for your desired combos and don't forge to give it an Id. Call the function in the onload (or documentReady or whatever).<br/>\nAs simple ass that :)<br/>\nIt will use the width that you defined for the combo as minimun length.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function fixIeCombos() {\n if ($.browser.msie && $.browser.version < 9) {\n var style = $('<style>select.expand { width: auto; }</style>');\n $('html > head').append(style);\n\n var defaultWidth = \"200\";\n\n // get predefined combo's widths.\n var widths = new Array();\n $('select.wide').each(function() {\n var width = $(this).width();\n if (!width) {\n width = defaultWidth;\n }\n widths[$(this).attr('id')] = width;\n });\n\n $('select.wide')\n .bind('focus mouseover', function() {\n // We're going to do the expansion only if the resultant size is bigger\n // than the original size of the combo.\n // In order to find out the resultant size, we first clon the combo as\n // a hidden element, add to the dom, and then test the width.\n var originalWidth = widths[$(this).attr('id')];\n\n var $selectClone = $(this).clone();\n $selectClone.addClass('expand').hide();\n $(this).after( $selectClone );\n var expandedWidth = $selectClone.width()\n $selectClone.remove();\n if (expandedWidth > originalWidth) {\n $(this).addClass('expand').removeClass('clicked');\n }\n })\n .bind('click', function() {\n $(this).toggleClass('clicked'); \n })\n .bind('mouseout', function() {\n if (!$(this).hasClass('clicked')) {\n $(this).removeClass('expand');\n }\n })\n .bind('blur', function() {\n $(this).removeClass('expand clicked');\n })\n }\n}\n</code></pre>\n"
},
{
"answer_id": 7659553,
"author": "Ahmad Alfy",
"author_id": 497828,
"author_profile": "https://Stackoverflow.com/users/497828",
"pm_score": 0,
"selected": false,
"text": "<p>Based on the solution posted by <a href=\"https://stackoverflow.com/questions/73960/dropdownlist-width-in-ie/2969250#2969250\">Sai</a>, this is how to do it with jQuery.</p>\n\n<pre><code>$(document).ready(function() {\n if ($.browser.msie) $('select.wide')\n .bind('onmousedown', function() { $(this).css({position:'absolute',width:'auto'}); })\n .bind('blur', function() { $(this).css({position:'static',width:''}); });\n});\n</code></pre>\n"
},
{
"answer_id": 9115565,
"author": "mcmwhfy",
"author_id": 1057912,
"author_profile": "https://Stackoverflow.com/users/1057912",
"pm_score": 2,
"selected": false,
"text": "<p>this is the best way to do this:</p>\n\n<pre><code>select:focus{\n min-width:165px;\n width:auto;\n z-index:9999999999;\n position:absolute;\n}\n</code></pre>\n\n<p>it's exactly the same like BalusC solution. \nOnly this is easier. ;)</p>\n"
},
{
"answer_id": 9200617,
"author": "n0nag0n",
"author_id": 721019,
"author_profile": "https://Stackoverflow.com/users/721019",
"pm_score": 0,
"selected": false,
"text": "<p>I thought I'd throw my hat in the ring. I make a SaaS application and I had a select menu embedded inside a table. This method worked, but it skewed everything in the table.</p>\n\n<pre><code>onmousedown=\"if(navigator.appName=='Microsoft Internet Explorer'){this.style.position='absolute';this.style.width='auto'}\nonblur=\"if(navigator.appName=='Microsoft Internet Explorer'){this.style.position=''; this.style.width= '225px';}\"\n</code></pre>\n\n<p>So what I did to make it all better was throw the select inside a z-indexed div.</p>\n\n<pre><code><td valign=\"top\" style=\"width:225px; overflow:hidden;\">\n <div style=\"position: absolute; z-index: 5;\" onmousedown=\"var select = document.getElementById('select'); if(navigator.appName=='Microsoft Internet Explorer'){select.style.position='absolute';select.style.width='auto'}\">\n <select name=\"select_name\" id=\"select\" style=\"width: 225px;\" onblur=\"if(navigator.appName=='Microsoft Internet Explorer'){this.style.position=''; this.style.width= '225px';}\" onChange=\"reportFormValues('filter_<?=$job_id?>','form_values')\">\n <option value=\"0\">All</option>\n <!--More Options-->\n </select>\n </div>\n</td>\n</code></pre>\n"
},
{
"answer_id": 10497987,
"author": "Arif",
"author_id": 1196718,
"author_profile": "https://Stackoverflow.com/users/1196718",
"pm_score": 0,
"selected": false,
"text": "<p>Its tested in all version of IE, Chrome, FF & Safari</p>\n<p><strong>JavaScript code:</strong></p>\n<pre class=\"lang-js prettyprint-override\"><code><!-- begin hiding\nfunction expandSELECT(sel) {\n sel.style.width = '';\n}\n\nfunction contractSELECT(sel) {\n sel.style.width = '100px';\n}\n// end hiding -->\n</code></pre>\n<p><strong>Html code:</strong></p>\n<pre class=\"lang-html prettyprint-override\"><code><select name="sideeffect" id="sideeffect" style="width:100px;" onfocus="expandSELECT(this);" onblur="contractSELECT(this);" >\n <option value="0" selected="selected" readonly="readonly">Select</option>\n <option value="1" >Apple</option>\n <option value="2" >Orange + Banana + Grapes</option>\n</code></pre>\n"
},
{
"answer_id": 11236037,
"author": "Aerendel",
"author_id": 1349107,
"author_profile": "https://Stackoverflow.com/users/1349107",
"pm_score": 0,
"selected": false,
"text": "<p>I've had to work around this issue and once came up with a pretty complete and scalable solution working for IE6, 7 and 8 (and compatible with other browsers obviously).\nI've written a whole article about it right here: <a href=\"http://www.edgeoftheworld.fr/wp/work/dealing-with-fixed-sized-dropdown-lists-in-internet-explorer\" rel=\"nofollow\">http://www.edgeoftheworld.fr/wp/work/dealing-with-fixed-sized-dropdown-lists-in-internet-explorer</a></p>\n\n<p>Thought I'd share this for people who are still running into this problem, as none of the above solutions work in every case (in my opinion).</p>\n"
},
{
"answer_id": 12037082,
"author": "PowerKiKi",
"author_id": 37706,
"author_profile": "https://Stackoverflow.com/users/37706",
"pm_score": 2,
"selected": false,
"text": "<p>A full fledged jQuery plugin is available. It supports non-breaking layout and keyboard interactions, check out the demo page: <a href=\"http://powerkiki.github.com/ie_expand_select_width/\" rel=\"nofollow\">http://powerkiki.github.com/ie_expand_select_width/</a></p>\n\n<p>disclaimer: I coded that thing, patches welcome</p>\n"
},
{
"answer_id": 13035783,
"author": "RasTheDestroyer",
"author_id": 836366,
"author_profile": "https://Stackoverflow.com/users/836366",
"pm_score": 0,
"selected": false,
"text": "<p>I tried all of these solutions and none worked completely for me. This is what I came up with</p>\n\n<pre><code>$(document).ready(function () {\n\nvar clicknum = 0;\n\n$('.dropdown').click(\n function() {\n clicknum++;\n if (clicknum == 2) {\n clicknum = 0;\n $(this).css('position', '');\n $(this).css('width', '');\n }\n }).blur(\n function() {\n $(this).css('position', '');\n $(this).css('width', '');\n clicknum = 0;\n }).focus(\n function() {\n $(this).css('position', 'relative');\n $(this).css('width', 'auto');\n }).mousedown(\n function() {\n $(this).css('position', 'relative');\n $(this).css('width', 'auto');\n });\n})(jQuery);\n</code></pre>\n\n<p>Be sure to add a dropdown class to each dropdown in your html</p>\n\n<p>The trick here is using the specialized click function (I found it here <a href=\"https://stackoverflow.com/questions/898463/fire-event-each-time-a-dropdownlist-item-is-selected-with-jquery\">Fire event each time a DropDownList item is selected with jQuery</a>). Many of the other solutions on here use the event handler change, which works well but won't trigger if the user selects the same option as was previously selected. </p>\n\n<p>Like many of the other solutions, focus and mousedown is for when the user puts the dropdown in focus, blur is for when they click away.</p>\n\n<p>You may also want to stick some kind of browser detection in this so it only effects ie. It doesn't look bad in other browsers though</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/747/"
]
| In IE, the dropdown-list takes the same width as the dropbox (I hope I am making sense) whereas in Firefox the dropdown-list's width varies according to the content.
This basically means that I have to make sure that the dropbox is wide enough to display the longest selection possible. This makes my page look very ugly :(
Is there any workaround for this problem?
How can I use CSS to set different widths for dropbox and the dropdownlist? | Here's another [jQuery](http://jquery.com) based example. In contrary to all the other answers posted here, it takes all keyboard and mouse events into account, especially clicks:
```
if (!$.support.leadingWhitespace) { // if IE6/7/8
$('select.wide')
.bind('focus mouseover', function() { $(this).addClass('expand').removeClass('clicked'); })
.bind('click', function() { $(this).toggleClass('clicked'); })
.bind('mouseout', function() { if (!$(this).hasClass('clicked')) { $(this).removeClass('expand'); }})
.bind('blur', function() { $(this).removeClass('expand clicked'); });
}
```
Use it in combination with this piece of CSS:
```
select {
width: 150px; /* Or whatever width you want. */
}
select.expand {
width: auto;
}
```
All you need to do is to add the class `wide` to the dropdown element(s) in question.
```
<select class="wide">
...
</select>
```
[Here is a jsfiddle example](http://jsfiddle.net/HnV9Q/). Hope this helps. |
73,964 | <p>I would like to turn the HTML generated by my CFM page into a PDF, and have the user prompted with the standard "Save As" prompt when navigating to my page.</p>
| [
{
"answer_id": 73982,
"author": "Frank Wiles",
"author_id": 12568,
"author_profile": "https://Stackoverflow.com/users/12568",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not that familiar with ColdFusion, but what you need to do is set the Content-Type of the page when the user requests it to be application/octet-stream. This will prompt them for a download every time. </p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 74374,
"author": "Soldarnal",
"author_id": 3420,
"author_profile": "https://Stackoverflow.com/users/3420",
"pm_score": 5,
"selected": true,
"text": "<p>You should use the cfdocument tag (with format=\"PDF\") to generate the PDF by placing it around the page you are generating. You'll want to specify a filename attribute, otherwise the document will just stream right to your browser.</p>\n\n<p>After you have saved the content as a PDF, use cfheader and cfcontent in combination to output the PDF as an attachment (\"Save As\") and add the file to the response stream. I also added deletefile=\"Yes\" on the cfcontent tag to keep the file system clean of the files.</p>\n\n<pre><code><cfdocument format=\"PDF\" filename=\"file.pdf\" overwrite=\"Yes\">\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<html>\n<head>\n <title>Hello World</title>\n</head>\n<body>\n Hello World\n</body>\n</html>\n</cfdocument>\n<cfheader name=\"Content-Disposition\" value=\"attachment;filename=file.pdf\">\n<cfcontent type=\"application/octet-stream\" file=\"#expandPath('.')#\\file.pdf\" deletefile=\"Yes\">\n</code></pre>\n\n<p>As an aside: I'm just using file.pdf for the filename in the example below, but you might want to use some random or session generated string for the filename to avoid problems resulting from race conditions.</p>\n"
},
{
"answer_id": 75118,
"author": "Ben Doom",
"author_id": 12267,
"author_profile": "https://Stackoverflow.com/users/12267",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to avoid storing the PDF at all, using cfdocument without a filename will send the pdf (of flashpaper) directly to the browser without using the cfheader and cfcontent.</p>\n\n<p>Caveat: Like with using cfheader/cfcontent, you need to do this before the cache gets flushed to the browser, since it's basically doing the same thing without having to store the file.</p>\n\n<p>To get the content, I would probably use cfsavecontent wrapped around the same calls/includes/etc. that generate the page, with two major exceptions. cfdocument seems to have issues with external stylesheets, so using an include to put the styles directly into the document is probably a good idea. You can try using an @import instead -- it works for some people. Also, I'd be careful about relative links to images, as they can sometimes break. </p>\n"
},
{
"answer_id": 88297,
"author": "Andy Waschick",
"author_id": 6000,
"author_profile": "https://Stackoverflow.com/users/6000",
"pm_score": 2,
"selected": false,
"text": "<p>The <code><cfdocument></code> approach is the sanctioned way to get it done, however it does not offer everything possible in the way of manipulating existing PDF documents. I had a project where I needed to generate coupons based using a pre-designed, print-resolution PDF template. <code><cfdocument></code> would have let me approximate the output, but only with bitmap images embedded in HTML. True, I could fake print-resolution by making a large image and scaling it in HTML, but the original was a nice, clean, vector-image file and I wanted to use that instead. </p>\n\n<p>I ended up using a copy of <code><cfx_pdf></code> to get the job done. (<a href=\"http://www.easel2.com/\" rel=\"nofollow noreferrer\">Developer's Site</a>, <a href=\"http://www.cftagstore.com/tags/cfxpdf.cfm\" rel=\"nofollow noreferrer\">CF Tag Store</a>) It's a CF wrapper around a Java PDF library that lets you manipulate existing PDF documents, including filling out PDF forms, setting permissions, merging files, drawing vector graphics, tables, and text, use custom fonts, etc, etc. If you are willing to work with it, you can get some pretty spectacular results. </p>\n\n<p>The one drawback is that it appears the developer has left this product out to pasture for a long time. The developer site is still copyright 2003 and doesn't mention anything past ColdFusion MX 6.1. I ended up having to break some of the encrypted templates in order to fix a couple of bugs and make it work as I needed it to. Nontheless, it is a powerful tool.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2232/"
]
| I would like to turn the HTML generated by my CFM page into a PDF, and have the user prompted with the standard "Save As" prompt when navigating to my page. | You should use the cfdocument tag (with format="PDF") to generate the PDF by placing it around the page you are generating. You'll want to specify a filename attribute, otherwise the document will just stream right to your browser.
After you have saved the content as a PDF, use cfheader and cfcontent in combination to output the PDF as an attachment ("Save As") and add the file to the response stream. I also added deletefile="Yes" on the cfcontent tag to keep the file system clean of the files.
```
<cfdocument format="PDF" filename="file.pdf" overwrite="Yes">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Hello World</title>
</head>
<body>
Hello World
</body>
</html>
</cfdocument>
<cfheader name="Content-Disposition" value="attachment;filename=file.pdf">
<cfcontent type="application/octet-stream" file="#expandPath('.')#\file.pdf" deletefile="Yes">
```
As an aside: I'm just using file.pdf for the filename in the example below, but you might want to use some random or session generated string for the filename to avoid problems resulting from race conditions. |
73,971 | <p>In JavaScript, what is the best way to determine if a date provided falls within a valid range?</p>
<p>An example of this might be checking to see if the user input <code>requestedDate</code> is part of the next valid work week. Note that this is not just checking to see if one date is larger than another as a valid date would be equal to or greater than the lower end of the range while less than or equal to the upper end of the range.</p>
| [
{
"answer_id": 74024,
"author": "Jesper Blad Jensen",
"author_id": 11559,
"author_profile": "https://Stackoverflow.com/users/11559",
"pm_score": 3,
"selected": false,
"text": "<p>So if i understand currenctly, you need to look if one date is bigger than the other.</p>\n\n<pre><code>function ValidRange(date1,date2)\n{\n return date2.getTime() > date1.getTime();\n}\n</code></pre>\n\n<p>You then need to parse the strings you are getting from the UI, with Date.parse, like this:</p>\n\n<pre><code>ValidRange(Date.parse('10-10-2008'),Date.parse('11-11-2008'));\n</code></pre>\n\n<p>Does that help?</p>\n"
},
{
"answer_id": 74040,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 5,
"selected": true,
"text": "<p>This is actually a problem that I have seen come up before a lot in my works and the following bit of code is my answer to the problem.</p>\n\n<pre><code>// checkDateRange - Checks to ensure that the values entered are dates and \n// are of a valid range. By this, the dates must be no more than the \n// built-in number of days appart.\nfunction checkDateRange(start, end) {\n // Parse the entries\n var startDate = Date.parse(start);\n var endDate = Date.parse(end);\n // Make sure they are valid\n if (isNaN(startDate)) {\n alert(\"The start date provided is not valid, please enter a valid date.\");\n return false;\n }\n if (isNaN(endDate)) {\n alert(\"The end date provided is not valid, please enter a valid date.\");\n return false;\n }\n // Check the date range, 86400000 is the number of milliseconds in one day\n var difference = (endDate - startDate) / (86400000 * 7);\n if (difference < 0) {\n alert(\"The start date must come before the end date.\");\n return false;\n }\n if (difference <= 1) {\n alert(\"The range must be at least seven days apart.\");\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>Now a couple things to note about this code, the <code>Date.parse</code> function should work for most input types, but has been known to have issues with some formats such as \"YYYY MM DD\" so you should test that before using it. However, I seem to recall that most browsers will interpret the date string given to Date.parse based upon the computers region settings.</p>\n\n<p>Also, the multiplier for 86400000 should be whatever the range of days you are looking for is. So if you are looking for dates that are at least one week apart then it should be seven.</p>\n"
},
{
"answer_id": 74051,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 3,
"selected": false,
"text": "<pre><code>var myDate = new Date(2008, 9, 16);\n\n// is myDate between Sept 1 and Sept 30?\n\nvar startDate = new Date(2008, 9, 1);\nvar endDate = new Date(2008, 9, 30);\n\nif (startDate < myDate && myDate < endDate) {\n alert('yes');\n // myDate is between startDate and endDate\n}\n</code></pre>\n\n<p>There are a variety of formats you can pass to the Date() constructor to construct a date. You can also construct a new date with the current time:</p>\n\n<pre><code>var now = new Date();\n</code></pre>\n\n<p>and set various properties on it:</p>\n\n<pre><code>now.setYear(...);\nnow.setMonth(...);\n// etc\n</code></pre>\n\n<p>See <a href=\"http://www.javascriptkit.com/jsref/date.shtml\" rel=\"noreferrer\">http://www.javascriptkit.com/jsref/date.shtml</a> or <a href=\"http://www.google.ca/search?q=javascript+date+object\" rel=\"noreferrer\">Google</a> for more details.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/73971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1185/"
]
| In JavaScript, what is the best way to determine if a date provided falls within a valid range?
An example of this might be checking to see if the user input `requestedDate` is part of the next valid work week. Note that this is not just checking to see if one date is larger than another as a valid date would be equal to or greater than the lower end of the range while less than or equal to the upper end of the range. | This is actually a problem that I have seen come up before a lot in my works and the following bit of code is my answer to the problem.
```
// checkDateRange - Checks to ensure that the values entered are dates and
// are of a valid range. By this, the dates must be no more than the
// built-in number of days appart.
function checkDateRange(start, end) {
// Parse the entries
var startDate = Date.parse(start);
var endDate = Date.parse(end);
// Make sure they are valid
if (isNaN(startDate)) {
alert("The start date provided is not valid, please enter a valid date.");
return false;
}
if (isNaN(endDate)) {
alert("The end date provided is not valid, please enter a valid date.");
return false;
}
// Check the date range, 86400000 is the number of milliseconds in one day
var difference = (endDate - startDate) / (86400000 * 7);
if (difference < 0) {
alert("The start date must come before the end date.");
return false;
}
if (difference <= 1) {
alert("The range must be at least seven days apart.");
return false;
}
return true;
}
```
Now a couple things to note about this code, the `Date.parse` function should work for most input types, but has been known to have issues with some formats such as "YYYY MM DD" so you should test that before using it. However, I seem to recall that most browsers will interpret the date string given to Date.parse based upon the computers region settings.
Also, the multiplier for 86400000 should be whatever the range of days you are looking for is. So if you are looking for dates that are at least one week apart then it should be seven. |
74,010 | <p>I am a bit rusty on my cursor lingo in PL/SQL. Anyone know this?</p>
| [
{
"answer_id": 74105,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 2,
"selected": false,
"text": "<p>An explicit cursor is one you declare, like:</p>\n\n<pre><code>CURSOR my_cursor IS\n SELECT table_name FROM USER_TABLES\n</code></pre>\n\n<p>An implicit cursor is one created to support any in-line SQL you write (either static or dynamic).</p>\n"
},
{
"answer_id": 74135,
"author": "stjohnroe",
"author_id": 2985,
"author_profile": "https://Stackoverflow.com/users/2985",
"pm_score": 4,
"selected": false,
"text": "<p>An explicit cursor is defined as such in a declaration block:</p>\n\n<pre><code>DECLARE \nCURSOR cur IS \n SELECT columns FROM table WHERE condition;\nBEGIN\n...\n</code></pre>\n\n<p>an implicit cursor is implented directly in a code block:</p>\n\n<pre><code>...\nBEGIN\n SELECT columns INTO variables FROM table where condition;\nEND;\n...\n</code></pre>\n"
},
{
"answer_id": 74624,
"author": "Kristian",
"author_id": 12911,
"author_profile": "https://Stackoverflow.com/users/12911",
"pm_score": 2,
"selected": false,
"text": "<p>With explicit cursors, you have complete control over how to access information in the database. You decide when to OPEN the cursor, when to FETCH records from the cursor (and therefore from the table or tables in the SELECT statement of the cursor) how many records to fetch, and when to CLOSE the cursor. Information about the current state of your cursor is available through examination of the cursor attributes.</p>\n\n<p>See <a href=\"http://www.unix.com.ua/orelly/oracle/prog2/ch06_03.htm\" rel=\"nofollow noreferrer\">http://www.unix.com.ua/orelly/oracle/prog2/ch06_03.htm</a> for details.</p>\n"
},
{
"answer_id": 76178,
"author": "Sten Vesterli",
"author_id": 9363,
"author_profile": "https://Stackoverflow.com/users/9363",
"pm_score": 6,
"selected": true,
"text": "<p>An implicit cursor is one created \"automatically\" for you by Oracle when you execute a query. It is simpler to code, but suffers from </p>\n\n<ul>\n<li>inefficiency (the ANSI standard specifies that it must fetch twice to check if there is more than one record)</li>\n<li>vulnerability to data errors (if you ever get two rows, it raises a TOO_MANY_ROWS exception)</li>\n</ul>\n\n<p>Example</p>\n\n<pre><code>SELECT col INTO var FROM table WHERE something;\n</code></pre>\n\n<p>An explicit cursor is one you create yourself. It takes more code, but gives more control - for example, you can just open-fetch-close if you only want the first record and don't care if there are others. </p>\n\n<p>Example</p>\n\n<pre><code>DECLARE \n CURSOR cur IS SELECT col FROM table WHERE something; \nBEGIN\n OPEN cur;\n FETCH cur INTO var;\n CLOSE cur;\nEND;\n</code></pre>\n"
},
{
"answer_id": 78765,
"author": "ropable",
"author_id": 14508,
"author_profile": "https://Stackoverflow.com/users/14508",
"pm_score": 0,
"selected": false,
"text": "<p>Every SQL statement executed by the Oracle database has a cursor associated with it, which is a private work area to store processing information. Implicit cursors are implicitly created by the Oracle server for all DML and SELECT statements.</p>\n\n<p>You can declare and use Explicit cursors to name the private work area, and access its stored information in your program block.</p>\n"
},
{
"answer_id": 80246,
"author": "Ethan Post",
"author_id": 4527,
"author_profile": "https://Stackoverflow.com/users/4527",
"pm_score": -1,
"selected": false,
"text": "<p>Explicit...</p>\n\n<p>cursor foo is select * from blah;\nbegin\n open fetch exit when close cursor yada yada yada</p>\n\n<p>don't use them, use implicit</p>\n\n<p>cursor foo is select * from blah;</p>\n\n<p>for n in foo loop\n x = n.some_column\nend loop</p>\n\n<p>I think you can even do this</p>\n\n<p>for n in (select * from blah) loop...</p>\n\n<p>Stick to implicit, they close themselves, they are more readable, they make life easy.</p>\n"
},
{
"answer_id": 84014,
"author": "pablo",
"author_id": 16112,
"author_profile": "https://Stackoverflow.com/users/16112",
"pm_score": 2,
"selected": false,
"text": "<p>These days implicit cursors are more efficient than explicit cursors.</p>\n\n<p><a href=\"http://www.oracle.com/technology/oramag/oracle/04-sep/o54plsql.html\" rel=\"nofollow noreferrer\">http://www.oracle.com/technology/oramag/oracle/04-sep/o54plsql.html</a></p>\n\n<p><a href=\"http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1205168148688\" rel=\"nofollow noreferrer\">http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1205168148688</a></p>\n"
},
{
"answer_id": 2824542,
"author": "Derek Swingley",
"author_id": 1934,
"author_profile": "https://Stackoverflow.com/users/1934",
"pm_score": 1,
"selected": false,
"text": "<p>Google is your friend: <a href=\"http://docstore.mik.ua/orelly/oracle/prog2/ch06_03.htm\" rel=\"nofollow noreferrer\">http://docstore.mik.ua/orelly/oracle/prog2/ch06_03.htm</a></p>\n\n<blockquote>\n <p>PL/SQL issues an implicit cursor\n whenever you execute a SQL statement\n directly in your code, as long as that\n code does not employ an explicit\n cursor. It is called an \"implicit\"\n cursor because you, the developer, do\n not explicitly declare a cursor for\n the SQL statement.</p>\n \n <p>An explicit cursor is a SELECT\n statement that is explicitly defined\n in the declaration section of your\n code and, in the process, assigned a\n name. There is no such thing as an\n explicit cursor for UPDATE, DELETE,\n and INSERT statements.</p>\n</blockquote>\n"
},
{
"answer_id": 2825689,
"author": "Ian Carpenter",
"author_id": 55640,
"author_profile": "https://Stackoverflow.com/users/55640",
"pm_score": 2,
"selected": false,
"text": "<p>In answer to the first question. Straight from the Oracle <a href=\"http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10472/static.htm#LNPLS00602\" rel=\"nofollow noreferrer\">documentation</a></p>\n\n<blockquote>\n <p>A cursor is a pointer to a private SQL\n area that stores information about\n processing a specific SELECT or DML\n statement.</p>\n</blockquote>\n"
},
{
"answer_id": 2833203,
"author": "UltraCommit",
"author_id": 297267,
"author_profile": "https://Stackoverflow.com/users/297267",
"pm_score": 1,
"selected": false,
"text": "<p>A cursor is a SELECTed window on an Oracle table, this means a group of records present in an Oracle table, and satisfying certain conditions. A cursor can SELECT all the content of a table, too. With a cursor you can manipulate Oracle columns, aliasing them in the result. An example of implicit cursor is the following:</p>\n\n<pre><code>BEGIN\n DECLARE\n CURSOR C1\n IS\n SELECT DROPPED_CALLS FROM ALARM_UMTS;\n\n C1_REC C1%ROWTYPE;\n BEGIN\n FOR C1_REC IN C1\n LOOP\n DBMS_OUTPUT.PUT_LINE ('DROPPED CALLS: ' || C1_REC.DROPPED_CALLS);\n END LOOP;\n END;\nEND;\n/\n</code></pre>\n\n<p>With FOR ... LOOP... END LOOP you open and close the cursor authomatically, when the records of the cursor have been all analyzed.</p>\n\n<p>An example of explicit cursor is the following:</p>\n\n<pre><code>BEGIN\n DECLARE\n CURSOR C1\n IS\n SELECT DROPPED_CALLS FROM ALARM_UMTS;\n\n C1_REC C1%ROWTYPE;\n BEGIN\n OPEN c1;\n\n LOOP\n FETCH c1 INTO c1_rec;\n\n EXIT WHEN c1%NOTFOUND;\n\n DBMS_OUTPUT.PUT_LINE ('DROPPED CALLS: ' || C1_REC.DROPPED_CALLS);\n END LOOP;\n\n CLOSE c1;\n END;\nEND;\n/\n</code></pre>\n\n<p>In the explicit cursor you open and close the cursor in an explicit way, checking the presence of records and stating an exit condition.</p>\n"
},
{
"answer_id": 3138202,
"author": "shaiksyedbasha",
"author_id": 378667,
"author_profile": "https://Stackoverflow.com/users/378667",
"pm_score": 1,
"selected": false,
"text": "<p>Implicit cursor returns only one record and are called automatically. However, explicit cursors are called manually and can return more than one record.</p>\n"
},
{
"answer_id": 9258147,
"author": "Ganesh Pathare",
"author_id": 1206438,
"author_profile": "https://Stackoverflow.com/users/1206438",
"pm_score": 2,
"selected": false,
"text": "<p>1.CURSOR: When PLSQL issues sql statements it creates private work area\n to parse & execute the sql statement is called cursor.</p>\n\n<p>2.IMPLICIT: When any PL/SQLexecutable block issues sql statement.\n PL/SQL creates implicit cursor and manages automatically means\n implcit open & close takes place. It used when sql statement return\n only one row.It has 4 attributes SQL%ROWCOUNT, SQL%FOUND,\n SQL%NOTFOUND, SQL%ISOPEN.</p>\n\n<p>3.EXPLICIT: It is created & managed by the programmer. It needs every\n time explicit open,fetch & close. It is used when sql statement\n returns more than one row. It has also 4 attributes\n CUR_NAME%ROWCOUNT, CUR_NAME%FOUND, CUR_NAME%NOTFOUND, \n CUR_NAME%ISOPEN. It process several rows by using loop. \n The programmer can pass the parameter too to explicit cursor.</p>\n\n<ul>\n<li>Example: Explicit Cursor</li>\n</ul>\n\n<p> </p>\n\n<pre><code>declare \n cursor emp_cursor \n is \n select id,name,salary,dept_id \n from employees; \n v_id employees.id%type; \n v_name employees.name%type; \n v_salary employees.salary%type; \n v_dept_id employees.dept_id%type; \n begin \n open emp_cursor; \n loop \n fetch emp_cursor into v_id,v_name,v_salary,v_dept_id; \n exit when emp_cursor%notfound;\n dbms_output.put_line(v_id||', '||v_name||', '||v_salary||','||v_dept_id); \n end loop; \n close emp_cursor; \n end;\n</code></pre>\n"
},
{
"answer_id": 11323942,
"author": "prince",
"author_id": 1500760,
"author_profile": "https://Stackoverflow.com/users/1500760",
"pm_score": 2,
"selected": false,
"text": "<p>Implicit cursors require anonymous buffer memory. </p>\n\n<p>Explicit cursors can be executed again and again by using their name.They are stored in user defined memory space rather than being stored in an anonymous buffer memory and hence can be easily accessed afterwards.</p>\n"
},
{
"answer_id": 28938170,
"author": "Lalit Kumar B",
"author_id": 3989608,
"author_profile": "https://Stackoverflow.com/users/3989608",
"pm_score": 2,
"selected": false,
"text": "<p><strong>From a performance point of view, Implicit cursors are faster.</strong></p>\n<p>Let's compare the performance between an explicit and implicit cursor:</p>\n<pre><code>SQL> DECLARE\n 2 l_loops NUMBER := 100000;\n 3 l_dummy dual.dummy%TYPE;\n 4 l_start NUMBER;\n 5 -- explicit cursor declaration\n 6 CURSOR c_dual IS\n 7 SELECT dummy\n 8 FROM dual;\n 9 BEGIN\n 10 l_start := DBMS_UTILITY.get_time;\n 11 -- explicitly open, fetch and close the cursor\n 12 FOR i IN 1 .. l_loops LOOP\n 13 OPEN c_dual;\n 14 FETCH c_dual\n 15 INTO l_dummy;\n 16 CLOSE c_dual;\n 17 END LOOP;\n 18\n 19 DBMS_OUTPUT.put_line('Explicit: ' ||\n 20 (DBMS_UTILITY.get_time - l_start) || ' hsecs');\n 21\n 22 l_start := DBMS_UTILITY.get_time;\n 23 -- implicit cursor for loop\n 24 FOR i IN 1 .. l_loops LOOP\n 25 SELECT dummy\n 26 INTO l_dummy\n 27 FROM dual;\n 28 END LOOP;\n 29\n 30 DBMS_OUTPUT.put_line('Implicit: ' ||\n 31 (DBMS_UTILITY.get_time - l_start) || ' hsecs');\n 32 END;\n 33 /\nExplicit: 332 hsecs\nImplicit: 176 hsecs\n\nPL/SQL procedure successfully completed.\n</code></pre>\n<p>So, a significant difference is clearly visible. Implicit cursor is much faster than an explicit cursor.</p>\n<p>More examples <a href=\"http://oracle-base.com/articles/misc/implicit-vs-explicit-cursors-in-oracle-plsql.php\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 47336170,
"author": "Vadzim",
"author_id": 603516,
"author_profile": "https://Stackoverflow.com/users/603516",
"pm_score": 1,
"selected": false,
"text": "<p>As stated in other answers, implicit cursors are easier to use and less error-prone. </p>\n\n<p>And <a href=\"https://oracle-base.com/articles/misc/implicit-vs-explicit-cursors-in-oracle-plsql\" rel=\"nofollow noreferrer\">Implicit vs. Explicit Cursors in Oracle PL/SQL</a> shows that implicit cursors are up to two times faster than explicit ones too.</p>\n\n<p>It's strange that no one had yet mentioned <a href=\"https://docs.oracle.com/cloud/latest/db112/LNPLS/cursor_for_loop_statement.htm#LNPLS1155\" rel=\"nofollow noreferrer\">Implicit FOR LOOP Cursor</a>:</p>\n\n<pre><code>begin\n for cur in (\n select t.id from parent_trx pt inner join trx t on pt.nested_id = t.id\n where t.started_at > sysdate - 31 and t.finished_at is null and t.extended_code is null\n )\n loop\n update trx set finished_at=sysdate, extended_code = -1 where id = cur.id;\n update parent_trx set result_code = -1 where nested_id = cur.id;\n end loop cur;\nend;\n</code></pre>\n\n<p>Another example on SO: <a href=\"https://stackoverflow.com/questions/15854749/pl-sql-for-loop-implicit-cursor\">PL/SQL FOR LOOP IMPLICIT CURSOR</a>.</p>\n\n<p>It's way more shorter than explicit form.</p>\n\n<p>This also provides a nice workaround for <a href=\"https://stackoverflow.com/questions/15113086/postgresql-and-oracle-update-multiple-tables-from-common-subquery/47335611#47335611\">updating multiple tables from CTE</a>.</p>\n"
},
{
"answer_id": 55813639,
"author": "GOVIND DIXIT",
"author_id": 8549281,
"author_profile": "https://Stackoverflow.com/users/8549281",
"pm_score": 1,
"selected": false,
"text": "<p>In PL/SQL, A cursor is a pointer to this context area. It contains all the information needed for processing the statement. </p>\n\n<p><strong>Implicit Cursors:</strong>\nImplicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it.</p>\n\n<p><strong>Explicit Cursors:</strong>\nExplicit cursors are programmer-defined cursors for gaining more control over the context area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns more than one row.</p>\n\n<p>The syntax for creating an explicit cursor is:</p>\n\n<pre><code>CURSOR cursor_name IS select_statement; \n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/74010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
]
| I am a bit rusty on my cursor lingo in PL/SQL. Anyone know this? | An implicit cursor is one created "automatically" for you by Oracle when you execute a query. It is simpler to code, but suffers from
* inefficiency (the ANSI standard specifies that it must fetch twice to check if there is more than one record)
* vulnerability to data errors (if you ever get two rows, it raises a TOO\_MANY\_ROWS exception)
Example
```
SELECT col INTO var FROM table WHERE something;
```
An explicit cursor is one you create yourself. It takes more code, but gives more control - for example, you can just open-fetch-close if you only want the first record and don't care if there are others.
Example
```
DECLARE
CURSOR cur IS SELECT col FROM table WHERE something;
BEGIN
OPEN cur;
FETCH cur INTO var;
CLOSE cur;
END;
``` |
74,019 | <p>How can I specify the filename when dumping data into the response stream?</p>
<p>Right now I'm doing the following:</p>
<pre><code>byte[] data= GetFoo();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.BinaryWrite(data);
Response.End();
</code></pre>
<p>With the code above, I get "foo.aspx.pdf" as the filename to save. I seem to remember being able to add a header to the response to specify the filename to save.</p>
| [
{
"answer_id": 74044,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 4,
"selected": false,
"text": "<pre><code>Response.AppendHeader(\"Content-Disposition\", \"attachment; filename=foo.pdf\");\n</code></pre>\n"
},
{
"answer_id": 74049,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 7,
"selected": true,
"text": "<p>Add a content-disposition to the header: </p>\n\n<pre><code>Response.AddHeader(\"content-disposition\", @\"attachment;filename=\"\"MyFile.pdf\"\"\");\n</code></pre>\n"
},
{
"answer_id": 74060,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 1,
"selected": false,
"text": "<pre><code> Response.AddHeader(\"Content-Disposition\", \"attachment;filename=\" & FileName & \";\")\n</code></pre>\n"
},
{
"answer_id": 14347162,
"author": "EMR",
"author_id": 729980,
"author_profile": "https://Stackoverflow.com/users/729980",
"pm_score": 5,
"selected": false,
"text": "<p>FYI... if you use \"inline\" instead of \"attachment\" the file will open automatically in IE. Instead of prompting the user with a Open/Save dialogue.</p>\n\n<pre><code>Response.AppendHeader(\"content-disposition\", string.Format(\"inline;FileName=\\\"{0}\\\"\", fileName));\n</code></pre>\n"
},
{
"answer_id": 30972670,
"author": "Sam",
"author_id": 238753,
"author_profile": "https://Stackoverflow.com/users/238753",
"pm_score": 2,
"selected": false,
"text": "<p>For some reason, most of the answers out there don't seem to even attempt to encode the file name value. If the file contains spaces, semicolons or quotes, it mightn't come across correctly.</p>\n\n<p>It looks like you can use the <a href=\"http://msdn.microsoft.com/library/system.net.mime.contentdisposition.aspx\" rel=\"nofollow\"><code>ContentDisposition</code></a> class to generate a correct header value:</p>\n\n<pre><code>Response.AppendHeader(\"Content-Disposition\", new ContentDisposition\n{\n FileName = yourFilename\n}.ToString());\n</code></pre>\n\n<p>You can check out <a href=\"http://referencesource.microsoft.com/System/net/System/Net/mail/ContentDisposition.cs.html#234ee68565525ad0\" rel=\"nofollow\">the source code for <code>ContentDisposition.ToString()</code></a> to confirm that it's trying to encode it properly.</p>\n\n<p><strong>Warning</strong>: This seems to crash when the filename contains a dash (not a hyphen). I haven't bothered looking into this yet.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/74019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1672/"
]
| How can I specify the filename when dumping data into the response stream?
Right now I'm doing the following:
```
byte[] data= GetFoo();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.BinaryWrite(data);
Response.End();
```
With the code above, I get "foo.aspx.pdf" as the filename to save. I seem to remember being able to add a header to the response to specify the filename to save. | Add a content-disposition to the header:
```
Response.AddHeader("content-disposition", @"attachment;filename=""MyFile.pdf""");
``` |
74,032 | <p>I'm looking for real world best practices, how other people might have implemented solutions with complex domains.</p>
| [
{
"answer_id": 74070,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 2,
"selected": false,
"text": "<p>This is what <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.iequalitycomparer.aspx\" rel=\"nofollow noreferrer\">MSDN</a> has to say about IEqualityComparer (non-generic):</p>\n<blockquote>\n<p>This interface allows the implementation of customized equality comparison for collections. That is, you can create your own definition of equality, and specify that this definition be used with a collection type that accepts the <code>IEqualityComparer</code> interface. In the .NET Framework, constructors of the <code>Hashtable</code>, <code>NameValueCollection</code>, and <code>OrderedDictionary</code> collection types accept this interface.</p>\n<p>This interface supports only equality comparisons. Customization of comparisons for sorting and ordering is provided by the <code>IComparer</code> interface.</p>\n</blockquote>\n<p>It looks like the generic version of this interface performs the same function but is used for <code>Dictionary<(Of <(TKey, TValue>)>)</code> collections.</p>\n<p>As far as best practices around using this interface for your own purposes. I would say that the best practice would be to use it when you are deriving or implementing a class that has similar functionality to the above mentioned .NET framework collections and where you want to add the same capability to your own collections. This will ensure that you are consistent with how the .NET framework uses the interface.</p>\n<p>In other words support the use of this interface if you are developing a custom collection and you want to allow your consumers to control equality which is used in a number of LINQ and collection related methods (eg. Sort).</p>\n"
},
{
"answer_id": 74110,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 1,
"selected": false,
"text": "<p>I would say that the best use would be when you need to plug in different equality rules for a certain algorithm. Much in the same way that a sorting algorithm might accept an <code>IComparer<T></code>, a finding algorithm might accept an <code>IEqualityComparer<T></code></p>\n"
},
{
"answer_id": 74125,
"author": "Jesper Blad Jensen",
"author_id": 11559,
"author_profile": "https://Stackoverflow.com/users/11559",
"pm_score": 1,
"selected": false,
"text": "<p>The list uses this interface alot, so you can say a.Substract(b) or other of these nice functions.</p>\n\n<p>Just remember: If you're objects don't return the same Hashcode, the Equals is not called.</p>\n"
},
{
"answer_id": 533826,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I did the following, I'm not sure if it is real-world best practice, but it worked fine for me. :)</p>\n\n<pre><code>public class GenericEqualityComparer<T> : IEqualityComparer<T>\n{\n private Func<T, T, Boolean> _comparer;\n private Func<T, int> _hashCodeEvaluator;\n public GenericEqualityComparer(Func<T, T, Boolean> comparer)\n {\n _comparer = comparer;\n }\n\n public GenericEqualityComparer(Func<T, T, Boolean> comparer, Func<T, int> hashCodeEvaluator)\n {\n _comparer = comparer;\n _hashCodeEvaluator = hashCodeEvaluator;\n }\n\n #region IEqualityComparer<T> Members\n\n public bool Equals(T x, T y)\n {\n return _comparer(x, y);\n }\n\n public int GetHashCode(T obj)\n {\n if(obj == null) {\n throw new ArgumentNullException(\"obj\");\n }\n if(_hashCodeEvaluator == null) {\n return 0;\n } \n return _hashCodeEvaluator(obj);\n }\n\n #endregion\n}\n</code></pre>\n\n<p>Then you can use it in your collections.</p>\n\n<pre><code>var comparer = new GenericEqualityComparer<ShopByProduct>((x, y) => x.ProductId == y.ProductId);\nvar current = SelectAll().Where(p => p.ShopByGroup == group).ToList();\nvar toDelete = current.Except(products, comparer);\nvar toAdd = products.Except(current, comparer);\n</code></pre>\n\n<p>If you need to support custom GetHashCode() functionality, use the alternative constructor to provide a lambda to do the alternative calculation:</p>\n\n<pre><code>var comparer = new GenericEqualityComparer<ShopByProduct>(\n (x, y) => { return x.ProductId == y.ProductId; }, \n (x) => { return x.Product.GetHashCode()}\n);\n</code></pre>\n\n<p>I hope this helps. =)</p>\n"
},
{
"answer_id": 1535426,
"author": "dahlbyk",
"author_id": 54249,
"author_profile": "https://Stackoverflow.com/users/54249",
"pm_score": 4,
"selected": false,
"text": "<p>Any time you consider using an <code>IEqualityComparer<T></code>, pause to think if the class could be made to implement <code>IEquatable<T></code> instead. If a <code>Product</code> should always be compared by ID, just define it to be equated as such so you can use the default comparer.</p>\n\n<p>That said, there are still a few of reasons you might want a custom comparer:</p>\n\n<ol>\n<li>If there are multiple ways instances of a class could be considered equal. The best example of this is a string, for which the framework provides six different comparers in <a href=\"http://msdn.microsoft.com/en-us/library/system.stringcomparer.aspx\" rel=\"noreferrer\"><code>StringComparer</code></a>.</li>\n<li>If the class is defined in such a way that you can't define it as <code>IEquatable<T></code>. This would include classes defined by others and classes generated by the compiler (specifically anonymous types, which use a property-wise comparison by default).</li>\n</ol>\n\n<p>If you do decide you need a comparer, you can certainly use a generalized comparer (see DMenT's answer), but if you need to reuse that logic you should encapsulate it in a dedicated class. You could even declare it by inheriting from the generic base:</p>\n\n<pre><code>class ProductByIdComparer : GenericEqualityComparer<ShopByProduct>\n{\n public ProductByIdComparer()\n : base((x, y) => x.ProductId == y.ProductId, z => z.ProductId)\n { }\n}\n</code></pre>\n\n<p>As far as use, you should take advantage of comparers when possible. For example, rather than calling <code>ToLower()</code> on every string used as a dictionary key (logic for which will be strewn across your app), you should declare the dictionary to use a case-insensitive <code>StringComparer</code>. The same goes for the LINQ operators that accept a comparer. But again, always consider if the equatable behavior that should be intrinsic to the class rather than defined externally.</p>\n"
},
{
"answer_id": 4679491,
"author": "Peet Brits",
"author_id": 371917,
"author_profile": "https://Stackoverflow.com/users/371917",
"pm_score": 3,
"selected": false,
"text": "<p>See this post for (better) alternatives: <a href=\"https://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer\">Wrap a delegate in an IEqualityComparer</a></p>\n\n<p>Scroll down to the part on <a href=\"https://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer/1239337#1239337\">KeyEqualityComparer</a> and especially the part on <a href=\"https://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer/3719802#3719802\">the importance of GetHashCode</a>. There is a whole <a href=\"https://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer/3719617#3719617\">discussion</a> on why <code>obj.GetHashCode();</code> (as suggested by DMenT's post) is wrong and should just return 0 instead.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/74032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5802/"
]
| I'm looking for real world best practices, how other people might have implemented solutions with complex domains. | Any time you consider using an `IEqualityComparer<T>`, pause to think if the class could be made to implement `IEquatable<T>` instead. If a `Product` should always be compared by ID, just define it to be equated as such so you can use the default comparer.
That said, there are still a few of reasons you might want a custom comparer:
1. If there are multiple ways instances of a class could be considered equal. The best example of this is a string, for which the framework provides six different comparers in [`StringComparer`](http://msdn.microsoft.com/en-us/library/system.stringcomparer.aspx).
2. If the class is defined in such a way that you can't define it as `IEquatable<T>`. This would include classes defined by others and classes generated by the compiler (specifically anonymous types, which use a property-wise comparison by default).
If you do decide you need a comparer, you can certainly use a generalized comparer (see DMenT's answer), but if you need to reuse that logic you should encapsulate it in a dedicated class. You could even declare it by inheriting from the generic base:
```
class ProductByIdComparer : GenericEqualityComparer<ShopByProduct>
{
public ProductByIdComparer()
: base((x, y) => x.ProductId == y.ProductId, z => z.ProductId)
{ }
}
```
As far as use, you should take advantage of comparers when possible. For example, rather than calling `ToLower()` on every string used as a dictionary key (logic for which will be strewn across your app), you should declare the dictionary to use a case-insensitive `StringComparer`. The same goes for the LINQ operators that accept a comparer. But again, always consider if the equatable behavior that should be intrinsic to the class rather than defined externally. |
74,057 | <p>Is there a way to use sql-server like analytic functions in Hibernate?</p>
<p>Something like </p>
<pre><code>select foo from Foo foo where f.x = max(f.x) over (partition by f.y)
</code></pre>
| [
{
"answer_id": 75287,
"author": "Jason Weathered",
"author_id": 3736,
"author_profile": "https://Stackoverflow.com/users/3736",
"pm_score": 3,
"selected": false,
"text": "<p>You are after a native SQL query.</p>\n\n<p>If you are using JPA the syntax is:</p>\n\n<pre><code>Query q = em.createNativeQuery(\"select foo.* from Foo foo \" +\n \"where f.x = max(f.x) over \" +\n \"(partition by f.y)\", Foo.class);\n</code></pre>\n\n<p>If you need to return multiple types, take a look at the <a href=\"http://java.sun.com/javaee/5/docs/api/javax/persistence/SqlResultSetMapping.html\" rel=\"noreferrer\">SQLResultSetMapping</a> annotation.</p>\n\n<p>If you're using the the Hibernate API directly:</p>\n\n<pre><code>Query q = session.createSQLQuery(\"select {foo.*} from Foo foo \" +\n \"where f.x = max(f.x) over \"+\n \"(partition by f.y)\");\nq.addEntity(\"foo\", Foo.class);\n</code></pre>\n\n<p>See <a href=\"http://www.hibernate.org/hib_docs/v3/reference/en/html/objectstate.html#objectstate-querying-nativesql\" rel=\"noreferrer\">10.4.4. Queries in native SQL</a> in the Hibernate documentation for more details.</p>\n\n<p>In both APIs you can pass in parameters as normal using setParameter. </p>\n"
},
{
"answer_id": 2027784,
"author": "Petr Macek",
"author_id": 15045,
"author_profile": "https://Stackoverflow.com/users/15045",
"pm_score": 2,
"selected": false,
"text": "<p>Another approach would be to use the mapping. Please see this article: <a href=\"https://forums.hibernate.org/viewtopic.php?f=1&t=998482\" rel=\"nofollow noreferrer\">https://forums.hibernate.org/viewtopic.php?f=1&t=998482</a></p>\n\n<p>I am against the usage of native SQL queries in Hibernate... you lose the benefits of having a mapping:-)</p>\n"
},
{
"answer_id": 33003427,
"author": "Eric Mayes",
"author_id": 1661071,
"author_profile": "https://Stackoverflow.com/users/1661071",
"pm_score": 2,
"selected": false,
"text": "<p>Yes you can, but you will need to extend the hibernate dialect like the following:</p>\n\n<p>import org.hibernate.dialect.Oracle10gDialect;</p>\n\n<pre><code>public class ExtendedDialect extends Oracle10gDialect{\n public ExtendedDialect()\n {\n super();\n registerKeyword(\"over\");\n registerKeyword(\"partition\");\n }\n}\n</code></pre>\n\n<p>Once this class is on your classpath, you will need to tell hibernate to use it instead of the original dialect (in this case Oracle10gDialect). I am not sure which frameworks you are using, but in the case of Spring, you can use the following property under the LocalContainerEntityManagerFactoryBean:</p>\n\n<pre><code> <property name=\"jpaVendorAdapter\">\n <bean class=\"org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter\">\n <property name=\"databasePlatform\" value=\"path.to.dialect.ExtendedDialect\" />\n </bean>\n </property>\n</code></pre>\n\n<p>Then you can use over and partition in @Formula annotations, @Where annotations and other hibernate features without confusing hibernate.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/74057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12905/"
]
| Is there a way to use sql-server like analytic functions in Hibernate?
Something like
```
select foo from Foo foo where f.x = max(f.x) over (partition by f.y)
``` | You are after a native SQL query.
If you are using JPA the syntax is:
```
Query q = em.createNativeQuery("select foo.* from Foo foo " +
"where f.x = max(f.x) over " +
"(partition by f.y)", Foo.class);
```
If you need to return multiple types, take a look at the [SQLResultSetMapping](http://java.sun.com/javaee/5/docs/api/javax/persistence/SqlResultSetMapping.html) annotation.
If you're using the the Hibernate API directly:
```
Query q = session.createSQLQuery("select {foo.*} from Foo foo " +
"where f.x = max(f.x) over "+
"(partition by f.y)");
q.addEntity("foo", Foo.class);
```
See [10.4.4. Queries in native SQL](http://www.hibernate.org/hib_docs/v3/reference/en/html/objectstate.html#objectstate-querying-nativesql) in the Hibernate documentation for more details.
In both APIs you can pass in parameters as normal using setParameter. |
74,083 | <p>When using Business Objects' CrystalReportViewer control, how can you detect and manually print the report the user has currently drilled into? You can print this automatically using the Print() method of the CrystalReportViewer, but I want to be able to do a manual printing of this report.</p>
<p>It is possible to print the main ReportSource of the CrystalReportViewer, but I need to know what report the user has drilled into and then do a manual printing of that particular drill down. Any ideas?</p>
| [
{
"answer_id": 75287,
"author": "Jason Weathered",
"author_id": 3736,
"author_profile": "https://Stackoverflow.com/users/3736",
"pm_score": 3,
"selected": false,
"text": "<p>You are after a native SQL query.</p>\n\n<p>If you are using JPA the syntax is:</p>\n\n<pre><code>Query q = em.createNativeQuery(\"select foo.* from Foo foo \" +\n \"where f.x = max(f.x) over \" +\n \"(partition by f.y)\", Foo.class);\n</code></pre>\n\n<p>If you need to return multiple types, take a look at the <a href=\"http://java.sun.com/javaee/5/docs/api/javax/persistence/SqlResultSetMapping.html\" rel=\"noreferrer\">SQLResultSetMapping</a> annotation.</p>\n\n<p>If you're using the the Hibernate API directly:</p>\n\n<pre><code>Query q = session.createSQLQuery(\"select {foo.*} from Foo foo \" +\n \"where f.x = max(f.x) over \"+\n \"(partition by f.y)\");\nq.addEntity(\"foo\", Foo.class);\n</code></pre>\n\n<p>See <a href=\"http://www.hibernate.org/hib_docs/v3/reference/en/html/objectstate.html#objectstate-querying-nativesql\" rel=\"noreferrer\">10.4.4. Queries in native SQL</a> in the Hibernate documentation for more details.</p>\n\n<p>In both APIs you can pass in parameters as normal using setParameter. </p>\n"
},
{
"answer_id": 2027784,
"author": "Petr Macek",
"author_id": 15045,
"author_profile": "https://Stackoverflow.com/users/15045",
"pm_score": 2,
"selected": false,
"text": "<p>Another approach would be to use the mapping. Please see this article: <a href=\"https://forums.hibernate.org/viewtopic.php?f=1&t=998482\" rel=\"nofollow noreferrer\">https://forums.hibernate.org/viewtopic.php?f=1&t=998482</a></p>\n\n<p>I am against the usage of native SQL queries in Hibernate... you lose the benefits of having a mapping:-)</p>\n"
},
{
"answer_id": 33003427,
"author": "Eric Mayes",
"author_id": 1661071,
"author_profile": "https://Stackoverflow.com/users/1661071",
"pm_score": 2,
"selected": false,
"text": "<p>Yes you can, but you will need to extend the hibernate dialect like the following:</p>\n\n<p>import org.hibernate.dialect.Oracle10gDialect;</p>\n\n<pre><code>public class ExtendedDialect extends Oracle10gDialect{\n public ExtendedDialect()\n {\n super();\n registerKeyword(\"over\");\n registerKeyword(\"partition\");\n }\n}\n</code></pre>\n\n<p>Once this class is on your classpath, you will need to tell hibernate to use it instead of the original dialect (in this case Oracle10gDialect). I am not sure which frameworks you are using, but in the case of Spring, you can use the following property under the LocalContainerEntityManagerFactoryBean:</p>\n\n<pre><code> <property name=\"jpaVendorAdapter\">\n <bean class=\"org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter\">\n <property name=\"databasePlatform\" value=\"path.to.dialect.ExtendedDialect\" />\n </bean>\n </property>\n</code></pre>\n\n<p>Then you can use over and partition in @Formula annotations, @Where annotations and other hibernate features without confusing hibernate.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/74083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| When using Business Objects' CrystalReportViewer control, how can you detect and manually print the report the user has currently drilled into? You can print this automatically using the Print() method of the CrystalReportViewer, but I want to be able to do a manual printing of this report.
It is possible to print the main ReportSource of the CrystalReportViewer, but I need to know what report the user has drilled into and then do a manual printing of that particular drill down. Any ideas? | You are after a native SQL query.
If you are using JPA the syntax is:
```
Query q = em.createNativeQuery("select foo.* from Foo foo " +
"where f.x = max(f.x) over " +
"(partition by f.y)", Foo.class);
```
If you need to return multiple types, take a look at the [SQLResultSetMapping](http://java.sun.com/javaee/5/docs/api/javax/persistence/SqlResultSetMapping.html) annotation.
If you're using the the Hibernate API directly:
```
Query q = session.createSQLQuery("select {foo.*} from Foo foo " +
"where f.x = max(f.x) over "+
"(partition by f.y)");
q.addEntity("foo", Foo.class);
```
See [10.4.4. Queries in native SQL](http://www.hibernate.org/hib_docs/v3/reference/en/html/objectstate.html#objectstate-querying-nativesql) in the Hibernate documentation for more details.
In both APIs you can pass in parameters as normal using setParameter. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.