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
41,699
<p>So creating a Windows service using Visual Studio is fairly trivial. My question goes a bit deeper as to what actually makes an executable installable as a service &amp; how to write a service as a straight C application. I couldn't find a lot of references on this, but I'm presuming there has to be some interface I can implement so my .exe can be installed as a service.</p>
[ { "answer_id": 41706, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 1, "selected": false, "text": "<p>Hope this helps:</p>\n<p><a href=\"http://support.microsoft.com/kb/251192\" rel=\"nofollow noreferrer\">http://support.mi...
2008/09/03
[ "https://Stackoverflow.com/questions/41699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/634/" ]
So creating a Windows service using Visual Studio is fairly trivial. My question goes a bit deeper as to what actually makes an executable installable as a service & how to write a service as a straight C application. I couldn't find a lot of references on this, but I'm presuming there has to be some interface I can implement so my .exe can be installed as a service.
Setting up your executable as a service is part of it, but realistically it's usually handled by whatever installation software you're using. You can use the command line SC tool while testing (or if you don't need an installer). The important thing is that your program has to call StartServiceCtrlDispatcher() upon startup. This connects your service to the service control manager and sets up a ServiceMain routine which is your services main entry point. ServiceMain (you can call it whatever you like actually, but it always seems to be ServiceMain) should then call RegisterServiceCtrlHandlerEx() to define a callback routine so that the OS can notify your service when certain events occur. Here are some snippets from a service I wrote a few years ago: set up as service: ``` SERVICE_TABLE_ENTRY ServiceStartTable[] = { { "ServiceName", ServiceMain }, { 0, 0 } }; if (!StartServiceCtrlDispatcher(ServiceStartTable)) { DWORD err = GetLastError(); if (err == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) return false; } ``` ServiceMain: ``` void WINAPI ServiceMain(DWORD, LPTSTR*) { hServiceStatus = RegisterServiceCtrlHandlerEx("ServiceName", ServiceHandlerProc, 0); ``` service handler: ``` DWORD WINAPI ServiceHandlerProc(DWORD ControlCode, DWORD, void*, void*) { switch (ControlCode) { case SERVICE_CONTROL_INTERROGATE : // update OS about our status case SERVICE_CONTROL_STOP : // shut down service } return 0; } ```
41,701
<p>I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)</p> <p>For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job</p> <p>I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?</p> <p>Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields</p> <p>or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)</p>
[ { "answer_id": 41707, "author": "Chris Upchurch", "author_id": 2600, "author_profile": "https://Stackoverflow.com/users/2600", "pm_score": 5, "selected": true, "text": "<p>I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each valu...
2008/09/03
[ "https://Stackoverflow.com/questions/41701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4397/" ]
I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username) For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this? Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)
I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values. For example: ``` job={} job['jobid'], job['label'], job['username']=<querycode> ```
41,717
<p>Like many others on this site I am considering a move to ASP.NET MVC for future projects. Currently my sites are running the traditional ASP.NET 2.0 Web Forms, and it works OK for us, so my other option is just to stick with what I know and make the move to ASP.NET 3.5 with the integrated AJAX stuff.</p> <p>I'm wondering about how user controls work in ASP.NET MVC. We have tons of <code>.ASCX</code> controls, and a few composite controls. When I work with web designers it is very easy to get them to use ASCX controls effectively, even without any programming knowledge, so that's a definite plus. But then of course the downsides are the page life cycle, which can be maddening, and the fact that ASCX controls are hard to share between different projects. Composite controls are share-able, but basically a black box to a designer.</p> <p>What's the model in ASP.NET MVC? Is there a way to create controls that solves the problems we've dealt with using ASCX and composite controls? Allowing easy access for web designers without having to worry about code being broken is an important consideration.</p>
[ { "answer_id": 41722, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 4, "selected": true, "text": "<p>To implement a user control you do the following call:</p>\n\n<pre><code>&lt;% Html.RenderPartial(\"~/Views/Shared/MyContr...
2008/09/03
[ "https://Stackoverflow.com/questions/41717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
Like many others on this site I am considering a move to ASP.NET MVC for future projects. Currently my sites are running the traditional ASP.NET 2.0 Web Forms, and it works OK for us, so my other option is just to stick with what I know and make the move to ASP.NET 3.5 with the integrated AJAX stuff. I'm wondering about how user controls work in ASP.NET MVC. We have tons of `.ASCX` controls, and a few composite controls. When I work with web designers it is very easy to get them to use ASCX controls effectively, even without any programming knowledge, so that's a definite plus. But then of course the downsides are the page life cycle, which can be maddening, and the fact that ASCX controls are hard to share between different projects. Composite controls are share-able, but basically a black box to a designer. What's the model in ASP.NET MVC? Is there a way to create controls that solves the problems we've dealt with using ASCX and composite controls? Allowing easy access for web designers without having to worry about code being broken is an important consideration.
To implement a user control you do the following call: ``` <% Html.RenderPartial("~/Views/Shared/MyControl.ascx", {data model object}) %> ``` You may also see the older syntax which as of PR5 is not valid anymore ``` <%= Html.RenderUserControl("~/Views/Shared/MyControl.ascx", {data model object}) %> ``` You will always have to worry about code breaking when moving from Web Forms to MVC, however the ASP.NET MVC team has done a great job to minimize the problems.
41,724
<p>I'm hearing more and more about domain specific languages being thrown about and how they change the way you treat business logic, and I've seen <a href="http://ayende.com/blog/tags/domain-specific-languages" rel="noreferrer">Ayende's blog posts</a> and things, but I've never really gotten exactly why I would take my business logic away from the methods and situations I'm using in my provider.</p> <p>If you've got some background using these things, any chance you could put it in real laymans terms:</p> <ul> <li>What exactly building DSLs means?</li> <li>What languages are you using?</li> <li>Where using a DSL makes sense?</li> <li>What is the benefit of using DSLs?</li> </ul>
[ { "answer_id": 41735, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": false, "text": "<p><strong>DSL</strong> stands for <em>Domain Specific Language</em> i.e. language designed specifically for solving problems in ...
2008/09/03
[ "https://Stackoverflow.com/questions/41724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3717/" ]
I'm hearing more and more about domain specific languages being thrown about and how they change the way you treat business logic, and I've seen [Ayende's blog posts](http://ayende.com/blog/tags/domain-specific-languages) and things, but I've never really gotten exactly why I would take my business logic away from the methods and situations I'm using in my provider. If you've got some background using these things, any chance you could put it in real laymans terms: * What exactly building DSLs means? * What languages are you using? * Where using a DSL makes sense? * What is the benefit of using DSLs?
DSL's are good in situations where you need to give some aspect of the system's control over to someone else. I've used them in Rules Engines, where you create a simple language that is easier for less-technical folks to use to express themselves- particularly in workflows. In other words, instead of making them learn java: ``` DocumentDAO myDocumentDAO = ServiceLocator.getDocumentDAO(); for (int id : documentIDS) { Document myDoc = MyDocumentDAO.loadDoc(id); if (myDoc.getDocumentStatus().equals(DocumentStatus.UNREAD)) { ReminderService.sendUnreadReminder(myDoc) } ``` I can write a DSL that lets me say: ``` for (document : documents) { if (document is unread) { document.sendReminder } ``` There are other situations, but basically, anywhere you might want to use a macro language, script a workflow, or allow after-market customization- these are all candidates for DSL's.
41,733
<p>Say I have an array of records which I want to sort based on one of the fields in the record. What's the best way to achieve this?</p> <pre><code>TExample = record SortOrder : integer; SomethingElse : string; end; var SomeVar : array of TExample; </code></pre>
[ { "answer_id": 41809, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 0, "selected": false, "text": "<p>Use one of the sort alorithms propose by <a href=\"http://en.wikipedia.org/wiki/Sorting_algorithm\" rel=...
2008/09/03
[ "https://Stackoverflow.com/questions/41733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1008/" ]
Say I have an array of records which I want to sort based on one of the fields in the record. What's the best way to achieve this? ``` TExample = record SortOrder : integer; SomethingElse : string; end; var SomeVar : array of TExample; ```
You can add pointers to the elements of the array to a `TList`, then call `TList.Sort` with a comparison function, and finally create a new array and copy the values out of the TList in the desired order. However, if you're using the next version, D2009, there is a new collections library which can sort arrays. It takes an optional `IComparer<TExample>` implementation for custom sorting orders. Here it is in action for your specific case: ``` TArray.Sort<TExample>(SomeVar , TDelegatedComparer<TExample>.Construct( function(const Left, Right: TExample): Integer begin Result := TComparer<Integer>.Default.Compare(Left.SortOrder, Right.SortOrder); end)); ```
41,763
<p>What is the best way to calculate Age using Flex?</p>
[ { "answer_id": 41845, "author": "Richard Braxton", "author_id": 4393, "author_profile": "https://Stackoverflow.com/users/4393", "pm_score": 4, "selected": false, "text": "<p>I found an answer at <a href=\"http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?conte...
2008/09/03
[ "https://Stackoverflow.com/questions/41763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4393/" ]
What is the best way to calculate Age using Flex?
I found an answer at [the bottom of this page in comments section (which is now offline)](http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Book_Parts&file=08_Dates_and_times_164_2.html). > > **jpwrunyan said on Apr 30, 2007 at 10:10 PM :** > > > > > > > By the way, here is how to calculate age in years (only) from DOB without needing to account for leap years: > > > > > > > > > With a slight correction by [Fine-Wei Lin](https://stackoverflow.com/users/210612/fine-wei-lin), the code reads ``` private function getYearsOld(dob:Date):uint { var now:Date = new Date(); var yearsOld:uint = Number(now.fullYear) - Number(dob.fullYear); if (dob.month > now.month || (dob.month == now.month && dob.date > now.date)) { yearsOld--; } return yearsOld; } ``` > > > > > > This handles most situations where you need to calculate age. > > > > > > > > >
41,792
<p>I am re-factoring some code and am wondering about the use of a <code>lock</code> in the instance constructor.</p> <pre><code>public class MyClass { private static Int32 counter = 0; private Int32 myCount; public MyClass() { lock(this) { counter++; myCount = counter; } } } </code></pre> <p>Please confirm</p> <ol> <li>Instance constructors are thread-safe.</li> <li>The lock statement prevents access to that code block, not to the static 'counter' member.</li> </ol> <p>If the intent of the original programmer were to have each instance know its 'count', how would I synchronize access to the 'counter' member to ensure that another thread isn't new'ing a <code>MyClass</code> and changing the count before this one sets its count?</p> <p><em>FYI - This class is not a singleton. Instances must simply be aware of their number.</em></p>
[ { "answer_id": 41801, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 2, "selected": false, "text": "<p>I'm guessing this is for a singleton pattern or something like it. What you want to do is not lock your object, but lock ...
2008/09/03
[ "https://Stackoverflow.com/questions/41792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3619/" ]
I am re-factoring some code and am wondering about the use of a `lock` in the instance constructor. ``` public class MyClass { private static Int32 counter = 0; private Int32 myCount; public MyClass() { lock(this) { counter++; myCount = counter; } } } ``` Please confirm 1. Instance constructors are thread-safe. 2. The lock statement prevents access to that code block, not to the static 'counter' member. If the intent of the original programmer were to have each instance know its 'count', how would I synchronize access to the 'counter' member to ensure that another thread isn't new'ing a `MyClass` and changing the count before this one sets its count? *FYI - This class is not a singleton. Instances must simply be aware of their number.*
@ajmastrean I am not saying you should use the singleton pattern itself, but adopt its method of encapsulating the instantiation process. i.e. * Make the constructor private. * Create a static instance method that returns the type. * In the static instance method, use the lock keyword before instantiating. * Instantiate a new instance of the type. * Increment the count. * Unlock and return the new instance. ### EDIT One problem that has occurred to me, if how would you know when the count has gone down? ;) ### EDIT AGAIN Thinking about it, you could add code to the destructor that calls another static method to decrement the counter :D
41,824
<p>I'm using Microsoft AjaxControlToolkit for modal popup window.</p> <p>And on a modal popup window, when a postback occurred, the window was closing. How do I prevent from the closing action of the modal popup?</p>
[ { "answer_id": 41910, "author": "Ricky Supit", "author_id": 4191, "author_profile": "https://Stackoverflow.com/users/4191", "pm_score": 3, "selected": false, "text": "<p>You can call <code>Show()</code> method during postback to prevent the modal popup window from closing</p>\n\n<pre><co...
2008/09/03
[ "https://Stackoverflow.com/questions/41824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4215/" ]
I'm using Microsoft AjaxControlToolkit for modal popup window. And on a modal popup window, when a postback occurred, the window was closing. How do I prevent from the closing action of the modal popup?
Put you controls inside the update panel. Please see my sample code, pnlControls is control that holds controls that will be displayed on popup: ``` <asp:Panel ID="pnlControls" runat="server"> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:Button ID="TestButton" runat="server" Text="Test Button" onclick="TestButton_Click" /> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </ContentTemplate> </asp:UpdatePanel> ``` This will do the job for you :) Best regards, Gregor Primar
41,836
<p>I have tried both of :</p> <pre><code>ini_set('include_path', '.:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes'); </code></pre> <p>and also :</p> <pre><code>php_value include_path ".:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes" </code></pre> <p>in the .htaccess file.</p> <p>Both methods actually <strong>do work</strong> but only intermittently. That is, they will work fine for about 37 pages requests and then fail about 42 pages requests resulting in an require() call to cause a fatal error effectively crashing the site.</p> <p>I'm not even sure where to begin trying to find out what is going on!</p> <hr> <p>@<a href="https://stackoverflow.com/questions/41836/setting-include-path-in-php-intermittently-fails-why#41877">cnote</a></p> <blockquote> <p>Looks like you duplicated the current directory in your include path. Try removing one of the '.:' from your string.</p> </blockquote> <p>The in script version was originally </p> <pre><code>ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes'); </code></pre> <p>and thus the .:.: was coming from the existing path:</p> <pre><code>ini_get('include_path') </code></pre> <p>I tried removing it anyway and the problem persists.</p>
[ { "answer_id": 41877, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Looks like you duplicated the current directory in your include path. Try removing one of the '.:' from your string.</p>\n" ...
2008/09/03
[ "https://Stackoverflow.com/questions/41836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/319/" ]
I have tried both of : ``` ini_set('include_path', '.:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes'); ``` and also : ``` php_value include_path ".:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes" ``` in the .htaccess file. Both methods actually **do work** but only intermittently. That is, they will work fine for about 37 pages requests and then fail about 42 pages requests resulting in an require() call to cause a fatal error effectively crashing the site. I'm not even sure where to begin trying to find out what is going on! --- @[cnote](https://stackoverflow.com/questions/41836/setting-include-path-in-php-intermittently-fails-why#41877) > > Looks like you duplicated the current directory in your include path. Try removing one of the '.:' from your string. > > > The in script version was originally ``` ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes'); ``` and thus the .:.: was coming from the existing path: ``` ini_get('include_path') ``` I tried removing it anyway and the problem persists.
It turned out the issue was related to a PHP bug in 5.2.5 Setting an "admin\_flag" for include\_path caused the include path to be empty in some requests, and Plesk sets an admin\_flag in the default config for something or other. An update of PHP solved the issue. <http://bugs.php.net/bug.php?id=43677>
41,839
<p>I'm writing a tool to run a series of integration tests on my product. It will install it and then run a bunch of commands against it to make sure its doing what it is supposed to. I'm exploring different options for how to markup the commands for each test case and wondering if folks had insight to share on this. I'm thinking of using YAML and doing something like this (kinda adapted from rails fixtures): </p> <pre><code>case: name: caseN description: this tests foo to make sure bar happens expected_results: bar should happen commands: | command to run next command to run verification: command to see if it worked </code></pre> <p>Does anyone have another, or better idea? Or is there a domain specific language I'm unaware of? </p>
[ { "answer_id": 41848, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 1, "selected": false, "text": "<p>You might want to check out <a href=\"http://www.cpan.org/\" rel=\"nofollow noreferrer\">CPAN</a>. It does for Perl scrip...
2008/09/03
[ "https://Stackoverflow.com/questions/41839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/511/" ]
I'm writing a tool to run a series of integration tests on my product. It will install it and then run a bunch of commands against it to make sure its doing what it is supposed to. I'm exploring different options for how to markup the commands for each test case and wondering if folks had insight to share on this. I'm thinking of using YAML and doing something like this (kinda adapted from rails fixtures): ``` case: name: caseN description: this tests foo to make sure bar happens expected_results: bar should happen commands: | command to run next command to run verification: command to see if it worked ``` Does anyone have another, or better idea? Or is there a domain specific language I'm unaware of?
Go and have a look at the XUnit suite of test tools. This framework was originally designed for Smalltalk by Kent Beck and, I think, Erich Gamma, and it has now been ported to a whole stack of other languages, e.g. [CUnit](http://cunit.sourceforge.net/)
41,869
<p>If I run the following query in SQL Server 2000 Query Analyzer:</p> <pre><code>BULK INSERT OurTable FROM 'c:\OurTable.txt' WITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\t', ROWS_PER_BATCH = 10000, TABLOCK) </code></pre> <p>On a text file that conforms to OurTable's schema for 40 lines, but then changes format for the last 20 lines (lets say the last 20 lines have fewer fields), I receive an error. However, the first 40 lines are committed to the table. Is there something about the way I'm calling Bulk Insert that makes it not be transactional, or do I need to do something explicit to force it to rollback on failure?</p>
[ { "answer_id": 41942, "author": "kaiz.net", "author_id": 3714, "author_profile": "https://Stackoverflow.com/users/3714", "pm_score": 0, "selected": false, "text": "<p>Try to put it inside user-defined transaction and see what happens. Actually it should roll-back as you described it.</p>...
2008/09/03
[ "https://Stackoverflow.com/questions/41869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2831/" ]
If I run the following query in SQL Server 2000 Query Analyzer: ``` BULK INSERT OurTable FROM 'c:\OurTable.txt' WITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\t', ROWS_PER_BATCH = 10000, TABLOCK) ``` On a text file that conforms to OurTable's schema for 40 lines, but then changes format for the last 20 lines (lets say the last 20 lines have fewer fields), I receive an error. However, the first 40 lines are committed to the table. Is there something about the way I'm calling Bulk Insert that makes it not be transactional, or do I need to do something explicit to force it to rollback on failure?
`BULK INSERT` acts as a series of individual `INSERT` statements and thus, if the job fails, it doesn't roll back all of the committed inserts. It can, however, be placed within a transaction so you could do something like this: ``` BEGIN TRANSACTION BEGIN TRY BULK INSERT OurTable FROM 'c:\OurTable.txt' WITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\t', ROWS_PER_BATCH = 10000, TABLOCK) COMMIT TRANSACTION END TRY BEGIN CATCH ROLLBACK TRANSACTION END CATCH ```
41,894
<p>Is there a way to find the name of the program that is running in Java? The class of the main method would be good enough.</p>
[ { "answer_id": 41904, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 7, "selected": true, "text": "<p>Try this:</p>\n\n<pre><code> StackTraceElement[] stack = Thread.currentThread ().getStackTrace ();\n StackTraceElem...
2008/09/03
[ "https://Stackoverflow.com/questions/41894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/823/" ]
Is there a way to find the name of the program that is running in Java? The class of the main method would be good enough.
Try this: ``` StackTraceElement[] stack = Thread.currentThread ().getStackTrace (); StackTraceElement main = stack[stack.length - 1]; String mainClass = main.getClassName (); ``` Of course, this only works if you're running from the main thread. Unfortunately I don't think there's a system property you can query to find this out. **Edit:** Pulling in @John Meagher's comment, which is a great idea: > > To expand on @jodonnell you can also > get all stack traces in the system > using Thread.getAllStackTraces(). From > this you can search all the stack > traces for the "main" Thread to > determine what the main class is. This > will work even if your class is not > running in the main thread. > > >
41,925
<p>What is a good data structure for storing phone numbers in database fields? I'm looking for something that is flexible enough to handle international numbers, and also something that allows the various parts of the number to be queried efficiently.</p> <p><strong>Edit:</strong> Just to clarify the use case here: I currently store numbers in a single varchar field, and I leave them just as the customer entered them. Then, when the number is needed by code, I normalize it. The problem is that if I want to query a few million rows to find matching phone numbers, it involves a function, like</p> <pre><code>where dbo.f_normalizenum(num1) = dbo.f_normalizenum(num2) </code></pre> <p>which is terribly inefficient. Also queries that are looking for things like the area code become extremely tricky when it's just a single varchar field.</p> <p><strong>[Edit]</strong></p> <p>People have made lots of good suggestions here, thanks! As an update, here is what I'm doing now: I still store numbers exactly as they were entered, in a varchar field, but instead of normalizing things at query time, I have a trigger that does all that work as records are inserted or updated. So I have ints or bigints for any parts that I need to query, and those fields are indexed to make queries run faster.</p>
[ { "answer_id": 41929, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 2, "selected": false, "text": "<p>Perhaps storing the phone number sections in different columns, allowing for blank or null entries?</p>\n" }, { ...
2008/09/03
[ "https://Stackoverflow.com/questions/41925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
What is a good data structure for storing phone numbers in database fields? I'm looking for something that is flexible enough to handle international numbers, and also something that allows the various parts of the number to be queried efficiently. **Edit:** Just to clarify the use case here: I currently store numbers in a single varchar field, and I leave them just as the customer entered them. Then, when the number is needed by code, I normalize it. The problem is that if I want to query a few million rows to find matching phone numbers, it involves a function, like ``` where dbo.f_normalizenum(num1) = dbo.f_normalizenum(num2) ``` which is terribly inefficient. Also queries that are looking for things like the area code become extremely tricky when it's just a single varchar field. **[Edit]** People have made lots of good suggestions here, thanks! As an update, here is what I'm doing now: I still store numbers exactly as they were entered, in a varchar field, but instead of normalizing things at query time, I have a trigger that does all that work as records are inserted or updated. So I have ints or bigints for any parts that I need to query, and those fields are indexed to make queries run faster.
First, beyond the country code, there is no real standard. About the best you can do is recognize, by the country code, which nation a particular phone number belongs to and deal with the rest of the number according to that nation's format. Generally, however, phone equipment and such is standardized so you can almost always break a given phone number into the following components * C Country code 1-10 digits (right now 4 or less, but that may change) * A Area code (Province/state/region) code 0-10 digits (may actually want a region field and an area field separately, rather than one area code) * E Exchange (prefix, or switch) code 0-10 digits * L Line number 1-10 digits With this method you can potentially separate numbers such that you can find, for instance, people that might be close to each other because they have the same country, area, and exchange codes. With cell phones that is no longer something you can count on though. Further, inside each country there are differing standards. You can always depend on a (AAA) EEE-LLLL in the US, but in another country you may have exchanges in the cities (AAA) EE-LLL, and simply line numbers in the rural areas (AAA) LLLL. You will have to start at the top in a tree of some form, and format them as you have information. For example, country code 0 has a known format for the rest of the number, but for country code 5432 you might need to examine the area code before you understand the rest of the number. You may also want to handle `vanity` numbers such as `(800) Lucky-Guy`, which requires recognizing that, if it's a US number, there's one too many digits (and you may need to full representation for advertising or other purposes) and that in the US the letters map to the numbers differently than in Germany. You may also want to store the entire number separately as a text field (with internationalization) so you can go back later and re-parse numbers as things change, or as a backup in case someone submits a bad method to parse a particular country's format and loses information.
41,928
<p>I have just received and bypassed a problem with LightWindow and IE7 where, on page load, it throws a JavaScript error on line 444 of <code>lightwindow.js</code>, claiming that the <code>object does not support this property or method</code>. Despite finding various postings on various forums, no Google result I could find had a solution, so I am posting this here in the hopes that it will help someone / myself later.</p> <p>Many suggested a specific order of the script files but I was already using this order (prototype, scriptaculous, lightwindow).</p> <p>These are the steps I took that seemed to finally work, I write them here only as a record as I do not know nor have time to test which ones specifically "fixed" the issue:</p> <ol> <li>Moved the call to lightwindow.js to the bottom of the page.</li> <li>Changed line 444 to: <code>if (this._getGalleryInfo(link.rel)) {</code></li> <li>Changed line 1157 to: <code>if (this._getGalleryInfo(this.element.rel)) {</code></li> <li>Finally, I enclosed (and this is dirty, my apologies) lines 1417 to 1474 with a <code>try/catch</code> block, swallowing the exception.</li> </ol> <p><strong>EDIT:</strong> </p> <p>I realised that this broke Firefox. Adding the following as line 445 now makes it work - <code>try { gallery = this._getGalleryInfo(link.rel); } catch (e) { }</code></p> <p>It's not a very nice fix, but my page (which contains a lightwindow link with no "rel" tag, several lightwindow links which do have "rel" tags, and one "inline" link) works just fine in IE7 now. Please comment if you have anything to add about this issue or problems with / improvements to my given solution.</p>
[ { "answer_id": 47224, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 1, "selected": false, "text": "<p>Instead of the try..catch maybe you could try using </p>\n\n<pre><code>if( this &amp;&amp; this._getGalleryInfo )\n{\n ...
2008/09/03
[ "https://Stackoverflow.com/questions/41928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
I have just received and bypassed a problem with LightWindow and IE7 where, on page load, it throws a JavaScript error on line 444 of `lightwindow.js`, claiming that the `object does not support this property or method`. Despite finding various postings on various forums, no Google result I could find had a solution, so I am posting this here in the hopes that it will help someone / myself later. Many suggested a specific order of the script files but I was already using this order (prototype, scriptaculous, lightwindow). These are the steps I took that seemed to finally work, I write them here only as a record as I do not know nor have time to test which ones specifically "fixed" the issue: 1. Moved the call to lightwindow.js to the bottom of the page. 2. Changed line 444 to: `if (this._getGalleryInfo(link.rel)) {` 3. Changed line 1157 to: `if (this._getGalleryInfo(this.element.rel)) {` 4. Finally, I enclosed (and this is dirty, my apologies) lines 1417 to 1474 with a `try/catch` block, swallowing the exception. **EDIT:** I realised that this broke Firefox. Adding the following as line 445 now makes it work - `try { gallery = this._getGalleryInfo(link.rel); } catch (e) { }` It's not a very nice fix, but my page (which contains a lightwindow link with no "rel" tag, several lightwindow links which do have "rel" tags, and one "inline" link) works just fine in IE7 now. Please comment if you have anything to add about this issue or problems with / improvements to my given solution.
I fixed this by changing line 444 to: ``` var gallery = this._getGalleryInfo(link.rel) ``` Then changing the subsequent comparison statement to: ``` if(gallery.length > 0) { // Rest of code here... ``` ...which seems to have sorted it in IE6+ and kept it working in Firefox etc. I didn't change line 1157 at all, but I haven't read the code to see what I actually does so I can't comment on its relevance? I suspect the ? used in the example rel attribute (Evoution?[man]) may be causing the problem with IE but without spending some time testing a few things, I can't be sure? HTH.
41,948
<p>I'm creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.</p>
[ { "answer_id": 41960, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 7, "selected": true, "text": "<p>In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the <code>getTime()</c...
2008/09/03
[ "https://Stackoverflow.com/questions/41948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2688/" ]
I'm creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.
In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the `getTime()` method **or** just using the date in a numeric expression. So to get the difference, just subtract the two dates. To create a new date based on the difference, just pass the number of milliseconds in the constructor. ``` var oldBegin = ... var oldEnd = ... var newBegin = ... var newEnd = new Date(newBegin + oldEnd - oldBegin); ``` This should just work **EDIT**: Fixed bug pointed by @bdukes **EDIT**: For an explanation of the behavior, `oldBegin`, `oldEnd`, and `newBegin` are `Date` instances. Calling operators `+` and `-` will trigger Javascript auto casting and will automatically call the `valueOf()` prototype method of those objects. It happens that the `valueOf()` method is implemented in the `Date` object as a call to `getTime()`. So basically: `date.getTime() === date.valueOf() === (0 + date) === (+date)`
41,969
<p>I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application.</p> <p>On OSX, I can open a window in the finder with</p> <pre><code>os.system('open "%s"' % foldername) </code></pre> <p>and on Windows with</p> <pre><code>os.startfile(foldername) </code></pre> <p>What about unix/linux? Is there a standard way to do this or do I have to special case gnome/kde/etc and manually run the appropriate application (nautilus/konqueror/etc)?</p> <p>This looks like something that could be specified by the <a href="http://freedesktop.org" rel="noreferrer">freedesktop.org</a> folks (a python module, similar to <code>webbrowser</code>, would also be nice!).</p>
[ { "answer_id": 41999, "author": "Tanj", "author_id": 4275, "author_profile": "https://Stackoverflow.com/users/4275", "pm_score": 0, "selected": false, "text": "<p>this would probably have to be done manually, or have as a config item since there are many file managers that users may want...
2008/09/03
[ "https://Stackoverflow.com/questions/41969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3002/" ]
I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application. On OSX, I can open a window in the finder with ``` os.system('open "%s"' % foldername) ``` and on Windows with ``` os.startfile(foldername) ``` What about unix/linux? Is there a standard way to do this or do I have to special case gnome/kde/etc and manually run the appropriate application (nautilus/konqueror/etc)? This looks like something that could be specified by the [freedesktop.org](http://freedesktop.org) folks (a python module, similar to `webbrowser`, would also be nice!).
``` os.system('xdg-open "%s"' % foldername) ``` `xdg-open` can be used for files/urls also
42,017
<p>I am looking for simple straightforward solution for accessing EXIF information of jpeg images in .Net. Does anybody has experience with this?</p>
[ { "answer_id": 42058, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I like <a href=\"http://www.atalasoft.com/products/dotimage/photo/default.aspx\" rel=\"nofollow noreferrer\">Atalasoft's Dot...
2008/09/03
[ "https://Stackoverflow.com/questions/42017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361/" ]
I am looking for simple straightforward solution for accessing EXIF information of jpeg images in .Net. Does anybody has experience with this?
If you're willing to use an open-source library, may I humbly suggest one of my own creation? The *metadata-extractor* project has been alive and well since 2002 for Java, and is now available for .NET. * Open source (Apache 2.0) * Heavily tested and widely used * Supports many image types (JPEG, TIFF, PNG, WebP, GIF, BMP, ICO, PCX...) * Supports many metadata types (Exif, IPTC, XMP, JFIF, ...) * Supports many manufacturer-specific fields (Canon, Nikon, ...) * Very fast (fully processes ~400 images totalling 1.33GB in ~3 seconds) with low memory consumption * Builds for .NET 3.5, .NET 4.0+ and PCL It's available via [NuGet](https://www.nuget.org/packages/MetadataExtractor/) or [GitHub](https://github.com/drewnoakes/metadata-extractor-dotnet). Sample usage: ``` IEnumerable<Directory> directories = ImageMetadataReader.ReadMetadata(path); foreach (var directory in directories) foreach (var tag in directory.Tags) Console.WriteLine($"{directory.Name} - {tag.TagName} = {tag.Description}"); ```
42,068
<p>I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have:</p> <pre><code>var data = '{"count" : 1, "stack" : "sometext\n\n"}'; var dataObj = eval('('+data+')'); </code></pre> <p>This gives me an error: </p> <pre><code>unterminated string literal </code></pre> <p>With <code>JSON.parse(data)</code>, I see similar error messages: "<code>Unexpected token ↵</code>" in Chrome, and "<code>unterminated string literal</code>" in Firefox and IE.</p> <p>When I take out the <code>\n</code> after <code>sometext</code> the error goes away in both cases. I can't seem to figure out why the <code>\n</code> makes <code>eval</code> and <code>JSON.parse</code> fail. </p>
[ { "answer_id": 42073, "author": "BlaM", "author_id": 999, "author_profile": "https://Stackoverflow.com/users/999", "pm_score": 10, "selected": true, "text": "<p>This is what you want:</p>\n<pre><code>var data = '{&quot;count&quot; : 1, &quot;stack&quot; : &quot;sometext\\\\n\\\\n&quot;}'...
2008/09/03
[ "https://Stackoverflow.com/questions/42068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3636/" ]
I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have: ``` var data = '{"count" : 1, "stack" : "sometext\n\n"}'; var dataObj = eval('('+data+')'); ``` This gives me an error: ``` unterminated string literal ``` With `JSON.parse(data)`, I see similar error messages: "`Unexpected token ↵`" in Chrome, and "`unterminated string literal`" in Firefox and IE. When I take out the `\n` after `sometext` the error goes away in both cases. I can't seem to figure out why the `\n` makes `eval` and `JSON.parse` fail.
This is what you want: ``` var data = '{"count" : 1, "stack" : "sometext\\n\\n"}'; ``` You need to escape the `\` in your string (turning it into a double-`\`), otherwise it will become a newline in the JSON source, not the JSON data.
42,070
<p>What's going on here?</p> <p>printf.sh:</p> <pre><code>#! /bin/sh NAME="George W. Bush" printf "Hello, %s\n" $NAME </code></pre> <p>Command line session:</p> <pre><code>$ ./printf.sh Hello, George Hello, W. Hello, Bush </code></pre> <p>UPDATE: <code>printf "Hello, %s\n" "$NAME"</code> works. For why I'm not using <code>echo</code>, consider</p> <p>echo.sh:</p> <pre><code>#! /bin/sh FILE="C:\tmp" echo "Filename: $FILE" </code></pre> <p>Command-line:</p> <pre><code>$ ./echo.sh Filename: C: mp </code></pre> <p>The <a href="http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html" rel="noreferrer">POSIX spec for <code>echo</code></a> says, "New applications are encouraged to use <code>printf</code> instead of <code>echo</code>" (for this and other reasons). </p>
[ { "answer_id": 42087, "author": "Redbaron", "author_id": 41, "author_profile": "https://Stackoverflow.com/users/41", "pm_score": 0, "selected": false, "text": "<p>If you want all of those words to be printed out on their own, use <strong>print</strong> instead of <strong>printf</strong> ...
2008/09/03
[ "https://Stackoverflow.com/questions/42070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
What's going on here? printf.sh: ``` #! /bin/sh NAME="George W. Bush" printf "Hello, %s\n" $NAME ``` Command line session: ``` $ ./printf.sh Hello, George Hello, W. Hello, Bush ``` UPDATE: `printf "Hello, %s\n" "$NAME"` works. For why I'm not using `echo`, consider echo.sh: ``` #! /bin/sh FILE="C:\tmp" echo "Filename: $FILE" ``` Command-line: ``` $ ./echo.sh Filename: C: mp ``` The [POSIX spec for `echo`](http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html) says, "New applications are encouraged to use `printf` instead of `echo`" (for this and other reasons).
Your NAME variable is being substituted like this: ``` printf "Hello, %s\n" George W. Bush ``` Use this: ``` #! /bin/sh NAME="George W. Bush" printf "Hello, %s\n" "$NAME" ```
42,102
<p>I have a Singleton/Factory object that I'd like to write a JUnit test for. The Factory method decides which implementing class to instantiate based upon a classname in a properties file on the classpath. If no properties file is found, or the properties file does not contain the classname key, then the class will instantiate a default implementing class.</p> <p>Since the factory keeps a static instance of the Singleton to use once it has been instantiated, to be able to test the "failover" logic in the Factory method I would need to run each test method in a different classloader. </p> <p>Is there any way with JUnit (or with another unit testing package) to do this?</p> <p>edit: here is some of the Factory code that is in use:</p> <pre><code>private static MyClass myClassImpl = instantiateMyClass(); private static MyClass instantiateMyClass() { MyClass newMyClass = null; String className = null; try { Properties props = getProperties(); className = props.getProperty(PROPERTY_CLASSNAME_KEY); if (className == null) { log.warn("instantiateMyClass: Property [" + PROPERTY_CLASSNAME_KEY + "] not found in properties, using default MyClass class [" + DEFAULT_CLASSNAME + "]"); className = DEFAULT_CLASSNAME; } Class MyClassClass = Class.forName(className); Object MyClassObj = MyClassClass.newInstance(); if (MyClassObj instanceof MyClass) { newMyClass = (MyClass) MyClassObj; } } catch (...) { ... } return newMyClass; } private static Properties getProperties() throws IOException { Properties props = new Properties(); InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTIES_FILENAME); if (stream != null) { props.load(stream); } else { log.error("getProperties: could not load properties file [" + PROPERTIES_FILENAME + "] from classpath, file not found"); } return props; } </code></pre>
[ { "answer_id": 42108, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 2, "selected": false, "text": "<p>When I run into these sort of situations I prefer to use what is a bit of a hack. I might instead expose a protected met...
2008/09/03
[ "https://Stackoverflow.com/questions/42102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
I have a Singleton/Factory object that I'd like to write a JUnit test for. The Factory method decides which implementing class to instantiate based upon a classname in a properties file on the classpath. If no properties file is found, or the properties file does not contain the classname key, then the class will instantiate a default implementing class. Since the factory keeps a static instance of the Singleton to use once it has been instantiated, to be able to test the "failover" logic in the Factory method I would need to run each test method in a different classloader. Is there any way with JUnit (or with another unit testing package) to do this? edit: here is some of the Factory code that is in use: ``` private static MyClass myClassImpl = instantiateMyClass(); private static MyClass instantiateMyClass() { MyClass newMyClass = null; String className = null; try { Properties props = getProperties(); className = props.getProperty(PROPERTY_CLASSNAME_KEY); if (className == null) { log.warn("instantiateMyClass: Property [" + PROPERTY_CLASSNAME_KEY + "] not found in properties, using default MyClass class [" + DEFAULT_CLASSNAME + "]"); className = DEFAULT_CLASSNAME; } Class MyClassClass = Class.forName(className); Object MyClassObj = MyClassClass.newInstance(); if (MyClassObj instanceof MyClass) { newMyClass = (MyClass) MyClassObj; } } catch (...) { ... } return newMyClass; } private static Properties getProperties() throws IOException { Properties props = new Properties(); InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTIES_FILENAME); if (stream != null) { props.load(stream); } else { log.error("getProperties: could not load properties file [" + PROPERTIES_FILENAME + "] from classpath, file not found"); } return props; } ```
This question might be old but since this was the nearest answer I found when I had this problem I though I'd describe my solution. **Using JUnit 4** Split your tests up so that there is one test method per class (this solution only changes classloaders between classes, not between methods as the parent runner gathers all the methods once per class) Add the `@RunWith(SeparateClassloaderTestRunner.class)` annotation to your test classes. Create the `SeparateClassloaderTestRunner` to look like this: ``` public class SeparateClassloaderTestRunner extends BlockJUnit4ClassRunner { public SeparateClassloaderTestRunner(Class<?> clazz) throws InitializationError { super(getFromTestClassloader(clazz)); } private static Class<?> getFromTestClassloader(Class<?> clazz) throws InitializationError { try { ClassLoader testClassLoader = new TestClassLoader(); return Class.forName(clazz.getName(), true, testClassLoader); } catch (ClassNotFoundException e) { throw new InitializationError(e); } } public static class TestClassLoader extends URLClassLoader { public TestClassLoader() { super(((URLClassLoader)getSystemClassLoader()).getURLs()); } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { if (name.startsWith("org.mypackages.")) { return super.findClass(name); } return super.loadClass(name); } } } ``` Note I had to do this to test code running in a legacy framework which I couldn't change. Given the choice I'd reduce the use of statics and/or put test hooks in to allow the system to be reset. It may not be pretty but it allows me to test an awful lot of code that would be difficult otherwise. Also this solution breaks anything else that relies on classloading tricks such as Mockito.
42,115
<p>I am running into an issue I had before; can't find my reference on how to solve it.</p> <p>Here is the issue. We encrypt the connection strings section in the app.config for our client application using code below:</p> <pre><code> config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) If config.ConnectionStrings.SectionInformation.IsProtected = False Then config.ConnectionStrings.SectionInformation.ProtectSection(Nothing) ' We must save the changes to the configuration file.' config.Save(ConfigurationSaveMode.Modified, True) End If </code></pre> <p>The issue is we had a salesperson leave. The old laptop is going to a new salesperson and under the new user's login, when it tries to to do this we get an error. The error is:</p> <pre><code>Unhandled Exception: System.Configuration.ConfigurationErrorsException: An error occurred executing the configuration section handler for connectionStrings. ---&gt; System.Configuration.ConfigurationErrorsException: Failed to encrypt the section 'connectionStrings' using provider 'RsaProtectedConfigurationProvider'. Error message from the provider: Object already exists. ---&gt; System.Security.Cryptography.CryptographicException: Object already exists </code></pre>
[ { "answer_id": 42206, "author": "Booji Boy", "author_id": 1433, "author_profile": "https://Stackoverflow.com/users/1433", "pm_score": 0, "selected": false, "text": "<p>Sounds like a permissions issue. The (new) user in question has write permissions to the app.config file? Was the previo...
2008/09/03
[ "https://Stackoverflow.com/questions/42115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1889/" ]
I am running into an issue I had before; can't find my reference on how to solve it. Here is the issue. We encrypt the connection strings section in the app.config for our client application using code below: ``` config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) If config.ConnectionStrings.SectionInformation.IsProtected = False Then config.ConnectionStrings.SectionInformation.ProtectSection(Nothing) ' We must save the changes to the configuration file.' config.Save(ConfigurationSaveMode.Modified, True) End If ``` The issue is we had a salesperson leave. The old laptop is going to a new salesperson and under the new user's login, when it tries to to do this we get an error. The error is: ``` Unhandled Exception: System.Configuration.ConfigurationErrorsException: An error occurred executing the configuration section handler for connectionStrings. ---> System.Configuration.ConfigurationErrorsException: Failed to encrypt the section 'connectionStrings' using provider 'RsaProtectedConfigurationProvider'. Error message from the provider: Object already exists. ---> System.Security.Cryptography.CryptographicException: Object already exists ```
I found a more elegant solution that in my original answer to myself. I found if I just logged in as th euser who orignally installed the application and caused the config file connectionstrings to be encrypted and go to the .net framework directory in a commadn prompt and run ``` aspnet_regiis -pa "NetFrameworkConfigurationKey" "{domain}\{user}" ``` it gave the other user permission to access the RSA encryption key container and it then works for the other user(s). Just wanted to add it here as I thought I had blogged this issue on our dev blog but found it here, so in case I need to look it up again it will be here. Will add link to our dev blog point at this thread as well.
42,125
<p>I have a library I created,</p> <h3>File <em>mylib.c:</em></h3> <pre><code>#include &lt;mylib.h&gt; int testlib() { printf(&quot;Hello, World!\n&quot;); return (0); } </code></pre> <h3>File <em>mylib.h:</em></h3> <pre><code>#include &lt;stdio.h&gt; extern int testlib(); </code></pre> <p>In my program, I've attempted to call this library function:</p> <h3>File <em>myprogram.c</em>:</h3> <pre><code>#include &lt;mylib.h&gt; int main (int argc, char *argv[]) { testlib(); return (0); } </code></pre> <p>When I attempt to compile this program I get the following error:</p> <pre>In file included from myprogram.c:1 mylib.h:2 warning: function declaration isn't a prototype</pre> <p>I'm using: <code>gcc (GCC) 3.4.5 20051201 (Red Hat 3.4.5-2)</code></p> <p>What is the proper way to declare a function prototype?</p>
[ { "answer_id": 42133, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 5, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>extern int testlib(void);\n</code></pre>\n" }, { "answer_id": 47693, "author": "...
2008/09/03
[ "https://Stackoverflow.com/questions/42125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3807/" ]
I have a library I created, ### File *mylib.c:* ``` #include <mylib.h> int testlib() { printf("Hello, World!\n"); return (0); } ``` ### File *mylib.h:* ``` #include <stdio.h> extern int testlib(); ``` In my program, I've attempted to call this library function: ### File *myprogram.c*: ``` #include <mylib.h> int main (int argc, char *argv[]) { testlib(); return (0); } ``` When I attempt to compile this program I get the following error: ``` In file included from myprogram.c:1 mylib.h:2 warning: function declaration isn't a prototype ``` I'm using: `gcc (GCC) 3.4.5 20051201 (Red Hat 3.4.5-2)` What is the proper way to declare a function prototype?
In C `int foo()` and `int foo(void)` are different functions. `int foo()` accepts an arbitrary number of arguments, while `int foo(void)` accepts 0 arguments. In C++ they mean the same thing. I suggest that you use `void` consistently when you mean no arguments. If you have a variable `a`, `extern int a;` is a way to tell the compiler that `a` is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function (`extern`, `static`) only affects its visibility and `extern` is the default, so `extern` is actually unnecessary. I suggest removing the `extern`, it is extraneous and is usually omitted.
42,153
<p>I searched for this subject on Google and got some website about an experts exchange...so I figured I should just ask here instead.</p> <p>How do you embed a <code>JApplet</code> in HTML on a webpage?</p>
[ { "answer_id": 42162, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 1, "selected": false, "text": "<p>Use the &lt;applet&gt; tag. For more info: <a href=\"http://java.sun.com/docs/books/tutorial/deployment/applet/html.html...
2008/09/03
[ "https://Stackoverflow.com/questions/42153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
I searched for this subject on Google and got some website about an experts exchange...so I figured I should just ask here instead. How do you embed a `JApplet` in HTML on a webpage?
Here is an example from [sun's website](http://java.sun.com/docs/books/tutorial/uiswing/components/applet.html): ``` <applet code="TumbleItem.class" codebase="examples/" archive="tumbleClasses.jar, tumbleImages.jar" width="600" height="95"> <param name="maxwidth" value="120"> <param name="nimgs" value="17"> <param name="offset" value="-57"> <param name="img" value="images/tumble"> Your browser is completely ignoring the &lt;APPLET&gt; tag! </applet> ```
42,182
<p>I'm trying to write a blog post which includes a code segment inside a <code>&lt;pre&gt;</code> tag. The code segment includes a generic type and uses <code>&lt;&gt;</code> to define that type. This is what the segment looks like:</p> <pre><code>&lt;pre&gt; PrimeCalc calc = new PrimeCalc(); Func&lt;int, int&gt; del = calc.GetNextPrime; &lt;/pre&gt; </code></pre> <p>The resulting HTML removes the <code>&lt;&gt;</code> and ends up like this:</p> <pre><code>PrimeCalc calc = new PrimeCalc(); Func del = calc.GetNextPrime; </code></pre> <p>How do I escape the <code>&lt;&gt;</code> so they show up in the HTML?</p>
[ { "answer_id": 42189, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": -1, "selected": false, "text": "<p>It's probably something specific to your blog software, but you might want to give the following strings a try (remove the ...
2008/09/03
[ "https://Stackoverflow.com/questions/42182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373/" ]
I'm trying to write a blog post which includes a code segment inside a `<pre>` tag. The code segment includes a generic type and uses `<>` to define that type. This is what the segment looks like: ``` <pre> PrimeCalc calc = new PrimeCalc(); Func<int, int> del = calc.GetNextPrime; </pre> ``` The resulting HTML removes the `<>` and ends up like this: ``` PrimeCalc calc = new PrimeCalc(); Func del = calc.GetNextPrime; ``` How do I escape the `<>` so they show up in the HTML?
``` <pre> PrimeCalc calc = new PrimeCalc(); Func&lt;int, int&gt; del = calc.GetNextPrime; </pre> ```
42,187
<p>I have read about partial methods in the latest <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx" rel="noreferrer">C# language specification</a>, so I understand the principles, but I'm wondering how people are actually using them. Is there a particular design pattern that benefits from partial methods?</p>
[ { "answer_id": 42190, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "<p><strong><a href=\"http://msdn.microsoft.com/en-us/library/bb531348.aspx\" rel=\"nofollow noreferrer\">Code generatio...
2008/09/03
[ "https://Stackoverflow.com/questions/42187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
I have read about partial methods in the latest [C# language specification](http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx), so I understand the principles, but I'm wondering how people are actually using them. Is there a particular design pattern that benefits from partial methods?
Partial methods have been introduced for similar reasons to why partial classes were in .Net 2. A partial class is one that can be split across multiple files - the compiler builds them all into one file as it runs. The advantage for this is that Visual Studio can provide a graphical designer for part of the class while coders work on the other. The most common example is the Form designer. Developers don't want to be positioning buttons, input boxes, etc by hand most of the time. * In .Net 1 it was auto-generated code in a `#region` block * In .Net 2 these became separate designer classes - the form is still one class, it's just split into one file edited by the developers and one by the form designer This makes maintaining both much easier. Merges are simpler and there's less risk of the VS form designer accidentally undoing coders' manual changes. In .Net 3.5 Linq has been introduced. Linq has a DBML designer for building your data structures, and that generates auto-code. The extra bit here is that code needed to provide methods that developers might want to fill in. As developers will extend these classes (with extra partial files) they couldn't use abstract methods here. The other issue is that most of the time these methods wont be called, and calling empty methods is a waste of time. Empty methods [are not optimised out](https://stackoverflow.com/questions/11783/in-net-will-empty-method-calls-be-optimized-out). So Linq generates empty partial methods. If you don't create your own partial to complete them the C# compiler will just optimise them out. So that it can do this partial methods always return void. If you create a new Linq DBML file it will auto-generate a partial class, something like ``` [System.Data.Linq.Mapping.DatabaseAttribute(Name="MyDB")] public partial class MyDataContext : System.Data.Linq.DataContext { ... partial void OnCreated(); partial void InsertMyTable(MyTable instance); partial void UpdateMyTable(MyTable instance); partial void DeleteMyTable(MyTable instance); ... ``` Then in your own partial file you can extend this: ``` public partial class MyDataContext { partial void OnCreated() { //do something on data context creation } } ``` If you don't extend these methods they get optimised right out. Partial methods can't be public - as then they'd have to be there for other classes to call. If you write your own code generators I can see them being useful, but otherwise they're only really useful for the VS designer. The example I mentioned before is one possibility: ``` //this code will get optimised out if no body is implemented partial void DoSomethingIfCompFlag(); #if COMPILER_FLAG //this code won't exist if the flag is off partial void DoSomethingIfCompFlag() { //your code } #endif ``` Another potential use is if you had a large and complex class spilt across multiple files you might want partial references in the calling file. However I think in that case you should consider simplifying the class first.
42,215
<p>We get the following error;</p> <pre><code>The request was aborted: Could not create SSL/TLS secure channel </code></pre> <p>while using a <code>WebRequest</code> object to make an <code>HTTPS</code> request. The funny thing is that this only happens after a while, and is temporarily fixed when the application is restarted, which suggests that something is being filled to capacity or something. </p> <p>Has anyone seen this kind of thing before?</p>
[ { "answer_id": 42228, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "<p>It looks like it may be a Conenction: Keep-alive thing: <a href=\"http://blogs.x2line.com/al/archive/2005/01/04/759.as...
2008/09/03
[ "https://Stackoverflow.com/questions/42215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659/" ]
We get the following error; ``` The request was aborted: Could not create SSL/TLS secure channel ``` while using a `WebRequest` object to make an `HTTPS` request. The funny thing is that this only happens after a while, and is temporarily fixed when the application is restarted, which suggests that something is being filled to capacity or something. Has anyone seen this kind of thing before?
I seem to recall having this problem last year. I suspect that you aren't closing your WebRequest objects properly, which is why after a certain amount of use it won't allow you to create any new connections.
42,246
<p>I have somewhat interesting development situation. The client and deployment server are inside a firewall without access to the Subversion server. But the developers are outside the firewall and are able to use the Subversion server. Right now the solution I have worked out is to update my local copy of the code and then pull out the most recently updated files using UnleashIT. </p> <p>The question is how to get just the updated files out of Subversion so that they can be physically transported through the firewall and put on the deployment server.</p> <p>I'm not worried about trying to change the firewall setup or trying to figure out an easier way to get to the Subversion server from inside the firewall. I'm just interested in a way to get a partial export from the repository of the most recently changed files.</p> <p>Are there any other suggestions?</p> <p>Answer found: In addition to the answer I marked as Answer, I've also found the following here to be able to do this from TortoiseSVN:</p> <p>from <a href="http://svn.haxx.se/tsvn/archive-2006-08/0051.shtml" rel="nofollow noreferrer">http://svn.haxx.se/tsvn/archive-2006-08/0051.shtml</a></p> <pre><code>* select the two revisions * right-click, "compare revisions" * select all files in the list * right-click, choose "export to..." </code></pre>
[ { "answer_id": 42295, "author": "Brian Lyttle", "author_id": 636, "author_profile": "https://Stackoverflow.com/users/636", "pm_score": -1, "selected": false, "text": "<p>You don't provide information on what is allowed through the firewall. I'm not familiar with UnleashIT.</p>\n\n<p>I gu...
2008/09/03
[ "https://Stackoverflow.com/questions/42246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3442/" ]
I have somewhat interesting development situation. The client and deployment server are inside a firewall without access to the Subversion server. But the developers are outside the firewall and are able to use the Subversion server. Right now the solution I have worked out is to update my local copy of the code and then pull out the most recently updated files using UnleashIT. The question is how to get just the updated files out of Subversion so that they can be physically transported through the firewall and put on the deployment server. I'm not worried about trying to change the firewall setup or trying to figure out an easier way to get to the Subversion server from inside the firewall. I'm just interested in a way to get a partial export from the repository of the most recently changed files. Are there any other suggestions? Answer found: In addition to the answer I marked as Answer, I've also found the following here to be able to do this from TortoiseSVN: from <http://svn.haxx.se/tsvn/archive-2006-08/0051.shtml> ``` * select the two revisions * right-click, "compare revisions" * select all files in the list * right-click, choose "export to..." ```
I've found [rsync](http://samba.anu.edu.au/rsync/) extremely useful for synchronizing directory trees across multiple systems. If you have shell access to your server from a development workstation, you can regularly check out code locally and run rsync, which will transfer only the files that have changed to the server. (This assumes a Unix-like environment on your development workstations. Cygwin will work fine.) ``` cd deploy svn update rsync -a . server:webdir/ ``` Your question sounds like you don't actually have any direct network access from your development workstations to your server, and what you're really looking for is a way to get Subversion to tell you which files have changed. **svn export** supports an argument to let you check out only the files that changed between particular revisions. From the svn help: ``` -r [--revision] arg : ARG (some commands also take ARG1:ARG2 range) A revision argument can be one of: NUMBER revision number '{' DATE '}' revision at start of the date 'HEAD' latest in repository 'BASE' base rev of item's working copy 'COMMITTED' last commit at or before BASE 'PREV' revision just before COMMITTED ``` You'll need to keep track of what the latest revision you copied to the server. Assuming it's SVN revision xxxx: ``` svn export -r xxxx:HEAD http://svn/ ``` Then simply copy the contents of the *deploy* directory to your server on top of the existing files. This won't handle deleted files, which may prove problematic in some environments.
42,247
<p>The following code illustrates an object literal being assigned, but with no semicolon afterwards:</p> <pre><code>var literal = { say: function(msg) { alert(msg); } } literal.say("hello world!"); </code></pre> <p>This appears to be legal, and doesn't issue a warning (at least in Firefox&nbsp;3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed?</p> <p>I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it.</p>
[ { "answer_id": 42252, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 6, "selected": true, "text": "<p>Not technically, JavaScript has semicolons as optional in many situations. </p>\n\n<p>But, as a general rule, use the...
2008/09/03
[ "https://Stackoverflow.com/questions/42247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
The following code illustrates an object literal being assigned, but with no semicolon afterwards: ``` var literal = { say: function(msg) { alert(msg); } } literal.say("hello world!"); ``` This appears to be legal, and doesn't issue a warning (at least in Firefox 3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed? I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it.
Not technically, JavaScript has semicolons as optional in many situations. But, as a general rule, use them at the end of any statement. Why? Because if you ever want to compress the script, it will save you from countless hours of frustration. Automatic semicolon insertion is performed by the interpreter, so you *can* leave them out if you so choose. In the comments, someone claimed that > > Semicolons are not optional with statements like break/continue/throw > > > but this is incorrect. They are optional; what is really happening is that line terminators affect the automatic semicolon insertion; it is a subtle difference. Here is the rest of the standard on semicolon insertion: > > For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations. > > >
42,254
<p>I would like to flash a success message on my page.</p> <p>I am using the jQuery <code>fadeOut</code> method to fade and then remove the element. I can increase the duration to make it last longer, however this looks strange.</p> <p>What I would like to happen is have the element be displayed for five seconds, then fade quickly, and finally be removed.</p> <p>How can you animate this using jQuery? </p>
[ { "answer_id": 42255, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": false, "text": "<p>use <code>setTimeout(function(){$elem.hide();}, 5000);</code></p>\n\n<p>Where <code>$elem</code> is the element you ...
2008/09/03
[ "https://Stackoverflow.com/questions/42254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3645/" ]
I would like to flash a success message on my page. I am using the jQuery `fadeOut` method to fade and then remove the element. I can increase the duration to make it last longer, however this looks strange. What I would like to happen is have the element be displayed for five seconds, then fade quickly, and finally be removed. How can you animate this using jQuery?
The new `delay()` function in jQuery 1.4 should do the trick. ``` $('#foo').fadeIn(200).delay(5000).fadeOut(200).remove(); ```
42,282
<p>Which way do you prefer to create your forms in MVC?</p> <pre><code>&lt;% Html.Form() { %&gt; &lt;% } %&gt; </code></pre> <p>Or</p> <pre><code>&lt;form action="&lt;%= Url.Action("ManageImage", "UserAccount") %&gt;" method="post"&gt; &lt;/form&gt; </code></pre> <p>I understand that Html.Form() as of PR5 now just uses the URL provided by the request. However something about that doesn't sit well with me, especially since I will be getting all the baggage of any querystrings that are included. </p> <p>What is your take?</p>
[ { "answer_id": 42289, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 2, "selected": false, "text": "<p>On the whole, I think I'm kinda old-school as I prefer to roll my own HTML elements.</p>\n\n<p>I also prefer a view en...
2008/09/03
[ "https://Stackoverflow.com/questions/42282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17/" ]
Which way do you prefer to create your forms in MVC? ``` <% Html.Form() { %> <% } %> ``` Or ``` <form action="<%= Url.Action("ManageImage", "UserAccount") %>" method="post"> </form> ``` I understand that Html.Form() as of PR5 now just uses the URL provided by the request. However something about that doesn't sit well with me, especially since I will be getting all the baggage of any querystrings that are included. What is your take?
The second way, definitely. The first way is programmer-centric, which is not what the V part of MVC is about. The second way is more designer centric, only binding to the model where it is necessary, leaving the HTML as natural as possible.
42,286
<p>It seems like there should be something shorter than this:</p> <pre><code>private string LoadFromFile(string path) { try { string fileContents; using(StreamReader rdr = File.OpenText(path)) { fileContents = rdr.ReadToEnd(); } return fileContents; } catch { throw; } } </code></pre>
[ { "answer_id": 42290, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 2, "selected": false, "text": "<p>File.ReadAllText() maybe?</p>\n\n<p>ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/fxref_mscorlib/html/4803f846-3d8a-de8a-18e...
2008/09/03
[ "https://Stackoverflow.com/questions/42286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3475/" ]
It seems like there should be something shorter than this: ``` private string LoadFromFile(string path) { try { string fileContents; using(StreamReader rdr = File.OpenText(path)) { fileContents = rdr.ReadToEnd(); } return fileContents; } catch { throw; } } ```
First of all, the title asks for "how to write the contents of strnig to a text file" but your code example is for "how to read the contents of a text file to a string. Answer to both questions: ``` using System.IO; ... string filename = "C:/example.txt"; string content = File.ReadAllText(filename); File.WriteAllText(filename, content); ``` See also ReadAllLines/WriteAllLines and ReadAllBytes/WriteAllBytes if instead of a string you want a string array or byte array.
42,294
<p>I have a simple 2-column layout with a footer that clears both the right and left div in my markup. My problem is that I can't get the footer to stay at the bottom of the page in all browsers. It works if the content pushes the footer down, but that's not always the case. </p>
[ { "answer_id": 42301, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 9, "selected": true, "text": "<p>To get a sticky footer:</p>\n\n<ol>\n<li><p>Have a <code>&lt;div&gt;</code> with <code>class=\"wrapper\"</code> for your con...
2008/09/03
[ "https://Stackoverflow.com/questions/42294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
I have a simple 2-column layout with a footer that clears both the right and left div in my markup. My problem is that I can't get the footer to stay at the bottom of the page in all browsers. It works if the content pushes the footer down, but that's not always the case.
To get a sticky footer: 1. Have a `<div>` with `class="wrapper"` for your content. 2. Right **before** the closing `</div>` of the `wrapper` place the `<div class="push"></div>`. 3. Right **after** the closing `</div>` of the `wrapper` place the `<div class="footer"></div>`. ```css * { margin: 0; } html, body { height: 100%; } .wrapper { min-height: 100%; height: auto !important; height: 100%; margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */ } .footer, .push { height: 142px; /* .push must be the same height as .footer */ } ```
42,323
<p>I have the next function:</p> <pre><code>function setImagesWidth(id,width) { var images = document.getElementById(id).getElementsByTagName("img"); for(var i = 0; i &lt; images.length;i++) { // If the real width is bigger than width parameter images[i].style.width=width; //} } } </code></pre> <p>I would like to set the css width attribute of all my img tags to a particular value only when the image real width is bigger than the attribute value. If it is possible, i would like a solution which does not use any particular framework. </p> <hr> <p><code>images[i].offsetWidth</code> returns 111 for an image of 109px width. Is this because 1px each side border? </p>
[ { "answer_id": 42331, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "<p>Here is, hopefully, enough sample code to give you what you want:</p>\n\n<pre><code>var myImage = document.getElemen...
2008/09/03
[ "https://Stackoverflow.com/questions/42323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
I have the next function: ``` function setImagesWidth(id,width) { var images = document.getElementById(id).getElementsByTagName("img"); for(var i = 0; i < images.length;i++) { // If the real width is bigger than width parameter images[i].style.width=width; //} } } ``` I would like to set the css width attribute of all my img tags to a particular value only when the image real width is bigger than the attribute value. If it is possible, i would like a solution which does not use any particular framework. --- `images[i].offsetWidth` returns 111 for an image of 109px width. Is this because 1px each side border?
@Sergio del Amo: Indeed, if you check out my link you'll see that you want `clientWidth` instead. @Sergio del Amo: You cannot, unfortunately, accept your own answer. But you do have an extraneous period in the "px" suffix, so let's go with this, including the `clientWidth` change: ``` // width in pixels function setImagesWidth(id, width) { var images = document.getElementById(id).getElementsByTagName("img"); var newWidth = width + "px"; for (var i = 0; i < images.length; ++i) { if (images[i].clientWidth > width) { images[i].style.width = newWidth; } } } ```
42,342
<p>Sometimes IE6 will render the text of a <code>&lt;ul&gt;</code> list the same color as the background color. If you select it, they show back up, or if you scroll the page up and back down.</p> <p>It is obviously a rendering bug, but I was wondering if anyone knows of a workaround to make it reliable?</p>
[ { "answer_id": 42346, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 0, "selected": false, "text": "<p>Have you tried explicitly setting a line-height? For some reason this seems to be the solution to a great many IE6 renderi...
2008/09/03
[ "https://Stackoverflow.com/questions/42342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
Sometimes IE6 will render the text of a `<ul>` list the same color as the background color. If you select it, they show back up, or if you scroll the page up and back down. It is obviously a rendering bug, but I was wondering if anyone knows of a workaround to make it reliable?
try giving it hasLayout with ```css zoom: 1 ```
42,345
<p>How can I determine if a string is an IP address? Either <em>IPv4</em> or <em>IPv6</em>?</p> <p>What is the least and most number of characters?</p> <p>I assume this would be a <strong>regex</strong> answer.</p>
[ { "answer_id": 42359, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<p>For IPv4 you can use this regular expression.</p>\n\n<pre><code>\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.)...
2008/09/03
[ "https://Stackoverflow.com/questions/42345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ]
How can I determine if a string is an IP address? Either *IPv4* or *IPv6*? What is the least and most number of characters? I assume this would be a **regex** answer.
In .NET there's an IPAddress type which has a handy method [TryParse](http://msdn.microsoft.com/en-us/library/system.net.ipaddress.tryparse.aspx). Example: ``` if(System.Net.IPAddress.TryParse(PossibleIPAddress, validatedIPAddress)){ //validatedIPAddress is good } // or more simply: bool IsValidIPAddress(string possibleIP){ return System.Net.IPAddress.TryParse(PossibleIPAddress, null) } ```
42,386
<p>Is there a one statement or one line way to accomplish something like this, where the string s is declared AND assigned the first non-null value in the expression?</p> <pre><code>//pseudo-codeish string s = Coalesce(string1, string2, string3); </code></pre> <p>or, more generally,</p> <pre><code>object obj = Coalesce(obj1, obj2, obj3, ...objx); </code></pre>
[ { "answer_id": 42387, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": false, "text": "<p>the <strong>??</strong> operator.</p>\n\n<pre><code>string a = nullstring ?? \"empty!\";\n</code></pre>\n" }, { "a...
2008/09/03
[ "https://Stackoverflow.com/questions/42386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4438/" ]
Is there a one statement or one line way to accomplish something like this, where the string s is declared AND assigned the first non-null value in the expression? ``` //pseudo-codeish string s = Coalesce(string1, string2, string3); ``` or, more generally, ``` object obj = Coalesce(obj1, obj2, obj3, ...objx); ```
As Darren Kopp said. Your statement ``` object obj = Coalesce(obj1, obj2, obj3, ...objx); ``` Can be written like this: ``` object obj = obj1 ?? obj2 ?? obj3 ?? ... objx; ``` to put it in other words: ``` var a = b ?? c; ``` is equivalent to ``` var a = b != null ? b : c; ```
42,395
<p>How do you write the syntax for a While loop?</p> <h2>C<code>#</code></h2> <pre><code>int i = 0; while (i != 10) { Console.WriteLine(i); i++; } </code></pre> <h2>VB.Net</h2> <pre><code>Dim i As Integer = 0 While i &lt;&gt; 10 Console.WriteLine(i) i += 1 End While </code></pre> <h2>PHP</h2> <pre><code>&lt;?php while(CONDITION) { //Do something here. } ?&gt; &lt;?php //MySQL query stuff here $result = mysql_query($sql, $link) or die("Opps"); while($row = mysql_fetch_assoc($result)) { $_SESSION['fName'] = $row['fName']; $_SESSION['lName'] = $row['lName']; //... } ?&gt; </code></pre> <h2>Python</h2> <pre><code>i = 0 while i != 10: print i i += 1 </code></pre>
[ { "answer_id": 42409, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 4, "selected": true, "text": "<p>In PHP a while loop will look like this:</p>\n\n<pre><code>&lt;?php\nwhile(CONDITION)\n{\n//Do something here.\n}\n?&gt;\n<...
2008/09/03
[ "https://Stackoverflow.com/questions/42395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1048/" ]
How do you write the syntax for a While loop? C`#` ---- ``` int i = 0; while (i != 10) { Console.WriteLine(i); i++; } ``` VB.Net ------ ``` Dim i As Integer = 0 While i <> 10 Console.WriteLine(i) i += 1 End While ``` PHP --- ``` <?php while(CONDITION) { //Do something here. } ?> <?php //MySQL query stuff here $result = mysql_query($sql, $link) or die("Opps"); while($row = mysql_fetch_assoc($result)) { $_SESSION['fName'] = $row['fName']; $_SESSION['lName'] = $row['lName']; //... } ?> ``` Python ------ ``` i = 0 while i != 10: print i i += 1 ```
In PHP a while loop will look like this: ``` <?php while(CONDITION) { //Do something here. } ?> ``` A real world example of this might look something like this ``` <?php //MySQL query stuff here $result = mysql_query($sql, $link) or die("Opps"); while($row = mysql_fetch_assoc($result)) { $_SESSION['fName'] = $row['fName']; $_SESSION['lName'] = $row['lName']; //... } ?> ```
42,396
<p>Here's the code from the ascx that has the repeater:</p> <pre><code>&lt;asp:Repeater ID="ListOfEmails" runat="server" &gt; &lt;HeaderTemplate&gt;&lt;h3&gt;A sub-header:&lt;/h3&gt;&lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; [Some other stuff is here] &lt;asp:Button ID="removeEmail" runat="server" Text="X" ToolTip="remove" /&gt; &lt;/ItemTemplate&gt; &lt;/asp:Repeater&gt; </code></pre> <p>And in the codebehind for the repeater's databound and events:</p> <pre><code>Protected Sub ListOfEmails_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles ListOfEmails.ItemDataBound If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then Dim removeEmail As Button = CType(e.Item.FindControl("removeEmail"), Button) removeEmail.CommandArgument = e.Item.ItemIndex.ToString() AddHandler removeEmail.Click, AddressOf removeEmail_Click AddHandler removeEmail.Command, AddressOf removeEmail_Command End If End Sub Sub removeEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Response.Write("&lt;h1&gt;click&lt;/h1&gt;") End Sub Sub removeEmail_Command(ByVal sender As Object, ByVal e As CommandEventArgs) Response.Write("&lt;h1&gt;command&lt;/h1&gt;") End Sub </code></pre> <p>Neither the click or command is getting called, what am I doing wrong?</p>
[ { "answer_id": 42404, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 0, "selected": false, "text": "<p>Here's an experiment for you to try:</p>\n\n<p>Set a breakpoint on ListOfEmails_ItemDataBound and see if it's being ca...
2008/09/03
[ "https://Stackoverflow.com/questions/42396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1414/" ]
Here's the code from the ascx that has the repeater: ``` <asp:Repeater ID="ListOfEmails" runat="server" > <HeaderTemplate><h3>A sub-header:</h3></HeaderTemplate> <ItemTemplate> [Some other stuff is here] <asp:Button ID="removeEmail" runat="server" Text="X" ToolTip="remove" /> </ItemTemplate> </asp:Repeater> ``` And in the codebehind for the repeater's databound and events: ``` Protected Sub ListOfEmails_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles ListOfEmails.ItemDataBound If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then Dim removeEmail As Button = CType(e.Item.FindControl("removeEmail"), Button) removeEmail.CommandArgument = e.Item.ItemIndex.ToString() AddHandler removeEmail.Click, AddressOf removeEmail_Click AddHandler removeEmail.Command, AddressOf removeEmail_Command End If End Sub Sub removeEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Response.Write("<h1>click</h1>") End Sub Sub removeEmail_Command(ByVal sender As Object, ByVal e As CommandEventArgs) Response.Write("<h1>command</h1>") End Sub ``` Neither the click or command is getting called, what am I doing wrong?
Controls nested inside of Repeaters do not intercept events. Instead you need to bind to the `Repeater.ItemCommand` Event. [`ItemCommand`](https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.repeater.itemcommand) contains [`RepeaterCommandEventArgs`](https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.repeatercommandeventargs) which has two important fields: * CommandName * CommandArgument So, a trivial example: ```cs void rptr_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) { // Stuff to databind Button myButton = (Button)e.Item.FindControl("myButton"); myButton.CommandName = "Add"; myButton.CommandArgument = "Some Identifying Argument"; } } void rptr_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName == "Add") { // Do your event } } ```
42,416
<p>I want to use the Web Browser control within an mono application, but when I do get the error "libgluezilla not found. To have webbrowser support, you need libgluezilla installed." Installing the Intrepid Deb causes any application that references the web browser control to crash on startup with : 'Thread (nil) may have been prematurely finalized'.</p>
[ { "answer_id": 42431, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 0, "selected": false, "text": "<p>here's a link to it on the ubuntu site:</p>\n\n<p><a href=\"http://packages.ubuntu.com/intrepid/libgluezilla\" rel=\"no...
2008/09/03
[ "https://Stackoverflow.com/questions/42416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3798/" ]
I want to use the Web Browser control within an mono application, but when I do get the error "libgluezilla not found. To have webbrowser support, you need libgluezilla installed." Installing the Intrepid Deb causes any application that references the web browser control to crash on startup with : 'Thread (nil) may have been prematurely finalized'.
``` apt-cache search libgluezilla libmono-mozilla0.1-cil - Mono Mozilla library ``` From the package description: ``` Description: Mono Mozilla library Mono is a platform for running and developing applications based on the ECMA/ISO Standards. Mono is an open source effort led by Novell. Mono provides a complete CLR (Common Language Runtime) including compiler and runtime, which can produce and execute CIL (Common Intermediate Language) bytecode (aka assemblies), and a class library. . This package contains the implementation of the WebControl class based on the Mozilla engine using libgluezilla. Homepage: http://www.mono-project.com/ ``` You'll probably need to uninstall anything that came in from intrepid without being properly backported.
42,422
<p>Essentially I want to know if in VB.NET 2005 if using a sqlcommand and then reusing it by using the NEW is wrong. Will it cause a memory leak.</p> <p>EG:</p> <pre><code>try dim mySQL as new sqlcommand(sSQL, cnInput) // do a sql execute and read the data mySQL = new sqlcommand(sSQLdifferent, cnInput) // do sql execute and read the data catch ... finally if mysql isnot nothing then mysql.dispose mysql = nothing end if </code></pre> <p>EDIT: put try catch in to avoid the comments about not using them</p>
[ { "answer_id": 42434, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 2, "selected": false, "text": "<p>Garbage collection will gather up the first new when it is run.</p>\n\n<p>Only the second one you purposely dispose ...
2008/09/03
[ "https://Stackoverflow.com/questions/42422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2357/" ]
Essentially I want to know if in VB.NET 2005 if using a sqlcommand and then reusing it by using the NEW is wrong. Will it cause a memory leak. EG: ``` try dim mySQL as new sqlcommand(sSQL, cnInput) // do a sql execute and read the data mySQL = new sqlcommand(sSQLdifferent, cnInput) // do sql execute and read the data catch ... finally if mysql isnot nothing then mysql.dispose mysql = nothing end if ``` EDIT: put try catch in to avoid the comments about not using them
Just to extend what Longhorn213 said, here's the code for it: ``` Using mysql as SqlCommand = new SqlCommand(sSql, cnInput) ' do stuff' End Using Using mysql as SqlCommand = new SqlCommand(otherSql, cnInput) ' do other stuff' End Using ``` (edit) Just as an FYI, using automatically wraps the block of code around a try/finally that calls the Dispose method on the variable it is created with. Thus, it's an easy way to ensure your resource is released. <http://msdn.microsoft.com/en-us/library/htd05whh(VS.80).aspx>
42,428
<p>X Windows has special processes called Window Managers that manage the layout of windows and decorations like their title bar, control buttons etc. Such processes use an X Windows API to detect events related to windows sizes and positions.</p> <p>Are there any consistent ways for writing such processes for Microsoft Windows or Mac OS/X?</p> <p>I know that in general these systems are less flexible but I'm looking for something that will use public APIs and not undocumented hacks.</p>
[ { "answer_id": 42434, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 2, "selected": false, "text": "<p>Garbage collection will gather up the first new when it is run.</p>\n\n<p>Only the second one you purposely dispose ...
2008/09/03
[ "https://Stackoverflow.com/questions/42428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476/" ]
X Windows has special processes called Window Managers that manage the layout of windows and decorations like their title bar, control buttons etc. Such processes use an X Windows API to detect events related to windows sizes and positions. Are there any consistent ways for writing such processes for Microsoft Windows or Mac OS/X? I know that in general these systems are less flexible but I'm looking for something that will use public APIs and not undocumented hacks.
Just to extend what Longhorn213 said, here's the code for it: ``` Using mysql as SqlCommand = new SqlCommand(sSql, cnInput) ' do stuff' End Using Using mysql as SqlCommand = new SqlCommand(otherSql, cnInput) ' do other stuff' End Using ``` (edit) Just as an FYI, using automatically wraps the block of code around a try/finally that calls the Dispose method on the variable it is created with. Thus, it's an easy way to ensure your resource is released. <http://msdn.microsoft.com/en-us/library/htd05whh(VS.80).aspx>
42,446
<pre><code>class Foo { static bool Bar(Stream^ stream); }; class FooWrapper { bool Bar(LPCWSTR szUnicodeString) { return Foo::Bar(??); } }; </code></pre> <p><code>MemoryStream</code> will take a <code>byte[]</code> but I'd <em>like</em> to do this without copying the data if possible.</p>
[ { "answer_id": 42605, "author": "Adam Tegen", "author_id": 4066, "author_profile": "https://Stackoverflow.com/users/4066", "pm_score": 0, "selected": false, "text": "<p>If I had to copy the memory, I think the following would work:</p>\n\n<pre><code>\nstatic Stream^ UnicodeStringToStream...
2008/09/03
[ "https://Stackoverflow.com/questions/42446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066/" ]
``` class Foo { static bool Bar(Stream^ stream); }; class FooWrapper { bool Bar(LPCWSTR szUnicodeString) { return Foo::Bar(??); } }; ``` `MemoryStream` will take a `byte[]` but I'd *like* to do this without copying the data if possible.
You can avoid the copy if you use an [`UnmanagedMemoryStream()`](http://msdn.microsoft.com/en-us/library/system.io.unmanagedmemorystream.aspx) instead (class exists in .NET FCL 2.0 and later). Like `MemoryStream`, it is a subclass of `IO.Stream`, and has all the usual stream operations. Microsoft's description of the class is: > > Provides access to unmanaged blocks of memory from managed code. > > > which pretty much tells you what you need to know. Note that `UnmanagedMemoryStream()` is not CLS-compliant.
42,482
<p>Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.)</p> <p>Antiword seems like it might be a reasonable option, but it seems like it might be abandoned.</p> <p>A Python solution would be ideal, but doesn't appear to be available.</p>
[ { "answer_id": 42485, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 1, "selected": false, "text": "<p>Open Office has an <a href=\"http://api.openoffice.org/\" rel=\"nofollow noreferrer\">API</a></p>\n" }, { "answer...
2008/09/03
[ "https://Stackoverflow.com/questions/42482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2678/" ]
Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.) Antiword seems like it might be a reasonable option, but it seems like it might be abandoned. A Python solution would be ideal, but doesn't appear to be available.
I use catdoc or antiword for this, whatever gives the result that is the easiest to parse. I have embedded this in python functions, so it is easy to use from the parsing system (which is written in python). ``` import os def doc_to_text_catdoc(filename): (fi, fo, fe) = os.popen3('catdoc -w "%s"' % filename) fi.close() retval = fo.read() erroroutput = fe.read() fo.close() fe.close() if not erroroutput: return retval else: raise OSError("Executing the command caused an error: %s" % erroroutput) # similar doc_to_text_antiword() ``` The -w switch to catdoc turns off line wrapping, BTW.
42,490
<p><em>Disclaimer: I'm stuck on TFS and I hate it.</em></p> <p>My source control structure looks like this:</p> <ul> <li>/dev</li> <li>/releases</li> <li>/branches</li> <li>/experimental-upgrade</li> </ul> <p>I branched from dev to experimental-upgrade and didn't touch it. I then did some more work in dev and merged to experimental-upgrade. Somehow TFS complained that I had changes in both source and target and I had to resolve them. I chose to "Copy item from source branch" for all 5 items.</p> <p>I check out the experimental-upgrade to a local folder and try to open the main solution file in there. TFS prompts me: </p> <blockquote> <p>"Projects have recently been added to this solution. Would you like to get them from source control?</p> </blockquote> <p>If I say yes it does some stuff but ultimately comes back failing to load a handful of the projects. If I say no I get the same result.</p> <p>Comparing my sln in both branches tells me that they are equal.</p> <p>Can anyone let me know what I'm doing wrong? This should be a straightforward branch/merge operation...</p> <p>TIA.</p> <hr> <p><strong>UPDATE:</strong></p> <p>I noticed that if I click "yes" on the above dialog, the projects are downloaded to the $/ root of source control... (i.e. out of the dev &amp; branches folders)</p> <p>If I open up the solution in the branch and remove the dead projects and try to re-add them (by right-clicking sln, add existing project, choose project located in the branch folder, it gives me the error...</p> <blockquote> <p>Cannot load the project c:\sandbox\my_solution\proj1\proj1.csproj, the file has been removed or deleted. The project path I was trying to add is this: c:\sandbox\my_solution\branches\experimental-upgrade\proj1\proj1.csproj</p> </blockquote> <p>What in the world is pointing these projects <em>outside</em> of their local root? The solution file is identical to the one in the dev branch, and those projects load just fine. I also looked at the vspscc and vssscc files but didn't find anything.</p> <p>Ideas?</p>
[ { "answer_id": 42534, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 0, "selected": false, "text": "<p>@Nick: No changes have been made to this just yet. I may have to delete it and re-branch (however you really can't...
2008/09/03
[ "https://Stackoverflow.com/questions/42490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3381/" ]
*Disclaimer: I'm stuck on TFS and I hate it.* My source control structure looks like this: * /dev * /releases * /branches * /experimental-upgrade I branched from dev to experimental-upgrade and didn't touch it. I then did some more work in dev and merged to experimental-upgrade. Somehow TFS complained that I had changes in both source and target and I had to resolve them. I chose to "Copy item from source branch" for all 5 items. I check out the experimental-upgrade to a local folder and try to open the main solution file in there. TFS prompts me: > > "Projects have recently been added to this solution. Would you like to get them from source control? > > > If I say yes it does some stuff but ultimately comes back failing to load a handful of the projects. If I say no I get the same result. Comparing my sln in both branches tells me that they are equal. Can anyone let me know what I'm doing wrong? This should be a straightforward branch/merge operation... TIA. --- **UPDATE:** I noticed that if I click "yes" on the above dialog, the projects are downloaded to the $/ root of source control... (i.e. out of the dev & branches folders) If I open up the solution in the branch and remove the dead projects and try to re-add them (by right-clicking sln, add existing project, choose project located in the branch folder, it gives me the error... > > Cannot load the project c:\sandbox\my\_solution\proj1\proj1.csproj, the file has been removed or deleted. The project path I was trying to add is this: c:\sandbox\my\_solution\branches\experimental-upgrade\proj1\proj1.csproj > > > What in the world is pointing these projects *outside* of their local root? The solution file is identical to the one in the dev branch, and those projects load just fine. I also looked at the vspscc and vssscc files but didn't find anything. Ideas?
@Ben You can actually do a full delete in TFS, but it is highly not recommended unless you know what you are doing. You have to do it from the command line with the command tf destroy ``` tf destroy [/keephistory] itemspec1 [;versionspec] [itemspec2...itemspecN] [/stopat:versionspec] [/preview] [/startcleanup] [/noprompt] Versionspec: Date/Time Dmm/dd/yyyy or any .Net Framework-supported format or any of the date formats of the local machine Changeset number Cnnnnnn Label Llabelname Latest version T Workspace Wworkspacename;workspaceowner ``` Just before you do this make sure you try it out with the /preview. Also everybody has their own methodology for branching. Mine is to branch releases, and do all development in the development or root folder. Also it sounded like branching worked fine for you, just the solution file was screwed up, which may be because of a binding issue and the vssss file.
42,505
<p>I have a C# singleton class that multiple classes use. Is access through <code>Instance</code> to the <code>Toggle()</code> method thread-safe? If yes, by what assumptions, rules, etc. If no, why <em>and</em> how can I fix it?</p> <pre><code>public class MyClass { private static readonly MyClass instance = new MyClass(); public static MyClass Instance { get { return instance; } } private int value = 0; public int Toggle() { if(value == 0) { value = 1; } else if(value == 1) { value = 0; } return value; } } </code></pre>
[ { "answer_id": 42511, "author": "juan", "author_id": 1782, "author_profile": "https://Stackoverflow.com/users/1782", "pm_score": 0, "selected": false, "text": "<p>Quote:</p>\n\n<pre><code>if(value == 0) { value = 1; }\nif(value == 1) { value = 0; }\nreturn value;\n</code></pre>\n\n<p><co...
2008/09/03
[ "https://Stackoverflow.com/questions/42505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3619/" ]
I have a C# singleton class that multiple classes use. Is access through `Instance` to the `Toggle()` method thread-safe? If yes, by what assumptions, rules, etc. If no, why *and* how can I fix it? ``` public class MyClass { private static readonly MyClass instance = new MyClass(); public static MyClass Instance { get { return instance; } } private int value = 0; public int Toggle() { if(value == 0) { value = 1; } else if(value == 1) { value = 0; } return value; } } ```
> > Is access through 'Instance' to the 'Toggle()' class threadsafe? If yes, by what assumptions, rules, etc. If no, why and how can I fix it? > > > No, it's not threadsafe. Basically, both threads can run the `Toggle` function at the same time, so this could happen ``` // thread 1 is running this code if(value == 0) { value = 1; // RIGHT NOW, thread 2 steps in. // It sees value as 1, so runs the other branch, and changes it to 0 // This causes your method to return 0 even though you actually want 1 } else if(value == 1) { value = 0; } return value; ``` You need to operate with the following assumption. If 2 threads are running, they can and will interleave and interact with eachother randomly at any point. You can be half way through writing or reading a 64 bit integer or float (on a 32 bit CPU) and another thread can jump in and change it out from underneath you. If the 2 threads never access anything in common, it doesn't matter, but as soon as they do, you need to prevent them from stepping on each others toes. The way to do this in .NET is with locks. You can decide what and where to lock by thinking about things like this: For a given block of code, if the value of `something` got changed out from underneath me, would it matter? If it would, you need to lock that `something` for the duration of the code where it would matter. Looking at your example again ``` // we read value here if(value == 0) { value = 1; } else if(value == 1) { value = 0; } // and we return it here return value; ``` In order for this to return what we expect it to, we assume that `value` won't get changed between the read and the `return`. In order for this assumption to actually be correct, you need to lock `value` for the duration of that code block. So you'd do this: ``` lock( value ) { if(value == 0) ... // all your code here return value; } ``` **HOWEVER** In .NET you can only lock Reference Types. Int32 is a Value Type, so we can't lock it. We solve this by introducing a 'dummy' object, and locking *that* wherever we'd want to lock 'value'. This is what [Ben Scheirman](https://stackoverflow.com/questions/42505/thread-safe-use-of-a-singletons-members/42517#42517) is referring to.
42,519
<p>Inspired by <a href="https://devblogs.microsoft.com/oldnewthing/20080902-00/?p=21003" rel="noreferrer">Raymond Chen's post</a>, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff.</p> <pre><code>[1][2][3][4] [5][6][7][8] [9][0][1][2] [3][4][5][6] </code></pre> <p>Becomes:</p> <pre><code>[3][9][5][1] [4][0][6][2] [5][1][7][3] [6][2][8][4] </code></pre> <p><strong>Update</strong>: Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000?</p>
[ { "answer_id": 42535, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 8, "selected": true, "text": "<p>Here it is in C#</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>int[,] array = new int[4,4] {\n { 1,2,3,4...
2008/09/03
[ "https://Stackoverflow.com/questions/42519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/736/" ]
Inspired by [Raymond Chen's post](https://devblogs.microsoft.com/oldnewthing/20080902-00/?p=21003), say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff. ``` [1][2][3][4] [5][6][7][8] [9][0][1][2] [3][4][5][6] ``` Becomes: ``` [3][9][5][1] [4][0][6][2] [5][1][7][3] [6][2][8][4] ``` **Update**: Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000?
Here it is in C# ```csharp int[,] array = new int[4,4] { { 1,2,3,4 }, { 5,6,7,8 }, { 9,0,1,2 }, { 3,4,5,6 } }; int[,] rotated = RotateMatrix(array, 4); static int[,] RotateMatrix(int[,] matrix, int n) { int[,] ret = new int[n, n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { ret[i, j] = matrix[n - j - 1, i]; } } return ret; } ```
42,531
<p>Looking for an example that:</p> <ol> <li>Launches an EXE</li> <li>Waits for the EXE to finish.</li> <li>Properly closes all the handles when the executable finishes.</li> </ol>
[ { "answer_id": 42543, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 5, "selected": false, "text": "<p>There is an example at <a href=\"http://msdn.microsoft.com/en-us/library/ms682512(VS.85).aspx\" rel=\"noreferrer\"><a hr...
2008/09/03
[ "https://Stackoverflow.com/questions/42531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814/" ]
Looking for an example that: 1. Launches an EXE 2. Waits for the EXE to finish. 3. Properly closes all the handles when the executable finishes.
Something like this: ``` STARTUPINFO info={sizeof(info)}; PROCESS_INFORMATION processInfo; if (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo)) { WaitForSingleObject(processInfo.hProcess, INFINITE); CloseHandle(processInfo.hProcess); CloseHandle(processInfo.hThread); } ```
42,566
<p>I'm in the process of maintaining a Ruby on Rails app and am looking for an easy way to find the hostname or IP address of the box I'm on (since it's a VM and new instances may have different hostnames or IP addresses). Is there a quick and easy way to do this in Ruby on Rails?</p> <p>Edit: The answer below is correct but the clarification Craig provided is useful (see also provided link in answer):</p> <blockquote> <p>The [below] code does NOT make a connection or send any packets (to 64.233.187.99 which is google). Since UDP is a stateless protocol connect() merely makes a system call which figures out how to route the packets based on the address and what interface (and therefore IP address) it should bind to. addr() returns an array containing the family (AF_INET), local port, and local address (which is what we want) of the socket.</p> </blockquote>
[ { "answer_id": 42595, "author": "Craig", "author_id": 1611, "author_profile": "https://Stackoverflow.com/users/1611", "pm_score": 0, "selected": false, "text": "<p>try: <a href=\"http://apidock.com/rails/v2.3.8/ActionController/Request/remote_ip\" rel=\"nofollow noreferrer\">Request.remo...
2008/09/03
[ "https://Stackoverflow.com/questions/42566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
I'm in the process of maintaining a Ruby on Rails app and am looking for an easy way to find the hostname or IP address of the box I'm on (since it's a VM and new instances may have different hostnames or IP addresses). Is there a quick and easy way to do this in Ruby on Rails? Edit: The answer below is correct but the clarification Craig provided is useful (see also provided link in answer): > > The [below] code does NOT make a > connection or send any packets (to > 64.233.187.99 which is google). Since UDP is a stateless protocol connect() > merely makes a system call which > figures out how to route the packets > based on the address and what > interface (and therefore IP address) > it should bind to. addr() returns an > array containing the family (AF\_INET), > local port, and local address (which > is what we want) of the socket. > > >
From [coderrr.wordpress.com](http://coderrr.wordpress.com/2008/05/28/get-your-local-ip-address/): ``` require 'socket' def local_ip orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily UDPSocket.open do |s| s.connect '64.233.187.99', 1 s.addr.last end ensure Socket.do_not_reverse_lookup = orig end # irb:0> local_ip # => "192.168.0.127" ```
42,575
<p>We're currently using Lucene 2.1.0 for our site search and we've hit a difficult problem: one of our index fields is being ignored during a targeted search. Here is the code for adding the field to a document in our index:</p> <pre><code>// Add market_local to index contactDocument.add( new Field( "market_local" , StringUtils.objectToString( currClip.get( "market_local" ) ) , Field.Store.YES , Field.Index.UN_TOKENIZED ) ); </code></pre> <p>Running a query ( * ) against the index will return the following results:</p> <pre><code>Result 1: title: Foo Bar market_local: Local Result 2: title: Bar Foo market_local: National </code></pre> <p>Running a targeted query:</p> <pre><code>+( market_local:Local ) </code></pre> <p>won't find any results.</p> <p>I realize this is a highly specific question, I'm just trying to get information on where to start debugging this issue, as I'm a Lucene newbie.</p> <hr> <p><strong>UPDATE</strong></p> <p>Installed Luke, checking out latest index... the Field <em>market_local</em> is available in searches, so if I execute something like:</p> <pre><code>market_local:Local </code></pre> <p>The search works correctly (in Luke). I'm going over our Analyzer code now, is there any way I could chalk this issue up to the fact that our search application is using Lucene 2.1.0 and the latest version of Luke is using 2.3.0?</p>
[ { "answer_id": 42734, "author": "Darren Hague", "author_id": 4450, "author_profile": "https://Stackoverflow.com/users/4450", "pm_score": 4, "selected": true, "text": "<p>For debugging Lucene, the best tool to use is <a href=\"http://www.getopt.org/luke/\" rel=\"noreferrer\">Luke</a>, whi...
2008/09/03
[ "https://Stackoverflow.com/questions/42575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302/" ]
We're currently using Lucene 2.1.0 for our site search and we've hit a difficult problem: one of our index fields is being ignored during a targeted search. Here is the code for adding the field to a document in our index: ``` // Add market_local to index contactDocument.add( new Field( "market_local" , StringUtils.objectToString( currClip.get( "market_local" ) ) , Field.Store.YES , Field.Index.UN_TOKENIZED ) ); ``` Running a query ( \* ) against the index will return the following results: ``` Result 1: title: Foo Bar market_local: Local Result 2: title: Bar Foo market_local: National ``` Running a targeted query: ``` +( market_local:Local ) ``` won't find any results. I realize this is a highly specific question, I'm just trying to get information on where to start debugging this issue, as I'm a Lucene newbie. --- **UPDATE** Installed Luke, checking out latest index... the Field *market\_local* is available in searches, so if I execute something like: ``` market_local:Local ``` The search works correctly (in Luke). I'm going over our Analyzer code now, is there any way I could chalk this issue up to the fact that our search application is using Lucene 2.1.0 and the latest version of Luke is using 2.3.0?
For debugging Lucene, the best tool to use is [Luke](http://www.getopt.org/luke/), which lets you poke around in the index itself to see what got indexed, carry out searches, etc. I recommend downloading it, pointing it at your index, and seeing what's in there.
42,581
<p>The Python docs say:</p> <blockquote> <p>re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string...</p> </blockquote> <p>So what's going on when I get the following unexpected result?</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = """// The quick brown fox. ... // Jumped over the lazy dog.""" &gt;&gt;&gt; re.sub('^//', '', s, re.MULTILINE) ' The quick brown fox.\n// Jumped over the lazy dog.' </code></pre>
[ { "answer_id": 42597, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 8, "selected": true, "text": "<p>Look at the definition of <a href=\"http://docs.python.org/library/re.html#re.sub\" rel=\"noreferrer\"><code>re.sub</code></a>:...
2008/09/03
[ "https://Stackoverflow.com/questions/42581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
The Python docs say: > > re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string... > > > So what's going on when I get the following unexpected result? ``` >>> import re >>> s = """// The quick brown fox. ... // Jumped over the lazy dog.""" >>> re.sub('^//', '', s, re.MULTILINE) ' The quick brown fox.\n// Jumped over the lazy dog.' ```
Look at the definition of [`re.sub`](http://docs.python.org/library/re.html#re.sub): ``` re.sub(pattern, repl, string[, count, flags]) ``` The 4th argument is the count, you are using `re.MULTILINE` (which is 8) as the count, not as a flag. Either use a named argument: ``` re.sub('^//', '', s, flags=re.MULTILINE) ``` Or compile the regex first: ``` re.sub(re.compile('^//', re.MULTILINE), '', s) ```
42,587
<p>I have heard/read the term but don't quite understand what it means.</p> <p>When should I use this technique and how would I use it? Can anyone provide a good code sample?</p>
[ { "answer_id": 42656, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 7, "selected": true, "text": "<p>The visitor pattern is a way of doing double-dispatch in an object-oriented way.</p>\n\n<p>It's useful for when you wan...
2008/09/03
[ "https://Stackoverflow.com/questions/42587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1583/" ]
I have heard/read the term but don't quite understand what it means. When should I use this technique and how would I use it? Can anyone provide a good code sample?
The visitor pattern is a way of doing double-dispatch in an object-oriented way. It's useful for when you want to choose which method to use for a given argument based on its type at runtime rather than compile time. Double dispatch is a special case of **multiple dispatch**. When you call a virtual method on an object, that's considered single-dispatch because which actual method is called depends on the type of the single object. For double dispatch, both the object's type and the method sole argument's type is taken into account. This is like method overload resolution, except that the argument type is determined at runtime in double-dispatch instead of statically at compile-time. In multiple-dispatch, a method can have multiple arguments passed to it and which implementation is used depends on each argument's type. The order that the types are evaluated depends on the language. In LISP, it checks each type from first to last. Languages with multiple dispatch make use of generic functions, which are just function delcarations and aren't like generic methods, which use type parameters. **To do double-dispatch in C#**, you can declare a method with a sole object argument and then specific methods with specific types: ``` using System.Linq; class DoubleDispatch { public T Foo<T>(object arg) { var method = from m in GetType().GetMethods() where m.Name == "Foo" && m.GetParameters().Length==1 && arg.GetType().IsAssignableFrom (m.GetParameters()[0].GetType()) && m.ReturnType == typeof(T) select m; return (T) method.Single().Invoke(this,new object[]{arg}); } public int Foo(int arg) { /* ... */ } static void Test() { object x = 5; Foo<int>(x); //should call Foo(int) via Foo<T>(object). } } ```
42,703
<p>I am using sp_send_dbmail in SQL2005 to send an email with the results in an attachment. When the attachment is sent it is UCS-2 Encoded, I want it to be ANSI or UTF-8.</p> <p>Here is the SQL</p> <pre><code>EXEC msdb.dbo.sp_send_dbmail @recipients = 'temp@example.com' , @query = 'DECLARE @string_to_trim varchar(60);SET @string_to_trim = ''1234''; select rtrim(@string_to_trim), ''tom''' , @query_result_header=0 , @subject = 'see attach' , @body= 'temp body' , @profile_name= N'wksql01tAdmin' , @body_format = 'HTML' ,@query_result_separator = ',' ,@query_attachment_filename = 'results.csv' ,@query_no_truncate = '0' ,@attach_query_result_as_file = 1 </code></pre> <p>I have seen some comments on the internet that this is fixed with sql2005 SP2, but do not find it to be the case.</p>
[ { "answer_id": 42728, "author": "Craig", "author_id": 2894, "author_profile": "https://Stackoverflow.com/users/2894", "pm_score": 1, "selected": true, "text": "<p>I think the only way to get around what you are seeing is to use BCP to dump the data to a flat file and then attach that fil...
2008/09/03
[ "https://Stackoverflow.com/questions/42703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am using sp\_send\_dbmail in SQL2005 to send an email with the results in an attachment. When the attachment is sent it is UCS-2 Encoded, I want it to be ANSI or UTF-8. Here is the SQL ``` EXEC msdb.dbo.sp_send_dbmail @recipients = 'temp@example.com' , @query = 'DECLARE @string_to_trim varchar(60);SET @string_to_trim = ''1234''; select rtrim(@string_to_trim), ''tom''' , @query_result_header=0 , @subject = 'see attach' , @body= 'temp body' , @profile_name= N'wksql01tAdmin' , @body_format = 'HTML' ,@query_result_separator = ',' ,@query_attachment_filename = 'results.csv' ,@query_no_truncate = '0' ,@attach_query_result_as_file = 1 ``` I have seen some comments on the internet that this is fixed with sql2005 SP2, but do not find it to be the case.
I think the only way to get around what you are seeing is to use BCP to dump the data to a flat file and then attach that file. Sorry I couldn't be more help. :(
42,710
<p>I need to implement a 4-to-1 function in Veriog. The input is 4 bits, a number from 0-15. The output is a single bit, 0 or 1. Each input gives a different output and the mapping from inputs to outputs is known, but the inputs and outputs themselves are not. I want vcs to successfully optimizing the code and also have it be as short/neat as possible. My solution so far:</p> <pre><code>wire [3:0] a; wire b; wire [15:0] c; assign c = 16'b0100110010111010; //for example but could be any constant assign b = c[a]; </code></pre> <p>Having to declare c is ugly and I don't know if vcs will recognize the K-map there. Will this work as well as a case statement or an assignment in conjunctive normal form?</p>
[ { "answer_id": 43143, "author": "DMC", "author_id": 3148, "author_profile": "https://Stackoverflow.com/users/3148", "pm_score": 2, "selected": false, "text": "<p>My preference - if it makes sense for your problem - is for a case statement that makes use of enums or `defines. Anything to ...
2008/09/03
[ "https://Stackoverflow.com/questions/42710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4454/" ]
I need to implement a 4-to-1 function in Veriog. The input is 4 bits, a number from 0-15. The output is a single bit, 0 or 1. Each input gives a different output and the mapping from inputs to outputs is known, but the inputs and outputs themselves are not. I want vcs to successfully optimizing the code and also have it be as short/neat as possible. My solution so far: ``` wire [3:0] a; wire b; wire [15:0] c; assign c = 16'b0100110010111010; //for example but could be any constant assign b = c[a]; ``` Having to declare c is ugly and I don't know if vcs will recognize the K-map there. Will this work as well as a case statement or an assignment in conjunctive normal form?
What you have is fine. A case statement would also work equally well. It's just a matter of how expressive you wish to be. Your solution, indexing, works fine if the select encodings don't have any special meaning (a memory address selector for example). If the select encodings do have some special semantic meaning to you the designer (and there aren't too many of them), then go with a case statement and enums. Synthesis wise, it doesn't matter which one you use. Any decent synthesis tool will produce the same result.
42,762
<p>Here is some code I could not get to format properly in markdown, this is straight C code, pasted into the text box with the '4 spaces' format to denote code:</p> <pre><code>#define PRINT(x, format, ...) \ if ( x ) { \ if ( debug_fd != NULL ) { \ fprintf(debug_fd, format, ##__VA_ARGS__); \ } \ else { \ fprintf(stdout, format, ##__VA_ARGS__); \ } \ } </code></pre> <p>It seems as though the '\' causes the newlines to be ignored. Ok fine, I am used to this in bash, but if I put '\' the second one doesn't show up. As if the second one is absorbed. Am I missing something?</p>
[ { "answer_id": 42764, "author": "Julio César", "author_id": 2148, "author_profile": "https://Stackoverflow.com/users/2148", "pm_score": 2, "selected": false, "text": "<p>Add at least four spaces or a hard tab before each line of the code. Like this:</p>\n\n<pre><code>#define PRINT(x, for...
2008/09/03
[ "https://Stackoverflow.com/questions/42762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3663/" ]
Here is some code I could not get to format properly in markdown, this is straight C code, pasted into the text box with the '4 spaces' format to denote code: ``` #define PRINT(x, format, ...) \ if ( x ) { \ if ( debug_fd != NULL ) { \ fprintf(debug_fd, format, ##__VA_ARGS__); \ } \ else { \ fprintf(stdout, format, ##__VA_ARGS__); \ } \ } ``` It seems as though the '\' causes the newlines to be ignored. Ok fine, I am used to this in bash, but if I put '\' the second one doesn't show up. As if the second one is absorbed. Am I missing something?
You can also use the HTML tags <pre><code> in succession. I find this easier for pasting code into the window. ``` #define PRINT(x, format, ...) if ( x ) { if ( debug_fd != NULL ) { fprintf(debug_fd, format, ##VA_ARGS); } else { fprintf(stdout, format, ##VA_ARGS); } } ```
42,774
<p>I'm using <kbd>Ctrl</kbd>+<kbd>Left</kbd> / <kbd>Ctrl</kbd>+<kbd>Right</kbd> in a GreaseMonkey script as a hotkey to turn back / forward pages. It seems to works fine, but I want to disable this behavior if I'm in a text edit area. I'm trying to use document.activeElement to get the page active element and test if it's an editable area, but it always returns "undefined".</p>
[ { "answer_id": 42807, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 3, "selected": true, "text": "<p>document.activeElement works for me in FF3 but the following also works</p>\n\n<pre><code>(function() {\n\nvar myActiveElemen...
2008/09/03
[ "https://Stackoverflow.com/questions/42774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/394/" ]
I'm using `Ctrl`+`Left` / `Ctrl`+`Right` in a GreaseMonkey script as a hotkey to turn back / forward pages. It seems to works fine, but I want to disable this behavior if I'm in a text edit area. I'm trying to use document.activeElement to get the page active element and test if it's an editable area, but it always returns "undefined".
document.activeElement works for me in FF3 but the following also works ``` (function() { var myActiveElement; document.onkeypress = function(event) { if ((myActiveElement || document.activeElement || {}).tagName != 'INPUT') // do your magic }; if (!document.activeElement) { var elements = document.getElementsByTagName('input'); for(var i=0; i<elements.length; i++) { elements[i].addEventListener('focus',function() { myActiveElement = this; },false); elements[i].addEventListener('blur',function() { myActiveElement = null; },false); } } })(); ```
42,793
<p>What techniques do you know\use to create user-friendly GUI ? </p> <p>I can name following techniques that I find especially useful: </p> <ul> <li>Non-blocking notifications (floating dialogs like in Firefox3 or Vista's pop-up messages in tray area)</li> <li>Absence of "Save" button<br> MS OneNote as an example.<br> IM clients can save conversation history automatically</li> <li>Integrated search<br> Search not only through help files but rather make UI elements searchable.<br> Vista made a good step toward such GUI.<br> <a href="http://www.istartedsomething.com/20070124/scout-office-2007/" rel="nofollow noreferrer">Scout</a> addin Microsoft Office was a really great idea.</li> <li>Context oriented UI (Ribbon bar in MS Office 2007)</li> </ul> <p>Do you implement something like listed techniques in your software?</p> <p><strong>Edit:</strong><br> As <a href="https://stackoverflow.com/questions/42793/gui-design-techinques-to-enhance-user-experience#42843">Ryan P</a> mentioned, one of the best way to create usable app is to put yourself in user's place. I totally agree with it, but what I want to see in this topic is specific techniques (like those I mentioned above) rather than general recommendations.</p>
[ { "answer_id": 42843, "author": "Ryan P", "author_id": 1539, "author_profile": "https://Stackoverflow.com/users/1539", "pm_score": 0, "selected": false, "text": "<p>The best technique I found is to put your self in the users shoes. What would you like to see from the GUI and put that in ...
2008/09/03
[ "https://Stackoverflow.com/questions/42793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1196/" ]
What techniques do you know\use to create user-friendly GUI ? I can name following techniques that I find especially useful: * Non-blocking notifications (floating dialogs like in Firefox3 or Vista's pop-up messages in tray area) * Absence of "Save" button MS OneNote as an example. IM clients can save conversation history automatically * Integrated search Search not only through help files but rather make UI elements searchable. Vista made a good step toward such GUI. [Scout](http://www.istartedsomething.com/20070124/scout-office-2007/) addin Microsoft Office was a really great idea. * Context oriented UI (Ribbon bar in MS Office 2007) Do you implement something like listed techniques in your software? **Edit:** As [Ryan P](https://stackoverflow.com/questions/42793/gui-design-techinques-to-enhance-user-experience#42843) mentioned, one of the best way to create usable app is to put yourself in user's place. I totally agree with it, but what I want to see in this topic is specific techniques (like those I mentioned above) rather than general recommendations.
If you do give the user a question, don't make it a yes/no question. Take the time to make a new form and put the verbs as choices like in mac. For example: ``` Would you like to save? Yes No ``` Should Be: ``` Would you like to save? Save Don't Save ``` There is a more detailed explanation [here.](http://www.usabilitypost.com/post/11-usability-tip-use-verbs-as-labels-on-buttons)
42,797
<p>I'm looking for something that can copy (preferably only changed) files from a development machine to a staging machine and finally to a set of production machines.</p> <p>A "what if" mode would be nice as would the capability to "rollback" the last deployment. Database migrations aren't a necessary feature.</p> <p>UPDATE: A free/low-cost tool would be great, but cost isn't the only concern. A tool that could actually manage deployment from one environment to the next (dev->staging->production instead of from a development machine to each environment) would also be ideal.</p> <p>The other big nice-to-have is the ability to only copy changed files - some of our older sites contain hundreds of .asp files.</p>
[ { "answer_id": 42811, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 0, "selected": false, "text": "<p>We used <a href=\"http://www.eworldui.net/unleashit/\" rel=\"nofollow noreferrer\">UnleashIt</a> (unfortunate name I know) wh...
2008/09/03
[ "https://Stackoverflow.com/questions/42797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/729/" ]
I'm looking for something that can copy (preferably only changed) files from a development machine to a staging machine and finally to a set of production machines. A "what if" mode would be nice as would the capability to "rollback" the last deployment. Database migrations aren't a necessary feature. UPDATE: A free/low-cost tool would be great, but cost isn't the only concern. A tool that could actually manage deployment from one environment to the next (dev->staging->production instead of from a development machine to each environment) would also be ideal. The other big nice-to-have is the ability to only copy changed files - some of our older sites contain hundreds of .asp files.
**@Sean Carpenter** can you tell us a little more about your environment? Should the solution be free? simple? I find robocopy to be pretty slick for this sort of thing. Wrap in up in a batch file and you are good to go. It's a glorified xcopy, but deploying my website isn't really hard. Just copy out the files. As far as rollbacks... You are using source control right? Just pull the old source out of there. Or, in your batch file, ALSO copy the deployment to another folder called website yyyy.mm.dd so you have a lovely folder ready to go in an emergency. look at the for command for details on how to get the parts of the date. ``` robocopy.exe for /? ``` Yeah, it's a total "hack" but it moves the files nicely.
42,814
<p>How can I get the MAC Address using only the compact framework?</p>
[ { "answer_id": 42824, "author": "Greg Roberts", "author_id": 4269, "author_profile": "https://Stackoverflow.com/users/4269", "pm_score": -1, "selected": false, "text": "<p>Add a reference to System.Management.dll and use something like:</p>\n\n<pre><code>Dim mc As System.Management.Manag...
2008/09/03
[ "https://Stackoverflow.com/questions/42814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4463/" ]
How can I get the MAC Address using only the compact framework?
1.4 of the OpenNETCF code gets the information from the following P/Invoke call: ``` [DllImport ("iphlpapi.dll", SetLastError=true)] public static extern int GetAdaptersInfo( byte[] ip, ref int size ); ``` The physical address (returned as MAC address) I think is around about index 400 - 408 of the byte array after the call. So you can just use that directly if you don't want to use OpenNETCF (why though? OpenNETCF rocks more than stone henge!) Wonderful P/Invoke.net gives a full example [here](http://www.pinvoke.net/default.aspx/iphlpapi/GetAdaptersInfo.html). Oh and to properly answer your question: > > only using the Compact Framework > > > You cant. That's life with CF, if you want some fun try sending data with a socket synchronously with a timeout. :D
42,830
<p>I'm using the <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AutoComplete/AutoComplete.aspx" rel="nofollow noreferrer">AutoComplete</a> control from the ASP.NET AJAX Control Toolkit and I'm experiencing an issue where the AutoComplete does not populate when I set the focus to the assigned textbox. </p> <p>I've tried setting the focus in the Page_Load, Page_PreRender, and Page_Init events and the focus is set properly but the AutoComplete does not work. If I don't set the focus, everything works fine but I'd like to set it so the users don't have that extra click. </p> <p>Is there a special place I need to set the focus or something else I need to do to make this work? Thanks.</p>
[ { "answer_id": 42858, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 3, "selected": true, "text": "<p>We had exactly the same problem. What we had to do is write a script at the bottom of the page that quickly blurs the...
2008/09/03
[ "https://Stackoverflow.com/questions/42830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2034/" ]
I'm using the [AutoComplete](http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AutoComplete/AutoComplete.aspx) control from the ASP.NET AJAX Control Toolkit and I'm experiencing an issue where the AutoComplete does not populate when I set the focus to the assigned textbox. I've tried setting the focus in the Page\_Load, Page\_PreRender, and Page\_Init events and the focus is set properly but the AutoComplete does not work. If I don't set the focus, everything works fine but I'd like to set it so the users don't have that extra click. Is there a special place I need to set the focus or something else I need to do to make this work? Thanks.
We had exactly the same problem. What we had to do is write a script at the bottom of the page that quickly blurs then refocuses to the textbox. You can have a look at the (terribly hacky) solution here: <http://www.drive.com.au> The textbox id is `MainSearchBox_SearchTextBox`. Have a look at about line 586 & you can see where I'm wiring up all the events (I'm actually using prototype for this bit. Basically on the focus event of the textbox I set a global var called `textBoxHasFocus` to true and on the blur event I set it to false. The on the load event of the page I call this script: ``` if (textBoxHasFocus) { $get("MainSearchBox_SearchTextBox").blur(); $get("MainSearchBox_SearchTextBox").focus(); } ``` This resets the textbox. It's really dodgy, but it's the only solution I could find
42,833
<p>In the web-application I'm developing I currently use a naive solution when connecting to the database:</p> <pre><code>Connection c = DriverManager.getConnection("url", "username", "password"); </code></pre> <p>This is pretty unsafe. If an attacker gains access to the sourcecode he also gains access to the database itself. How can my web-application connect to the database without storing the database-password in plaintext in the sourcecode?</p>
[ { "answer_id": 42838, "author": "Julio César", "author_id": 2148, "author_profile": "https://Stackoverflow.com/users/2148", "pm_score": 5, "selected": true, "text": "<p>You can store the connection string in Web.config or App.config file and encrypt the section that holds it. Here's a ve...
2008/09/03
[ "https://Stackoverflow.com/questions/42833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4464/" ]
In the web-application I'm developing I currently use a naive solution when connecting to the database: ``` Connection c = DriverManager.getConnection("url", "username", "password"); ``` This is pretty unsafe. If an attacker gains access to the sourcecode he also gains access to the database itself. How can my web-application connect to the database without storing the database-password in plaintext in the sourcecode?
You can store the connection string in Web.config or App.config file and encrypt the section that holds it. Here's a very good article I used in a previous project to encrypt the connection string: <http://www.ondotnet.com/pub/a/dotnet/2005/02/15/encryptingconnstring.html>
42,876
<p>Why does the following code not work as I was expecting?</p> <pre><code>&lt;?php $data = array( array('Area1', null, null), array(null, 'Section1', null), array(null, null, 'Location1'), array('Area2', null, null), array(null, 'Section2', null), array(null, null, 'Location2') ); $root = array(); foreach ($data as $row) { if ($row[0]) { $area = array(); $root[$row[0]] =&amp; $area; } elseif ($row[1]) { $section = array(); $area[$row[1]] =&amp; $section; } elseif ($row[2]) { $section[] = $row[2]; } } print_r($root); </code></pre> <p>Expected result:</p> <pre><code>Array( [Area1] =&gt; Array( [Section1] =&gt; Array( [0] =&gt; Location1 ) ) [Area2] =&gt; Array( [Section2] =&gt; Array( [0] =&gt; Location2 ) ) ) </code></pre> <p>Actual result:</p> <pre><code>Array( [Area1] =&gt; Array( [Section2] =&gt; Array( [0] =&gt; Location2 ) ) [Area2] =&gt; Array( [Section2] =&gt; Array( [0] =&gt; Location2 ) ) ) </code></pre>
[ { "answer_id": 42885, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 3, "selected": true, "text": "<p>If you modify your code on two lines as follows:</p>\n\n<pre><code>$area = array();\n\n$section = array();\n</code></pre>\n\n<p>t...
2008/09/04
[ "https://Stackoverflow.com/questions/42876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486/" ]
Why does the following code not work as I was expecting? ``` <?php $data = array( array('Area1', null, null), array(null, 'Section1', null), array(null, null, 'Location1'), array('Area2', null, null), array(null, 'Section2', null), array(null, null, 'Location2') ); $root = array(); foreach ($data as $row) { if ($row[0]) { $area = array(); $root[$row[0]] =& $area; } elseif ($row[1]) { $section = array(); $area[$row[1]] =& $section; } elseif ($row[2]) { $section[] = $row[2]; } } print_r($root); ``` Expected result: ``` Array( [Area1] => Array( [Section1] => Array( [0] => Location1 ) ) [Area2] => Array( [Section2] => Array( [0] => Location2 ) ) ) ``` Actual result: ``` Array( [Area1] => Array( [Section2] => Array( [0] => Location2 ) ) [Area2] => Array( [Section2] => Array( [0] => Location2 ) ) ) ```
If you modify your code on two lines as follows: ``` $area = array(); $section = array(); ``` to this: ``` unset($area); $area = array(); unset($section); $section = array(); ``` it will work as expected. In the first version, `$area` and `$section` are acting as "pointers" to the value inside the `$root` array. If you reset the values first, those variables can then be used to create brand new arrays instead of overwriting the previous arrays.
42,934
<p>It seems that everybody is jumping on the dynamic, non-compiled bandwagon lately. I've mostly only worked in compiled, static typed languages (C, Java, .Net). The experience I have with dynamic languages is stuff like ASP (Vb Script), JavaScript, and PHP. Using these technologies has left a bad taste in my mouth when thinking about dynamic languages. Things that usually would have been caught by the compiler such as misspelled variable names and assigning an value of the wrong type to a variable don't occur until runtime. And even then, you may not notice an error, as it just creates a new variable, and assigns some default value. I've also never seen intellisense work well in a dynamic language, since, well, variables don't have any explicit type.</p> <p>What I want to know is, what people find so appealing about dynamic languages? What are the main advantages in terms of things that dynamic languages allow you to do that can't be done, or are difficult to do in compiled languages. It seems to me that we decided a long time ago, that things like uncompiled asp pages throwing runtime exceptions was a bad idea. Why is there is a resurgence of this type of code? And why does it seem to me at least, that Ruby on Rails doesn't really look like anything you couldn't have done with ASP 10 years ago?</p>
[ { "answer_id": 42945, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 2, "selected": false, "text": "<p>The argument is more complex than this (read <a href=\"http://steve.yegge.googlepages.com/is-weak-typing-strong-enough...
2008/09/04
[ "https://Stackoverflow.com/questions/42934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1862/" ]
It seems that everybody is jumping on the dynamic, non-compiled bandwagon lately. I've mostly only worked in compiled, static typed languages (C, Java, .Net). The experience I have with dynamic languages is stuff like ASP (Vb Script), JavaScript, and PHP. Using these technologies has left a bad taste in my mouth when thinking about dynamic languages. Things that usually would have been caught by the compiler such as misspelled variable names and assigning an value of the wrong type to a variable don't occur until runtime. And even then, you may not notice an error, as it just creates a new variable, and assigns some default value. I've also never seen intellisense work well in a dynamic language, since, well, variables don't have any explicit type. What I want to know is, what people find so appealing about dynamic languages? What are the main advantages in terms of things that dynamic languages allow you to do that can't be done, or are difficult to do in compiled languages. It seems to me that we decided a long time ago, that things like uncompiled asp pages throwing runtime exceptions was a bad idea. Why is there is a resurgence of this type of code? And why does it seem to me at least, that Ruby on Rails doesn't really look like anything you couldn't have done with ASP 10 years ago?
I think the reason is that people are used to statically typed languages that have very limited and inexpressive type systems. These are languages like Java, C++, Pascal, etc. Instead of going in the direction of more expressive type systems and better type inference, (as in Haskell, for example, and even SQL to some extent), some people like to just keep all the "type" information in their head (and in their tests) and do away with static typechecking altogether. What this buys you in the end is unclear. There are many misconceived notions about typechecking, the ones I most commonly come across are these two. **Fallacy: Dynamic languages are less verbose.** The misconception is that type information equals type annotation. This is totally untrue. We all know that type annotation is annoying. The machine should be able to figure that stuff out. And in fact, it does in modern compilers. Here is a statically typed QuickSort in two lines of Haskell (from [haskell.org](http://haskell.org)): ``` qsort [] = [] qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs) ``` And here is a dynamically typed QuickSort in LISP (from [swisspig.net](http://swisspig.net/r/post/blog-200603301157)): ``` (defun quicksort (lis) (if (null lis) nil (let* ((x (car lis)) (r (cdr lis)) (fn (lambda (a) (< a x)))) (append (quicksort (remove-if-not fn r)) (list x) (quicksort (remove-if fn r)))))) ``` The Haskell example falsifies the hypothesis *statically typed, therefore verbose*. The LISP example falsifies the hypothesis *verbose, therefore statically typed*. There is no implication in either direction between typing and verbosity. You can safely put that out of your mind. **Fallacy: Statically typed languages have to be compiled, not interpreted.** Again, not true. Many statically typed languages have interpreters. There's the Scala interpreter, The GHCi and Hugs interpreters for Haskell, and of course SQL has been both statically typed and interpreted for longer than I've been alive. You know, maybe the dynamic crowd just wants freedom to not have to think as carefully about what they're doing. The software might not be correct or robust, but maybe it doesn't have to be. Personally, I think that those who would give up type safety to purchase a little temporary liberty, deserve neither liberty nor type safety.
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
[ { "answer_id": 42997, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 7, "selected": false, "text": "<p>EDIT: See @Blair Conrad's answer for a cleaner solution</p>\n\n<hr>\n\n<pre><code>&gt;&gt;&gt; import datetime\n&gt;...
2008/09/04
[ "https://Stackoverflow.com/questions/42950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680/" ]
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month? If the standard library doesn't support that, does the dateutil package support this?
[`calendar.monthrange`](https://docs.python.org/library/calendar.html#calendar.monthrange) provides this information: > > calendar.**monthrange**(year, month) > >     Returns weekday of first day of the month and number of days in month, for the specified *year* and *month*. > > > ``` >>> import calendar >>> calendar.monthrange(2002, 1) (1, 31) >>> calendar.monthrange(2008, 2) # leap years are handled correctly (4, 29) >>> calendar.monthrange(2100, 2) # years divisible by 100 but not 400 aren't leap years (0, 28) ``` so: ``` calendar.monthrange(year, month)[1] ``` seems like the simplest way to go.
42,966
<p>What would be the best way to develop a text box that remembers the last x number of entries that were put into it. This is a standalone app written with C#.</p>
[ { "answer_id": 43003, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 3, "selected": false, "text": "<p>This is actually fairly easy, especially in terms of showing the \"AutoComplete\" part of it. In terms of remembering th...
2008/09/04
[ "https://Stackoverflow.com/questions/42966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2066/" ]
What would be the best way to develop a text box that remembers the last x number of entries that were put into it. This is a standalone app written with C#.
[@Ethan](https://stackoverflow.com/questions/42966/google-suggestish-text-box#45014) I forgot about the fact that you would want to save that so it wasn't a per session only thing :P But yes, you are completely correct. This is easily done, especially since it's just basic strings, just write out the contents of AutoCompleteCustomSource from the TextBox to a text file, on separate lines. I had a few minutes, so I wrote up a complete code example...I would've before as I always try to show code, but didn't have time. Anyway, here's the whole thing (minus the designer code). ``` namespace AutoComplete { public partial class Main : Form { //so you don't have to address "txtMain.AutoCompleteCustomSource" every time AutoCompleteStringCollection acsc; public Main() { InitializeComponent(); //Set to use a Custom source txtMain.AutoCompleteSource = AutoCompleteSource.CustomSource; //Set to show drop down *and* append current suggestion to end txtMain.AutoCompleteMode = AutoCompleteMode.SuggestAppend; //Init string collection. acsc = new AutoCompleteStringCollection(); //Set txtMain's AutoComplete Source to acsc txtMain.AutoCompleteCustomSource = acsc; } private void txtMain_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { //Only keep 10 AutoComplete strings if (acsc.Count < 10) { //Add to collection acsc.Add(txtMain.Text); } else { //remove oldest acsc.RemoveAt(0); //Add to collection acsc.Add(txtMain.Text); } } } private void Main_FormClosed(object sender, FormClosedEventArgs e) { //open stream to AutoComplete save file StreamWriter sw = new StreamWriter("AutoComplete.acs"); //Write AutoCompleteStringCollection to stream foreach (string s in acsc) sw.WriteLine(s); //Flush to file sw.Flush(); //Clean up sw.Close(); sw.Dispose(); } private void Main_Load(object sender, EventArgs e) { //open stream to AutoComplete save file StreamReader sr = new StreamReader("AutoComplete.acs"); //initial read string line = sr.ReadLine(); //loop until end while (line != null) { //add to AutoCompleteStringCollection acsc.Add(line); //read again line = sr.ReadLine(); } //Clean up sr.Close(); sr.Dispose(); } } } ``` This code will work exactly as is, you just need to create the GUI with a TextBox named txtMain and hook up the KeyDown, Closed and Load events to the TextBox and Main form. Also note that, for this example and to make it simple, I just chose to detect the Enter key being pressed as my trigger to save the string to the collection. There is probably more/different events that would be better, depending on your needs. Also, the model used for populating the collection is not very "smart." It simply deletes the oldest string when the collection gets to the limit of 10. This is likely not ideal, but works for the example. You would probably want some sort of rating system (especially if you really want it to be Google-ish) A final note, the suggestions will actually show up in the order they are in the collection. If for some reason you want them to show up differently, just sort the list however you like. Hope that helps!
42,980
<p>Does anyone know how to setup <a href="http://www.selenic.com/mercurial/wiki/index.cgi/Mercurial" rel="noreferrer">Mercurial</a> to use <a href="http://www.perforce.com/perforce/products/merge.html" rel="noreferrer">p4merge</a> as the merge/diff tool on OS X 10.5?</p>
[ { "answer_id": 43241, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 0, "selected": false, "text": "<p>I'm guessing there's a CLI tool for p4merge (which I know nothing about).</p>\n\n<p>I wrote a blog post about usin...
2008/09/04
[ "https://Stackoverflow.com/questions/42980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3547/" ]
Does anyone know how to setup [Mercurial](http://www.selenic.com/mercurial/wiki/index.cgi/Mercurial) to use [p4merge](http://www.perforce.com/perforce/products/merge.html) as the merge/diff tool on OS X 10.5?
**This will work for merging:** Place this into your `~/.hgrc` (or, optionally, your `Mercurial.ini` on Windows): ``` [merge-tools] p4.priority = 100 p4.premerge = True # change this to False if you're don't trust hg's internal merge p4.executable = /Applications/p4merge.app/Contents/MacOS/p4merge p4.gui = True p4.args = $base $local $other $output ``` Requires Mercurial 1.0 or newer. Clearly you'll need to update the path to that executable to reflect where you'd got p4merge installed. --- **You can't change what `hg diff` uses**; but you *can* use the `extdiff` extension to create new diff commands that use the display you want. So `hg pdiff` could run p4 merge, etc.
42,990
<p>I am looking for a regex that will match a string that starts with one substring and does not end with a certain substring.</p> <p>Example:</p> <pre><code>// Updated to be correct, thanks @Apocalisp ^foo.*(?&lt;!bar)$ </code></pre> <p>Should match anything that starts with "foo" and doesn't end with "bar". I know about the [^...] syntax, but I can't find anything that will do that for a string instead of single characters. </p> <p>I am specifically trying to do this for Java's regex, but I've run into this before so answers for other regex engines would be great too. </p> <p>Thanks to @Kibbee for verifying that this works in C# as well. </p>
[ { "answer_id": 43010, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 1, "selected": false, "text": "<p>I'm not familiar with Java regex but documentation for the <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/util/...
2008/09/04
[ "https://Stackoverflow.com/questions/42990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3535/" ]
I am looking for a regex that will match a string that starts with one substring and does not end with a certain substring. Example: ``` // Updated to be correct, thanks @Apocalisp ^foo.*(?<!bar)$ ``` Should match anything that starts with "foo" and doesn't end with "bar". I know about the [^...] syntax, but I can't find anything that will do that for a string instead of single characters. I am specifically trying to do this for Java's regex, but I've run into this before so answers for other regex engines would be great too. Thanks to @Kibbee for verifying that this works in C# as well.
I think in this case you want **negative lookbehind**, like so: ``` foo.*(?<!bar) ```
43,021
<p>Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?</p> <p>For instance, I currently do something like this depending on the circumstances:</p> <pre><code>int i = 0; foreach (Object o in collection) { // ... i++; } </code></pre>
[ { "answer_id": 43026, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 2, "selected": false, "text": "<p>Unless your collection can return the index of the object via some method, the only way is to use a counter like in yo...
2008/09/04
[ "https://Stackoverflow.com/questions/43021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop? For instance, I currently do something like this depending on the circumstances: ``` int i = 0; foreach (Object o in collection) { // ... i++; } ```
The `foreach` is for iterating over collections that implement [`IEnumerable`](http://msdn.microsoft.com/en-us/library/9eekhta0%28v=vs.110%29.aspx). It does this by calling [`GetEnumerator`](http://msdn.microsoft.com/en-us/library/s793z9y2(v=vs.110).aspx) on the collection, which will return an [`Enumerator`](http://msdn.microsoft.com/en-us/library/78dfe2yb(v=vs.110).aspx). This Enumerator has a method and a property: * `MoveNext()` * `Current` `Current` returns the object that Enumerator is currently on, `MoveNext` updates `Current` to the next object. The concept of an index is foreign to the concept of enumeration, and cannot be done. Because of that, most collections are able to be traversed using an indexer and the for loop construct. I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.
43,044
<p>I'm looking for a simple algorithm to generate a large number of random, aesthetically pleasing colors. So no crazy neon colors, colors reminiscent of feces, etc. </p> <p>I've found solutions to this problem but they rely on alternative color palettes than RGB. I would rather just use straight RGB than mapping back and forth. These other solutions also can at most generate only 32 or so pleasing random colors. </p> <p>Any ideas would be great.</p>
[ { "answer_id": 43081, "author": "helloandre", "author_id": 50, "author_profile": "https://Stackoverflow.com/users/50", "pm_score": 0, "selected": false, "text": "<p>you could have them be within a certain brightness. that would control the ammount of \"neon\" colors a bit. for instance, ...
2008/09/04
[ "https://Stackoverflow.com/questions/43044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3415/" ]
I'm looking for a simple algorithm to generate a large number of random, aesthetically pleasing colors. So no crazy neon colors, colors reminiscent of feces, etc. I've found solutions to this problem but they rely on alternative color palettes than RGB. I would rather just use straight RGB than mapping back and forth. These other solutions also can at most generate only 32 or so pleasing random colors. Any ideas would be great.
You could average the RGB values of random colors with those of a constant color: *(example in Java)* ``` public Color generateRandomColor(Color mix) { Random random = new Random(); int red = random.nextInt(256); int green = random.nextInt(256); int blue = random.nextInt(256); // mix the color if (mix != null) { red = (red + mix.getRed()) / 2; green = (green + mix.getGreen()) / 2; blue = (blue + mix.getBlue()) / 2; } Color color = new Color(red, green, blue); return color; } ``` Mixing random colors with white (255, 255, 255) creates neutral pastels by increasing the lightness while keeping the hue of the original color. These randomly generated pastels usually go well together, especially in large numbers. Here are some pastel colors generated using the above method: ![First](https://i.stack.imgur.com/8jKGx.jpg) You could also mix the random color with a constant pastel, which results in a tinted set of neutral colors. For example, using a light blue creates colors like these: ![Second](https://i.stack.imgur.com/zI406.jpg) Going further, you could add heuristics to your generator that take into account complementary colors or levels of shading, but it all depends on the impression you want to achieve with your random colors. Some additional resources: * <http://en.wikipedia.org/wiki/Color_theory> * <http://en.wikipedia.org/wiki/Complementary_color>
43,051
<p>I have the following C# code:</p> <pre><code>byte rule = 0; ... rule = rule | 0x80; </code></pre> <p>which produces the error: </p> <blockquote> <p><em>Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)</em></p> </blockquote> <p>[Update: first version of the question was wrong ... I misread the compiler output]</p> <p>Adding the cast <strong>doesn't</strong> fix the problem:</p> <pre><code>rule = rule | (byte) 0x80; </code></pre> <p>I need to write it as:</p> <pre><code>rule |= 0x80; </code></pre> <p>Which just seems weird. Why is the <code>|=</code> operator any different to the <code>|</code> operator?</p> <p>Is there any other way of telling the compiler to treat the constant as a byte?</p> <hr> <p><strong>@ Giovanni Galbo</strong> : yes and no. The code is dealing with the programming of the flash memory in an external device, and logically represents a single byte of memory. I could cast it later, but this seemed more obvious. I guess my C heritage is showing through too much!</p> <p><strong>@ Jonathon Holland</strong> : the 'as' syntax looks neater but unfortunately doesn't appear to work ... it produces:</p> <blockquote> <p><em>The as operator must be used with a reference type or nullable type ('byte' is a non-nullable value type)</em> </p> </blockquote>
[ { "answer_id": 43057, "author": "John Rutherford", "author_id": 3880, "author_profile": "https://Stackoverflow.com/users/3880", "pm_score": 1, "selected": false, "text": "<p>Looks like you may just have to do it the ugly way: <a href=\"http://msdn.microsoft.com/en-us/library/5bdb6693.asp...
2008/09/04
[ "https://Stackoverflow.com/questions/43051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3631/" ]
I have the following C# code: ``` byte rule = 0; ... rule = rule | 0x80; ``` which produces the error: > > *Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)* > > > [Update: first version of the question was wrong ... I misread the compiler output] Adding the cast **doesn't** fix the problem: ``` rule = rule | (byte) 0x80; ``` I need to write it as: ``` rule |= 0x80; ``` Which just seems weird. Why is the `|=` operator any different to the `|` operator? Is there any other way of telling the compiler to treat the constant as a byte? --- **@ Giovanni Galbo** : yes and no. The code is dealing with the programming of the flash memory in an external device, and logically represents a single byte of memory. I could cast it later, but this seemed more obvious. I guess my C heritage is showing through too much! **@ Jonathon Holland** : the 'as' syntax looks neater but unfortunately doesn't appear to work ... it produces: > > *The as operator must be used with a reference type or nullable type ('byte' is a non-nullable value type)* > > >
``` int rule = 0; rule |= 0x80; ``` <http://msdn.microsoft.com/en-us/library/kxszd0kx.aspx> The | operator is defined for all value types. I think this will produced the intended result. The "|=" operator is an or then assign operator, which is simply shorthand for rule = rule | 0x80. One of the niftier things about C# is that it lets you do crazy things like abuse value types simply based on their size. An 'int' is exactly the same as a byte, except the compiler will throw warnings if you try and use them as both at the same time. Simply sticking with one (in this case, int) works well. If you're concerned about 64bit readiness, you can specify int32, but all ints are int32s, even running in x64 mode.
43,126
<pre><code>public static IList&lt;T&gt; LoadObjectListAll&lt;T&gt;() { ISession session = CheckForExistingSession(); var cfg = new NHibernate.Cfg.Configuration().Configure(); var returnList = session.CreateCriteria(typeof(T)); var list = returnList.List(); var castList = list.Cast&lt;typeof(T)&gt;(); return castList; } </code></pre> <p>So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here? </p>
[ { "answer_id": 43128, "author": "jfs", "author_id": 718, "author_profile": "https://Stackoverflow.com/users/718", "pm_score": 3, "selected": false, "text": "<p>I think </p>\n\n<pre><code>var castList = list.Cast&lt;typeof(T)&gt;();\n</code></pre>\n\n<p>should be </p>\n\n<pre><code>var ca...
2008/09/04
[ "https://Stackoverflow.com/questions/43126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4140/" ]
``` public static IList<T> LoadObjectListAll<T>() { ISession session = CheckForExistingSession(); var cfg = new NHibernate.Cfg.Configuration().Configure(); var returnList = session.CreateCriteria(typeof(T)); var list = returnList.List(); var castList = list.Cast<typeof(T)>(); return castList; } ``` So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here?
`T` is not a type nor a `System.Type`. `T` is a type parameter. `typeof(T)` returns the type of `T`. The `typeof` operator does not act on an object, it returns the `Type` object of a type. <http://msdn.microsoft.com/en-us/library/58918ffs.aspx> @John is correct in answering your direct question. But the NHibernate code there is a little off. You shouldn't be configuring the `ISessionFactory` *after* getting the `ISession`, for example. ``` public static T[] LoadObjectListAll() { var session = GetNewSession(); var criteria = session.CreateCriteria(typeof(T)); var results = criteria.List<T>(); return results.ToArray(); } ```
43,134
<p>Simple question, but one that I've been curious about...is there a functional difference between the following two commands?</p> <pre><code>String::class String.class </code></pre> <p>They both do what I expect -- that is to say they return <code>Class</code> -- but what is the difference between using the <code>::</code> and the <code>.</code>?</p> <p>I notice that on those classes that have constants defined, IRB's auto-completion will return the constants as available options when you press tab after <code>::</code> but not after <code>.</code>, but I don't know what the reason for this is...</p>
[ { "answer_id": 43146, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 6, "selected": true, "text": "<p>The <code>.</code> operator basically says \"send this message to the object\". In your example it is calling that part...
2008/09/04
[ "https://Stackoverflow.com/questions/43134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4142/" ]
Simple question, but one that I've been curious about...is there a functional difference between the following two commands? ``` String::class String.class ``` They both do what I expect -- that is to say they return `Class` -- but what is the difference between using the `::` and the `.`? I notice that on those classes that have constants defined, IRB's auto-completion will return the constants as available options when you press tab after `::` but not after `.`, but I don't know what the reason for this is...
The `.` operator basically says "send this message to the object". In your example it is calling that particular member. The `::` operator "drills down" to the scope defined to the left of the operator, and then calls the member defined on the right side of operator. When you use `::` you have to be referencing members that are defined. When using `.` you are simply sending a message to the object. Because that message could be anything, auto-completion does not work for `.` while it does for `::`.
43,157
<p>I was surprised to find today that I couldn't track down any simple way to write the contents of an <code>InputStream</code> to an <code>OutputStream</code> in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer).</p> <p>So, given an <code>InputStream</code> <code>in</code> and an <code>OutputStream</code> <code>out</code>, is there a simpler way to write the following?</p> <pre><code>byte[] buffer = new byte[1024]; int len = in.read(buffer); while (len != -1) { out.write(buffer, 0, len); len = in.read(buffer); } </code></pre>
[ { "answer_id": 43163, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 7, "selected": false, "text": "<p>I think this will work, but make sure to test it... minor \"improvement\", but it might be a bit of a cost at readability...
2008/09/04
[ "https://Stackoverflow.com/questions/43157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
I was surprised to find today that I couldn't track down any simple way to write the contents of an `InputStream` to an `OutputStream` in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer). So, given an `InputStream` `in` and an `OutputStream` `out`, is there a simpler way to write the following? ``` byte[] buffer = new byte[1024]; int len = in.read(buffer); while (len != -1) { out.write(buffer, 0, len); len = in.read(buffer); } ```
Java 9 ====== Since Java 9, `InputStream` provides a method called `transferTo` with the following signature: ``` public long transferTo(OutputStream out) throws IOException ``` As the [documentation](https://docs.oracle.com/javase/9/docs/api/java/io/InputStream.html#transferTo-java.io.OutputStream-) states, `transferTo` will: > > Reads all bytes from this input stream and writes the bytes to the > given output stream in the order that they are read. On return, this > input stream will be at end of stream. This method does not close > either stream. > > > This method may block indefinitely reading from the > input stream, or writing to the output stream. The behavior for the > case where the input and/or output stream is asynchronously closed, or > the thread interrupted during the transfer, is highly input and output > stream specific, and therefore not specified > > > So in order to write contents of a Java `InputStream` to an `OutputStream`, you can write: ``` input.transferTo(output); ```
43,199
<p>The login page in my Tapestry application has a property in which the password the user types in is stored, which is then compared against the value from the database. If the user enters a password with multi-byte characters, such as:</p> <pre><code>áéíóú </code></pre> <p>...an inspection of the return value of getPassword() (the abstract method for the corresponding property) gives:</p> <pre><code>áéíóú </code></pre> <p>Clearly, that's not encoded properly. Yet Firebug reports that the page is served up in UTF-8, so presumably the form submission request would also be encoded in UTF-8. Inspecting the value as it comes from the database produces the correct string, so it wouldn't appear to be an OS or IDE encoding issue. I have not overridden Tapestry's default value for org.apache.tapestry.output-encoding in the .application file, and the Tapestry 4 <a href="http://tapestry.apache.org/tapestry4/UsersGuide/configuration.html#configuration.properties" rel="nofollow noreferrer">documentation</a> indicates that the default value for the property is UTF-8.</p> <p>So why does Tapestry appear to botch the encoding when setting the property?</p> <p>Relevant code follows:</p> <h2>Login.html</h2> <pre class="lang-html prettyprint-override"><code>&lt;html jwcid="@Shell" doctype='html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"' ...&gt; &lt;body jwcid="@Body"&gt; ... &lt;form jwcid="@Form" listener="listener:attemptLogin" ...&gt; ... &lt;input jwcid="password"/&gt; ... &lt;/form&gt; ... &lt;/body&gt; &lt;/html&gt; </code></pre> <h2>Login.page</h2> <pre class="lang-jsp prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE page-specification PUBLIC "-//Apache Software Foundation//Tapestry Specification 4.0//EN" "http://jakarta.apache.org/tapestry/dtd/Tapestry_4_0.dtd"&gt; &lt;page-specification class="mycode.Login"&gt; ... &lt;property name="password" /&gt; ... &lt;component id="password" type="TextField"&gt; &lt;binding name="value" value="password"/&gt; &lt;binding name="hidden" value="true"/&gt; ... &lt;/component&gt; ... &lt;/page-specification&gt; </code></pre> <h2>Login.java</h2> <pre><code>... public abstract class Login extends BasePage { ... public abstract String getPassword(); ... public void attemptLogin() { // At this point, inspecting getPassword() returns // the incorrectly encoded String. } ... } </code></pre> <h2>Updates</h2> <p>@Jan Soltis: Well, if I inspect the value that comes from the database, it displays the correct string, so it would seem that my editor, OS and database are all encoding the value correctly. I've also checked my .application file; it does not contain an org.apache.tapestry.output-encoding entry, and the Tapestry 4 <a href="http://tapestry.apache.org/tapestry4/UsersGuide/configuration.html#configuration.properties" rel="nofollow noreferrer">documentation</a> indicates that the default value for this property is UTF-8. I have updated the description above to reflect the answers to your questions.</p> <p>@myself: Solution found.</p>
[ { "answer_id": 43238, "author": "Palgar", "author_id": 3479, "author_profile": "https://Stackoverflow.com/users/3479", "pm_score": 2, "selected": false, "text": "<p>If you have built them as Hyper-V machines, I don't think you can go back. There are serious differences in the HAL for Vi...
2008/09/04
[ "https://Stackoverflow.com/questions/43199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4287/" ]
The login page in my Tapestry application has a property in which the password the user types in is stored, which is then compared against the value from the database. If the user enters a password with multi-byte characters, such as: ``` áéíóú ``` ...an inspection of the return value of getPassword() (the abstract method for the corresponding property) gives: ``` áéíóú ``` Clearly, that's not encoded properly. Yet Firebug reports that the page is served up in UTF-8, so presumably the form submission request would also be encoded in UTF-8. Inspecting the value as it comes from the database produces the correct string, so it wouldn't appear to be an OS or IDE encoding issue. I have not overridden Tapestry's default value for org.apache.tapestry.output-encoding in the .application file, and the Tapestry 4 [documentation](http://tapestry.apache.org/tapestry4/UsersGuide/configuration.html#configuration.properties) indicates that the default value for the property is UTF-8. So why does Tapestry appear to botch the encoding when setting the property? Relevant code follows: Login.html ---------- ```html <html jwcid="@Shell" doctype='html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"' ...> <body jwcid="@Body"> ... <form jwcid="@Form" listener="listener:attemptLogin" ...> ... <input jwcid="password"/> ... </form> ... </body> </html> ``` Login.page ---------- ```jsp <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE page-specification PUBLIC "-//Apache Software Foundation//Tapestry Specification 4.0//EN" "http://jakarta.apache.org/tapestry/dtd/Tapestry_4_0.dtd"> <page-specification class="mycode.Login"> ... <property name="password" /> ... <component id="password" type="TextField"> <binding name="value" value="password"/> <binding name="hidden" value="true"/> ... </component> ... </page-specification> ``` Login.java ---------- ``` ... public abstract class Login extends BasePage { ... public abstract String getPassword(); ... public void attemptLogin() { // At this point, inspecting getPassword() returns // the incorrectly encoded String. } ... } ``` Updates ------- @Jan Soltis: Well, if I inspect the value that comes from the database, it displays the correct string, so it would seem that my editor, OS and database are all encoding the value correctly. I've also checked my .application file; it does not contain an org.apache.tapestry.output-encoding entry, and the Tapestry 4 [documentation](http://tapestry.apache.org/tapestry4/UsersGuide/configuration.html#configuration.properties) indicates that the default value for this property is UTF-8. I have updated the description above to reflect the answers to your questions. @myself: Solution found.
VPC to Hyper-V is one way.
43,201
<p>I'm looking for some examples or samples of routing for the following sort of scenario:</p> <p>The general example of doing things is: {controller}/{action}/{id}</p> <p>So in the scenario of doing a product search for a store you'd have:</p> <pre><code>public class ProductsController: Controller { public ActionResult Search(string id) // id being the search string { ... } } </code></pre> <p>Say you had a few stores to do this and you wanted that consistently, is there any way to then have: {category}/{controller}/{action}/{id}</p> <p>So that you could have a particular search for a particular store, but use a different search method for a different store?</p> <p>(If you required the store name to be a higher priority than the function itself in the url)</p> <p>Or would it come down to:</p> <pre><code>public class ProductsController: Controller { public ActionResult Search(int category, string id) // id being the search string { if(category == 1) return Category1Search(); if(category == 2) return Category2Search(); ... } } </code></pre> <p>It may not be a great example, but basically the idea is to use the same controller name and therefore have a simple URL across a few different scenarios, or are you kind of stuck with requiring unique controller names, and no way to put them in slightly different namespaces/directories?</p> <p>Edit to add:</p> <p>The other reason I want this is because I might want a url that has the categories, and that certain controllers will only work under certain categories.</p> <p>IE:</p> <p>/this/search/items/search+term &lt;-- works</p> <p>/that/search/items/search+term &lt;-- won't work - because the search controller isn't allowed.</p>
[ { "answer_id": 43623, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 1, "selected": false, "text": "<p>The best way to do this without any compromises would be to implement your own ControllerFactory by inheriting off of I...
2008/09/04
[ "https://Stackoverflow.com/questions/43201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3717/" ]
I'm looking for some examples or samples of routing for the following sort of scenario: The general example of doing things is: {controller}/{action}/{id} So in the scenario of doing a product search for a store you'd have: ``` public class ProductsController: Controller { public ActionResult Search(string id) // id being the search string { ... } } ``` Say you had a few stores to do this and you wanted that consistently, is there any way to then have: {category}/{controller}/{action}/{id} So that you could have a particular search for a particular store, but use a different search method for a different store? (If you required the store name to be a higher priority than the function itself in the url) Or would it come down to: ``` public class ProductsController: Controller { public ActionResult Search(int category, string id) // id being the search string { if(category == 1) return Category1Search(); if(category == 2) return Category2Search(); ... } } ``` It may not be a great example, but basically the idea is to use the same controller name and therefore have a simple URL across a few different scenarios, or are you kind of stuck with requiring unique controller names, and no way to put them in slightly different namespaces/directories? Edit to add: The other reason I want this is because I might want a url that has the categories, and that certain controllers will only work under certain categories. IE: /this/search/items/search+term <-- works /that/search/items/search+term <-- won't work - because the search controller isn't allowed.
I actually found it not even by searching, but by scanning through the ASP .NET forums in [this question](http://forums.asp.net/t/1296928.aspx?PageIndex=1). Using this you can have the controllers of the same name under any part of the namespace, so long as you qualify which routes belong to which namespaces (you can have multiple namespaces per routes if you need be!) But from here, you can put in a directory under your controller, so if your controller was "MyWebShop.Controllers", you'd put a directory of "Shop1" and the namespace would be "MyWebShop.Controllers.Shop1" Then this works: ``` public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); var shop1namespace = new RouteValueDictionary(); shop1namespace.Add("namespaces", new HashSet<string>(new string[] { "MyWebShop.Controllers.Shop1" })); routes.Add("Shop1", new Route("Shop1/{controller}/{action}/{id}", new MvcRouteHandler()) { Defaults = new RouteValueDictionary(new { action = "Index", id = (string)null }), DataTokens = shop1namespace }); var shop2namespace = new RouteValueDictionary(); shop2namespace.Add("namespaces", new HashSet<string>(new string[] { "MyWebShop.Controllers.Shop2" })); routes.Add("Shop2", new Route("Shop2/{controller}/{action}/{id}", new MvcRouteHandler()) { Defaults = new RouteValueDictionary(new { action = "Index", id = (string)null }), DataTokens = shop2namespace }); var defaultnamespace = new RouteValueDictionary(); defaultnamespace.Add("namespaces", new HashSet<string>(new string[] { "MyWebShop.Controllers" })); routes.Add("Default", new Route("{controller}/{action}/{id}", new MvcRouteHandler()) { Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = "" }), DataTokens = defaultnamespace }); } ``` The only other thing is that it will reference a view still in the base directory, so if you put the view into directories to match, you will have to put the view name in when you return it inside the controller.
43,218
<p>I'm working on a C#/ASP.NET project that has all the javascript files in a /Javascript folder. If I refer to the JS file using this syntax: src="/Javascript/jsfile.js" then the file is correctly picked up if the project is deployed to the root of the URL.</p> <p>However, if this "web site" is deployed to a sub-folder of the main url this won't work. So the solution could be to use relative urls - but there's a problem with that as well because the master pages reference many of the javascript files and these master pages can be used by pages in the root and in subfolders many levels deep.</p> <p>Does anybody have any ideas for resolving this?</p>
[ { "answer_id": 43222, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 5, "selected": true, "text": "<p>If you reference the JS-file in a section that is \"runat=server\" you could write src=\"~/Javascript/jsfile.js\" and it will ...
2008/09/04
[ "https://Stackoverflow.com/questions/43218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
I'm working on a C#/ASP.NET project that has all the javascript files in a /Javascript folder. If I refer to the JS file using this syntax: src="/Javascript/jsfile.js" then the file is correctly picked up if the project is deployed to the root of the URL. However, if this "web site" is deployed to a sub-folder of the main url this won't work. So the solution could be to use relative urls - but there's a problem with that as well because the master pages reference many of the javascript files and these master pages can be used by pages in the root and in subfolders many levels deep. Does anybody have any ideas for resolving this?
If you reference the JS-file in a section that is "runat=server" you could write src="~/Javascript/jsfile.js" and it will always work. You could also do this in your Page\_Load (In your masterpage): ``` Page.ClientScript.RegisterClientScriptInclude("myJsFile", Page.ResolveClientUrl("~/Javascript/jsfile.js")) ```
43,249
<p>Is there a graceful way to handle passing a list of ids as a parameter to a stored procedure? </p> <p>For instance, I want departments 1, 2, 5, 7, 20 returned by my stored procedure. In the past, I have passed in a comma delimited list of ids, like the below code, but feel really dirty doing it. </p> <p>SQL Server 2005 is my only applicable limitation I think.</p> <pre><code>create procedure getDepartments @DepartmentIds varchar(max) as declare @Sql varchar(max) select @Sql = 'select [Name] from Department where DepartmentId in (' + @DepartmentIds + ')' exec(@Sql) </code></pre>
[ { "answer_id": 43260, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 4, "selected": false, "text": "<p>Yeah, your current solution is prone to SQL injection attacks.</p>\n\n<p>The best solution that I've found is to use a...
2008/09/04
[ "https://Stackoverflow.com/questions/43249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1865/" ]
Is there a graceful way to handle passing a list of ids as a parameter to a stored procedure? For instance, I want departments 1, 2, 5, 7, 20 returned by my stored procedure. In the past, I have passed in a comma delimited list of ids, like the below code, but feel really dirty doing it. SQL Server 2005 is my only applicable limitation I think. ``` create procedure getDepartments @DepartmentIds varchar(max) as declare @Sql varchar(max) select @Sql = 'select [Name] from Department where DepartmentId in (' + @DepartmentIds + ')' exec(@Sql) ```
Erland Sommarskog has maintained the authoritative answer to this question for the last 16 years: *[Arrays and Lists in SQL Server](http://www.sommarskog.se/arrays-in-sql.html)*. There are at least a dozen ways to pass an array or list to a query; each has their own unique pros and cons. * [Table-Valued Parameters](http://www.sommarskog.se/arrays-in-sql-2008.html). SQL Server 2008 and higher only, and probably the closest to a universal "best" approach. * [The Iterative Method](http://www.sommarskog.se/arrays-in-sql-2005.html#iterative). Pass a delimited string and loop through it. * [Using the CLR](http://www.sommarskog.se/arrays-in-sql-2005.html#CLR). SQL Server 2005 and higher from .NET languages only. * [XML](http://www.sommarskog.se/arrays-in-sql-2005.html#XML). Very good for inserting many rows; may be overkill for SELECTs. * [Table of Numbers](http://www.sommarskog.se/arrays-in-sql-2005.html#tblnum). Higher performance/complexity than simple iterative method. * [Fixed-length Elements](http://www.sommarskog.se/arrays-in-sql-2005.html#fixed-length). Fixed length improves speed over the delimited string * [Function of Numbers](http://www.sommarskog.se/arrays-in-sql-2005.html#fn_nums). Variations of Table of Numbers and fixed-length where the number are generated in a function rather than taken from a table. * [Recursive Common Table Expression](http://www.sommarskog.se/arrays-in-sql-2005.html#CTEs) (CTE). SQL Server 2005 and higher, still not too complex and higher performance than iterative method. * [Dynamic SQL](http://www.sommarskog.se/arrays-in-sql-2005.html#dynamic-sql). Can be slow and has security implications. * Passing the List as [Many Parameters](http://www.sommarskog.se/arrays-in-sql-2005.html#manyparameters). Tedious and error prone, but simple. * [Really Slow Methods](http://www.sommarskog.se/arrays-in-sql-2005.html#realslow). Methods that uses charindex, patindex or LIKE. I really can't recommend enough to [read the article](http://www.sommarskog.se/arrays-in-sql.html) to learn about the tradeoffs among all these options.
43,289
<p>How can I do this fast?</p> <p>Sure I can do this:</p> <pre><code>static bool ByteArrayCompare(byte[] a1, byte[] a2) { if (a1.Length != a2.Length) return false; for (int i=0; i&lt;a1.Length; i++) if (a1[i]!=a2[i]) return false; return true; } </code></pre> <p>But I'm looking for either a <a href="https://en.wikipedia.org/wiki/Standard_Libraries_%28CLI%29#Base_Class_Library" rel="noreferrer">BCL</a> function or some highly optimized proven way to do this.</p> <pre><code>java.util.Arrays.equals((sbyte[])(Array)a1, (sbyte[])(Array)a2); </code></pre> <p>works nicely, but it doesn't look like that would work for x64.</p> <p>Note my super-fast answer <a href="https://stackoverflow.com/a/8808245/4489">here</a>.</p>
[ { "answer_id": 43300, "author": "gil", "author_id": 195, "author_profile": "https://Stackoverflow.com/users/195", "pm_score": 3, "selected": false, "text": "<p>I would use unsafe code and run the <code>for</code> loop comparing Int32 pointers.</p>\n\n<p>Maybe you should also consider che...
2008/09/04
[ "https://Stackoverflow.com/questions/43289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4489/" ]
How can I do this fast? Sure I can do this: ``` static bool ByteArrayCompare(byte[] a1, byte[] a2) { if (a1.Length != a2.Length) return false; for (int i=0; i<a1.Length; i++) if (a1[i]!=a2[i]) return false; return true; } ``` But I'm looking for either a [BCL](https://en.wikipedia.org/wiki/Standard_Libraries_%28CLI%29#Base_Class_Library) function or some highly optimized proven way to do this. ``` java.util.Arrays.equals((sbyte[])(Array)a1, (sbyte[])(Array)a2); ``` works nicely, but it doesn't look like that would work for x64. Note my super-fast answer [here](https://stackoverflow.com/a/8808245/4489).
Edit: modern fast way is to use `a1.SequenceEquals(a2)` User *gil* suggested unsafe code which spawned this solution: ``` // Copyright (c) 2008-2013 Hafthor Stefansson // Distributed under the MIT/X11 software license // Ref: http://www.opensource.org/licenses/mit-license.php. static unsafe bool UnsafeCompare(byte[] a1, byte[] a2) { unchecked { if(a1==a2) return true; if(a1==null || a2==null || a1.Length!=a2.Length) return false; fixed (byte* p1=a1, p2=a2) { byte* x1=p1, x2=p2; int l = a1.Length; for (int i=0; i < l/8; i++, x1+=8, x2+=8) if (*((long*)x1) != *((long*)x2)) return false; if ((l & 4)!=0) { if (*((int*)x1)!=*((int*)x2)) return false; x1+=4; x2+=4; } if ((l & 2)!=0) { if (*((short*)x1)!=*((short*)x2)) return false; x1+=2; x2+=2; } if ((l & 1)!=0) if (*((byte*)x1) != *((byte*)x2)) return false; return true; } } } ``` which does 64-bit based comparison for as much of the array as possible. This kind of counts on the fact that the arrays start qword aligned. It'll work if not qword aligned, just not as fast as if it were. It performs about seven timers faster than the simple `for` loop. Using the J# library performed equivalently to the original `for` loop. Using .SequenceEqual runs around seven times slower; I think just because it is using IEnumerator.MoveNext. I imagine LINQ-based solutions being at least that slow or worse.
43,290
<p>In Django's template language, you can use <code>{% url [viewname] [args] %}</code> to generate a URL to a specific view with parameters. How can you programatically do the same in Python code?</p> <p>What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language.</p>
[ { "answer_id": 43312, "author": "Peter Hoffmann", "author_id": 720, "author_profile": "https://Stackoverflow.com/users/720", "pm_score": 7, "selected": true, "text": "<p>If you need to use something similar to the <code>{% url %}</code> template tag in your code, Django provides the <cod...
2008/09/04
[ "https://Stackoverflow.com/questions/43290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355/" ]
In Django's template language, you can use `{% url [viewname] [args] %}` to generate a URL to a specific view with parameters. How can you programatically do the same in Python code? What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language.
If you need to use something similar to the `{% url %}` template tag in your code, Django provides the `django.core.urlresolvers.reverse()`. The `reverse` function has the following signature: ``` reverse(viewname, urlconf=None, args=None, kwargs=None) ``` <https://docs.djangoproject.com/en/dev/ref/urlresolvers/> At the time of this edit the import is `django.urls import reverse`
43,291
<p>I know that I can do something like</p> <pre><code>$int = (int)99; //(int) has a maximum or 99 </code></pre> <p>To set the variable <code>$int</code> to an integer and give it a value of <code>99</code>. </p> <p>Is there a way to set the type to something like <code>LongBlob</code> in MySQL for <code>LARGE</code> Integers in PHP?</p>
[ { "answer_id": 43295, "author": "erlando", "author_id": 4192, "author_profile": "https://Stackoverflow.com/users/4192", "pm_score": 4, "selected": true, "text": "<p>No. PHP does what is called automatic type conversion.</p>\n\n<p>In your example</p>\n\n<pre><code>$int = (int)123;\n</code...
2008/09/04
[ "https://Stackoverflow.com/questions/43291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
I know that I can do something like ``` $int = (int)99; //(int) has a maximum or 99 ``` To set the variable `$int` to an integer and give it a value of `99`. Is there a way to set the type to something like `LongBlob` in MySQL for `LARGE` Integers in PHP?
No. PHP does what is called automatic type conversion. In your example ``` $int = (int)123; ``` the "(int)" just assures that at that exact moment 123 will be handled as an int. I think your best bet would be to use a class to provide some sort of type safety.
43,320
<p>One of the things that get me thoroughly confused is the use of <code>session.Flush</code>,in conjunction with <code>session.Commit</code>, and <code>session.Close</code>.</p> <p>Sometimes <code>session.Close</code> works, e.g., it commits all the changes that I need. I know I need to use commit when I have a transaction, or a unit of work with several creates/updates/deletes, so that I can choose to rollback if an error occurs.</p> <p>But sometimes I really get stymied by the logic behind <code>session.Flush</code>. I have seen examples where you have a <code>session.SaveOrUpdate()</code> followed by a flush, but when I remove Flush it works fine anyway. Sometimes I run into errors on the Flush statement saying that the session timed out, and removing it made sure that I didn't run into that error.</p> <p>Does anyone have a good guideline as to where or when to use a Flush? I've checked out the NHibernate documentation for this, but I still can't find a straightforward answer.</p>
[ { "answer_id": 43567, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 9, "selected": true, "text": "<p>Briefly:</p>\n<ol>\n<li>Always use transactions</li>\n<li>Don't use <code>Close()</code>, instead wrap your calls on an ...
2008/09/04
[ "https://Stackoverflow.com/questions/43320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/372/" ]
One of the things that get me thoroughly confused is the use of `session.Flush`,in conjunction with `session.Commit`, and `session.Close`. Sometimes `session.Close` works, e.g., it commits all the changes that I need. I know I need to use commit when I have a transaction, or a unit of work with several creates/updates/deletes, so that I can choose to rollback if an error occurs. But sometimes I really get stymied by the logic behind `session.Flush`. I have seen examples where you have a `session.SaveOrUpdate()` followed by a flush, but when I remove Flush it works fine anyway. Sometimes I run into errors on the Flush statement saying that the session timed out, and removing it made sure that I didn't run into that error. Does anyone have a good guideline as to where or when to use a Flush? I've checked out the NHibernate documentation for this, but I still can't find a straightforward answer.
Briefly: 1. Always use transactions 2. Don't use `Close()`, instead wrap your calls on an `ISession` inside a `using` statement or **manage the lifecycle of your ISession somewhere else**. From [the documentation](http://nhibernate.info/doc/nh/en/index.html#manipulatingdata-flushing): > > From time to time the `ISession` will execute the SQL statements needed to synchronize the ADO.NET connection's state with the state of objects held in memory. This process, flush, occurs by default at the following points > > > * from some invocations of `Find()` or `Enumerable()` > * from `NHibernate.ITransaction.Commit()` > * from `ISession.Flush()` > > > The SQL statements are issued in the following order > > > 1. all entity insertions, in the same order the corresponding objects were saved using `ISession.Save()` > 2. all entity updates > 3. all collection deletions > 4. all collection element deletions, updates and insertions > 5. all collection insertions > 6. all entity deletions, in the same order the corresponding objects were deleted using `ISession.Delete()` > > > (An exception is that objects using native ID generation are inserted when they are saved.) > > > **Except when you explicity `Flush()`, there are absolutely no guarantees about when the Session executes the ADO.NET calls, only the order in which they are executed**. However, NHibernate does guarantee that the `ISession.Find(..)` methods will never return stale data; nor will they return the wrong data. > > > It is possible to change the default behavior so that flush occurs less frequently. The `FlushMode` class defines three different modes: only flush at commit time (and only when the NHibernate `ITransaction` API is used), flush automatically using the explained routine, or never flush unless `Flush()` is called explicitly. The last mode is useful for long running units of work, where an `ISession` is kept open and disconnected for a long time. > > > ... Also refer to [this section](http://nhibernate.info/doc/nh/en/index.html#manipulatingdata-endingsession): > > Ending a session involves four distinct phases: > > > * flush the session > * commit the transaction > * close the session > * handle exceptions > > > Flushing the Session > -------------------- > > > If you happen to be using the `ITransaction` API, you don't need to worry about this step. It will be performed implicitly when the transaction is committed. Otherwise you should call `ISession.Flush()` to ensure that all changes are synchronized with the database. > > > Committing the database transaction > ----------------------------------- > > > If you are using the NHibernate ITransaction API, this looks like: > > > > ``` > tx.Commit(); // flush the session and commit the transaction > > ``` > > If you are managing ADO.NET transactions yourself you should manually `Commit()` the ADO.NET transaction. > > > > ``` > sess.Flush(); > currentTransaction.Commit(); > > ``` > > If you decide not to commit your changes: > > > > ``` > tx.Rollback(); // rollback the transaction > > ``` > > or: > > > > ``` > currentTransaction.Rollback(); > > ``` > > If you rollback the transaction you should immediately close and discard the current session to ensure that NHibernate's internal state is consistent. > > > Closing the ISession > -------------------- > > > A call to `ISession.Close()` marks the end of a session. The main implication of Close() is that the ADO.NET connection will be relinquished by the session. > > > > ``` > tx.Commit(); > sess.Close(); > > sess.Flush(); > currentTransaction.Commit(); > sess.Close(); > > ``` > > If you provided your own connection, `Close()` returns a reference to it, so you can manually close it or return it to the pool. Otherwise `Close()` returns it to the pool. > > >
43,321
<p>The default shell in Mac OS X is <code>bash</code>, which I'm generally happy to be using. I just take it for granted. It would be really nice if it auto-completed <em>more stuff</em>, though, and I've heard good things about <code>zsh</code> in this regard. But I don't really have the inclination to spend hours fiddling with settings to improve my command line usage by a tiny amount, since my life on the command line isn't that bad. </p> <p>(As I understand it, <code>bash</code> can also be configured to auto-complete more cleverly. It's the configuring I'm not all that keen on.)</p> <p>Will switching to <code>zsh</code>, even in a small number cases, make my life easier? Or is it only a better shell if you put in the time to learn <em>why</em> it's better? (Examples would be nice, too <code>:)</code> )</p> <hr> <p>@<a href="https://stackoverflow.com/questions/43321/worth-switching-to-zsh-for-casual-use#43340">Rodney Amato</a> &amp; @<a href="https://stackoverflow.com/questions/43321/worth-switching-to-zsh-for-casual-use#43338">Vulcan Eager</a> give two good reasons to respectively stick to <code>bash</code> and switch to <code>zsh</code>. Looks like I'll have to investigate both! Oh well <code>:)</code></p> <p>Is there anyone with an opinion from both sides of the argument?</p>
[ { "answer_id": 43323, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 3, "selected": false, "text": "<p>zsh has a console gui configuration thing. You can set it up pretty quickly and easily without having to fiddle with config...
2008/09/04
[ "https://Stackoverflow.com/questions/43321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4161/" ]
The default shell in Mac OS X is `bash`, which I'm generally happy to be using. I just take it for granted. It would be really nice if it auto-completed *more stuff*, though, and I've heard good things about `zsh` in this regard. But I don't really have the inclination to spend hours fiddling with settings to improve my command line usage by a tiny amount, since my life on the command line isn't that bad. (As I understand it, `bash` can also be configured to auto-complete more cleverly. It's the configuring I'm not all that keen on.) Will switching to `zsh`, even in a small number cases, make my life easier? Or is it only a better shell if you put in the time to learn *why* it's better? (Examples would be nice, too `:)` ) --- @[Rodney Amato](https://stackoverflow.com/questions/43321/worth-switching-to-zsh-for-casual-use#43340) & @[Vulcan Eager](https://stackoverflow.com/questions/43321/worth-switching-to-zsh-for-casual-use#43338) give two good reasons to respectively stick to `bash` and switch to `zsh`. Looks like I'll have to investigate both! Oh well `:)` Is there anyone with an opinion from both sides of the argument?
For casual use you are probably better off sticking with bash and just installing bash completion. Installing it is pretty easy, grab the bash-completion-20060301.tar.gz from <http://www.caliban.org/bash/index.shtml#completion> and extract it with ``` tar -xzvf bash-completion-20060301.tar.gz ``` then copy the bash\_completion/bash\_completion file to /etc with ``` sudo cp bash_completion/bash_completion /etc ``` which will prompt you for your password. You probably will want to make a /etc/bash\_completion.d directory for any additional completion scripts (for instance I have the git completion script in there). Once this is done the last step is to make sure the .bash\_profile file in your home directory has ``` if [ -f /etc/bash_completion ]; then . /etc/bash_completion fi ``` in it to load the completion file when you login. To test it just open a new terminal, and try completing on cvs and it should show you the cvs options in the list of completions.
43,324
<p>I'm using the Yahoo Uploader, part of the Yahoo UI Library, on my ASP.Net website to allow users to upload files. For those unfamiliar, the uploader works by using a Flash applet to give me more control over the FileOpen dialog. I can specify a filter for file types, allow multiple files to be selected, etc. It's great, but it has the following documented limitation:</p> <blockquote> <p>Because of a known Flash bug, the Uploader running in Firefox in Windows does not send the correct cookies with the upload; instead of sending Firefox cookies, it sends Internet Explorer’s cookies for the respective domain. As a workaround, we suggest either using a cookieless upload method or appending document.cookie to the upload request.</p> </blockquote> <p>So, if a user is using Firefox, I can't rely on cookies to persist their session when they upload a file. I need their session because I need to know who they are! As a workaround, I'm using the Application object thusly:</p> <pre><code>Guid UploadID = Guid.NewGuid(); Application.Add(Guid.ToString(), User); </code></pre> <p>So, I'm creating a unique ID and using it as a key to store the <code>Page.User</code> object in the Application scope. I include that ID as a variable in the POST when the file is uploaded. Then, in the handler that accepts the file upload, I grab the User object thusly:</p> <pre><code>IPrincipal User = (IPrincipal)Application[Request.Form["uploadid"]]; </code></pre> <p>This actually works, but it has two glaring drawbacks: </p> <ul> <li><p>If IIS, the app pool, or even just the application is restarted between the time the user visits the upload page, and actually uploads a file, their "uploadid" is deleted from application scope and the upload fails because I can't authenticate them.</p></li> <li><p>If I ever scale to a web farm (possibly even a web garden) scenario, this will completely break. I might not be worried, except I do plan on scaling this app in the future.</p></li> </ul> <p>Does anyone have a better way? Is there a way for me to pass the actual ASP.Net session ID in a POST variable, then use that ID at the other end to retrieve the session?</p> <p>I know I can get the session ID through <code>Session.SessionID</code>, and I know how to use YUI to post it to the next page. What I don't know is how to use that <code>SessionID</code> to grab the session from the state server.</p> <p>Yes, I'm using a state server to store the sessions, so they persist application/IIS restarts, and will work in a web farm scenario.</p>
[ { "answer_id": 43353, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 0, "selected": false, "text": "<p>The ASP.Net Session ID is stored in <code>Session.SessionID</code> so you could set that in a hidden field and then post it t...
2008/09/04
[ "https://Stackoverflow.com/questions/43324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2527/" ]
I'm using the Yahoo Uploader, part of the Yahoo UI Library, on my ASP.Net website to allow users to upload files. For those unfamiliar, the uploader works by using a Flash applet to give me more control over the FileOpen dialog. I can specify a filter for file types, allow multiple files to be selected, etc. It's great, but it has the following documented limitation: > > Because of a known Flash bug, the Uploader running in Firefox in Windows does not send the correct cookies with the upload; instead of sending Firefox cookies, it sends Internet Explorer’s cookies for the respective domain. As a workaround, we suggest either using a cookieless upload method or appending document.cookie to the upload request. > > > So, if a user is using Firefox, I can't rely on cookies to persist their session when they upload a file. I need their session because I need to know who they are! As a workaround, I'm using the Application object thusly: ``` Guid UploadID = Guid.NewGuid(); Application.Add(Guid.ToString(), User); ``` So, I'm creating a unique ID and using it as a key to store the `Page.User` object in the Application scope. I include that ID as a variable in the POST when the file is uploaded. Then, in the handler that accepts the file upload, I grab the User object thusly: ``` IPrincipal User = (IPrincipal)Application[Request.Form["uploadid"]]; ``` This actually works, but it has two glaring drawbacks: * If IIS, the app pool, or even just the application is restarted between the time the user visits the upload page, and actually uploads a file, their "uploadid" is deleted from application scope and the upload fails because I can't authenticate them. * If I ever scale to a web farm (possibly even a web garden) scenario, this will completely break. I might not be worried, except I do plan on scaling this app in the future. Does anyone have a better way? Is there a way for me to pass the actual ASP.Net session ID in a POST variable, then use that ID at the other end to retrieve the session? I know I can get the session ID through `Session.SessionID`, and I know how to use YUI to post it to the next page. What I don't know is how to use that `SessionID` to grab the session from the state server. Yes, I'm using a state server to store the sessions, so they persist application/IIS restarts, and will work in a web farm scenario.
[Here](http://swfupload.org/forum/generaldiscussion/98) is a post from the maintainer of [SWFUpload](http://swfupload.org) which explains how to load the session from an ID stored in Request.Form. I imagine the same thing would work for the Yahoo component. Note the security disclaimers at the bottom of the post. --- > > By including a Global.asax file and the following code you can override the missing Session ID cookie: > > > ``` using System; using System.Web; public class Global_asax : System.Web.HttpApplication { private void Application_BeginRequest(object sender, EventArgs e) { /* Fix for the Flash Player Cookie bug in Non-IE browsers. Since Flash Player always sends the IE cookies even in FireFox we have to bypass the cookies by sending the values as part of the POST or GET and overwrite the cookies with the passed in values. The theory is that at this point (BeginRequest) the cookies have not been ready by the Session and Authentication logic and if we update the cookies here we'll get our Session and Authentication restored correctly */ HttpRequest request = HttpContext.Current.Request; try { string sessionParamName = "ASPSESSID"; string sessionCookieName = "ASP.NET_SESSIONID"; string sessionValue = request.Form[sessionParamName] ?? request.QueryString[sessionParamName]; if (sessionValue != null) { UpdateCookie(sessionCookieName, sessionValue); } } catch (Exception ex) { // TODO: Add logging here. } try { string authParamName = "AUTHID"; string authCookieName = FormsAuthentication.FormsCookieName; string authValue = request.Form[authParamName] ?? request.QueryString[authParamName]; if (authValue != null) { UpdateCookie(authCookieName, authValue); } } catch (Exception ex) { // TODO: Add logging here. } } private void UpdateCookie(string cookieName, string cookieValue) { HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookieName); if (cookie == null) { HttpCookie newCookie = new HttpCookie(cookieName, cookieValue); Response.Cookies.Add(newCookie); } else { cookie.Value = cookieValue; HttpContext.Current.Request.Cookies.Set(cookie); } } } ``` > > **Security Warning:** Don't just copy and paste this code in to your ASP.Net application without knowing what you are doing. It introduces security issues and possibilities of Cross-site Scripting. > > >
43,354
<p>How do you reference a bitmap on the stage in flash using actionscript 3?</p> <p>I have a bitmap on the stage in flash and at the end of the movie I would like to swap it out for the next in the sequence before the movie loops. in my library i have 3 images, exported for actionscript, with the class name img1/img2/img3. here is how my layers in flash are set out.</p> <pre><code>layer 5 : mask2:MovieClip layer 4 : img2:Bitmap layer 3 : mask1:MovieClip layer 2 : img1:Bitmap layer 1 : background:Bitmap </code></pre> <p>at the end of the movie I would like to swap img1 with img2, so the movie loops seamlessly, then ideally swap img2 (on layer 4) with img3 and so on until I get to the end of my images.</p> <p>but I can not find out how to reference the images that have already been put on the stage (in design time), any one have any idea of how to do this?</p> <p>The end movie will hopefully load images dynamically from the web server (I have the code for this bit) and display them as well as img1/img2/img3.</p> <p>Any help would be appreciated.</p> <p><strong>EDIT:</strong></p> <p>@<a href="https://stackoverflow.com/questions/43354/how-do-you-reference-a-bitmap-on-the-stage-in-actionscript#43735">81bronco</a> , I tried this but the instance name is greyed out for graphics, it will only allow me to do it with movieclips and buttons. I half got it to work by turning them into moveclips, and clearing the images in the moveclip out before adding a new one (using something simpler to what <a href="https://stackoverflow.com/questions/43354/how-do-you-reference-a-bitmap-on-the-stage-in-actionscript#44347">vanhornRF</a> suggested), but for some odd reason when the mask kicks in the images I cleared out come back for the mask animation.</p>
[ { "answer_id": 43477, "author": "bitbonk", "author_id": 4227, "author_profile": "https://Stackoverflow.com/users/4227", "pm_score": 1, "selected": false, "text": "<p>It should be something like this:</p>\n\n<pre><code>imageHolder.removeChild( imageIndex )\n</code></pre>\n\n<p>or</p>\n\n<...
2008/09/04
[ "https://Stackoverflow.com/questions/43354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2098/" ]
How do you reference a bitmap on the stage in flash using actionscript 3? I have a bitmap on the stage in flash and at the end of the movie I would like to swap it out for the next in the sequence before the movie loops. in my library i have 3 images, exported for actionscript, with the class name img1/img2/img3. here is how my layers in flash are set out. ``` layer 5 : mask2:MovieClip layer 4 : img2:Bitmap layer 3 : mask1:MovieClip layer 2 : img1:Bitmap layer 1 : background:Bitmap ``` at the end of the movie I would like to swap img1 with img2, so the movie loops seamlessly, then ideally swap img2 (on layer 4) with img3 and so on until I get to the end of my images. but I can not find out how to reference the images that have already been put on the stage (in design time), any one have any idea of how to do this? The end movie will hopefully load images dynamically from the web server (I have the code for this bit) and display them as well as img1/img2/img3. Any help would be appreciated. **EDIT:** @[81bronco](https://stackoverflow.com/questions/43354/how-do-you-reference-a-bitmap-on-the-stage-in-actionscript#43735) , I tried this but the instance name is greyed out for graphics, it will only allow me to do it with movieclips and buttons. I half got it to work by turning them into moveclips, and clearing the images in the moveclip out before adding a new one (using something simpler to what [vanhornRF](https://stackoverflow.com/questions/43354/how-do-you-reference-a-bitmap-on-the-stage-in-actionscript#44347) suggested), but for some odd reason when the mask kicks in the images I cleared out come back for the mask animation.
To reference something on the stage, you need to give the stage instance a name - not give the symbol in the library a class name. Click on the item on the stage and look at the properties panel. There should be a text entry box just above the entry boxes for the item's dimensions. Enter a name there. Elsewhere in your code, you can then refer to that item on stage by it's instance name.
43,368
<p>I'm a firm believer of the heretic thought of tight coupling between the backend and frontend: I want existing, implied knowledge about a backend to be automatically made use of when generating user interfaces. E.g., if a VARCHAR column has a maximum with of 20 characters, there GUIs should automatically constrain the user from typing more than 20 characters in a related form field.</p> <p>And I have strong antipathy to ORMs which want to define my database tables, or are based on some hack where every table needs to have extra numeric ID columns because of the ORM.</p> <p>I've looked a bit into Python database frameworks and I think I can conclude the SQLAlchemy fits best to my mentality.</p> <p>Now, I need to find a web application framework which fits naturally with SQLAlchemy (or an equivalent) and perhaps even with my appetite for coupling. With "web application framework", I mean products/project such as Pyhons, Django, TurboGears, web2py, etc.</p> <p>E.g., it should ideally be able to:</p> <ul> <li><strong>automatically select a suitable form widget</strong> for data entering a given column if told to do so; e.g., if the column has a foreign key to a column with 10 different values, widget should display the 10 possible values as a dropdown</li> <li><strong>auto-generate javascript form validation code</strong> which gives the end-user quick error feedback if a string is entered into a field which is about to end up in an INTEGER column, etc</li> <li>auto-generate a <strong>calendar widget</strong> for data which will end up in a DATE column</li> <li><strong>hint NOT NULL constraints</strong> as javascript which complains about empty or whitespace-only data in a related input field</li> <li>generate javascript validation code which matches relevant (simple) <strong>CHECK-constraints</strong></li> <li>make it easy to <strong>avoid SQL injection</strong>, by using prepared statements and/or validation of externally derived data</li> <li>make it easy to <strong>avoid cross site scripting</strong> by automatically escape outgoing strings when appropriate</li> <li><strong>make use of constraint names</strong> to generate somewhat user friendly error messages in case a constrataint is violated</li> </ul> <p>All this should happen dynamically, so table adjustments are automatically reflected on the frontend - probably with a caching mechanism, so that all the model introspection wouldn't kill performance. In other words, I don't want to repeat my model definition in an XML file (or alike) when it has already been carefully been defined in my database.</p> <p>Does such a framework exist for Python (or for any language, for that matter)? If not: Which of the several Python web application frameworks will be least in the way if I were to add parts of the above features myself?</p>
[ { "answer_id": 43386, "author": "Peter Hoffmann", "author_id": 720, "author_profile": "https://Stackoverflow.com/users/720", "pm_score": 2, "selected": false, "text": "<p>You should have a look at django and especially its <a href=\"http://www.djangoproject.com/documentation/forms/\" rel...
2008/09/04
[ "https://Stackoverflow.com/questions/43368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4462/" ]
I'm a firm believer of the heretic thought of tight coupling between the backend and frontend: I want existing, implied knowledge about a backend to be automatically made use of when generating user interfaces. E.g., if a VARCHAR column has a maximum with of 20 characters, there GUIs should automatically constrain the user from typing more than 20 characters in a related form field. And I have strong antipathy to ORMs which want to define my database tables, or are based on some hack where every table needs to have extra numeric ID columns because of the ORM. I've looked a bit into Python database frameworks and I think I can conclude the SQLAlchemy fits best to my mentality. Now, I need to find a web application framework which fits naturally with SQLAlchemy (or an equivalent) and perhaps even with my appetite for coupling. With "web application framework", I mean products/project such as Pyhons, Django, TurboGears, web2py, etc. E.g., it should ideally be able to: * **automatically select a suitable form widget** for data entering a given column if told to do so; e.g., if the column has a foreign key to a column with 10 different values, widget should display the 10 possible values as a dropdown * **auto-generate javascript form validation code** which gives the end-user quick error feedback if a string is entered into a field which is about to end up in an INTEGER column, etc * auto-generate a **calendar widget** for data which will end up in a DATE column * **hint NOT NULL constraints** as javascript which complains about empty or whitespace-only data in a related input field * generate javascript validation code which matches relevant (simple) **CHECK-constraints** * make it easy to **avoid SQL injection**, by using prepared statements and/or validation of externally derived data * make it easy to **avoid cross site scripting** by automatically escape outgoing strings when appropriate * **make use of constraint names** to generate somewhat user friendly error messages in case a constrataint is violated All this should happen dynamically, so table adjustments are automatically reflected on the frontend - probably with a caching mechanism, so that all the model introspection wouldn't kill performance. In other words, I don't want to repeat my model definition in an XML file (or alike) when it has already been carefully been defined in my database. Does such a framework exist for Python (or for any language, for that matter)? If not: Which of the several Python web application frameworks will be least in the way if I were to add parts of the above features myself?
web2py does most of what you ask: Based on a field type and its validators it will render the field with the appropriate widget. You can override with ``` db.table.field.widget=... ``` and use a third party widget. web2py has js to blocks the user from entering a non-integer in a integer field or a non-double in a double field. time, date and datetime fields have their own pickers. These js validation work with (not instead) of server side validation. There is `IS_EMPTY_OR(...)` validator. The DAL prevents SQL injections since everthing is escaped when goes in the DB. web2py prevents XSS because in {{=variable}}, 'variable' is escaped unless specified otherwise {{=XML(variable)}} or {{=XML(variable,sanitize=True)}} Error messages are arguments of validators for example ``` db.table.field.requires=IS_NOT_EMPTY(error_message=T('hey! write something in here')) ``` T is for internationalization.
43,374
<p>What I have so far is </p> <pre><code>#!/bin/sh php_syntax_check() { retval=0 for i in $(git-diff-index --name-only --cached HEAD -- | grep -e '\.php$'); do if [ -f $i ]; then output=$(php -l $i) retval=$? if [ $retval -gt 0 ]; then echo "==============================================================================" echo "Unstaging $i for the commit due to the follow parse errors" echo "$output" git reset -q HEAD $i fi fi done if [ $retval -gt 0 ]; then exit $retval fi } php_syntax_check </code></pre>
[ { "answer_id": 173878, "author": "Anonymous", "author_id": 15073, "author_profile": "https://Stackoverflow.com/users/15073", "pm_score": 2, "selected": false, "text": "<p>I'm sorry if it's offtopic, but aren't you supposed to run some kind of automated tests (which would imply that the c...
2008/09/04
[ "https://Stackoverflow.com/questions/43374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4342/" ]
What I have so far is ``` #!/bin/sh php_syntax_check() { retval=0 for i in $(git-diff-index --name-only --cached HEAD -- | grep -e '\.php$'); do if [ -f $i ]; then output=$(php -l $i) retval=$? if [ $retval -gt 0 ]; then echo "==============================================================================" echo "Unstaging $i for the commit due to the follow parse errors" echo "$output" git reset -q HEAD $i fi fi done if [ $retval -gt 0 ]; then exit $retval fi } php_syntax_check ```
If the commit is a partial commit (not all the changes in the working tree are committed), then this make give incorrect results since it tests the working copy and not the staged copy. One way to do this could be: ``` git diff --cached --name-only --diff-filter=ACMR | xargs git checkout-index --prefix=$TMPDIR/ -- find $TMPDIR -name '*.php' -print | xargs -n 1 php -l ``` Which would make a copy of the staged images into a scratch space and then run the test command on them there. If any of the files include other files in the build then you may have to recreate the whole staged image in the test tree and then test the changed files there (See: [Git pre-commit hook : changed/added files](https://stackoverflow.com/questions/2412450/git-pre-commit-hook-changed-added-files/3068990#3068990)).
43,427
<p>Say I have a site on <a href="http://example.com" rel="noreferrer">http://example.com</a>. I would really like allowing bots to see the home page, but any other page need to blocked as it is pointless to spider. In other words</p> <p><a href="http://example.com" rel="noreferrer">http://example.com</a> &amp; <a href="http://example.com/" rel="noreferrer">http://example.com/</a> should be allowed, but <a href="http://example.com/anything" rel="noreferrer">http://example.com/anything</a> and <a href="http://example.com/someendpoint.aspx" rel="noreferrer">http://example.com/someendpoint.aspx</a> should be blocked.</p> <p>Further it would be great if I can allow certain query strings to passthrough to the home page: <a href="http://example.com?okparam=true" rel="noreferrer">http://example.com?okparam=true</a> </p> <p>but not <a href="http://example.com?anythingbutokparam=true" rel="noreferrer">http://example.com?anythingbutokparam=true</a></p>
[ { "answer_id": 43436, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 0, "selected": false, "text": "<p>Basic robots.txt:</p>\n\n<pre><code>Disallow: /subdir/\n</code></pre>\n\n<p>I don't think that you can create an expression say...
2008/09/04
[ "https://Stackoverflow.com/questions/43427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2892/" ]
Say I have a site on <http://example.com>. I would really like allowing bots to see the home page, but any other page need to blocked as it is pointless to spider. In other words <http://example.com> & <http://example.com/> should be allowed, but <http://example.com/anything> and <http://example.com/someendpoint.aspx> should be blocked. Further it would be great if I can allow certain query strings to passthrough to the home page: <http://example.com?okparam=true> but not <http://example.com?anythingbutokparam=true>
So after some research, here is what I found - a solution acceptable by the major search providers: [google](http://www.google.com/support/webmasters/bin/answer.py?answer=40367) , [yahoo](http://help.yahoo.com/l/us/yahoo/search/webcrawler/slurp-02.html) & msn (I could on find a validator here) : ``` User-Agent: * Disallow: /* Allow: /?okparam= Allow: /$ ``` The trick is using the $ to mark the end of URL.
43,490
<p>When is this called? More specifically, I have a control I'm creating - how can I release handles when the window is closed. In normal win32 I'd do it during <code>wm_close</code> - is <code>DestroyHandle</code> the .net equivalent?</p> <hr> <p>I don't want to destroy the window handle myself - my control is listening for events on another object and when my control is destroyed, I want to stop listening to those events. Eg:</p> <pre><code>void Dispose(bool disposing) { otherObject.Event -= myEventHandler; } </code></pre>
[ { "answer_id": 43499, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>Normally <code>DestroyHandle</code> is being called in <code>Dispose</code> method. So you need to make sure that all controls...
2008/09/04
[ "https://Stackoverflow.com/questions/43490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4495/" ]
When is this called? More specifically, I have a control I'm creating - how can I release handles when the window is closed. In normal win32 I'd do it during `wm_close` - is `DestroyHandle` the .net equivalent? --- I don't want to destroy the window handle myself - my control is listening for events on another object and when my control is destroyed, I want to stop listening to those events. Eg: ``` void Dispose(bool disposing) { otherObject.Event -= myEventHandler; } ```
Normally `DestroyHandle` is being called in `Dispose` method. So you need to make sure that all controls are disposed to avoid resource leaks.
43,503
<p>Is there a way to detect if a flash movie contains any sound or is playing any music?<br> It would be nice if this could be done inside a webbrowser (actionscript <strong>from another flash object</strong>, javascript,..) and could be done <em>before</em> the flash movie starts playing.</p> <p>However, I have my doubts this will be possible altogether, so any other (programmable) solution is also appreciated</p>
[ { "answer_id": 43519, "author": "Stu Thompson", "author_id": 2961, "author_profile": "https://Stackoverflow.com/users/2961", "pm_score": 3, "selected": true, "text": "<p>Yes, on the server side for sure. Client side? I don't know. (I'm a serverside kind of guy.) </p>\n\n<p>On the serv...
2008/09/04
[ "https://Stackoverflow.com/questions/43503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46/" ]
Is there a way to detect if a flash movie contains any sound or is playing any music? It would be nice if this could be done inside a webbrowser (actionscript **from another flash object**, javascript,..) and could be done *before* the flash movie starts playing. However, I have my doubts this will be possible altogether, so any other (programmable) solution is also appreciated
Yes, on the server side for sure. Client side? I don't know. (I'm a serverside kind of guy.) On the server side, one would have to parse the file, read the header and/or look for audio frames. (I've ported a haskel FLV parser to Java for indexing purposes myself, and there are other parsing utilities out there. It is possible.) [osflash.org's FLV page](http://osflash.org/flv) has the gory details. Check out the FLV Format sections's FLV Header table. ``` FIELD DATA TYPE EXAMPLE DESCRIPTION Signature byte[3] “FLV” Always “FLV” Version uint8 “\x01” (1) Currently 1 for known FLV files Flags uint8 bitmask “\x05” (5, audio+video) Bitmask: 4 is audio, 1 is video Offset uint32-be “\x00\x00\x00\x09” (9) Total size of header (always 9 for known FLV files) ``` --- EDIT: My client side coding with Flash is non-existent, but I believe there is an onMetaDataLoad event that your code could catch. That might be happening a bit late for you, but maybe it is good enough?
43,507
<p>I have seen simple example Ajax source codes in many online tutorials. What I want to know is whether using the source code in the examples are perfectly alright or not?</p> <p>Is there anything more to be added to the code that goes into a real world application?</p> <p>What all steps are to be taken to make the application more robust and secure?</p> <p>Here is a sample source code I got from the web:</p> <pre><code>function getChats() { xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { return; } var url="getchat.php?latest="+latest; xmlHttp.onreadystatechange=stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); } function GetXmlHttpObject() { var xmlHttp=null; try { xmlHttp=new XMLHttpRequest(); } catch (e) { try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } </code></pre>
[ { "answer_id": 43510, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 0, "selected": false, "text": "<p>I would use a framework like <a href=\"http://www.domassistant.com/\" rel=\"nofollow noreferrer\">DOMAssistant</a> which ...
2008/09/04
[ "https://Stackoverflow.com/questions/43507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
I have seen simple example Ajax source codes in many online tutorials. What I want to know is whether using the source code in the examples are perfectly alright or not? Is there anything more to be added to the code that goes into a real world application? What all steps are to be taken to make the application more robust and secure? Here is a sample source code I got from the web: ``` function getChats() { xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { return; } var url="getchat.php?latest="+latest; xmlHttp.onreadystatechange=stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); } function GetXmlHttpObject() { var xmlHttp=null; try { xmlHttp=new XMLHttpRequest(); } catch (e) { try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } ```
The code you posted is missing one important ingredient: the function stateChanged. If you don't quite understand the code you posted yourself, then what happens is when the call to getchats.php is complete, a function "stateChanged" is called and that function will be responsible for handling the response. Since the script you're calling and the function itself is prefixed with "gets" then I'm pretty sure the response is something you're going to be interested in. That aside, there are a number of ways to improve on the code you posted. I'd guess it works by declaring a single "xmlHttp" object and then making that available to every function (because if it doesn't, the stateChanged function has no way of getting the response). This is fine until you run an AJAX request before the last one (or last few) haven't replied yet, which in that case the object reference is overwritten to the latest request each time. Also, any AJAX code worth its salt provides functionality for sucess and failure (server errors, page not found, etc.) cases so that the appriopiate message can be delivered to the user. If you just want to use AJAX functionality on your website then I'd point you in the direction of [jQuery](http://www.jquery.com) or a [similar](http://www.prototypejs.org) [framework](http://www.mootools.net). BUT if you actually want to understand the technology and what is happening behind the scenes, I'd continue doing what you're doing and asking specific questions as you try to build a small lightweight AJAX class on your own. This is how I done it, and although I use the jQuery framework today.. I'm still glad I know how it works behind the scenes.
43,511
<p>I have some classes layed out like this</p> <pre><code>class A { public virtual void Render() { } } class B : A { public override void Render() { // Prepare the object for rendering SpecialRender(); // Do some cleanup } protected virtual void SpecialRender() { } } class C : B { protected override void SpecialRender() { // Do some cool stuff } } </code></pre> <p>Is it possible to prevent the C class from overriding the Render method, without breaking the following code?</p> <pre><code>A obj = new C(); obj.Render(); // calls B.Render -&gt; c.SpecialRender </code></pre>
[ { "answer_id": 43516, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 6, "selected": true, "text": "<p>You can seal individual methods to prevent them from being overridable:</p>\n\n<pre><code>public sealed override void R...
2008/09/04
[ "https://Stackoverflow.com/questions/43511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3602/" ]
I have some classes layed out like this ``` class A { public virtual void Render() { } } class B : A { public override void Render() { // Prepare the object for rendering SpecialRender(); // Do some cleanup } protected virtual void SpecialRender() { } } class C : B { protected override void SpecialRender() { // Do some cool stuff } } ``` Is it possible to prevent the C class from overriding the Render method, without breaking the following code? ``` A obj = new C(); obj.Render(); // calls B.Render -> c.SpecialRender ```
You can seal individual methods to prevent them from being overridable: ``` public sealed override void Render() { // Prepare the object for rendering SpecialRender(); // Do some cleanup } ```
43,525
<p>For some strange, bizarre reason, my images in my website just will not display on webkit based languages (such as safari and chrome).</p> <p>This is the image tag</p> <pre><code>&lt;img src="images/dukkah.jpg" class="imgleft"/&gt; </code></pre> <p>Not only does it not display in the website, it wont display when accessed directly at <code>http://kilkin.massiveatom.com/kilkin/images/dukkah.jpg</code></p> <p>...Why?</p>
[ { "answer_id": 43537, "author": "Niyaz", "author_id": 184, "author_profile": "https://Stackoverflow.com/users/184", "pm_score": 2, "selected": false, "text": "<p>I have come across this problem a couple of times.</p>\n\n<p>I think it is because of some problem in the file format.</p>\n\n...
2008/09/04
[ "https://Stackoverflow.com/questions/43525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ]
For some strange, bizarre reason, my images in my website just will not display on webkit based languages (such as safari and chrome). This is the image tag ``` <img src="images/dukkah.jpg" class="imgleft"/> ``` Not only does it not display in the website, it wont display when accessed directly at `http://kilkin.massiveatom.com/kilkin/images/dukkah.jpg` ...Why?
Imagemagick reports that this particular image is saved in CMYK colorspace instead of the more standard RGB. Try converting it, it should be more compatible with the webkit rendering engine. Imagemagick is available for download from [<http://www.imagemagick.org/script/index.php>](http://www.imagemagick.org/script/index.php) - it's available for windows and \*NIX systems.
43,569
<p>How to restrict the maximum number of characters that can be entered into an HTML <code>&lt;textarea&gt;</code>? I'm looking for a cross-browser solution.</p>
[ { "answer_id": 43571, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 5, "selected": true, "text": "<p>The <code>TEXTAREA</code> tag does not have a <code>MAXLENGTH</code> attribute the way that an\n<code>INPUT</code> tag does, a...
2008/09/04
[ "https://Stackoverflow.com/questions/43569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3512/" ]
How to restrict the maximum number of characters that can be entered into an HTML `<textarea>`? I'm looking for a cross-browser solution.
The `TEXTAREA` tag does not have a `MAXLENGTH` attribute the way that an `INPUT` tag does, at least not in most standard browsers. A very simple and effective way to limit the number of characters that can be *typed* into a `TEXTAREA` tag is: ``` <textarea onKeyPress="return ( this.value.length < 50 );"></textarea> ``` **Note:** `onKeyPress`, is going to prevent any button press, **any button** *including* the backspace key. This works because the Boolean expression compares the field's length before the new character is added to the maximum length you want (50 in this example, use your own here), and returns true if there is room for one more, `false` if not. Returning false from most events cancels the default action. So if the current length is already 50 (or more), the handler returns false, the `KeyPress` action is cancelled, and the character is not added. One fly in the ointment is the possibility of pasting into a `TEXTAREA`, which does not cause the `KeyPress` event to fire, circumventing this check. Internet Explorer 5+ contains an `onPaste` event whose handler can contain the check. However, note that you must also take into account how many characters are waiting in the clipboard to know if the total is going to take you over the limit or not. Fortunately, IE also contains a clipboard object from the window object.[1](http://lists.evolt.org/archive/Week-of-Mon-20040315/156773.html) Thus: ``` <textarea onKeyPress="return ( this.value.length < 50 );" onPaste="return (( this.value.length + window.clipboardData.getData('Text').length) < 50 );"></textarea> ``` Again, the `onPaste` event and `clipboardData` object are IE 5+ only. For a cross-browser solution, you will just have to use an `OnChange` or `OnBlur` handler to check the length, and handle it however you want (truncate the value silently, notify the user, etc.). Unfortunately, this doesn't catch the error as it's happening, only when the user attempts to leave the field, which is not quite as friendly. [Source](http://lists.evolt.org/archive/Week-of-Mon-20040315/156773.html) Also, there is another way here, including a finished script you could include in your page: <http://cf-bill.blogspot.com/2005/05/textarea-maxlength-revisited.html>
43,580
<p>Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.</p> <p>Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.</p> <p>Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.</p> <p>How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. </p> <p>Does the browser add this information when posting the file to the web page?</p> <p>Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?</p>
[ { "answer_id": 43588, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 7, "selected": false, "text": "<p>The <a href=\"https://docs.python.org/library/mimetypes.html\" rel=\"noreferrer\">mimetypes module</a> in the standard ...
2008/09/04
[ "https://Stackoverflow.com/questions/43580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ]
Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer. Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response. Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type. How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. Does the browser add this information when posting the file to the web page? Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?
The python-magic method suggested by [toivotuo](https://stackoverflow.com/a/2133843/5337834) is outdated. [Python-magic's](http://github.com/ahupp/python-magic) current trunk is at Github and based on the readme there, finding the MIME-type, is done like this. ``` # For MIME types import magic mime = magic.Magic(mime=True) mime.from_file("testdata/test.pdf") # 'application/pdf' ```
43,584
<p>A very niche problem:</p> <p>I sometimes (30% of the time) get an 'undefined handler' javascript error on line 3877 of the prototype.js library (version 1.6.0.2 from google: <a href="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js" rel="nofollow noreferrer">http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js</a>).</p> <p>Now on this page I have a Google Map and I use the Prototype Window library.</p> <p>The problem occurs in IE7 and FF3.</p> <p>This is the info FireBug gives:</p> <pre><code>handler is undefined ? in prototype.js@3871()prototype.js (line 3877) handler.call(element, event); </code></pre> <p>I switched to a local version of prototypejs and added some debugging in the offending method (createWraper) but the debugging never appears before the error...</p> <p>I googled around and found 1 other mention of the error on the same line, but no answer so I'm posting it here where maybe, some day someone will have an answer :).</p>
[ { "answer_id": 43646, "author": "David McLaughlin", "author_id": 3404, "author_profile": "https://Stackoverflow.com/users/3404", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>I switched to a local version of prototypejs and added some debugging\n in the offending method ...
2008/09/04
[ "https://Stackoverflow.com/questions/43584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4512/" ]
A very niche problem: I sometimes (30% of the time) get an 'undefined handler' javascript error on line 3877 of the prototype.js library (version 1.6.0.2 from google: <http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js>). Now on this page I have a Google Map and I use the Prototype Window library. The problem occurs in IE7 and FF3. This is the info FireBug gives: ``` handler is undefined ? in prototype.js@3871()prototype.js (line 3877) handler.call(element, event); ``` I switched to a local version of prototypejs and added some debugging in the offending method (createWraper) but the debugging never appears before the error... I googled around and found 1 other mention of the error on the same line, but no answer so I'm posting it here where maybe, some day someone will have an answer :).
I just found out this error also occurs if you accidentally leave on the parenthesis on your observer call: ``` Event.observe(document, 'myapp:application_ready', myapp.MyClass.initApp()); ``` instead of ``` Event.observe(document, 'myapp:application_ready', myapp.MyClass.initApp); ```
43,589
<p>I need to get the first and last day of a month in the format YYYY-MM-DD given only the month and year. Is there a good, easy way to do this?</p>
[ { "answer_id": 43607, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 3, "selected": false, "text": "<p>First day is always YYYY-MM-01, isn't it? Example: <code>date(\"Y-M-d\", mktime(0, 0, 0, 8, 1, 2008))</code></p>\n\n<p>Last day...
2008/09/04
[ "https://Stackoverflow.com/questions/43589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
I need to get the first and last day of a month in the format YYYY-MM-DD given only the month and year. Is there a good, easy way to do this?
``` $first = date('Y-m-d', mktime(0, 0, 0, $month, 1, $year)); $last = date('Y-m-t', mktime(0, 0, 0, $month, 1, $year)); ``` See [date()](http://ie2.php.net/date) in PHP documentation.
43,632
<p>I've seen lots of examples of making an entire regular expression case-insensitive. What I'm wondering about is having just part of the expression be case-insensitive.</p> <p>For example, let's say I have a string like this:</p> <pre><code>fooFOOfOoFoOBARBARbarbarbAr </code></pre> <p>What if I want to match all occurrences of "foo" regardless of case but I only want to match the upper-case "BAR"s?</p> <p>The ideal solution would be something that works across regex flavors but I'm interested in hearing language-specific ones as well (Thanks <a href="https://stackoverflow.com/questions/43632/can-you-make-just-part-of-a-regex-case-insensitive#43636">Espo</a>)</p> <p><strong><em>Edit</em></strong></p> <p>The link Espo provided was very helpful. There's a good example in there about turning modifiers on and off within the expression.</p> <p>For my contrived example, I can do something like this:</p> <pre><code>(?i)foo*(?-i)|BAR </code></pre> <p>which makes the match case-insensitive for just the foo portion of the match.</p> <p>That seemed to work in most regex implementations except Javascript, Python, and a few others (as Espo mentioned). </p> <p>The big ones that I was wondering about (Perl, PHP, .NET) all support inline mode changes.</p>
[ { "answer_id": 43636, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 8, "selected": true, "text": "<p>Perl lets you make part of your regular expression case-insensitive by using the (?i:) pattern modifier.</p>\n\n<p>Modern rege...
2008/09/04
[ "https://Stackoverflow.com/questions/43632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
I've seen lots of examples of making an entire regular expression case-insensitive. What I'm wondering about is having just part of the expression be case-insensitive. For example, let's say I have a string like this: ``` fooFOOfOoFoOBARBARbarbarbAr ``` What if I want to match all occurrences of "foo" regardless of case but I only want to match the upper-case "BAR"s? The ideal solution would be something that works across regex flavors but I'm interested in hearing language-specific ones as well (Thanks [Espo](https://stackoverflow.com/questions/43632/can-you-make-just-part-of-a-regex-case-insensitive#43636)) ***Edit*** The link Espo provided was very helpful. There's a good example in there about turning modifiers on and off within the expression. For my contrived example, I can do something like this: ``` (?i)foo*(?-i)|BAR ``` which makes the match case-insensitive for just the foo portion of the match. That seemed to work in most regex implementations except Javascript, Python, and a few others (as Espo mentioned). The big ones that I was wondering about (Perl, PHP, .NET) all support inline mode changes.
Perl lets you make part of your regular expression case-insensitive by using the (?i:) pattern modifier. Modern regex flavors allow you to apply modifiers to only part of the regular expression. If you insert the modifier (?ism) in the middle of the regex, the modifier only applies to the part of the regex to the right of the modifier. You can turn off modes by preceding them with a minus sign. All modes after the minus sign will be turned off. E.g. (?i-sm) turns on case insensitivity, and turns off both single-line mode and multi-line mode. Not all regex flavors support this. JavaScript and Python apply all mode modifiers to the entire regular expression. They don't support the (?-ismx) syntax, since turning off an option is pointless when mode modifiers apply to the whole regular expressions. All options are off by default. You can quickly test how the regex flavor you're using handles mode modifiers. The regex (?i)te(?-i)st should match test and TEst, but not teST or TEST. [Source](http://www.regular-expressions.info/modifiers.html)
43,643
<p>Given the code bellow, how do I style the radio buttons to be next to the labels and style the label of the selected radio button differently than the other labels?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css" rel="stylesheet"&gt; &lt;link href="http://yui.yahooapis.com/2.5.2/build/base/base-min.css" rel="stylesheet"&gt; &lt;div class="input radio"&gt; &lt;fieldset&gt; &lt;legend&gt;What color is the sky?&lt;/legend&gt; &lt;input type="hidden" name="color" value="" id="SubmitQuestion" /&gt; &lt;input type="radio" name="color" id="SubmitQuestion1" value="1" /&gt; &lt;label for="SubmitQuestion1"&gt;A strange radient green.&lt;/label&gt; &lt;input type="radio" name="color" id="SubmitQuestion2" value="2" /&gt; &lt;label for="SubmitQuestion2"&gt;A dark gloomy orange&lt;/label&gt; &lt;input type="radio" name="color" id="SubmitQuestion3" value="3" /&gt; &lt;label for="SubmitQuestion3"&gt;A perfect glittering blue&lt;/label&gt; &lt;/fieldset&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Also let me state that I use the yui css styles as base. If you are not familir with them, they can be found here:</p> <ul> <li><a href="http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css" rel="nofollow noreferrer">reset-fonts-grids.css</a></li> <li><a href="http://yui.yahooapis.com/2.5.2/build/base/base-min.css" rel="nofollow noreferrer">base-min.css</a></li> </ul> <p>Documentation for them both here : <a href="http://developer.yahoo.com/yui/reset/" rel="nofollow noreferrer">Yahoo! UI Library</a></p> <p>@pkaeding: Thanks. I tried some floating both thing that just looked messed up. The styling active radio button seemed to be doable with some input[type=radio]:active nomination on a google search, but I didnt get it to work properly. So the question I guess is more: Is this possible on all of todays modern browsers, and if not, what is the minimal JS needed?</p>
[ { "answer_id": 43703, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 3, "selected": false, "text": "<p>This will get your buttons and labels next to each other, at least. I believe the second part can't be done in css alone...
2008/09/04
[ "https://Stackoverflow.com/questions/43643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4013/" ]
Given the code bellow, how do I style the radio buttons to be next to the labels and style the label of the selected radio button differently than the other labels? ```html <link href="http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css" rel="stylesheet"> <link href="http://yui.yahooapis.com/2.5.2/build/base/base-min.css" rel="stylesheet"> <div class="input radio"> <fieldset> <legend>What color is the sky?</legend> <input type="hidden" name="color" value="" id="SubmitQuestion" /> <input type="radio" name="color" id="SubmitQuestion1" value="1" /> <label for="SubmitQuestion1">A strange radient green.</label> <input type="radio" name="color" id="SubmitQuestion2" value="2" /> <label for="SubmitQuestion2">A dark gloomy orange</label> <input type="radio" name="color" id="SubmitQuestion3" value="3" /> <label for="SubmitQuestion3">A perfect glittering blue</label> </fieldset> </div> ``` Also let me state that I use the yui css styles as base. If you are not familir with them, they can be found here: * [reset-fonts-grids.css](http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css) * [base-min.css](http://yui.yahooapis.com/2.5.2/build/base/base-min.css) Documentation for them both here : [Yahoo! UI Library](http://developer.yahoo.com/yui/reset/) @pkaeding: Thanks. I tried some floating both thing that just looked messed up. The styling active radio button seemed to be doable with some input[type=radio]:active nomination on a google search, but I didnt get it to work properly. So the question I guess is more: Is this possible on all of todays modern browsers, and if not, what is the minimal JS needed?
The first part of your question can be solved with just HTML & CSS; you'll need to use Javascript for the second part. ### Getting the Label Near the Radio Button I'm not sure what you mean by "next to": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into `float:` territory): * Use `<br />s` to split the options apart and some CSS to vertically align them: ``` <style type='text/css'> .input input { width: 20px; } </style> <div class="input radio"> <fieldset> <legend>What color is the sky?</legend> <input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" /> <input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1" /> <label for="SubmitQuestion1">A strange radient green.</label> <br /> <input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2" /> <label for="SubmitQuestion2">A dark gloomy orange</label> <br /> <input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3" /> <label for="SubmitQuestion3">A perfect glittering blue</label> </fieldset> </div> ``` * Follow *A List Apart*'s article: [Prettier Accessible Forms](http://www.alistapart.com/articles/prettyaccessibleforms) ### Applying a Style to the Currently Selected Label + Radio Button Styling the `<label>` is why you'll need to resort to Javascript. A library like [jQuery](http://jquery.com) is perfect for this: ``` <style type='text/css'> .input label.focused { background-color: #EEEEEE; font-style: italic; } </style> <script type='text/javascript' src='jquery.js'></script> <script type='text/javascript'> $(document).ready(function() { $('.input :radio').focus(updateSelectedStyle); $('.input :radio').blur(updateSelectedStyle); $('.input :radio').change(updateSelectedStyle); }) function updateSelectedStyle() { $('.input :radio').removeClass('focused').next().removeClass('focused'); $('.input :radio:checked').addClass('focused').next().addClass('focused'); } </script> ``` The `focus` and `blur` hooks are needed to make this work in IE.
43,711
<p>I've got some (C#) code that relies on today's date to correctly calculate things in the future. If I use today's date in the testing, I have to repeat the calculation in the test, which doesn't feel right. What's the best way to set the date to a known value within the test so that I can test that the result is a known value?</p>
[ { "answer_id": 43716, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 4, "selected": false, "text": "<p>I think creating a separate clock class for something simple like getting the current date is a bit overkill. </p>\n\n<p>Y...
2008/09/04
[ "https://Stackoverflow.com/questions/43711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1404/" ]
I've got some (C#) code that relies on today's date to correctly calculate things in the future. If I use today's date in the testing, I have to repeat the calculation in the test, which doesn't feel right. What's the best way to set the date to a known value within the test so that I can test that the result is a known value?
My preference is to have classes that use time actually rely on an interface, such as ``` interface IClock { DateTime Now { get; } } ``` With a concrete implementation ``` class SystemClock: IClock { DateTime Now { get { return DateTime.Now; } } } ``` Then if you want, you can provide any other kind of clock you want for testing, such as ``` class StaticClock: IClock { DateTime Now { get { return new DateTime(2008, 09, 3, 9, 6, 13); } } } ``` There may be some overhead in providing the clock to the class that relies on it, but that could be handled by any number of dependency injection solutions (using an Inversion of Control container, plain old constructor/setter injection, or even a [Static Gateway Pattern](http://codebetter.com/blogs/jean-paul_boodhoo/archive/2007/10/15/the-static-gateway-pattern.aspx)). Other mechanisms of delivering an object or method that provides desired times also work, but I think the key thing is to avoid resetting the system clock, as that's just going to introduce pain on other levels. Also, using `DateTime.Now` and including it in your calculations doesn't just not feel right - it robs you of the ability to test particular times, for example if you discover a bug that only happens near a midnight boundary, or on Tuesdays. Using the current time won't allow you to test those scenarios. Or at least not whenever you want.
43,738
<p>I have a line color property in my custom grid control. I want it to default to <code>Drawing.SystemColors.InactiveBorder</code>. I tried:</p> <pre><code>[DefaultValue(typeof(System.Drawing.SystemColors), "InactiveBorder")] public Color LineColor { get; set; } </code></pre> <p>But it doesn't seem to work. How do I do that with the default value attribute?</p>
[ { "answer_id": 43751, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": false, "text": "<p>You need to change first argument from <code>SystemColors</code> to <code>Color</code>.<br>\nIt seems that there is no type co...
2008/09/04
[ "https://Stackoverflow.com/questions/43738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/976/" ]
I have a line color property in my custom grid control. I want it to default to `Drawing.SystemColors.InactiveBorder`. I tried: ``` [DefaultValue(typeof(System.Drawing.SystemColors), "InactiveBorder")] public Color LineColor { get; set; } ``` But it doesn't seem to work. How do I do that with the default value attribute?
You need to change first argument from `SystemColors` to `Color`. It seems that there is no type converter for the `SystemColors` type, only for the `Color` type. ``` [DefaultValue(typeof(Color),"InactiveBorder")] ```
43,765
<p>For my day job, I live in Emacs. Utterly. I also have become pretty dependent on CScope to help me find things in the code.</p> <p>Normally, I have 2 windows in a split (C-x 3): <a href="http://bitthicket.com/files/emacs-2split.JPG">alt text http://bitthicket.com/files/emacs-2split.JPG</a></p> <p>And I use the right window for code buffers and the left window for the CScope search buffer. When you do a CScope search and select a result, it automatically updates the right-side window to show the buffer referred to by the result. This is all well and good, except that it causes me to lose my place in some other buffer that I was studying. Sometimes this is no biggie, because [C-s u] gets me back to where I was.</p> <p>What would be better, though, is to have 3 split windows like this ([C-x 2] in the left window): <a href="http://bitthicket.com/files/emacs-3split.jpg">alt text http://bitthicket.com/files/emacs-3split.jpg</a></p> <p>And have the bottom left window contain the CScope search buffer, and the top left window be the only buffer that CScope ever updates. That way, I can see my CScope searches and navigate around the code without losing the buffer I'm focused on.</p> <p>Anyone know how I can do that?</p>
[ { "answer_id": 44562, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 0, "selected": false, "text": "<p>Well, I decided to not be a reputation-whore and find the answer myself. I looked in cscope.el as shown on the Emacs ...
2008/09/04
[ "https://Stackoverflow.com/questions/43765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3279/" ]
For my day job, I live in Emacs. Utterly. I also have become pretty dependent on CScope to help me find things in the code. Normally, I have 2 windows in a split (C-x 3): [alt text http://bitthicket.com/files/emacs-2split.JPG](http://bitthicket.com/files/emacs-2split.JPG) And I use the right window for code buffers and the left window for the CScope search buffer. When you do a CScope search and select a result, it automatically updates the right-side window to show the buffer referred to by the result. This is all well and good, except that it causes me to lose my place in some other buffer that I was studying. Sometimes this is no biggie, because [C-s u] gets me back to where I was. What would be better, though, is to have 3 split windows like this ([C-x 2] in the left window): [alt text http://bitthicket.com/files/emacs-3split.jpg](http://bitthicket.com/files/emacs-3split.jpg) And have the bottom left window contain the CScope search buffer, and the top left window be the only buffer that CScope ever updates. That way, I can see my CScope searches and navigate around the code without losing the buffer I'm focused on. Anyone know how I can do that?
Put this in your .emacs file: ``` ;; Toggle window dedication (defun toggle-window-dedicated () "Toggle whether the current active window is dedicated or not" (interactive) (message (if (let (window (get-buffer-window (current-buffer))) (set-window-dedicated-p window (not (window-dedicated-p window)))) "Window '%s' is dedicated" "Window '%s' is normal") (current-buffer))) ``` Then bind it to some key - I use the Pause key: ``` (global-set-key [pause] 'toggle-window-dedicated) ``` And then use it to "dedicate" the window you want locked. then cscope can only open files from its result window in some OTHER window. Works a charm. I specifically use it for exactly this purpose - keeping one source file always on screen, while using cscope in a second buffer/window, and looking at cscope results in a third.