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
130,396
<p>Is there a way to use constants in <strong>JavaScript</strong>?</p> <p>If not, what's the common practice for specifying variables that are used as constants?</p>
[ { "answer_id": 130398, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 5, "selected": false, "text": "<p>No, not in general. Firefox implements <code>const</code> but I know IE doesn't.</p>\n\n<hr>\n\n<p><a href=\"https:...
2008/09/24
[ "https://Stackoverflow.com/questions/130396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
Is there a way to use constants in **JavaScript**? If not, what's the common practice for specifying variables that are used as constants?
Since [ES2015](https://www.ecma-international.org/ecma-262/6.0/), JavaScript has a notion of [`const`](https://www.ecma-international.org/ecma-262/6.0/#sec-let-and-const-declarations): ``` const MY_CONSTANT = "some-value"; ``` This will work in [pretty much all browsers except IE 8, 9 and 10](https://caniuse.com/#search=const). Some may also need [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) enabled. You can use `var` with conventions like ALL\_CAPS to show that certain values should not be modified if you need to support older browsers or are working with legacy code: ``` var MY_CONSTANT = "some-value"; ```
130,404
<p>I'm trying to find a way to &quot;pretty print&quot; a JavaScript data structure in a human-readable form for debugging.</p> <p>I have a rather big and complicated data structure being stored in JS and I need to write some code to manipulate it. In order to work out what I'm doing and where I'm going wrong, what I really need is to be able to see the data structure in its entirety, and update it whenever I make changes through the UI.</p> <p>All of this stuff I can handle myself, apart from finding a nice way to dump a JavaScript data structure to a human-readable string. JSON would do, but it really needs to be nicely formatted and indented. I'd usually use Firebug's excellent DOM dumping stuff for this, but I really need to be able to see the entire structure at once, which doesn't seem to be possible in Firebug.</p>
[ { "answer_id": 130420, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": false, "text": "<p>In <code>Firebug</code>, if you just <code>console.debug (\"%o\", my_object)</code> you can click on it in the cons...
2008/09/24
[ "https://Stackoverflow.com/questions/130404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17121/" ]
I'm trying to find a way to "pretty print" a JavaScript data structure in a human-readable form for debugging. I have a rather big and complicated data structure being stored in JS and I need to write some code to manipulate it. In order to work out what I'm doing and where I'm going wrong, what I really need is to be able to see the data structure in its entirety, and update it whenever I make changes through the UI. All of this stuff I can handle myself, apart from finding a nice way to dump a JavaScript data structure to a human-readable string. JSON would do, but it really needs to be nicely formatted and indented. I'd usually use Firebug's excellent DOM dumping stuff for this, but I really need to be able to see the entire structure at once, which doesn't seem to be possible in Firebug.
I wrote a function to dump a JS object in a readable form, although the output isn't indented, but it shouldn't be too hard to add that: I made this function from one I made for Lua (which is much more complex) which handled this indentation issue. Here is the "simple" version: ``` function DumpObject(obj) { var od = new Object; var result = ""; var len = 0; for (var property in obj) { var value = obj[property]; if (typeof value == 'string') value = "'" + value + "'"; else if (typeof value == 'object') { if (value instanceof Array) { value = "[ " + value + " ]"; } else { var ood = DumpObject(value); value = "{ " + ood.dump + " }"; } } result += "'" + property + "' : " + value + ", "; len++; } od.dump = result.replace(/, $/, ""); od.len = len; return od; } ``` I will look at improving it a bit. Note 1: To use it, do `od = DumpObject(something)` and use od.dump. Convoluted because I wanted the len value too (number of items) for another purpose. It is trivial to make the function return only the string. Note 2: it doesn't handle loops in references. **EDIT** I made the indented version. ``` function DumpObjectIndented(obj, indent) { var result = ""; if (indent == null) indent = ""; for (var property in obj) { var value = obj[property]; if (typeof value == 'string') value = "'" + value + "'"; else if (typeof value == 'object') { if (value instanceof Array) { // Just let JS convert the Array to a string! value = "[ " + value + " ]"; } else { // Recursive dump // (replace " " by "\t" or something else if you prefer) var od = DumpObjectIndented(value, indent + " "); // If you like { on the same line as the key //value = "{\n" + od + "\n" + indent + "}"; // If you prefer { and } to be aligned value = "\n" + indent + "{\n" + od + "\n" + indent + "}"; } } result += indent + "'" + property + "' : " + value + ",\n"; } return result.replace(/,\n$/, ""); } ``` Choose your indentation on the line with the recursive call, and you brace style by switching the commented line after this one. ... I see you whipped up your own version, which is good. Visitors will have a choice.
130,427
<p>Here's the situation. I have a webservice (C# 2.0), which consists of (mainly) a class inheriting from System.Web.Services.WebService. It contains a few methods, which all need to call a method that checks if they're authorized or not.</p> <p>Basically something like this (pardon the architecture, this is purely as an example): </p> <pre><code>public class ProductService : WebService { public AuthHeader AuthenticationHeader; [WebMethod(Description="Returns true")] [SoapHeader("AuthenticationHeader")] public bool MethodWhichReturnsTrue() { if(Validate(AuthenticationHeader)) { throw new SecurityException("Access Denied"); } return true; } [WebMethod(Description="Returns false")] [SoapHeader("AuthenticationHeader")] public bool MethodWhichReturnsFalse() { if(Validate(AuthenticationHeader)) { throw new SecurityException("Access Denied"); } return false; } private bool Validate(AuthHeader authHeader) { return authHeader.Username == "gooduser" &amp;&amp; authHeader.Password == "goodpassword"; } } </code></pre> <p>As you can see, the method <code>Validate</code> has to be called in each method. I'm looking for a way to be able to call that method, while still being able to access the soap headers in a sane way. I've looked at the events in the <code>global.asax</code>, but I don't think I can access the headers in that class... Can I?</p>
[ { "answer_id": 130584, "author": "GregK", "author_id": 8653, "author_profile": "https://Stackoverflow.com/users/8653", "pm_score": 2, "selected": false, "text": "<p>You can implement the so-called SOAP extension by deriving from <a href=\"http://msdn.microsoft.com/en-us/library/system.we...
2008/09/24
[ "https://Stackoverflow.com/questions/130427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/909/" ]
Here's the situation. I have a webservice (C# 2.0), which consists of (mainly) a class inheriting from System.Web.Services.WebService. It contains a few methods, which all need to call a method that checks if they're authorized or not. Basically something like this (pardon the architecture, this is purely as an example): ``` public class ProductService : WebService { public AuthHeader AuthenticationHeader; [WebMethod(Description="Returns true")] [SoapHeader("AuthenticationHeader")] public bool MethodWhichReturnsTrue() { if(Validate(AuthenticationHeader)) { throw new SecurityException("Access Denied"); } return true; } [WebMethod(Description="Returns false")] [SoapHeader("AuthenticationHeader")] public bool MethodWhichReturnsFalse() { if(Validate(AuthenticationHeader)) { throw new SecurityException("Access Denied"); } return false; } private bool Validate(AuthHeader authHeader) { return authHeader.Username == "gooduser" && authHeader.Password == "goodpassword"; } } ``` As you can see, the method `Validate` has to be called in each method. I'm looking for a way to be able to call that method, while still being able to access the soap headers in a sane way. I've looked at the events in the `global.asax`, but I don't think I can access the headers in that class... Can I?
Here is what you need to do to get this to work correctly. It is possible to create your own custom SoapHeader: ``` public class ServiceAuthHeader : SoapHeader { public string SiteKey; public string Password; public ServiceAuthHeader() {} } ``` Then you need a SoapExtensionAttribute: ``` public class AuthenticationSoapExtensionAttribute : SoapExtensionAttribute { private int priority; public AuthenticationSoapExtensionAttribute() { } public override Type ExtensionType { get { return typeof(AuthenticationSoapExtension); } } public override int Priority { get { return priority; } set { priority = value; } } } ``` And a custom SoapExtension: ``` public class AuthenticationSoapExtension : SoapExtension { private ServiceAuthHeader authHeader; public AuthenticationSoapExtension() { } public override object GetInitializer(Type serviceType) { return null; } public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute) { return null; } public override void Initialize(object initializer) { } public override void ProcessMessage(SoapMessage message) { if (message.Stage == SoapMessageStage.AfterDeserialize) { foreach (SoapHeader header in message.Headers) { if (header is ServiceAuthHeader) { authHeader = (ServiceAuthHeader)header; if(authHeader.Password == TheCorrectUserPassword) { return; //confirmed } } } throw new SoapException("Unauthorized", SoapException.ClientFaultCode); } } } ``` Then, in your web service add the following header to your method: ``` public ServiceAuthHeader AuthenticationSoapHeader; [WebMethod] [SoapHeader("AuthenticationSoapHeader")] [AuthenticationSoapExtension] public string GetSomeStuffFromTheCloud(string IdOfWhatYouWant) { return WhatYouWant; } ``` When you consume this service, you must instantiate the custom header with the correct values and attach it to the request: ``` private ServiceAuthHeader header; private PublicService ps; header = new ServiceAuthHeader(); header.SiteKey = "Thekey"; header.Password = "Thepassword"; ps.ServiceAuthHeaderValue = header; string WhatYouWant = ps.GetSomeStuffFromTheCloud(SomeId); ```
130,506
<p>I recently inherited a small Java program that takes information from a large database, does some processing and produces a detailed image regarding the information. The original author wrote the code using a single thread, then later modified it to allow it to use multiple threads. </p> <p>In the code he defines a constant;</p> <pre><code>// number of threads public static final int THREADS = Runtime.getRuntime().availableProcessors(); </code></pre> <p>Which then sets the number of threads that are used to create the image.</p> <p>I understand his reasoning that the number of threads cannot be greater than the number of available processors, so set it the the amount to get the full potential out of the processor(s). Is this correct? or is there a better way to utilize the full potential of the processor(s)?</p> <p>EDIT: To give some more clarification, The specific algorithm that is being threaded scales to the resolution of the picture being created, (1 thread per pixel). That is obviously not the best solution though. The work that this algorithm does is what takes all the time, and is wholly mathematical operations, there are no locks or other factors that will cause any given thread to sleep. I just want to maximize the programs CPU utilization to decrease the time to completion.</p>
[ { "answer_id": 130527, "author": "Rob", "author_id": 3542, "author_profile": "https://Stackoverflow.com/users/3542", "pm_score": 2, "selected": false, "text": "<p>The number that your application needs; no more, and no less.</p>\n\n<p>Obviously, if you're writing an application which con...
2008/09/24
[ "https://Stackoverflow.com/questions/130506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7613/" ]
I recently inherited a small Java program that takes information from a large database, does some processing and produces a detailed image regarding the information. The original author wrote the code using a single thread, then later modified it to allow it to use multiple threads. In the code he defines a constant; ``` // number of threads public static final int THREADS = Runtime.getRuntime().availableProcessors(); ``` Which then sets the number of threads that are used to create the image. I understand his reasoning that the number of threads cannot be greater than the number of available processors, so set it the the amount to get the full potential out of the processor(s). Is this correct? or is there a better way to utilize the full potential of the processor(s)? EDIT: To give some more clarification, The specific algorithm that is being threaded scales to the resolution of the picture being created, (1 thread per pixel). That is obviously not the best solution though. The work that this algorithm does is what takes all the time, and is wholly mathematical operations, there are no locks or other factors that will cause any given thread to sleep. I just want to maximize the programs CPU utilization to decrease the time to completion.
Threads are fine, but as others have noted, you have to be highly aware of your bottlenecks. Your algorithm sounds like it would be susceptible to cache contention between multiple CPUs - this is particularly nasty because it has the potential to hit the performance of all of your threads (normally you think of using multiple threads to continue processing while waiting for slow or high latency IO operations). Cache contention is a very important aspect of using multi CPUs to process a highly parallelized algorithm: Make sure that you take your memory utilization into account. If you can construct your data objects so each thread has it's own memory that it is working on, you can greatly reduce cache contention between the CPUs. For example, it may be easier to have a big array of ints and have different threads working on different parts of that array - but in Java, the bounds checks on that array are going to be trying to access the same address in memory, which can cause a given CPU to have to reload data from L2 or L3 cache. Splitting the data into it's own data structures, and configure those data structures so they are thread local (might even be more optimal to use [ThreadLocal](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html) - that actually uses constructs in the OS that provide guarantees that the CPU can use to optimize cache. The best piece of advice I can give you is test, test, test. Don't make assumptions about how CPUs will perform - there is a *huge* amount of magic going on in CPUs these days, often with counterintuitive results. Note also that the JIT runtime optimization will add an additional layer of complexity here (maybe good, maybe not).
130,547
<p>Ok I followed the steps for setting up ruby and rails on my Vista machine and I am having a problem connecting to the database.</p> <h2>Contents of <code>database.yml</code></h2> <pre><code>development: adapter: sqlserver database: APPS_SETUP Host: WindowsVT06\SQLEXPRESS Username: se Password: paswd </code></pre> <p>Run <code>rake db:migrate</code> from myapp directory</p> <pre><code>---------- rake aborted! no such file to load -- deprecated </code></pre> <h2><strong>ADO</strong></h2> <p>I have dbi 0.4.0 installed and have created the ADO folder in</p> <p><code>C:\Ruby\lib\ruby\site_ruby\1.8\DBD\ADO</code></p> <p>I got the ado.rb from the dbi 0.2.2</p> <p>What else should I be looking at to fix the issue connecting to the database? Please don't tell me to use MySql or Sqlite or Postgres.</p> <p>****UPDATE****</p> <p>I have installed the activerecord-sqlserver-adapter gem from --source=<a href="http://gems.rubyonrails.org" rel="nofollow noreferrer">http://gems.rubyonrails.org</a></p> <p>Still not working.</p> <p>I have verified that I can connect to the database by logging into SQL Management Studio with the credentials.</p> <hr> <p><strong>rake db:migrate --trace</strong></p> <hr> <pre><code>PS C:\Inetpub\wwwroot\myapp&gt; rake db:migrate --trace (in C:/Inetpub/wwwroot/myapp) ** Invoke db:migrate (first_time) ** Invoke environment (first_time) ** Execute environment ** Execute db:migrate rake aborted! no such file to load -- deprecated C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require' C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' C:/Ruby/lib/ruby/site_ruby/1.8/dbi.rb:48 C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require' C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/requires.rb:7:in `require_library_ or_gem' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnin gs' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/requires.rb:5:in `require_library_ or_gem' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-sqlserver-adapter-1.0.0.9250/lib/active_record/connection_adapters/sqlserver _adapter.rb:29:in `sqlserver_connection' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio n.rb:292:in `send' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio n.rb:292:in `connection=' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio n.rb:260:in `retrieve_connection' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio n.rb:78:in `connection' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:408:in `initialize' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `new' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `up' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:356:in `migrate' C:/Ruby/lib/ruby/gems/1.8/gems/rails-2.1.1/lib/tasks/databases.rake:99 C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:621:in `call' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:621:in `execute' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:616:in `each' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:616:in `execute' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:582:in `invoke_with_call_chain' C:/Ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:575:in `invoke_with_call_chain' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:568:in `invoke' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2031:in `invoke_task' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `top_level' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `each' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `top_level' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2048:in `standard_exception_handling' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2003:in `top_level' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:1982:in `run' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2048:in `standard_exception_handling' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:1979:in `run' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/bin/rake:31 C:/Ruby/bin/rake:19:in `load' C:/Ruby/bin/rake:19 PS C:\Inetpub\wwwroot\myapp&gt; </code></pre>
[ { "answer_id": 131501, "author": "hectorsq", "author_id": 14755, "author_profile": "https://Stackoverflow.com/users/14755", "pm_score": 2, "selected": false, "text": "<p>Did you install the SQL Server adapter?</p>\n\n<pre><code>gem install activerecord-sqlserver-adapter --source=http://g...
2008/09/24
[ "https://Stackoverflow.com/questions/130547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453046/" ]
Ok I followed the steps for setting up ruby and rails on my Vista machine and I am having a problem connecting to the database. Contents of `database.yml` -------------------------- ``` development: adapter: sqlserver database: APPS_SETUP Host: WindowsVT06\SQLEXPRESS Username: se Password: paswd ``` Run `rake db:migrate` from myapp directory ``` ---------- rake aborted! no such file to load -- deprecated ``` **ADO** ------- I have dbi 0.4.0 installed and have created the ADO folder in `C:\Ruby\lib\ruby\site_ruby\1.8\DBD\ADO` I got the ado.rb from the dbi 0.2.2 What else should I be looking at to fix the issue connecting to the database? Please don't tell me to use MySql or Sqlite or Postgres. \*\*\*\*UPDATE\*\*\*\* I have installed the activerecord-sqlserver-adapter gem from --source=<http://gems.rubyonrails.org> Still not working. I have verified that I can connect to the database by logging into SQL Management Studio with the credentials. --- **rake db:migrate --trace** --- ``` PS C:\Inetpub\wwwroot\myapp> rake db:migrate --trace (in C:/Inetpub/wwwroot/myapp) ** Invoke db:migrate (first_time) ** Invoke environment (first_time) ** Execute environment ** Execute db:migrate rake aborted! no such file to load -- deprecated C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require' C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' C:/Ruby/lib/ruby/site_ruby/1.8/dbi.rb:48 C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require' C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/requires.rb:7:in `require_library_ or_gem' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnin gs' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/requires.rb:5:in `require_library_ or_gem' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-sqlserver-adapter-1.0.0.9250/lib/active_record/connection_adapters/sqlserver _adapter.rb:29:in `sqlserver_connection' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio n.rb:292:in `send' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio n.rb:292:in `connection=' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio n.rb:260:in `retrieve_connection' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio n.rb:78:in `connection' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:408:in `initialize' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `new' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `up' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:356:in `migrate' C:/Ruby/lib/ruby/gems/1.8/gems/rails-2.1.1/lib/tasks/databases.rake:99 C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:621:in `call' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:621:in `execute' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:616:in `each' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:616:in `execute' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:582:in `invoke_with_call_chain' C:/Ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:575:in `invoke_with_call_chain' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:568:in `invoke' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2031:in `invoke_task' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `top_level' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `each' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `top_level' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2048:in `standard_exception_handling' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2003:in `top_level' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:1982:in `run' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2048:in `standard_exception_handling' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:1979:in `run' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/bin/rake:31 C:/Ruby/bin/rake:19:in `load' C:/Ruby/bin/rake:19 PS C:\Inetpub\wwwroot\myapp> ```
I ran into the same problem yesterday. Apparently 'deprecated' is a gem, so you want to run "gem install deprecated" to grab and install the latest version. Good luck.
130,561
<p>I am building an application where a page will load user controls (x.ascx) dynamically based on query string. </p> <p>I have a validation summary on the page and want to update it from the User Controls. This will allow me to have multiple controls using one Validation Summary. How can I pass data between controls and pages. </p> <p>I know I can define the control at design time and use events to do that but these controls are loaded dynamically using Page.LoadControl.</p> <p>Also, I want to avoid using sessions or querystring.</p>
[ { "answer_id": 130671, "author": "Jorge Alves", "author_id": 6195, "author_profile": "https://Stackoverflow.com/users/6195", "pm_score": 0, "selected": false, "text": "<p>Assuming you're talking about asp's validator controls, making them work with the validation summary should be easy: ...
2008/09/24
[ "https://Stackoverflow.com/questions/130561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/709/" ]
I am building an application where a page will load user controls (x.ascx) dynamically based on query string. I have a validation summary on the page and want to update it from the User Controls. This will allow me to have multiple controls using one Validation Summary. How can I pass data between controls and pages. I know I can define the control at design time and use events to do that but these controls are loaded dynamically using Page.LoadControl. Also, I want to avoid using sessions or querystring.
**Found a way of doing this:** Step 1: Create a Base User Control and define Delegates and Events in this control. Step 2: Create a Public function in the base user control to Raise Events defined in Step1. ``` 'SourceCode for Step 1 and Step 2 Public Delegate Sub UpdatePageHeaderHandler(ByVal PageHeading As String) Public Class CommonUserControl Inherits System.Web.UI.UserControl Public Event UpdatePageHeaderEvent As UpdatePageHeaderHandler Public Sub UpdatePageHeader(ByVal PageHeadinga As String) RaiseEvent UpdatePageHeaderEvent(PageHeadinga) End Sub End Class ``` Step 3: Inherit your Web User Control from the base user control that you created in Step1. Step 4: From your Web User Control - Call the MyBase.FunctionName that you defined in Step2. ``` 'SourceCode for Step 3 and Step 4 Partial Class DerievedUserControl Inherits CommonUserControl Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load MyBase.PageHeader("Test Header") End Sub End Class ``` Step 5: In your page, Load the control dynamically using Page.LoadControl and Cast the control as the Base user control. Step 6: Attach Event Handlers with this Control. ``` 'SourceCode for Step 5 and Step 6 Private Sub LoadDynamicControl() Try 'Try to load control Dim c As CommonUserControl = CType(LoadControl("/Common/Controls/Test.ascx", CommonUserControl)) 'Attach Event Handlers to the LoadedControl AddHandler c.UpdatePageHeaderEvent, AddressOf PageHeaders DynamicControlPlaceHolder.Controls.Add(c) Catch ex As Exception 'Log Error End Try End Sub ```
130,570
<p>We have recently moved back to InstallShield 2008 from rolling our own install. So, I am still trying to get up the learning curve on it. </p> <p>We are using Firebird and a usb driver, that we couldn't find good msi install solutions. So, we have a cmd line to install firebird silently and the usb driver mostly silently.</p> <p>We have put this code into the event handler DefaultFeatureInstalled. This works really well on the first time install. But, when I do an uninstall it trys to launch the firebird installer again, so it must be sending the DefaultFeatureInstalled event again.</p> <p>Is their another event to use, or is there a way to detect whether its an install or uninstall in the DefaultFeatureInstalled event?</p>
[ { "answer_id": 130757, "author": "Chris Tybur", "author_id": 741, "author_profile": "https://Stackoverflow.com/users/741", "pm_score": 0, "selected": false, "text": "<p>There are MSI properties you can look at that will tell you if a product is already installed or if an uninstall is tak...
2008/09/24
[ "https://Stackoverflow.com/questions/130570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12425/" ]
We have recently moved back to InstallShield 2008 from rolling our own install. So, I am still trying to get up the learning curve on it. We are using Firebird and a usb driver, that we couldn't find good msi install solutions. So, we have a cmd line to install firebird silently and the usb driver mostly silently. We have put this code into the event handler DefaultFeatureInstalled. This works really well on the first time install. But, when I do an uninstall it trys to launch the firebird installer again, so it must be sending the DefaultFeatureInstalled event again. Is their another event to use, or is there a way to detect whether its an install or uninstall in the DefaultFeatureInstalled event?
Chris, I had trouble getting the MsiGetProperty to work at all. Just adding the code that you have ``` string sRemove; number nBuffer; nBuffer = 256; if (MsiGetProperty(ISMSI_HANDLE, "REMOVE", sRemove, nBuffer) = ERROR_SUCCESS) then //do something endif; ``` I get "undefined identifier". I tried several things to get IS to recognize it without success. After some more poking around, I realized that IS was not calling the function on uninstall in the first place. I had another function, onEnd I think that was calling the same things. After cleaning that up, I was getting the result I had expected in the beginning. So the correct answer would be that you don't have to do anything for the code in the DefaultFeature\_Installed event not to be called on uninstall.
130,573
<p>The <a href="http://msdn.microsoft.com/en-us/library/ms724284(VS.85).aspx" rel="nofollow noreferrer"><code>FILETIME</code> structure</a> counts from January 1 1601 (presumably the start of that day) according to the Microsoft documentation, but does this include leap seconds?</p>
[ { "answer_id": 130659, "author": "Brent.Longborough", "author_id": 9634, "author_profile": "https://Stackoverflow.com/users/9634", "pm_score": -1, "selected": false, "text": "<p>A very crude summary:</p>\n\n<p>UTC = (Atomic Time) + (Leap Seconds) ~~ (Mean Solar Time)</p>\n\n<p>The MS doc...
2008/09/24
[ "https://Stackoverflow.com/questions/130573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10168/" ]
The [`FILETIME` structure](http://msdn.microsoft.com/en-us/library/ms724284(VS.85).aspx) counts from January 1 1601 (presumably the start of that day) according to the Microsoft documentation, but does this include leap seconds?
The question shouldn't be if `FILETIME` includes leap seconds. It should be: > > Do the people, functions, and libraries, who interpret a `FILETIME` (i.e. `FileTimeToSystemTime`) include leap seconds when counting the duration? > > > The simple answer is *"no"*. `FileTimeToSystemTime` returns seconds as `0..59`. --- The simpler answer is: "*of course not, how could it?*". My Windows 2000 machine doesn't know that there were 2 leap seconds added in the decade since it was released. Any interpretation it makes of a `FILETIME` is wrong. --- Finally, rather than relying on logic, we can determine by direct experimental observation, the answer to the posters question: ```pascal var systemTime: TSystemTime; fileTime: TFileTime; begin //Construct a system-time for the 12/31/2008 11:59:59 pm ZeroMemory(@systemTime, SizeOf(systemTime)); systemtime.wYear := 2008; systemTime.wMonth := 12; systemTime.wDay := 31; systemTime.wHour := 23; systemtime.wMinute := 59; systemtime.wSecond := 59; //Convert it to a file time SystemTimeToFileTime(systemTime, {var}fileTime); //There was a leap second 12/31/2008 11:59:60 pm //Add one second to our filetime to reach the leap second filetime.dwLowDateTime := fileTime.dwLowDateTime+10000000; //10,000,000 * 100ns = 1s //Convert the filetime, sitting on a leap second, to a displayable system time FileTimeToSystemTime(fileTime, {var}systemTime); //And now print the system time ShowMessage(DateTimeToStr(SystemTimeToDateTime(systemTime))); ``` Adding one second to ``` 12/31/2008 11:59:59pm ``` gives ``` 1/1/2009 12:00:00am ``` rather than ``` 1/1/2009 11:59:60pm ``` Q.E.D. Original poster might not like it, but god intentionally rigged it so that a year is not evenly divisible by a day. He did it just to screw up programmers.
130,574
<p>I seek an algorithm that will let me represent an incoming sequence of bits as letters ('a' .. 'z' ), in a minimal matter such that the stream of bits can be regenerated from the letters, without ever holding the entire sequence in memory.</p> <p>That is, given an external bit source (each read returns a practically random bit), and user input of a number of bits, I would like to print out the minimal number of characters that can represent those bits.</p> <p>Ideally there should be a parameterization - how much memory versus maximum bits before some waste is necessary.</p> <p>Efficiency Goal - The same number of characters as the base-26 representation of the bits. </p> <p>Non-solutions: </p> <ol> <li><p>If sufficient storage was present, store the entire sequence and use a big-integer MOD 26 operation. </p></li> <li><p>Convert every 9 bits to 2 characters - This seems suboptimal, wasting 25% of information capacity of the letters output.</p></li> </ol>
[ { "answer_id": 130597, "author": "Smashery", "author_id": 14902, "author_profile": "https://Stackoverflow.com/users/14902", "pm_score": 2, "selected": false, "text": "<p>Could <a href=\"http://en.wikipedia.org/wiki/Huffman_coding\" rel=\"nofollow noreferrer\">Huffman coding</a> be what y...
2008/09/24
[ "https://Stackoverflow.com/questions/130574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I seek an algorithm that will let me represent an incoming sequence of bits as letters ('a' .. 'z' ), in a minimal matter such that the stream of bits can be regenerated from the letters, without ever holding the entire sequence in memory. That is, given an external bit source (each read returns a practically random bit), and user input of a number of bits, I would like to print out the minimal number of characters that can represent those bits. Ideally there should be a parameterization - how much memory versus maximum bits before some waste is necessary. Efficiency Goal - The same number of characters as the base-26 representation of the bits. Non-solutions: 1. If sufficient storage was present, store the entire sequence and use a big-integer MOD 26 operation. 2. Convert every 9 bits to 2 characters - This seems suboptimal, wasting 25% of information capacity of the letters output.
If you assign a different number of bits per letter, you should be able to exactly encode the bits in the twenty-six letters allowed without wasting any bits. (This is a lot like a Huffman code, only with a pre-built balanced tree.) To encode bits into letters: Accumulate bits until you match exactly one of the bit codes in the lookup table. Output that letter, clear the bit buffer, and keep going. To decode letters into bits: For each letter, output the bit sequence in the table. Implementing in code is left as an exercise to the reader. (Or to me, if I get bored later.) ``` a 0000 b 0001 c 0010 d 0011 e 0100 f 0101 g 01100 h 01101 i 01110 j 01111 k 10000 l 10001 m 10010 n 10011 o 10100 p 10101 q 10110 r 10111 s 11000 t 11001 u 11010 v 11011 w 11100 x 11101 y 11110 z 11111 ```
130,587
<p><em>[NOTE: This questions is similar to but <strong>not the same</strong> as <a href="https://stackoverflow.com/questions/128634/how-to-use-system-environment-variables-in-vs-2008-post-build-events">this one</a>.]</em></p> <p>Visual Studio defines several dozen "Macros" which are sort of simulated environment variables (completely unrelated to C++ macros) which contain information about the build in progress. Examples:</p> <pre> ConfigurationName Release TargetPath D:\work\foo\win\Release\foo.exe VCInstallDir C:\ProgramFiles\Microsoft Visual Studio 9.0\VC\ </pre> <p>Here is the complete set of 43 built-in Macros that I see (yours may differ depending on which version of VS you use and which tools you have enabled):</p> <pre> ConfigurationName IntDir RootNamespace TargetFileName DevEnvDir OutDir SafeInputName TargetFramework FrameworkDir ParentName SafeParentName TargetName FrameworkSDKDir PlatformName SafeRootNamespace TargetPath FrameworkVersion ProjectDir SolutionDir VCInstallDir FxCopDir ProjectExt SolutionExt VSInstallDir InputDir ProjectFileName SolutionFileName WebDeployPath InputExt ProjectName SolutionName WebDeployRoot InputFileName ProjectPath SolutionPath WindowsSdkDir InputName References TargetDir WindowsSdkDirIA64 InputPath RemoteMachine TargetExt </pre> <p>Of these, only four (<code>FrameworkDir</code>, <code>FrameworkSDKDir</code>, <code>VCInstallDir</code> and <code>VSInstallDir</code>) are set in the environment used for build-events.</p> <p>As Brian mentions, user-defined Macros can be defined such as to be set in the environment in which build tasks execute. My problem is with the built-in Macros.</p> <p>I use a Visual Studio Post-Build Event to run a python script as part of my build process. I'd like to pass the entire set of Macros (built-in and user-defined) to my script in the environment but I don't know how. Within my script I can access regular environment variables (e.g., Path, SystemRoot) but NOT these "Macros". All I can do now is pass them on-by-one as named options which I then process within my script. For example, this is what my Post-Build Event command line looks like:</p> <pre> postbuild.py --t="$(TargetPath)" --c="$(ConfigurationName)" </pre> <p>Besides being a pain in the neck, there is a limit on the size of Post-Build Event command line so I can't pass dozens Macros using this method even if I wanted to because the command line is truncated.</p> <p>Does anyone know if there is a way to pass the entire set of Macro names and values to a command that does NOT require switching to MSBuild (which I believe is not available for native VC++) or some other make-like build tool?</p>
[ { "answer_id": 130773, "author": "TonyOssa", "author_id": 3276, "author_profile": "https://Stackoverflow.com/users/3276", "pm_score": 0, "selected": false, "text": "<p>This is a bit hacky, but it could work.</p>\n\n<p>Why not call multiple .py scripts in a row?</p>\n\n<p>Each scripts can...
2008/09/24
[ "https://Stackoverflow.com/questions/130587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ]
*[NOTE: This questions is similar to but **not the same** as [this one](https://stackoverflow.com/questions/128634/how-to-use-system-environment-variables-in-vs-2008-post-build-events).]* Visual Studio defines several dozen "Macros" which are sort of simulated environment variables (completely unrelated to C++ macros) which contain information about the build in progress. Examples: ``` ConfigurationName Release TargetPath D:\work\foo\win\Release\foo.exe VCInstallDir C:\ProgramFiles\Microsoft Visual Studio 9.0\VC\ ``` Here is the complete set of 43 built-in Macros that I see (yours may differ depending on which version of VS you use and which tools you have enabled): ``` ConfigurationName IntDir RootNamespace TargetFileName DevEnvDir OutDir SafeInputName TargetFramework FrameworkDir ParentName SafeParentName TargetName FrameworkSDKDir PlatformName SafeRootNamespace TargetPath FrameworkVersion ProjectDir SolutionDir VCInstallDir FxCopDir ProjectExt SolutionExt VSInstallDir InputDir ProjectFileName SolutionFileName WebDeployPath InputExt ProjectName SolutionName WebDeployRoot InputFileName ProjectPath SolutionPath WindowsSdkDir InputName References TargetDir WindowsSdkDirIA64 InputPath RemoteMachine TargetExt ``` Of these, only four (`FrameworkDir`, `FrameworkSDKDir`, `VCInstallDir` and `VSInstallDir`) are set in the environment used for build-events. As Brian mentions, user-defined Macros can be defined such as to be set in the environment in which build tasks execute. My problem is with the built-in Macros. I use a Visual Studio Post-Build Event to run a python script as part of my build process. I'd like to pass the entire set of Macros (built-in and user-defined) to my script in the environment but I don't know how. Within my script I can access regular environment variables (e.g., Path, SystemRoot) but NOT these "Macros". All I can do now is pass them on-by-one as named options which I then process within my script. For example, this is what my Post-Build Event command line looks like: ``` postbuild.py --t="$(TargetPath)" --c="$(ConfigurationName)" ``` Besides being a pain in the neck, there is a limit on the size of Post-Build Event command line so I can't pass dozens Macros using this method even if I wanted to because the command line is truncated. Does anyone know if there is a way to pass the entire set of Macro names and values to a command that does NOT require switching to MSBuild (which I believe is not available for native VC++) or some other make-like build tool?
As far as I can tell, the method described in the question is the only way to pass build variables to a Python script. Perhaps Visual Studio 2010 has something better?
130,604
<p>I use int.MaxValue as a penalty and sometimes I am computing the penalties together. Is there a function or how would you create one with the most grace and efficiency that does that. </p> <p>ie. </p> <p>50 + 100 = 150</p> <p>int.Max + 50 = int.Max and not int.Min + 50 </p>
[ { "answer_id": 130660, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 3, "selected": true, "text": "<pre><code>int penaltySum(int a, int b)\n{\n return (int.MaxValue - a &lt; b) ? int.MaxValue : a + b;\n}\n</code></pre>\n...
2008/09/24
[ "https://Stackoverflow.com/questions/130604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4694/" ]
I use int.MaxValue as a penalty and sometimes I am computing the penalties together. Is there a function or how would you create one with the most grace and efficiency that does that. ie. 50 + 100 = 150 int.Max + 50 = int.Max and not int.Min + 50
``` int penaltySum(int a, int b) { return (int.MaxValue - a < b) ? int.MaxValue : a + b; } ``` Update: If your penalties can be negative, this would be more appropriate: ``` int penaltySum(int a, int b) { if (a > 0 && b > 0) { return (int.MaxValue - a < b) ? int.MaxValue : a + b; } if (a < 0 && b < 0) { return (int.MinValue - a > b) ? int.MinValue : a + b; } return a + b; } ```
130,605
<p>I have a table of Users that includes a bitmask of roles that the user belongs to. I'd like to select users that belong to one or more of the roles in a bitmask value. For example:</p> <pre>select * from [User] where UserRolesBitmask | 22 = 22</pre> <p>This selects all users that have the roles '2', '4' or '16' in their bitmask. Is this possible to express this in a LINQ query? Thanks.</p>
[ { "answer_id": 130691, "author": "KevDog", "author_id": 13139, "author_profile": "https://Stackoverflow.com/users/13139", "pm_score": 4, "selected": true, "text": "<p>I think this will work, but I haven't tested it.Substitute the name of your DataContext object. YMMV. </p>\n\n<pre><code>...
2008/09/24
[ "https://Stackoverflow.com/questions/130605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14072/" ]
I have a table of Users that includes a bitmask of roles that the user belongs to. I'd like to select users that belong to one or more of the roles in a bitmask value. For example: ``` select * from [User] where UserRolesBitmask | 22 = 22 ``` This selects all users that have the roles '2', '4' or '16' in their bitmask. Is this possible to express this in a LINQ query? Thanks.
I think this will work, but I haven't tested it.Substitute the name of your DataContext object. YMMV. ``` from u in DataContext.Users where UserRolesBitmask | 22 == 22 select u ```
130,614
<p>I've got a dictionary, something like</p> <pre><code>Dictionary&lt;Foo,String&gt; fooDict </code></pre> <p>I step through everything in the dictionary, e.g.</p> <pre><code>foreach (Foo foo in fooDict.Keys) MessageBox.show(fooDict[foo]); </code></pre> <p>It does that in the order the foos were added to the dictionary, so the first item added is the first foo returned.</p> <p>How can I change the cardinality so that, for example, the third foo added will be the second foo returned? In other words, I want to change its "index."</p>
[ { "answer_id": 130653, "author": "Statement", "author_id": 2166173, "author_profile": "https://Stackoverflow.com/users/2166173", "pm_score": 0, "selected": false, "text": "<p>I am <em>not fully educated in the domain</em> to properly answer the question, but I have <strong>a feeling</str...
2008/09/24
[ "https://Stackoverflow.com/questions/130614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18210/" ]
I've got a dictionary, something like ``` Dictionary<Foo,String> fooDict ``` I step through everything in the dictionary, e.g. ``` foreach (Foo foo in fooDict.Keys) MessageBox.show(fooDict[foo]); ``` It does that in the order the foos were added to the dictionary, so the first item added is the first foo returned. How can I change the cardinality so that, for example, the third foo added will be the second foo returned? In other words, I want to change its "index."
If you read the documentation on MSDN you'll see this: "The order in which the items are returned is undefined." You can't gaurantee the order, because a Dictionary is not a list or an array. It's meant to look up a value by the key, and any ability to iterate values is just a convenience but the order is not behavior you should depend on.
130,616
<p>I'm trying to start a service as a user and things work fine, until I try a user that doesn't have a password. Then, it fails to start (due to log-on error).</p> <p>Am I doing something wrong or is this "by design"?</p> <p>The code to register this service:</p> <pre><code> SC_HANDLE schService = CreateService( schSCManager, strNameNoSpaces, strServiceName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, szPath, NULL, NULL, NULL, strUser, (strPassword.IsEmpty())?NULL:strPassword); </code></pre>
[ { "answer_id": 130658, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "<p>You need to specify an empty string, not NULL if there is no password. NULL is not a valid empty string, \"\" is...
2008/09/24
[ "https://Stackoverflow.com/questions/130616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20208/" ]
I'm trying to start a service as a user and things work fine, until I try a user that doesn't have a password. Then, it fails to start (due to log-on error). Am I doing something wrong or is this "by design"? The code to register this service: ``` SC_HANDLE schService = CreateService( schSCManager, strNameNoSpaces, strServiceName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, szPath, NULL, NULL, NULL, strUser, (strPassword.IsEmpty())?NULL:strPassword); ```
It may be due to an OS security requirement or security policy. Check the security policies to see if anything is relevant there.
130,617
<p>I got a program that writes some data to a file using a method like the one below.</p> <pre><code> public void ExportToFile(string filename) { using(FileStream fstream = new FileStream(filename,FileMode.Create)) using (TextWriter writer = new StreamWriter(fstream)) { // try catch block for write permissions writer.WriteLine(text); } } </code></pre> <p>When running the program I get an error:</p> <blockquote> <p>Unhandled Exception: System.UnauthorizedAccessException: Access to the path 'mypath' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions ptions, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolea bFromProxy)</p> </blockquote> <p>Question: What code do I need to catch this and how do I grant the access?</p>
[ { "answer_id": 130641, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 7, "selected": true, "text": "<p><strong>UPDATE:</strong></p>\n\n<p>Modified the code based on <a href=\"https://stackoverflow.com/a/4397002/11702\">this an...
2008/09/24
[ "https://Stackoverflow.com/questions/130617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1361/" ]
I got a program that writes some data to a file using a method like the one below. ``` public void ExportToFile(string filename) { using(FileStream fstream = new FileStream(filename,FileMode.Create)) using (TextWriter writer = new StreamWriter(fstream)) { // try catch block for write permissions writer.WriteLine(text); } } ``` When running the program I get an error: > > Unhandled Exception: System.UnauthorizedAccessException: Access to the path 'mypath' is denied. > at System.IO.\_\_Error.WinIOError(Int32 errorCode, String maybeFullPath) > at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, > nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions > ptions, SECURITY\_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) > at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access > FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolea > bFromProxy) > > > Question: What code do I need to catch this and how do I grant the access?
**UPDATE:** Modified the code based on [this answer](https://stackoverflow.com/a/4397002/11702) to get rid of obsolete methods. You can use the Security namespace to check this: ``` public void ExportToFile(string filename) { var permissionSet = new PermissionSet(PermissionState.None); var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename); permissionSet.AddPermission(writePermission); if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { using (FileStream fstream = new FileStream(filename, FileMode.Create)) using (TextWriter writer = new StreamWriter(fstream)) { // try catch block for write permissions writer.WriteLine("sometext"); } } else { //perform some recovery action here } } ``` As far as getting those permission, you are going to have to ask the user to do that for you somehow. If you could programatically do this, then we would all be in trouble ;)
130,618
<p>I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to: </p> <pre><code>if (datetime.now() - self.timestamp) &gt; 100 # Where 100 is either seconds or minutes </code></pre> <p>This generates a type error. </p> <p>What is the proper way to do date time comparison in python? I already looked at <a href="http://wiki.python.org/moin/WorkingWithTime" rel="noreferrer">WorkingWithTime</a> which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison. </p> <p>Please post lists of datetime best practices.</p>
[ { "answer_id": 130623, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 0, "selected": false, "text": "<p>You can subtract two <a href=\"http://docs.python.org/lib/module-datetime.html\" rel=\"nofollow noreferrer\">dat...
2008/09/24
[ "https://Stackoverflow.com/questions/130618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20794/" ]
I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to: ``` if (datetime.now() - self.timestamp) > 100 # Where 100 is either seconds or minutes ``` This generates a type error. What is the proper way to do date time comparison in python? I already looked at [WorkingWithTime](http://wiki.python.org/moin/WorkingWithTime) which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison. Please post lists of datetime best practices.
Use the `datetime.timedelta` class: ``` >>> from datetime import datetime, timedelta >>> then = datetime.now() - timedelta(hours = 2) >>> now = datetime.now() >>> (now - then) > timedelta(days = 1) False >>> (now - then) > timedelta(hours = 1) True ``` Your example could be written as: ``` if (datetime.now() - self.timestamp) > timedelta(seconds = 100) ``` or ``` if (datetime.now() - self.timestamp) > timedelta(minutes = 100) ```
130,636
<p>When I try to compile the newest version of Clisp on Ubuntu 8.04 I always get this error after running configure:</p> <pre><code>Configure findings: FFI: no (user requested: default) readline: yes (user requested: yes) libsigsegv: no, consider installing GNU libsigsegv ./configure: libsigsegv was not detected, thus some features, such as generational garbage collection and stack overflow detection in interpreted Lisp code cannot be provided. Please do this: mkdir tools; cd tools; prefix=`pwd`/i686-pc-linux-gnu wget http://ftp.gnu.org/pub/gnu/libsigsegv/libsigsegv-2.5.tar.gz tar xfz libsigsegv-2.5.tar.gz cd libsigsegv-2.5 ./configure --prefix=${prefix} &amp;&amp; make &amp;&amp; make check &amp;&amp; make install cd ../.. ./configure --with-libsigsegv-prefix=${prefix} --with-readline --with-unicode --with-module=i18n --with-module=gdbm --with-module=pcre --with-module=readline --with-module=regexp If you insist on building without libsigsegv, please pass --ignore-absence-of-libsigsegv to this script: ./configure --ignore-absence-of-libsigsegv --with-readline --with-unicode --with-module=i18n --with-module=gdbm --with-module=pcre --with-module=readline --with-module=regexp </code></pre> <p>I've tried doing as requested, but it didn't help: it seems to ignore the <code>--with-libsigsegv-prefix</code> option. I also tried putting installing libsigsegv in a standard location (<code>/usr/local</code>). Oh, and of course, Ubuntu tells me that libsigsegv and libsigsegv-dev are installed in the system.</p> <p>I'd really like to be able to compile this version of Clips, as it introduces some serious improvements over the version shipped with Ubuntu (I'd also like to have PCRE).</p>
[ { "answer_id": 130655, "author": "PiedPiper", "author_id": 19315, "author_profile": "https://Stackoverflow.com/users/19315", "pm_score": 1, "selected": false, "text": "<p>If you look at 'config.log' it might tell you why configure is not finding libsigsegv</p>\n" }, { "answer_id"...
2008/09/24
[ "https://Stackoverflow.com/questions/130636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19922/" ]
When I try to compile the newest version of Clisp on Ubuntu 8.04 I always get this error after running configure: ``` Configure findings: FFI: no (user requested: default) readline: yes (user requested: yes) libsigsegv: no, consider installing GNU libsigsegv ./configure: libsigsegv was not detected, thus some features, such as generational garbage collection and stack overflow detection in interpreted Lisp code cannot be provided. Please do this: mkdir tools; cd tools; prefix=`pwd`/i686-pc-linux-gnu wget http://ftp.gnu.org/pub/gnu/libsigsegv/libsigsegv-2.5.tar.gz tar xfz libsigsegv-2.5.tar.gz cd libsigsegv-2.5 ./configure --prefix=${prefix} && make && make check && make install cd ../.. ./configure --with-libsigsegv-prefix=${prefix} --with-readline --with-unicode --with-module=i18n --with-module=gdbm --with-module=pcre --with-module=readline --with-module=regexp If you insist on building without libsigsegv, please pass --ignore-absence-of-libsigsegv to this script: ./configure --ignore-absence-of-libsigsegv --with-readline --with-unicode --with-module=i18n --with-module=gdbm --with-module=pcre --with-module=readline --with-module=regexp ``` I've tried doing as requested, but it didn't help: it seems to ignore the `--with-libsigsegv-prefix` option. I also tried putting installing libsigsegv in a standard location (`/usr/local`). Oh, and of course, Ubuntu tells me that libsigsegv and libsigsegv-dev are installed in the system. I'd really like to be able to compile this version of Clips, as it introduces some serious improvements over the version shipped with Ubuntu (I'd also like to have PCRE).
Here are my notes from compiling CLISP on Ubuntu in the past, hope this helps: ``` sudo apt-get install libsigsegv-dev libreadline5-dev # as of 7.10, Ubuntu's libffcall1-dev is broken and I had to get it from CVS # and make sure CLISP didn't use Ubuntu's version. sudo apt-get remove libffcall1-dev libffcall1 cvs -z3 -d:pserver:anonymous@cvs.sv.gnu.org:/sources/libffcall co -P ffcall cd ffcall; ./configure; make sudo make install cvs -z3 -d:pserver:anonymous@clisp.cvs.sourceforge.net:/cvsroot/clisp co -P clisp cd clisp ./configure --with-libffcall-prefix=/usr/local --prefix=/home/luis/Software ulimit -s 16384 cd src; make install ```
130,640
<p>I would like to be able to say things like</p> <p><strong>cd [.fred]</strong> and have my default directory go there, and my prompt change to indicate the full path to my current location.</p>
[ { "answer_id": 131235, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 2, "selected": false, "text": "<p>My DCL is <em>really</em> rusty, but can't you create an alias for SET DEFAULT named CD?</p>\n" }, { "answer_id...
2008/09/24
[ "https://Stackoverflow.com/questions/130640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7734/" ]
I would like to be able to say things like **cd [.fred]** and have my default directory go there, and my prompt change to indicate the full path to my current location.
Here's my setup: You need 2 files (typed below) : godir.com and prompt.com in your sys$login You may define a symbole ``` CD == "@sys$login:godir.com" ``` But I suggest you to use something else... (ie SD == "@sys$login:godir.com") I modify the help text. It was in french... You will have to retype the escape caracters into godir.com Replace ESC by the real escape into GRAPH\_BOUCLE: (see bottom of godir.com) Then to use it: ``` SD ? SD a_directory ... ``` Hope it helps. --- Here's prompt.com ``` $ noeud = f$trnlnm("SYS$NODE") - "::" $ if noeud .eqs. "HQSVYC" then noeud = "¥" $! $ noeud = noeud - "MQO" $ def_dir = f$directory() $ def_dir = f$extract(1,f$length(def_dir)-2,def_dir) $boucle: $ i = f$locate(".",def_dir) $ if i .eq. f$length(def_dir) then goto fin_boucle $ def_dir = f$extract(i+1,f$length(def_dir)-1,def_dir) $ goto boucle $! $fin_boucle: $! temp = "''noeud' ''def_dir' " + "''car_prompt'" $ temp = "''noeud'" - + " ''def_dir' " - + "''f$logical(""environnement"")'" - + "''car_prompt'" $! temp = "''noeud'" - $! + "''def_dir'" - $! + "''f$logical(""environnement"")'" - $! + "''car_prompt'" $ set prompt="''temp' " $! $! PROMPT.COM $! ``` Here's godir.com ``` $! $! GODIR.COM $! $ set noon $ set_prompt = "@sys$login:prompt.com" $ if f$type(TAB_DIR_N) .nes. "" then goto 10$ $ goto 20$ $ INIT: $ temp2 = "INIT" $ CLEAR: $ temp = 0 $ $ INIT2: $ temp = temp +1 $ if temp .gt. TAB_DIR_N then goto INIT3 $ delete/symb/glo TAB_DIR_'temp' $ goto INIT2 $ $ INIT3: $ P1 = "" $ if temp2 .eqs. "INIT" then goto 20$ $ delete/symb/glo TAB_DIR_N $ delete/symb/glo TAB_DIR_P $ delete/symb/glo TAB_DIR_I $ exit $ $ 20$: $ TAB_DIR_N == 1 $ TAB_DIR_P == 1 $ TAB_DIR_I == 1 $ if "''car_prompt'" .eqs. "" then car_prompt == ">" $ TAB_DIR_1 == f$parse(f$dir(),,,"device")+f$dir() $ 10$: $ if P1 .eqs. "" then goto LIST $ if P1 .eqs. "?" then goto SHOW $ if P1 .eqs. "." then P1 = "[]" $ if P1 .eqs. "^" then goto SET_CUR $ if (P1 .eqs. "<") .or. (P1 .eqs. ">") .or. - (P1 .eqs. "..") then P1 = "[-]" $ if (P1 .eqs. "*") .or. (P1 .eqs. "0") then goto HOME $ if (P1 .eqs. "P") .or. (P1 .eqs. "p") then goto PREVIOUS $ if (P1 .eqs. "H") .or. (P1 .eqs. "h") then goto HELP $ if (P1 .eqs. "S") .or. (P1 .eqs. "s") then goto SET_PROMPT $ if (P1 .eqs. "G") .or. (P1 .eqs. "g") then goto SET_PROMPT_GRAPHIC $ temp2 = "" $ if (P1 .eqs. "~INIT") .or. (P1 .eqs. "~init") then goto INIT $ if (P1 .eqs. "~CLEAR") .or. (P1 .eqs. "~clear") then goto CLEAR $ $! *** Specification par un numero $ temp = f$extract(0,1,P1) $ if temp .eqs. "-" then goto DELETE $ temp2 = "" $boucle_reculer: $ if temp .nes. "\" then goto fin_reculer $ temp2 = temp2 + "-." $ P1 = P1 - "\" $ temp = f$extract(0,1,P1) $ goto boucle_reculer $! $fin_reculer: $ P1 = temp2 + P1 $ if (P1 .lts. "0") .or. (P1 .gts. "9") then goto SPEC $ temp = f$integer("''P1'") $ if temp .eq. 0 then goto HOME $ if (temp .lt. 1) .or. (temp .gt. TAB_DIR_N) then goto ERR $ TAB_DIR_P == TAB_DIR_I $ TAB_DIR_I == temp $ goto SET2 $ $ SPEC: $! *** Specification relative de directory $ $ temp = f$parse("[.''P1']","missing.mis") $ DD = f$extract(0,f$locate("]",temp)+1,temp) $ if DD .nes. "" then goto SET1 $ $! *** Specification de directory principal $ $ temp = f$parse("[''P1']","missing.mis") $ DD = f$extract(0,f$locate("]",temp)+1,temp) $ if DD .nes. "" then goto SET1 $ $ temp = f$parse("[''P1']","sys$login:missing.mis") $ DD = f$extract(0,f$locate("]",temp)+1,temp) $ if DD .nes. "" then goto SET1 $ $! *** Specification exacte de directory $ $ temp = f$parse(P1,"missing.mis") $ if f$locate("]"+P1,temp) .ne. f$length(temp) then goto ERR $ if f$locate(".][",temp) .ne. f$length(temp) then temp = temp - "][" $ DD = f$extract(0,f$locate("]",temp)+1,temp) $! if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SHOW $ if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SET2 $ if DD .nes. "" then goto SET1 $ $ temp = f$parse(P1,"sys$login:missing.mis") $ if f$locate("]"+P1,temp) .ne. f$length(temp) then goto ERR $ if f$locate(".][",temp) .ne. f$length(temp) then temp = temp - "][" $ DD = f$extract(0,f$locate("]",temp)+1,temp) $! if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SHOW $ if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SET2 $ if DD .nes. "" then goto SET1 $ $ goto ERR $ $ HOME: $ DD = "SYS$LOGIN" $ $ SET1: $ Set On $ On error then goto ERR1 $ set message/nofac/noid/nosever/notext $ Set def 'DD' $ dir/output=nl: $ set message/fac/id/sever/text $ temp = f$parse(f$dir()) - ".;" $ if temp .nes. "" then goto SET1F $ ERR1: $ set message/fac/id/sever/text $ temp = TAB_DIR_'TAB_DIR_I' $ Set def 'temp' $ goto ERR $ SET1F: $ I = 0 $ LOOP1: $ I = I + 1 $ if temp .eqs. TAB_DIR_'I' then goto FOUND $ if I .lt. TAB_DIR_N then goto LOOP1 $ $ TAB_DIR_N == TAB_DIR_N + 1 $ TAB_DIR_P == TAB_DIR_I $ TAB_DIR_I == TAB_DIR_N $ TAB_DIR_'TAB_DIR_I' == temp $ goto SHOW $ $ FOUND: $ TAB_DIR_P == TAB_DIR_I $ TAB_DIR_I == I $ goto SET2 $ $ SET_PROMPT: $ car_prompt == "''P2'" $ set_prompt $ exit $ $ PREVIOUS: $ temp = TAB_DIR_P $ TAB_DIR_P == TAB_DIR_I $ TAB_DIR_I == temp $ $ SET_CUR: $ SET2: $ DD = TAB_DIR_'TAB_DIR_I' $ set def 'DD' $ $ SHOW: $ temp = TAB_DIR_'TAB_DIR_I' $ ws " ''TAB_DIR_I' * ''temp'" $ set_prompt $ exit $ $ LIST: $ I = 0 $ LOOP2: $ I = I + 1 $ temp = TAB_DIR_'I' $ if I .eq. TAB_DIR_I then goto L_CUR $ if I .eq. TAB_DIR_P then GOTO L_PRE $ ws " ''I' = ''temp'" $ goto F_LOOP2 $ L_CUR: $ ws " ''I' * ''temp'" $ goto F_LOOP2 $ L_PRE: $ ws " ''I' + ''temp'" $ $ F_LOOP2: $ if I .lt. TAB_DIR_N then goto LOOP2 $ set_prompt $ $ exit $ $ DELETE: $ P1 = P1 - "-" $ temp2 = f$integer("''P1'") $ DEL_1: $ temp = f$integer("''P1'") $ if (temp .lt. 1) .or. (temp .gt. TAB_DIR_N) then goto ERR $ if temp .eq. TAB_DIR_I then goto ERR $ if temp .lt. TAB_DIR_I then TAB_DIR_I == TAB_DIR_I - 1 $ if temp .eq. TAB_DIR_P then TAB_DIR_P == TAB_DIR_I $ if temp .lt. TAB_DIR_P then TAB_DIR_P == TAB_DIR_P - 1 $ LOOP3: $ if temp .eq. TAB_DIR_N then goto F_LOOP3 $ temp3 = temp + 1 $ TAB_DIR_'temp' == TAB_DIR_'temp3' $ temp = temp + 1 $ goto LOOP3 $ F_LOOP3: $ delete/symb/glo tab_dir_'tab_dir_n' $ TAB_DIR_N == TAB_DIR_N - 1 $ if P2 .eqs. "" then goto FIN_DEL $ temp2 = temp2 + 1 $ if temp2 .le. f$integer("''P2'") then goto DEL_1 $ FIN_DEL: $ goto LIST $ $ ERR: $ ws "*** ERREUR ***" $ exit $ $ HELP: $ ws " H Show this menu" $ ws " null Show a list of directories" $ ws " ? Show current directory" $ ws " < or [-] or" $ ws " > or .. Remonte d'un niveau de directory" $ ws " * ou 0 Return to SYS$LOGIN" $ ws " P Last directory " $ ws " . ou [] Set cureent directory" $ ws " ^ Return to next directory" $ ws " x Set def to number x" $ ws " -x Remove the number x" $ ws " -x y Remove from x to y" $ ws " ddd Set def to [ddd] or [.ddd] or ddd:" $ ws " \ddd Set def to [-.ddd]" $ ws " S "">>"" Modify prompt for >>" $ ws " ~INIT Initialize to current directory " $ ws " (and delete all others references)" $ ws " ~CLEAR Remove all references $ ws "" $ $ exit $ $ SET_PROMPT_GRAPHIC: $ temp = "''P2'" $ i=0 $ car_prompt == "" $ GRAPH_BOUCLE: $ t=f$extract(i,1,temp) $ if (t .eqs. "e") .or. (t .eqs. "E") then t="ESC" $ if (t .eqs. "g") .or. (t .eqs. "G") then t="ESC(0" $ V° (} .L-_. "N") .-_. (} .L-_. "H") }NL+ }="ESC(B" $ car_prompt == car_prompt + t $ i = i+1 $ if i .lts. f$length(temp) then goto GRAPH_BOUCLE $ $ set_prompt $ exit ```
130,698
<p>I want to wrap a <a href="https://en.wikipedia.org/wiki/One-liner_program#Perl" rel="nofollow noreferrer">Perl one-liner</a> in a batch file. For a (trivial) example, in a Unix shell, I could quote up a command like this:</p> <pre><code>perl -e 'print localtime() . "\n"' </code></pre> <p>But DOS chokes on that with this helpful error message:</p> <blockquote> <p>Can't find string terminator "'" anywhere before EOF at -e line 1.</p> </blockquote> <p>What's the best way to do this within a <a href="https://en.wikipedia.org/wiki/Batch_file" rel="nofollow noreferrer">.bat file</a>?</p>
[ { "answer_id": 130726, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 5, "selected": true, "text": "<p>For Perl stuff on Windows, I try to use the generalized quoting as much as possible so I don't get leaning tooth...
2008/09/24
[ "https://Stackoverflow.com/questions/130698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21938/" ]
I want to wrap a [Perl one-liner](https://en.wikipedia.org/wiki/One-liner_program#Perl) in a batch file. For a (trivial) example, in a Unix shell, I could quote up a command like this: ``` perl -e 'print localtime() . "\n"' ``` But DOS chokes on that with this helpful error message: > > Can't find string terminator "'" anywhere before EOF at -e line 1. > > > What's the best way to do this within a [.bat file](https://en.wikipedia.org/wiki/Batch_file)?
For Perl stuff on Windows, I try to use the generalized quoting as much as possible so I don't get leaning toothpick syndrome. I save the quotes for the stuff that DOS needs: ``` perl -e "print scalar localtime() . qq(\n)" ``` If you just need a newline at the end of the print, you can let the `-l` switch do that for you: ``` perl -le "print scalar localtime()" ``` For other cool things you can do with switches, see the [perlrun](http://perldoc.perl.org/perlrun.html) documentation.
130,720
<p>In certain cases, I can't seem to get components to receive events.</p> <p>[edit] </p> <p>To clarify, the example code is just for demonstration sake, what I was really asking was if there was a central location that a listener could be added, to which one can reliably dispatch events to and from arbitrary objects.</p> <p>I ended up using parentApplication to dispatch and receive the event I needed to handle.</p> <p>[/edit]</p> <p>If two components have differing parents, or as in the example below, one is a popup, it would seem the event never reaches the listener (See the method "popUp" for the dispatch that doesn't work):</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="init()"&gt; &lt;mx:Script&gt; &lt;![CDATA[ import mx.controls.Menu; import mx.managers.PopUpManager; // Add listeners public function init():void { this.addEventListener("child", handleChild); this.addEventListener("stepchild", handleStepchild); } // Handle the no pop button event public function noPop(event:Event):void { dispatchEvent(new Event("child")); } // Handle the pop up public function popUp(event:Event):void { var menu:Menu = new Menu(); var btnMenu:Button = new Button(); btnMenu.label = "stepchild"; menu.addChild(btnMenu); PopUpManager.addPopUp(menu, this); // neither of these work... this.callLater(btnMenu.dispatchEvent, [new Event("stepchild", true)]); btnMenu.dispatchEvent(new Event("stepchild", true)); } // Event handlers public function handleChild(event:Event):void { trace("I handled child"); } public function handleStepchild(event:Event):void { trace("I handled stepchild"); } ]]&gt; &lt;/mx:Script&gt; &lt;mx:VBox&gt; &lt;mx:Button label="NoPop" id="btnNoPop" click="noPop(event)"/&gt; &lt;mx:Button label="PopUp" id="btnPop" click="popUp(event)"/&gt; &lt;/mx:VBox&gt; &lt;/mx:Application&gt; </code></pre> <p><strong>I can think of work-arounds, but it seems like there ought to be some central event bus...</strong> </p> <p>Am I missing something?</p>
[ { "answer_id": 131046, "author": "Antti", "author_id": 6037, "author_profile": "https://Stackoverflow.com/users/6037", "pm_score": 0, "selected": false, "text": "<p>You are attaching the listener to <code>this</code> when the event is getting dispatched from <code>btnMenu</code>.</p>\n\n...
2008/09/25
[ "https://Stackoverflow.com/questions/130720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16258/" ]
In certain cases, I can't seem to get components to receive events. [edit] To clarify, the example code is just for demonstration sake, what I was really asking was if there was a central location that a listener could be added, to which one can reliably dispatch events to and from arbitrary objects. I ended up using parentApplication to dispatch and receive the event I needed to handle. [/edit] If two components have differing parents, or as in the example below, one is a popup, it would seem the event never reaches the listener (See the method "popUp" for the dispatch that doesn't work): ``` <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="init()"> <mx:Script> <![CDATA[ import mx.controls.Menu; import mx.managers.PopUpManager; // Add listeners public function init():void { this.addEventListener("child", handleChild); this.addEventListener("stepchild", handleStepchild); } // Handle the no pop button event public function noPop(event:Event):void { dispatchEvent(new Event("child")); } // Handle the pop up public function popUp(event:Event):void { var menu:Menu = new Menu(); var btnMenu:Button = new Button(); btnMenu.label = "stepchild"; menu.addChild(btnMenu); PopUpManager.addPopUp(menu, this); // neither of these work... this.callLater(btnMenu.dispatchEvent, [new Event("stepchild", true)]); btnMenu.dispatchEvent(new Event("stepchild", true)); } // Event handlers public function handleChild(event:Event):void { trace("I handled child"); } public function handleStepchild(event:Event):void { trace("I handled stepchild"); } ]]> </mx:Script> <mx:VBox> <mx:Button label="NoPop" id="btnNoPop" click="noPop(event)"/> <mx:Button label="PopUp" id="btnPop" click="popUp(event)"/> </mx:VBox> </mx:Application> ``` **I can think of work-arounds, but it seems like there ought to be some central event bus...** Am I missing something?
Above is correct. You are dispatching the event from btnMenu, but you are not listening for events on btnMenu - you are listening for events on the Application. Either dispatch from Application: ``` dispatchEvent(new Event("stepchild", true)); ``` or listen on the btnMenu ``` btnMenu.addEventListener("stepchild",handleStepChild); btnMenu.dispatchEvent(new Event("stepchild",true)); ```
130,730
<p>I have an immutable class with some private fields that are set during the constructor execution. I want to unit test this constructor but I'm not sure the "best practice" in this case.</p> <p><strong>Simple Example</strong></p> <p>This class is defined in Assembly1:</p> <pre><code>public class Class2Test { private readonly string _StringProperty; public Class2Test() { _StringProperty = ConfigurationManager.AppSettings["stringProperty"]; } } </code></pre> <p>This class is defined in Assembly2:</p> <pre><code>[TestClass] public class TestClass { [TestMethod] public void Class2Test_Default_Constructor() { Class2Test x = new Class2Test(); //what do I assert to validate that the field was set properly? } } </code></pre> <p><strong>EDIT 1</strong>: I have answered this question with a potential solution but I'm not sure if it's the "right way to go". So if you think you have a better idea please post it.</p> <p>This example isn't really worth testing, but assume the constructor has some more complex logic. Is the best approach to avoid testing the constructor and to just assume it works if all the tests for the methods on the class work?</p> <p><strong>EDIT 2</strong>: Looks like I made the sample a little to simple. I have updated it with a more reasonable situation.</p>
[ { "answer_id": 130732, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 1, "selected": false, "text": "<p>I have properly enabled <code>[InternalsVisibleTo]</code> on Assembly1 (code) so that there is a trust relationsh...
2008/09/25
[ "https://Stackoverflow.com/questions/130730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
I have an immutable class with some private fields that are set during the constructor execution. I want to unit test this constructor but I'm not sure the "best practice" in this case. **Simple Example** This class is defined in Assembly1: ``` public class Class2Test { private readonly string _StringProperty; public Class2Test() { _StringProperty = ConfigurationManager.AppSettings["stringProperty"]; } } ``` This class is defined in Assembly2: ``` [TestClass] public class TestClass { [TestMethod] public void Class2Test_Default_Constructor() { Class2Test x = new Class2Test(); //what do I assert to validate that the field was set properly? } } ``` **EDIT 1**: I have answered this question with a potential solution but I'm not sure if it's the "right way to go". So if you think you have a better idea please post it. This example isn't really worth testing, but assume the constructor has some more complex logic. Is the best approach to avoid testing the constructor and to just assume it works if all the tests for the methods on the class work? **EDIT 2**: Looks like I made the sample a little to simple. I have updated it with a more reasonable situation.
Nothing, unless you are using that field. You don't want over-specification via tests. In other words, there is no need to test that the assignment operator works. If you are using that field in a method or something, call that method and assert on that. Edit: > > assume the constructor has some more complex logic > > > You shouldn't be performing any logic in constructors. Edit 2: > > > ``` > public Class2Test() > { > _StringProperty = ConfigurationManager.AppSettings["stringProperty"]; > } > > ``` > > Don't do that! =) Your simple unit test has now become an integration test because it depends on the successful operation of more than one class. Write a class that handles configuration values. WebConfigSettingsReader could be the name, and it should encapsulate the `ConfigurationManager.AppSettings` call. Pass an instance of that SettingsReader class into the constructor of `Class2Test`. Then, in your *unit test*, you can mock your `WebConfigSettingsReader` and stub out a response to any calls you might make to it.
130,734
<p>It's been a while since I've had to do any HTML-like code in <code>Vim</code>, but recently I came across this again. Say I'm writing some simple <code>HTML</code>:</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;title&gt;This is a title&lt;/title&gt;&lt;/head&gt;&lt;/html&gt; </code></pre> <p>How do I write those closing tags for title, head and html down quickly? I feel like I'm missing some really simple way here that does not involve me going through writing them all down one by one.</p> <p>Of course I can use <kbd>Ctrl</kbd><kbd>P</kbd> to autocomplete the individual tag names but what gets me on my laptop keyboard is actually getting the brackets and slash right.</p>
[ { "answer_id": 130741, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": 6, "selected": true, "text": "<p>Check this out..</p>\n\n<p>closetag.vim </p>\n\n<pre><code>Functions and mappings to close open HTML/XML tags\n</code></pr...
2008/09/25
[ "https://Stackoverflow.com/questions/130734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10098/" ]
It's been a while since I've had to do any HTML-like code in `Vim`, but recently I came across this again. Say I'm writing some simple `HTML`: ``` <html><head><title>This is a title</title></head></html> ``` How do I write those closing tags for title, head and html down quickly? I feel like I'm missing some really simple way here that does not involve me going through writing them all down one by one. Of course I can use `Ctrl``P` to autocomplete the individual tag names but what gets me on my laptop keyboard is actually getting the brackets and slash right.
Check this out.. closetag.vim ``` Functions and mappings to close open HTML/XML tags ``` <https://www.vim.org/scripts/script.php?script_id=13> I use something similar.
130,740
<p>I have the following program:</p> <pre><code>~/test&gt; cat test.cc int main() { int i = 3; int j = __sync_add_and_fetch(&amp;i, 1); return 0; } </code></pre> <p>I'm compiling this program using GCC 4.2.2 on Linux running on a multi-cpu 64-bit Intel machine:</p> <pre><code>~/test&gt; uname --all Linux doom 2.6.9-67.ELsmp #1 SMP Wed Nov 7 13:56:44 EST 2007 x86_64 x86_64 x86_64 GNU/Linux </code></pre> <p>When I compile the program in 64-bit mode, it compiles and links fine:</p> <pre><code>~/test&gt; /share/tools/gcc-4.2.2/bin/g++ test.cc ~/test&gt; </code></pre> <p>When I compile it in 32-bit mode, I get the following error:</p> <pre><code>~/test&gt; /share/tools/gcc-4.2.2/bin/g++ -m32 test.cc /tmp/ccEVHGkB.o(.text+0x27): In function `main': : undefined reference to `__sync_add_and_fetch_4' collect2: ld returned 1 exit status ~/test&gt; </code></pre> <p>Although I will never actually run on a 32-bit processor, I do need a 32-bit executable so I can link with some 32-bit libraries.</p> <p>My 2 questions are:</p> <ol> <li><p>Why do I get a link error when I compile in 32-bit mode?</p></li> <li><p>Is there some way to get the program to compile and link, while still being able to link with a 32-bit library?</p></li> </ol>
[ { "answer_id": 130754, "author": "Dan Udey", "author_id": 21450, "author_profile": "https://Stackoverflow.com/users/21450", "pm_score": 5, "selected": true, "text": "<p>From the <a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/Atomic-Builtins.html#Atomic-Builtins\" rel=\"noreferrer\...
2008/09/25
[ "https://Stackoverflow.com/questions/130740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21435/" ]
I have the following program: ``` ~/test> cat test.cc int main() { int i = 3; int j = __sync_add_and_fetch(&i, 1); return 0; } ``` I'm compiling this program using GCC 4.2.2 on Linux running on a multi-cpu 64-bit Intel machine: ``` ~/test> uname --all Linux doom 2.6.9-67.ELsmp #1 SMP Wed Nov 7 13:56:44 EST 2007 x86_64 x86_64 x86_64 GNU/Linux ``` When I compile the program in 64-bit mode, it compiles and links fine: ``` ~/test> /share/tools/gcc-4.2.2/bin/g++ test.cc ~/test> ``` When I compile it in 32-bit mode, I get the following error: ``` ~/test> /share/tools/gcc-4.2.2/bin/g++ -m32 test.cc /tmp/ccEVHGkB.o(.text+0x27): In function `main': : undefined reference to `__sync_add_and_fetch_4' collect2: ld returned 1 exit status ~/test> ``` Although I will never actually run on a 32-bit processor, I do need a 32-bit executable so I can link with some 32-bit libraries. My 2 questions are: 1. Why do I get a link error when I compile in 32-bit mode? 2. Is there some way to get the program to compile and link, while still being able to link with a 32-bit library?
From the [GCC page on Atomic Builtins](http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/Atomic-Builtins.html#Atomic-Builtins): > > Not all operations are supported by > all target processors. If a particular > operation cannot be implemented on the > target processor, a warning will be > generated and a call an external > function will be generated. The > external function will carry the same > name as the builtin, with an > additional suffix `\_n' where n is the > size of the data type. > > > Judging from your compiler output, which refers to `__sync_add_and_fetch_4`, this is what's happening. For some reason, GCC is not generating the external function properly. This is likely why you're only getting an error in 32-bit mode - when compiling for 64-bit mode, it compiles for your processor more closely. When compiling for 32-bit, it may well be using a generic arch (i386, for example) which does not natively support those features. Try specifying a specific architecture for your chip family (Xeon, Core 2, etc.) via -mcpu and see if that works. If not, you'll have to figure out why GCC isn't including the appropriate function that it should be generating.
130,748
<p>I've got a form where I have two radio buttons and two interchangeable controls (made up of a ListView and a handful of buttons). Based on which radio button is selected I want to display the proper control to the user.</p> <p>The way I'm doing this now is just loading both controls and setting up an OnRadioButtonSelectionChanged() method which gets called at form load (to set the initial state) and at any time the selection is changed. This method just sets the visible property on each control to the proper value.</p> <p>This seems to work well enough, but I was curious as to if there was a better or more common way of doing it?</p>
[ { "answer_id": 130805, "author": "Lloyd Cotten", "author_id": 21807, "author_profile": "https://Stackoverflow.com/users/21807", "pm_score": 3, "selected": true, "text": "<p>Yep, that's pretty much how I do it. I would set the CheckedChanged event of both radio buttons to point at a sing...
2008/09/25
[ "https://Stackoverflow.com/questions/130748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
I've got a form where I have two radio buttons and two interchangeable controls (made up of a ListView and a handful of buttons). Based on which radio button is selected I want to display the proper control to the user. The way I'm doing this now is just loading both controls and setting up an OnRadioButtonSelectionChanged() method which gets called at form load (to set the initial state) and at any time the selection is changed. This method just sets the visible property on each control to the proper value. This seems to work well enough, but I was curious as to if there was a better or more common way of doing it?
Yep, that's pretty much how I do it. I would set the CheckedChanged event of both radio buttons to point at a single event handler and would place the following code to swap out the visible control. ``` private void OnRadioButtonCheckedChanged(object sender, EventArgs e) { Control1.Visible = RadioButton1.Checked; Control2.Visible = RadioButton2.Checked; } ```
130,763
<p>I want my Python script to copy files on Vista. When I run it from a normal <code>cmd.exe</code> window, no errors are generated, yet the files are NOT copied. If I run <code>cmd.exe</code> "as administator" and then run my script, it works fine.</p> <p>This makes sense since User Account Control (UAC) normally prevents many file system actions.</p> <p>Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?")</p> <p>If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?</p>
[ { "answer_id": 131092, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 5, "selected": false, "text": "<p>It seems there's no way to elevate the application privileges for a while for you to perform a particular task. Window...
2008/09/25
[ "https://Stackoverflow.com/questions/130763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ]
I want my Python script to copy files on Vista. When I run it from a normal `cmd.exe` window, no errors are generated, yet the files are NOT copied. If I run `cmd.exe` "as administator" and then run my script, it works fine. This makes sense since User Account Control (UAC) normally prevents many file system actions. Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?") If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?
As of 2017, an easy method to achieve this is the following: ``` import ctypes, sys def is_admin(): try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False if is_admin(): # Code of your program here else: # Re-run the program with admin rights ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1) ``` If you are using Python 2.x, then you should replace the last line for: ``` ctypes.windll.shell32.ShellExecuteW(None, u"runas", unicode(sys.executable), unicode(" ".join(sys.argv)), None, 1) ``` Also note that if you converted you python script into an executable file (using tools like `py2exe`, `cx_freeze`, `pyinstaller`) then you should use `sys.argv[1:]` instead of `sys.argv` in the fourth parameter. Some of the advantages here are: * No external libraries required. It only uses `ctypes` and `sys` from standard library. * Works on both Python 2 and Python 3. * There is no need to modify the file resources nor creating a manifest file. * If you don't add code below if/else statement, the code won't ever be executed twice. * You can get the return value of the API call in the last line and take an action if it fails (code <= 32). Check possible return values [here](https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shellexecutea?redirectedfrom=MSDN#return-value). * You can change the display method of the spawned process modifying the sixth parameter. Documentation for the underlying ShellExecute call is [here](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762153%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396).
130,775
<p>As far as variable naming conventions go, should iterators be named <code>i</code> or something more semantic like <code>count</code>? If you don't use <code>i</code>, why not? If you feel that <code>i</code> is acceptable, are there cases of iteration where it shouldn't be used?</p>
[ { "answer_id": 130782, "author": "Matthew Rapati", "author_id": 15000, "author_profile": "https://Stackoverflow.com/users/15000", "pm_score": 0, "selected": false, "text": "<p>It helps if you name it something that describes what it is looping through. But I usually just use i.</p>\n" ...
2008/09/25
[ "https://Stackoverflow.com/questions/130775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ]
As far as variable naming conventions go, should iterators be named `i` or something more semantic like `count`? If you don't use `i`, why not? If you feel that `i` is acceptable, are there cases of iteration where it shouldn't be used?
Depends on the context I suppose. If you where looping through a set of Objects in some collection then it should be fairly obvious from the context what you are doing. ``` for(int i = 0; i < 10; i++) { // i is well known here to be the index objectCollection[i].SomeProperty = someValue; } ``` However if it is not immediately clear from the context what it is you are doing, or if you are making modifications to the index you should use a variable name that is more indicative of the usage. ``` for(int currentRow = 0; currentRow < numRows; currentRow++) { for(int currentCol = 0; currentCol < numCols; currentCol++) { someTable[currentRow][currentCol] = someValue; } } ```
130,789
<p>I heard that decision tables in relational database have been researched a lot in academia. I also know that business rules engines use decision tables and that many BPMS use them as well. I was wondering if people today use decision tables within their relational databases?</p>
[ { "answer_id": 130910, "author": "Dana the Sane", "author_id": 2567, "author_profile": "https://Stackoverflow.com/users/2567", "pm_score": -1, "selected": false, "text": "<p>I would look into using an Object database rather than a traditional RDBMS (Relational Database Management System)...
2008/09/25
[ "https://Stackoverflow.com/questions/130789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19272/" ]
I heard that decision tables in relational database have been researched a lot in academia. I also know that business rules engines use decision tables and that many BPMS use them as well. I was wondering if people today use decision tables within their relational databases?
A decision table is a cluster of conditions and actions. A condition can be simple enough that you can represent it with a simple "match a column against this value" string. Or a condition could be hellishly complex. An action, similarly, could be as simple as "move this value to a column". Or the action could involve multiple parts or steps or -- well -- anything. A CASE function in a SELECT or WHERE clause *is* a decision table. This is the first example of decision table "in" a relational database. You can have a "transformation" table with columns that have old-value and replacement-value. You can then write a small piece of code like the following. ``` def decision_table( aRow ): result= connection.execute( "SELECT replacement_value FROM transformation WHERE old_value = ?", aRow['somecolumn'] ) replacement= result.fetchone() aRow['anotherColumn']= result['replacement_value'] ``` Each row of the decision table has a "match this old\_value" and "move this replacement\_value" kind of definition. The "condition" parts of a decision table have to be evaluated somewhere. Your application is where this will happen. You will fetch the condition values from the database. You'll use those values in some function(s) to see if the rule is true. The "action" parts of a decision table have to be executed somewhere; again, your application does stuff. You'll fetch action values from the database. You'll use those values to insert, update or delete other values. Decision tables are used all the time; they've always been around in relational databases. Each table requires a highly customized data model. It also requires a unique condition function and action procedure. It doesn't generalize well. If you want, you could store XML in the database and invoke some rules engine to interpret and execute the BPEL rules. In this case, the rules engine does the condition and action processing. If you want, you could store Python (or Tcl or something else) in the database. Seriously. You'd write the conditions and actions in Python. You'd fetch it from the database and run the Python code fragment. Lots of choices. None of the "academic". Indeed, the basic condition - action stuff is done all the time.
130,790
<p>I have some C# code in an ASP.Net application that does this:</p> <p>Bitmap bmp = new Bitmap(1184, 1900);</p> <p>And occasionally it throws an exception "Parameter is not valid". Now i've been googling around and apparently GDI+ is infamous for throwing random exceptions, and lots of people have had this problem, but nobody has a solution to it! I've checked the system and it has plenty of both RAM and swap space. Now in the past if i do an 'iisreset' then the problem goes away, but it comes back in a few days. But i'm not convinced i've caused a memory leak, because as i say above there is plenty of ram+swap free.</p> <p>Anyone have any solutions?</p>
[ { "answer_id": 130891, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "<p>You not only need enough memory, it needs to be contiguous. Over time memory becomes fragmented and it becomes harder...
2008/09/25
[ "https://Stackoverflow.com/questions/130790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have some C# code in an ASP.Net application that does this: Bitmap bmp = new Bitmap(1184, 1900); And occasionally it throws an exception "Parameter is not valid". Now i've been googling around and apparently GDI+ is infamous for throwing random exceptions, and lots of people have had this problem, but nobody has a solution to it! I've checked the system and it has plenty of both RAM and swap space. Now in the past if i do an 'iisreset' then the problem goes away, but it comes back in a few days. But i'm not convinced i've caused a memory leak, because as i say above there is plenty of ram+swap free. Anyone have any solutions?
Stop using GDI+ and start using the WPF Imaging classes (.NET 3.0). These are a major cleanup of the GDI+ classes and tuned for performance. Additionally, it sets up a "bitmap chain" that allows you to easily perform multiple actions on the bitmap in an efficient manner. Find more by reading about [BitmapSource](http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource.aspx) Here's an example of starting with a blank bitmap just waiting to receive some pixels: ``` using System.Windows.Media.Imaging; class Program { public static void Main(string[] args) { var bmp = new WriteableBitmap(1184, 1900, 96.0, 96.0, PixelFormat.Bgr32, null); } } ```
130,794
<p>There have been several questions already posted with specific questions about <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer">dependency injection</a>, such as when to use it and what frameworks are there for it. However,</p> <p><strong>What is dependency injection and when/why should or shouldn't it be used?</strong></p>
[ { "answer_id": 130862, "author": "wds", "author_id": 10098, "author_profile": "https://Stackoverflow.com/users/10098", "pm_score": 12, "selected": true, "text": "<p><strong>Dependency Injection</strong> is passing dependency to other <strong>objects</strong> or <strong>framework</strong>...
2008/09/25
[ "https://Stackoverflow.com/questions/130794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1354/" ]
There have been several questions already posted with specific questions about [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection), such as when to use it and what frameworks are there for it. However, **What is dependency injection and when/why should or shouldn't it be used?**
**Dependency Injection** is passing dependency to other **objects** or **framework**( dependency injector). Dependency injection makes testing easier. The injection can be done through **constructor**. `SomeClass()` has its constructor as following: ```csh public SomeClass() { myObject = Factory.getObject(); } ``` **Problem**: If `myObject` involves complex tasks such as disk access or network access, it is **hard** to do unit test on `SomeClass()`. Programmers have to mock `myObject` and might **intercept** the factory call. **Alternative solution**: * Passing `myObject` in as an argument to the constructor ```csh public SomeClass (MyClass myObject) { this.myObject = myObject; } ``` `myObject` can be passed directly which makes testing easier. * One common alternative is defining a **do-nothing constructor**. Dependency injection can be done through setters. (h/t @MikeVella). * [Martin Fowler](http://martinfowler.com/articles/injection.html#InterfaceInjection) documents a third alternative (h/t @MarcDix), where **classes explicitly implement an interface** for the dependencies programmers wish injected. It is harder to isolate components in unit testing without dependency injection. In 2013, when I wrote this answer, this was a major theme on the [Google Testing Blog](http://googletesting.blogspot.com/). It remains the biggest advantage to me, as programmers not always need the extra flexibility in their run-time design (for instance, for service locator or similar patterns). Programmers often need to isolate the classes during testing.
130,801
<p>I'm using GNU autotools for the build system on a particular project. I want to start writing automated tests for verifcation. I would like to just type "make check" to have it automatically run these. My project is in C++, although I am still curious about writing automated tests for other languages as well.</p> <p><em>Is this compatible with pretty much every unit testing framework out there (I was thinking of using cppunit)? How do I hook these unit testing frameworks into make check? Can I make sure that I don't require the unit test software to be installed to be able to configure and build the rest of the project?</em></p>
[ { "answer_id": 131256, "author": "Kyle Burton", "author_id": 19784, "author_profile": "https://Stackoverflow.com/users/19784", "pm_score": 3, "selected": false, "text": "<p>You seem to be asking 2 questions in the first paragraph.</p>\n\n<p>The first is about adding tests to the GNU auto...
2008/09/25
[ "https://Stackoverflow.com/questions/130801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5963/" ]
I'm using GNU autotools for the build system on a particular project. I want to start writing automated tests for verifcation. I would like to just type "make check" to have it automatically run these. My project is in C++, although I am still curious about writing automated tests for other languages as well. *Is this compatible with pretty much every unit testing framework out there (I was thinking of using cppunit)? How do I hook these unit testing frameworks into make check? Can I make sure that I don't require the unit test software to be installed to be able to configure and build the rest of the project?*
To make test run when you issue `make check`, you need to add them to the `TESTS` variable Assuming you've already built the executable that runs the unit tests, you just add the name of the executable to the TESTS variable like this: ``` TESTS=my-test-executable ``` It should then be automatically run when you `make check`, and if the executable returns a non-zero value, it will report that as a test failure. If you have multiple unit test executables, just list them all in the `TESTS` variable: ``` TESTS=my-first-test my-second-test my-third-test ``` and they will all get run.
130,829
<p>I have 3 points in a 3D space of which I know the exact locations. Suppose they are: <code>(x0,y0,z0)</code>, <code>(x1,y1,z1)</code> and <code>(x2,y2,z2)</code>.</p> <p>Also I have a camera that is looking at these 3 points and I know the 2D locations of those three points on camera view plane. So for example <code>(x0,y0,z0)</code> will be <code>(x0',y0')</code>, and <code>(x1,y1,z1)</code> will be <code>(x1',y1')</code> and <code>(x2,y2,z2)</code> will be <code>(x2',y2')</code> from the camera's point of view.</p> <p>What is the easiest way to find the projection matrix that will project those 3D points into 2D points on camera view plane. We don't know anything about the camera location.</p>
[ { "answer_id": 130909, "author": "tye", "author_id": 21496, "author_profile": "https://Stackoverflow.com/users/21496", "pm_score": 5, "selected": true, "text": "<p>This gives you two sets, each of three equations in 3 variables:</p>\n\n<pre><code>a*x0+b*y0+c*z0 = x0'\na*x1+b*y1+c*z1 = x1...
2008/09/25
[ "https://Stackoverflow.com/questions/130829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have 3 points in a 3D space of which I know the exact locations. Suppose they are: `(x0,y0,z0)`, `(x1,y1,z1)` and `(x2,y2,z2)`. Also I have a camera that is looking at these 3 points and I know the 2D locations of those three points on camera view plane. So for example `(x0,y0,z0)` will be `(x0',y0')`, and `(x1,y1,z1)` will be `(x1',y1')` and `(x2,y2,z2)` will be `(x2',y2')` from the camera's point of view. What is the easiest way to find the projection matrix that will project those 3D points into 2D points on camera view plane. We don't know anything about the camera location.
This gives you two sets, each of three equations in 3 variables: ``` a*x0+b*y0+c*z0 = x0' a*x1+b*y1+c*z1 = x1' a*x2+b*y2+c*z2 = x2' d*x0+e*y0+f*z0 = y0' d*x1+e*y1+f*z1 = y1' d*x2+e*y2+f*z2 = y2' ``` Just use whatever method of solving simultaneous equations is easiest in your situation (it isn't even hard to solve these "by hand"). Then your transformation matrix is just ((a,b,c)(d,e,f)). ... Actually, that is over-simplified and assumes a camera pointed at the origin of your 3D coordinate system and no perspective. For perspective, the transformation matrix works more like: ``` ( a, b, c, d ) ( xt ) ( x, y, z, 1 ) ( e, f, g, h ) = ( yt ) ( i, j, k, l ) ( zt ) ( xv, yv ) = ( xc+s*xt/zt, yc+s*yt/zt ) if md < zt; ``` but the 4x3 matrix is more constrained than 12 degrees of freedom since we should have ``` a*a+b*b+c*c = e*e+f*f+g*g = i*i+j*j+k*k = 1 a*a+e*e+i*i = b*b+f*f+j*j = c*c+g*g+k*k = 1 ``` So you should probably have 4 points to get 8 equations to cover the 6 variables for camera position and angle and 1 more for scaling of the 2-D view points since we'll be able to eliminate the "center" coordinates (xc,yc). So if you have 4 points and transform your 2-D view points to be relative to the center of your display, then you can get 14 simultaneous equations in 13 variables and solve. Unfortunately, six of the equations are not linear equations. Fortunately, all of the variables in those equations are restricted to the values between -1 and 1 so it is still probably feasible to solve the equations.
130,837
<p>I'm still learning RegEx at the moment, but for the time being could someone help me out with this? I have a few special requirements for formatting the string:</p> <ol> <li>No directories. JUST the file name.</li> <li>File name needs to be all lowercase.</li> <li>Whitespaces need to be replaced with underscores.</li> </ol> <p>Shouldn't be hard, but I'm pressed for time and I'm not sure on the 'correct' way to ensure a valid file name (namely I forget which characters were supposed to be invalid for file names).</p>
[ { "answer_id": 130845, "author": "Grank", "author_id": 12975, "author_profile": "https://Stackoverflow.com/users/12975", "pm_score": 2, "selected": false, "text": "<p>If you're in a super-quick hurry, you can usually find acceptable regular expressions in the library at <a href=\"http://...
2008/09/25
[ "https://Stackoverflow.com/questions/130837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19825/" ]
I'm still learning RegEx at the moment, but for the time being could someone help me out with this? I have a few special requirements for formatting the string: 1. No directories. JUST the file name. 2. File name needs to be all lowercase. 3. Whitespaces need to be replaced with underscores. Shouldn't be hard, but I'm pressed for time and I'm not sure on the 'correct' way to ensure a valid file name (namely I forget which characters were supposed to be invalid for file names).
And a simple combination of RegExp and other javascript is what I would recommend: ``` var a = "c:\\some\\path\\to\\a\\file\\with Whitespace.TXT"; a = a.replace(/^.*[\\\/]([^\\\/]*)$/i,"$1"); a = a.replace(/\s/g,"_"); a = a.toLowerCase(); alert(a); ```
130,843
<p>Using Prototype 1.6's "new Element(...)" I am trying to create a &lt;table&gt; element with both a &lt;thead&gt; and &lt;tbody&gt; but nothing happens in IE6.</p> <pre><code>var tableProto = new Element('table').update('&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Situation Task&lt;/th&gt;&lt;th&gt;Action&lt;/th&gt;&lt;th&gt;Result&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;a&lt;/td&gt;&lt;td&gt;b&lt;/td&gt;&lt;td&gt;c&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;'); </code></pre> <p>I'm then trying to inject copies of it like this:</p> <pre><code>$$('div.question').each(function(o) { Element.insert(o, { after:$(tableProto.cloneNode(true)) }); }); </code></pre> <p>My current workaround is to create a &lt;div&gt; instead of a &lt;table&gt; element, and then "update" it with all of the table HTML.</p> <p>How does one successfully do this?</p>
[ { "answer_id": 130884, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 2, "selected": false, "text": "<p>If prototypes' .update() method internally tries to set the .innerHTML it will fail in IE. In IE, <strong>the .innerHT...
2008/09/25
[ "https://Stackoverflow.com/questions/130843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18265/" ]
Using Prototype 1.6's "new Element(...)" I am trying to create a <table> element with both a <thead> and <tbody> but nothing happens in IE6. ``` var tableProto = new Element('table').update('<thead><tr><th>Situation Task</th><th>Action</th><th>Result</th></tr></thead><tbody><tr><td>a</td><td>b</td><td>c</td></tr></tbody>'); ``` I'm then trying to inject copies of it like this: ``` $$('div.question').each(function(o) { Element.insert(o, { after:$(tableProto.cloneNode(true)) }); }); ``` My current workaround is to create a <div> instead of a <table> element, and then "update" it with all of the table HTML. How does one successfully do this?
As it turns out, there's nothing wrong with the example code I provided in the question--it works in IE6 just fine. The issue I was facing is that I was also specifying a class for the <table> element in the constructor incorrectly, but omitted that from my example. The "real" code was as follows, and is incorrect: ``` var tableProto = new Element('table', { class:'hide-on-screen'} ).update('<thead><tr><th>Situation Task</th><th>Action</th><th>Result</th></tr></thead><tbody><tr><td>a</td><td>b</td><td>c</td></tr></tbody>'); ``` This works correctly in Firefox, but fails in IE6 because it is **wrong**. The correct way to add attributes to an element via this constructor is to provides strings, not just attribute names. The following code works in both browsers: ``` var tableProto = new Element('table', { 'class':'hide-on-screen'} ).update('<thead><tr><th>Situation Task</th><th>Action</th><th>Result</th></tr></thead><tbody><tr><td>a</td><td>b</td><td>c</td></tr></tbody>'); ``` There is an error due to "class" being a reserved word in JavaScript. Doh! Let this be a lesson to those who don't supply their **actual** code!
130,877
<p>What function will let us know whether a date in VBA is in DST or not?</p>
[ { "answer_id": 130879, "author": "Lance Roberts", "author_id": 13295, "author_profile": "https://Stackoverflow.com/users/13295", "pm_score": 4, "selected": true, "text": "<p><b>For non-current dates (DST 2007+):</b></p>\n\n<p>First, you need a function to find the number of specific week...
2008/09/25
[ "https://Stackoverflow.com/questions/130877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13295/" ]
What function will let us know whether a date in VBA is in DST or not?
**For non-current dates (DST 2007+):** First, you need a function to find the number of specific weekdays in a month: ``` Public Function NDow(Y As Integer, M As Integer, _ N As Integer, DOW As Integer) As Date ' Returns Date of Nth Day of the Week in Month NDow = DateSerial(Y, M, (8 - Weekday(DateSerial(Y, M, 1), _ (DOW + 1) Mod 8)) + ((N - 1) * 7)) End Function ``` Then, you can check for the DST day versus the following function calls: Fall: NDow(Year(newdate), 11, 1, 1) Spring: NDow(Year(newdate), 3, 2, 1) **For the current date:** Call the Windows API function GetTimeZoneInformation, and it will return an enum (integer) with the status. I got the code for this from Chip Pearson's great Excel site. [Pearson's site](http://www.cpearson.com/excel/MainPage.aspx)
130,878
<p>What is the benefit of using singleton instead of global for database connections in PHP? I feel using singleton instead of global makes the code unnecessarily complex.</p> <h2>Code with Global</h2> <pre><code>$conn = new PDO(...); function getSomething() { global $conn; . . . } </code></pre> <h2>Code with Singleton</h2> <pre><code>class DB_Instance { private static $db; public static function getDBO() { if (!self::$db) self::$db = new PDO(...); return self::$db; } } function getSomething() { $conn = DB_Instance::getDBO(); . . . } </code></pre> <p>If there's a better way of initializing database connection other than global or singleton, please mention it and describe the advantages it have over global or singleton.</p>
[ { "answer_id": 130889, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "<p>It is quite simple. Never use global OR Singleton.</p>\n" }, { "answer_id": 130900, "author": "Gavin...
2008/09/25
[ "https://Stackoverflow.com/questions/130878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1897/" ]
What is the benefit of using singleton instead of global for database connections in PHP? I feel using singleton instead of global makes the code unnecessarily complex. Code with Global ---------------- ``` $conn = new PDO(...); function getSomething() { global $conn; . . . } ``` Code with Singleton ------------------- ``` class DB_Instance { private static $db; public static function getDBO() { if (!self::$db) self::$db = new PDO(...); return self::$db; } } function getSomething() { $conn = DB_Instance::getDBO(); . . . } ``` If there's a better way of initializing database connection other than global or singleton, please mention it and describe the advantages it have over global or singleton.
I know this is old, but Dr8k's answer was *almost* there. When you are considering writing a piece of code, assume it's going to change. That doesn't mean that you're assuming the kinds of changes it will have hoisted upon it at some point in the future, but rather that some form of change will be made. Make it a goal mitigate the pain of making changes in the future: a global is dangerous because it's hard to manage in a single spot. What if I want to make that database connection context aware in the future? What if I want it to close and reopen itself every 5th time it was used. What if I decide that in the interest of scaling my app I want to use a pool of 10 connections? Or a configurable number of connections? A **singleton factory** gives you that flexibility. I set it up with very little extra complexity and gain more than just access to the same connection; I gain the ability to change how that connection is passed to me later on in a simple manner. Note that I say *singleton factory* as opposed to simply *singleton*. There's precious little difference between a singleton and a global, true. And because of that, there's no reason to have a singleton connection: why would you spend the time setting that up when you could create a regular global instead? What a factory gets you is a why to get connections, and a separate spot to decide what connections (or connection) you're going to get. Example ------- ``` class ConnectionFactory { private static $factory; private $db; public static function getFactory() { if (!self::$factory) self::$factory = new ConnectionFactory(...); return self::$factory; } public function getConnection() { if (!$this->db) $this->db = new PDO(...); return $this->db; } } function getSomething() { $conn = ConnectionFactory::getFactory()->getConnection(); . . . } ``` Then, in 6 months when your app is super famous and getting dugg and slashdotted and you decide you need more than a single connection, all you have to do is implement some pooling in the getConnection() method. Or if you decide that you want a wrapper that implements SQL logging, you can pass a PDO subclass. Or if you decide you want a new connection on every invocation, you can do do that. It's flexible, instead of rigid. 16 lines of code, including braces, which will save you hours and hours and hours of refactoring to something eerily similar down the line. Note that I don't consider this "Feature Creep" because I'm not doing any feature implementation in the first go round. It's border line "Future Creep", but at some point, the idea that "coding for tomorrow today" is *always* a bad thing doesn't jive for me.
130,894
<p>I have the source of a program (taken from cvs/svn/git/...) and I'd like to build a Debian/Ubuntu package for it. The package is present in the repositories, but:</p> <ul> <li>It is an older version (lacking features I need)</li> <li>I need slightly different compile options than the default.</li> </ul> <p>What is the easiest way of doing it? I am concerned about a couple of things</p> <ul> <li>How can I check if I have listed all the dependencies correctly? (I can get some hints by looking on what the older version depended, but new dependencies may have been added.)</li> <li>How I can I prevent the update system installing the older version in the repo on an update?</li> <li>How I can prevent the system installing a newer version (when its out), overwriting my custom package?</li> </ul>
[ { "answer_id": 130908, "author": "Bernard", "author_id": 61, "author_profile": "https://Stackoverflow.com/users/61", "pm_score": 2, "selected": false, "text": "<p>I believe <a href=\"http://www.debian.org/doc/maint-guide/\" rel=\"nofollow noreferrer\">this</a> is the Debian package 'bibl...
2008/09/25
[ "https://Stackoverflow.com/questions/130894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19922/" ]
I have the source of a program (taken from cvs/svn/git/...) and I'd like to build a Debian/Ubuntu package for it. The package is present in the repositories, but: * It is an older version (lacking features I need) * I need slightly different compile options than the default. What is the easiest way of doing it? I am concerned about a couple of things * How can I check if I have listed all the dependencies correctly? (I can get some hints by looking on what the older version depended, but new dependencies may have been added.) * How I can I prevent the update system installing the older version in the repo on an update? * How I can prevent the system installing a newer version (when its out), overwriting my custom package?
you can use the special package "checkinstall" for all packages which are not even in debian/ubuntu yet. You can use "uupdate" (`apt-get install devscripts`) to build a package from source with existing debian sources: Example for libdrm2: ``` apt-get build-dep libdrm2 apt-get source libdrm2 cd libdrm-2.3.1 uupdate ~/Downloads/libdrm-2.4.1.tar.gz cd ../libdrm-2.4.1 dpkg-buildpackage -us -uc -nc ```
130,898
<p>How can I perform list comprehensions in C#?</p>
[ { "answer_id": 130915, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": -1, "selected": false, "text": "<p>While this isn't a tutorial, here's some code that illustrates the concept:</p>\n\n<pre><code>public List&lt;string&gt; ...
2008/09/25
[ "https://Stackoverflow.com/questions/130898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21944/" ]
How can I perform list comprehensions in C#?
Found this when I was looking up how to do list comprehensions in C#... When someone says list comprehensions I immediately think about Python. The below code generates a list that looks like this: ``` [0,2,4,6,8,10,12,14,16,18] ``` The Python way is like this: ``` list = [2*number for number in range(0,10)] ``` In C#: ``` var list2 = from number in Enumerable.Range(0, 10) select 2*number; ``` Both methods are lazily evaluated.
130,913
<p>Is it at the state where it is actually useful and can do more than rename classes?</p>
[ { "answer_id": 130926, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 6, "selected": true, "text": "<p>CDT (C/C++ Development Tools - eclipse project) 5.0 has a bunch of new refactorings</p>\n\n<pre><code>* Declare Method\n*...
2008/09/25
[ "https://Stackoverflow.com/questions/130913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13760/" ]
Is it at the state where it is actually useful and can do more than rename classes?
CDT (C/C++ Development Tools - eclipse project) 5.0 has a bunch of new refactorings ``` * Declare Method * Extract Baseclass * Extract Constant * Extract Method * Extract Subclass * Hide Method * Implement Method * Move Field / Method * Replace Number * Separate Class * Generate Getters and Setters ``` There is a CDT refactoring [wiki](http://r2.ifs.hsr.ch/cdtrefactoring)
130,916
<p>I need to keep as much as I can of large file in the operating system block cache even though it's bigger than I can fit in ram, and I'm continously reading another very very large file. ATM I'll remove large chunk of large important file from system cache when I stream read form another file.</p>
[ { "answer_id": 130955, "author": "William Hutchen", "author_id": 21944, "author_profile": "https://Stackoverflow.com/users/21944", "pm_score": 1, "selected": false, "text": "<p>Some operating systems have ramdisks that you can use to set aside a segment of ram for storage and then mounti...
2008/09/25
[ "https://Stackoverflow.com/questions/130916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15307/" ]
I need to keep as much as I can of large file in the operating system block cache even though it's bigger than I can fit in ram, and I'm continously reading another very very large file. ATM I'll remove large chunk of large important file from system cache when I stream read form another file.
In a POSIX system like Linux or Solaris, try using posix\_fadvise. On the streaming file, do something like this: ``` posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL); while( bytes > 0 ) { bytes = pread(fd, buffer, 64 * 1024, current_pos); current_pos += 64 * 1024; posix_fadvise(fd, 0, current_pos, POSIX_FADV_DONTNEED); } ``` And you can apply POSIX\_FADV\_WILLNEED to your other file, which should raise its memory priority. Now, I know that Windows Vista and Server 2008 can also do nifty tricks with memory priorities. Probably older versions like XP can do more basic tricks as well. But I don't know the functions off the top of my head and don't have time to look them up.
130,941
<p>In a VB.Net Windows Service I'm currently pooling units of work with: </p> <pre><code>ThreadPool.QueueUserWorkItem(operation, nextQueueID) </code></pre> <p>In each unit of work (or thread I'll use for ease of understanding), it will make a couple MSSQL operations like so: </p> <pre><code> Using sqlcmd As New SqlCommand("", New SqlConnection(ConnString)) With sqlcmd .CommandType = CommandType.Text .CommandText = "UPDATE [some table]" .Parameters.Add("@ID", SqlDbType.Int).Value = msgID .Connection.Open() .ExecuteNonQuery() .Connection.Close() 'Found connections not closed quick enough' End With End Using </code></pre> <p>When running a <code>netstat -a -o</code> on the server I'm seeing about 50 connections to SQL server sitting on <code>IDLE</code> or <code>ESTABLISHED</code>, this seems excessive to me especially since we have much larger Web Applications that get by with 5-10 connections. </p> <p>The connection string is global to the application (doesn't change), and has <code>Pooling=true</code> defined as well. </p> <p>Now will each of these threads have their own <code>ConnectionPool</code>, or is there one <code>ConnectionPool</code> for the entire .EXE process?</p>
[ { "answer_id": 130963, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 3, "selected": true, "text": "<p>From the MS Docs -</p>\n\n<p>\"Connections are pooled per process, per application domain, per connection string and when integr...
2008/09/25
[ "https://Stackoverflow.com/questions/130941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/952/" ]
In a VB.Net Windows Service I'm currently pooling units of work with: ``` ThreadPool.QueueUserWorkItem(operation, nextQueueID) ``` In each unit of work (or thread I'll use for ease of understanding), it will make a couple MSSQL operations like so: ``` Using sqlcmd As New SqlCommand("", New SqlConnection(ConnString)) With sqlcmd .CommandType = CommandType.Text .CommandText = "UPDATE [some table]" .Parameters.Add("@ID", SqlDbType.Int).Value = msgID .Connection.Open() .ExecuteNonQuery() .Connection.Close() 'Found connections not closed quick enough' End With End Using ``` When running a `netstat -a -o` on the server I'm seeing about 50 connections to SQL server sitting on `IDLE` or `ESTABLISHED`, this seems excessive to me especially since we have much larger Web Applications that get by with 5-10 connections. The connection string is global to the application (doesn't change), and has `Pooling=true` defined as well. Now will each of these threads have their own `ConnectionPool`, or is there one `ConnectionPool` for the entire .EXE process?
From the MS Docs - "Connections are pooled per process, per application domain, per connection string and when integrated security is used, per Windows identity" <http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx> Are you experiencing errors such as - *Exception Details: System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.* Also how many work items are being queued in the service?
130,948
<p>I need an easy way to take a tar file and convert it into a string (and vice versa). Is there a way to do this in Ruby? My best attempt was this:</p> <pre><code>file = File.open("path-to-file.tar.gz") contents = "" file.each {|line| contents &lt;&lt; line } </code></pre> <p>I thought that would be enough to convert it to a string, but then when I try to write it back out like this...</p> <pre><code>newFile = File.open("test.tar.gz", "w") newFile.write(contents) </code></pre> <p>It isn't the same file. Doing <code>ls -l</code> shows the files are of different sizes, although they are pretty close (and opening the file reveals most of the contents intact). Is there a small mistake I'm making or an entirely different (but workable) way to accomplish this?</p>
[ { "answer_id": 130984, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>You can probably encode the tar file in Base64. Base 64 will give you a pure ASCII representation of the file that you can ...
2008/09/25
[ "https://Stackoverflow.com/questions/130948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
I need an easy way to take a tar file and convert it into a string (and vice versa). Is there a way to do this in Ruby? My best attempt was this: ``` file = File.open("path-to-file.tar.gz") contents = "" file.each {|line| contents << line } ``` I thought that would be enough to convert it to a string, but then when I try to write it back out like this... ``` newFile = File.open("test.tar.gz", "w") newFile.write(contents) ``` It isn't the same file. Doing `ls -l` shows the files are of different sizes, although they are pretty close (and opening the file reveals most of the contents intact). Is there a small mistake I'm making or an entirely different (but workable) way to accomplish this?
First, you should open the file as a binary file. Then you can read the entire file in, in one command. ``` file = File.open("path-to-file.tar.gz", "rb") contents = file.read ``` That will get you the entire file in a string. After that, you probably want to `file.close`. If you don’t do that, `file` won’t be closed until it is garbage-collected, so it would be a slight waste of system resources while it is open.
131,014
<p>I have a table that has redundant data and I'm trying to identify all rows that have duplicate sub-rows (for lack of a better word). By sub-rows I mean considering <code>COL1</code> and <code>COL2</code> only. </p> <p>So let's say I have something like this:</p> <pre><code> COL1 COL2 COL3 --------------------- aa 111 blah_x aa 111 blah_j aa 112 blah_m ab 111 blah_s bb 112 blah_d bb 112 blah_d cc 112 blah_w cc 113 blah_p </code></pre> <p>I need a SQL query that returns this:</p> <pre><code> COL1 COL2 COL3 --------------------- aa 111 blah_x aa 111 blah_j bb 112 blah_d bb 112 blah_d </code></pre>
[ { "answer_id": 131018, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 2, "selected": false, "text": "<p>Join on yourself like this:</p>\n\n<pre><code>SELECT a.col3, b.col3, a.col1, a.col2 \nFROM tablename a, tablename b\nWHER...
2008/09/25
[ "https://Stackoverflow.com/questions/131014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
I have a table that has redundant data and I'm trying to identify all rows that have duplicate sub-rows (for lack of a better word). By sub-rows I mean considering `COL1` and `COL2` only. So let's say I have something like this: ``` COL1 COL2 COL3 --------------------- aa 111 blah_x aa 111 blah_j aa 112 blah_m ab 111 blah_s bb 112 blah_d bb 112 blah_d cc 112 blah_w cc 113 blah_p ``` I need a SQL query that returns this: ``` COL1 COL2 COL3 --------------------- aa 111 blah_x aa 111 blah_j bb 112 blah_d bb 112 blah_d ```
Does this work for you? ``` select t.* from table t left join ( select col1, col2, count(*) as count from table group by col1, col2 ) c on t.col1=c.col1 and t.col2=c.col2 where c.count > 1 ```
131,021
<p>I have a backroundrb scheduled task that takes quite a long time to run. However it seems that the process is ending after only 2.5 minutes.</p> <p>My background.yml file:</p> <pre><code>:schedules: :named_worker: :task_name: :trigger_args: 0 0 12 * * * * :data: input_data </code></pre> <p>I have zero activity on the server when the process is running. (Meaning I am the only one on the server watching the log files do their thing until the process suddenly stops.)</p> <p>Any ideas?</p>
[ { "answer_id": 131779, "author": "Andrew", "author_id": 17408, "author_profile": "https://Stackoverflow.com/users/17408", "pm_score": 3, "selected": true, "text": "<p>There's not much information here that allows us to get to the bottom of the problem.\nBecause backgroundrb operates in t...
2008/09/25
[ "https://Stackoverflow.com/questions/131021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/757/" ]
I have a backroundrb scheduled task that takes quite a long time to run. However it seems that the process is ending after only 2.5 minutes. My background.yml file: ``` :schedules: :named_worker: :task_name: :trigger_args: 0 0 12 * * * * :data: input_data ``` I have zero activity on the server when the process is running. (Meaning I am the only one on the server watching the log files do their thing until the process suddenly stops.) Any ideas?
There's not much information here that allows us to get to the bottom of the problem. Because backgroundrb operates in the background, it can be quite hard to monitor/debug. Here are some ideas I use: 1. Write a unit test to test the worker code itself and make sure there are no problems there 2. Put "puts" statements at multiple points in the code so you can at least see some responses while the worker is running. 3. Wrap the entire worker in a begin..rescue..end block so that you can catch any errors that might be occurring and cutting the process short.
131,040
<p>I am creating a component and want to expose a color property as many flex controls do, lets say I have simple component like this, lets call it foo_label:</p> <pre> <code> &lt;mx:Canvas> &lt;mx:Script> [Bindable] public var color:uint; &lt;/mx:Script> &lt;mx:Label text="foobar" color="{color}" /> &lt;/mx:Canvas> </code> </pre> <p>and then add the component in another mxml file, something along the lines of:</p> <pre> <code> &lt;foo:foo_label color="red" /> </code> </pre> <p>When I compile the compiler complains: cannot parse value of type uint from text 'red'. However if I use a plain label I can do</p> <pre><code>&lt;mx:Label text="foobar" color="red"></code></pre> <p>without any problems, and the color property is still type uint. </p> <p>My question is how can I expose a public property so that I can control the color of my components text? Why can I use the string "red" as a uint field for the mx controls but cannot seem to do the same in a custom component, do I need to do something special?</p> <p>Thanks.</p>
[ { "answer_id": 132076, "author": "Borek Bernard", "author_id": 21728, "author_profile": "https://Stackoverflow.com/users/21728", "pm_score": 4, "selected": true, "text": "<p>Color is not a property, it is a style. You need to define the style like this:</p>\n\n<pre><code>[Style(name=\"la...
2008/09/25
[ "https://Stackoverflow.com/questions/131040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
I am creating a component and want to expose a color property as many flex controls do, lets say I have simple component like this, lets call it foo\_label: ``` <mx:Canvas> <mx:Script> [Bindable] public var color:uint; </mx:Script> <mx:Label text="foobar" color="{color}" /> </mx:Canvas> ``` and then add the component in another mxml file, something along the lines of: ``` <foo:foo_label color="red" /> ``` When I compile the compiler complains: cannot parse value of type uint from text 'red'. However if I use a plain label I can do ``` <mx:Label text="foobar" color="red"> ``` without any problems, and the color property is still type uint. My question is how can I expose a public property so that I can control the color of my components text? Why can I use the string "red" as a uint field for the mx controls but cannot seem to do the same in a custom component, do I need to do something special? Thanks.
Color is not a property, it is a style. You need to define the style like this: ``` [Style(name="labelColor", type="uint", format="Color" )] ``` (enclose it in tag if you define it directly in MXML). You then need to add some ActionScript to handle this style and apply it to whichever control you need, please refer to <http://livedocs.adobe.com/flex/3/html/help.html?content=skinstyle_1.html> for more information.
131,049
<p>I installed mediawiki on my server as my personal knowledge base. Sometimes I copy some stuff from Web and paste to my wiki - such as tips &amp; tricks from somebody's blog. How do I make the copied content appear in a box with border?</p> <p>For example, the box at the end of this blog post looks pretty nice:<br> <a href="http://blog.dreamhost.com/2008/03/21/good-reminiscing-friday/" rel="noreferrer">http://blog.dreamhost.com/2008/03/21/good-reminiscing-friday/</a></p> <p>I could use the pre tag, but paragraphs in a pre tag won't wrap automatically.. Any ideas?</p>
[ { "answer_id": 131330, "author": "Steve K", "author_id": 739, "author_profile": "https://Stackoverflow.com/users/739", "pm_score": 2, "selected": false, "text": "<p>Mediawiki supports the div tag. Combine the div tag with some styles:</p>\n\n<pre><code>&lt;div style=\"background-color: ...
2008/09/25
[ "https://Stackoverflow.com/questions/131049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14068/" ]
I installed mediawiki on my server as my personal knowledge base. Sometimes I copy some stuff from Web and paste to my wiki - such as tips & tricks from somebody's blog. How do I make the copied content appear in a box with border? For example, the box at the end of this blog post looks pretty nice: <http://blog.dreamhost.com/2008/03/21/good-reminiscing-friday/> I could use the pre tag, but paragraphs in a pre tag won't wrap automatically.. Any ideas?
``` <blockquote style="background-color: lightgrey; border: solid thin grey;"> Det er jeg som kjenner hemmeligheten din. Ikke et pip, gutten min. </blockquote> ``` The blockquotes are better than divs because they "explain" that the text is actually a blockqoute, and not "just-some-text". Also a blockquote will most likely be properly indented, and actually look like a blockqoute.
131,050
<p>Since AS3 does not allow private constructors, it seems the only way to construct a singleton and guarantee the constructor isn't explicitly created via "new" is to pass a single parameter and check it.</p> <p>I've heard two recommendations, one is to check the caller and ensure it's the static getInstance(), and the other is to have a private/internal class in the same package namespace.</p> <p>The private object passed on the constructor seems preferable but it does not look like you can have a private class in the same package. Is this true? And more importantly is it the best way to implement a singleton?</p>
[ { "answer_id": 131294, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": 0, "selected": false, "text": "<p>The pattern which is used by Cairngorm (which may not be the best) is to throw a runtime exception in the constructor...
2008/09/25
[ "https://Stackoverflow.com/questions/131050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14747/" ]
Since AS3 does not allow private constructors, it seems the only way to construct a singleton and guarantee the constructor isn't explicitly created via "new" is to pass a single parameter and check it. I've heard two recommendations, one is to check the caller and ensure it's the static getInstance(), and the other is to have a private/internal class in the same package namespace. The private object passed on the constructor seems preferable but it does not look like you can have a private class in the same package. Is this true? And more importantly is it the best way to implement a singleton?
A slight adaptation of enobrev's answer is to have instance as a getter. Some would say this is more elegant. Also, enobrev's answer won't enforce a Singleton if you call the constructor before calling getInstance. This may not be perfect, but I have tested this and it works. (There is definitely another good way to do this in the book "Advanced ActionScrpt3 with Design Patterns" too). ``` package { public class Singleton { private static var _instance:Singleton; public function Singleton(enforcer:SingletonEnforcer) { if( !enforcer) { throw new Error( "Singleton and can only be accessed through Singleton.getInstance()" ); } } public static function get instance():Singleton { if(!Singleton._instance) { Singleton._instance = new Singleton(new SingletonEnforcer()); } return Singleton._instance; } } } class SingletonEnforcer{} ```
131,053
<p>I have been getting an error in <strong>VB .Net</strong> </p> <blockquote> <p>object reference not set to an instance of object.</p> </blockquote> <p>Can you tell me what are the causes of this error ?</p>
[ { "answer_id": 131055, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 3, "selected": false, "text": "<p>The object has not been initialized before use.</p>\n\n<p>At the top of your code file type:</p>\n\n<pre><code>Option St...
2008/09/25
[ "https://Stackoverflow.com/questions/131053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21963/" ]
I have been getting an error in **VB .Net** > > object reference not set to an instance of object. > > > Can you tell me what are the causes of this error ?
sef, If the problem is with Database return results, I presume it is in this scenario: ``` dsData = getSQLData(conn,sql, blah,blah....) dt = dsData.Tables(0) 'Perhaps the obj ref not set is occurring here ``` To fix that: ``` dsData = getSQLData(conn,sql, blah,blah....) If dsData.Tables.Count = 0 Then Exit Sub dt = dsData.Tables(0) 'Perhaps the obj ref not set is occurring here ``` **edit**: added code formatting tags ...
131,056
<p>Not sure how to ask a followup on SO, but this is in reference to an earlier question: <a href="https://stackoverflow.com/questions/94930/fetch-one-row-per-account-id-from-list">Fetch one row per account id from list</a></p> <p>The query I'm working with is:</p> <pre><code>SELECT * FROM scores s1 WHERE accountid NOT IN (SELECT accountid FROM scores s2 WHERE s1.score &lt; s2.score) ORDER BY score DESC </code></pre> <p>This selects the top scores, and limits results to one row per accountid; their top score.</p> <p>The last hurdle is that this query is returning multiple rows for accountids that have multiple occurrences of their top score. So if accountid 17 has scores of 40, 75, 30, 75 the query returns both rows with scores of 75.</p> <p>Can anyone modify this query (or provide a better one) to fix this case, and truly limit it to one row per account id?</p> <p>Thanks again!</p>
[ { "answer_id": 131060, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 0, "selected": false, "text": "<p>If you are selecting a subset of columns then you can use the DISTINCT keyword to filter results.</p>\n\n<pre><code>SELECT...
2008/09/25
[ "https://Stackoverflow.com/questions/131056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13636/" ]
Not sure how to ask a followup on SO, but this is in reference to an earlier question: [Fetch one row per account id from list](https://stackoverflow.com/questions/94930/fetch-one-row-per-account-id-from-list) The query I'm working with is: ``` SELECT * FROM scores s1 WHERE accountid NOT IN (SELECT accountid FROM scores s2 WHERE s1.score < s2.score) ORDER BY score DESC ``` This selects the top scores, and limits results to one row per accountid; their top score. The last hurdle is that this query is returning multiple rows for accountids that have multiple occurrences of their top score. So if accountid 17 has scores of 40, 75, 30, 75 the query returns both rows with scores of 75. Can anyone modify this query (or provide a better one) to fix this case, and truly limit it to one row per account id? Thanks again!
If you're only interested in the accountid and the score, then you can use the simple GROUP BY query given by Paul above. ``` SELECT accountid, MAX(score) FROM scores GROUP BY accountid; ``` If you need other attributes from the scores table, then you can get other attributes from the row with a query like the following: ``` SELECT s1.* FROM scores AS s1 LEFT OUTER JOIN scores AS s2 ON (s1.accountid = s2.accountid AND s1.score < s2.score) WHERE s2.accountid IS NULL; ``` But this still gives multiple rows, in your example where a given accountid has two scores matching its maximum value. To further reduce the result set to a single row, for example the row with the latest gamedate, try this: ``` SELECT s1.* FROM scores AS s1 LEFT OUTER JOIN scores AS s2 ON (s1.accountid = s2.accountid AND s1.score < s2.score) LEFT OUTER JOIN scores AS s3 ON (s1.accountid = s3.accountid AND s1.score = s3.score AND s1.gamedate < s3.gamedate) WHERE s2.accountid IS NULL AND s3.accountid IS NULL; ```
131,062
<p>I've read numerous posts about people having problems with <code>viewWillAppear</code> when you do not create your view hierarchy <em>just</em> right. My problem is I can't figure out what that means.</p> <p>If I create a <code>RootViewController</code> and call <code>addSubView</code> on that controller, I would expect the added view(s) to be wired up for <code>viewWillAppear</code> events. </p> <p>Does anyone have an example of a complex programmatic view hierarchy that successfully receives <code>viewWillAppear</code> events at every level?</p> <p>Apple's Docs state:</p> <blockquote> <p>Warning: If the view belonging to a view controller is added to a view hierarchy directly, the view controller will not receive this message. If you insert or add a view to the view hierarchy, and it has a view controller, you should send the associated view controller this message directly. Failing to send the view controller this message will prevent any associated animation from being displayed.</p> </blockquote> <p>The problem is that they don't describe how to do this. What does "directly" mean? How do you "indirectly" add a view?</p> <p>I am fairly new to Cocoa and iPhone so it would be nice if there were useful examples from Apple besides the basic Hello World crap.</p>
[ { "answer_id": 135418, "author": "Josh Gagnon", "author_id": 7944, "author_profile": "https://Stackoverflow.com/users/7944", "pm_score": 3, "selected": false, "text": "<p>I've been using a navigation controller. When I want to either descend to another level of data or show my custom vie...
2008/09/25
[ "https://Stackoverflow.com/questions/131062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21964/" ]
I've read numerous posts about people having problems with `viewWillAppear` when you do not create your view hierarchy *just* right. My problem is I can't figure out what that means. If I create a `RootViewController` and call `addSubView` on that controller, I would expect the added view(s) to be wired up for `viewWillAppear` events. Does anyone have an example of a complex programmatic view hierarchy that successfully receives `viewWillAppear` events at every level? Apple's Docs state: > > Warning: If the view belonging to a view controller is added to a view hierarchy directly, the view controller will not receive this message. If you insert or add a view to the view hierarchy, and it has a view controller, you should send the associated view controller this message directly. Failing to send the view controller this message will prevent any associated animation from being displayed. > > > The problem is that they don't describe how to do this. What does "directly" mean? How do you "indirectly" add a view? I am fairly new to Cocoa and iPhone so it would be nice if there were useful examples from Apple besides the basic Hello World crap.
If you use a navigation controller and set its delegate, then the view{Will,Did}{Appear,Disappear} methods are not invoked. You need to use the navigation controller delegate methods instead: ``` navigationController:willShowViewController:animated: navigationController:didShowViewController:animated: ```
131,116
<p>I'm wondering if updating statistics has helped you before and how did you know to update them?</p>
[ { "answer_id": 131168, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 3, "selected": true, "text": "<pre><code>exec sp_updatestats\n</code></pre>\n\n<p>Yes, updating statistics can be very helpful if you find that your ...
2008/09/25
[ "https://Stackoverflow.com/questions/131116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12261/" ]
I'm wondering if updating statistics has helped you before and how did you know to update them?
``` exec sp_updatestats ``` Yes, updating statistics can be very helpful if you find that your queries are not performing as well as they should. This is evidenced by inspecting the query plan and noticing when, for example, table scans or index scans are being performed instead of index seeks. All of this assumes that you have set up your indexes correctly. There is also the [UPDATE STATISTICS](http://doc.ddart.net/mssql/sql70/ua-uz_4.htm) command, but I've personally never used that.
131,121
<p>If I have a Range object--for example, let's say it refers to cell <code>A1</code> on a worksheet called <code>Book1</code>. So I know that calling <code>Address()</code> will get me a simple local reference: <code>$A$1</code>. I know it can also be called as <code>Address(External:=True)</code> to get a reference including the workbook name and worksheet name: <code>[Book1]Sheet1!$A$1</code>.</p> <p>What I want is to get an address including the sheet name, but not the book name. I really don't want to call <code>Address(External:=True)</code> and try to strip out the workbook name myself with string functions. Is there any call I can make on the range to get <code>Sheet1!$A$1</code>?</p>
[ { "answer_id": 131155, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 7, "selected": true, "text": "<p>Only way I can think of is to concatenate the worksheet name with the cell reference, as follows:</p>\n\n<pre><code>...
2008/09/25
[ "https://Stackoverflow.com/questions/131121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6209/" ]
If I have a Range object--for example, let's say it refers to cell `A1` on a worksheet called `Book1`. So I know that calling `Address()` will get me a simple local reference: `$A$1`. I know it can also be called as `Address(External:=True)` to get a reference including the workbook name and worksheet name: `[Book1]Sheet1!$A$1`. What I want is to get an address including the sheet name, but not the book name. I really don't want to call `Address(External:=True)` and try to strip out the workbook name myself with string functions. Is there any call I can make on the range to get `Sheet1!$A$1`?
Only way I can think of is to concatenate the worksheet name with the cell reference, as follows: ``` Dim cell As Range Dim cellAddress As String Set cell = ThisWorkbook.Worksheets(1).Cells(1, 1) cellAddress = cell.Parent.Name & "!" & cell.Address(External:=False) ``` EDIT: Modify last line to : ``` cellAddress = "'" & cell.Parent.Name & "'!" & cell.Address(External:=False) ``` if you want it to work even if there are spaces or other funny characters in the sheet name.
131,128
<p>Short version: I'm wondering if it's possible, and how best, to utilise CPU specific instructions within a DLL?</p> <p>Slightly longer version: When downloading (32bit) DLLs from, say, Microsoft it seems that one size fits all processors.</p> <p>Does this mean that they are strictly built for the lowest common denominator (ie. the minimum platform supported by the OS)? Or is there some technique that is used to export a single interface within the DLL but utilise CPU specific code behind the scenes to get optimal performance? And if so, how is it done?</p>
[ { "answer_id": 131199, "author": "ypnos", "author_id": 21974, "author_profile": "https://Stackoverflow.com/users/21974", "pm_score": 2, "selected": false, "text": "<p>The DLL is expected to work on every computer WIN32 runs on, so you are stuck to the i386 instruction set in general. The...
2008/09/25
[ "https://Stackoverflow.com/questions/131128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11694/" ]
Short version: I'm wondering if it's possible, and how best, to utilise CPU specific instructions within a DLL? Slightly longer version: When downloading (32bit) DLLs from, say, Microsoft it seems that one size fits all processors. Does this mean that they are strictly built for the lowest common denominator (ie. the minimum platform supported by the OS)? Or is there some technique that is used to export a single interface within the DLL but utilise CPU specific code behind the scenes to get optimal performance? And if so, how is it done?
I don't know of any *standard* technique but if I had to make such a thing, I would write some code in the DllMain() function to detect the CPU type and populate a jump table with function pointers to CPU-optimized versions of each function. There would also need to be a lowest common denominator function for when the CPU type is unknown. You can find current CPU info in the registry here: ``` HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor ```
131,164
<p>I have a number of code value tables that contain a code and a description with a Long id.</p> <p>I now want to create an entry for an Account Type that references a number of codes, so I have something like this:</p> <pre><code>insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id) ( select account_type_standard_seq.nextval, ts.tax_status_id, r.recipient_id from tax_status ts, recipient r where ts.tax_status_code = ? and r.recipient_code = ?) </code></pre> <p>This retrieves the appropriate values from the tax_status and recipient tables if a match is found for their respective codes. Unfortunately, recipient_code is nullable, and therefore the ? substitution value could be null. Of course, the implicit join doesn't return a row, so a row doesn't get inserted into my table.</p> <p>I've tried using NVL on the ? and on the r.recipient_id. </p> <p>I've tried to force an outer join on the r.recipient_code = ? by adding (+), but it's not an explicit join, so Oracle still didn't add another row.</p> <p>Anyone know of a way of doing this?</p> <p>I can obviously modify the statement so that I do the lookup of the recipient_id externally, and have a ? instead of r.recipient_id, and don't select from the recipient table at all, but I'd prefer to do all this in 1 SQL statement.</p>
[ { "answer_id": 131183, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 6, "selected": true, "text": "<p>Outter joins don't work \"as expected\" in that case because you have explicitly told Oracle you only want data if that c...
2008/09/25
[ "https://Stackoverflow.com/questions/131164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5382/" ]
I have a number of code value tables that contain a code and a description with a Long id. I now want to create an entry for an Account Type that references a number of codes, so I have something like this: ``` insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id) ( select account_type_standard_seq.nextval, ts.tax_status_id, r.recipient_id from tax_status ts, recipient r where ts.tax_status_code = ? and r.recipient_code = ?) ``` This retrieves the appropriate values from the tax\_status and recipient tables if a match is found for their respective codes. Unfortunately, recipient\_code is nullable, and therefore the ? substitution value could be null. Of course, the implicit join doesn't return a row, so a row doesn't get inserted into my table. I've tried using NVL on the ? and on the r.recipient\_id. I've tried to force an outer join on the r.recipient\_code = ? by adding (+), but it's not an explicit join, so Oracle still didn't add another row. Anyone know of a way of doing this? I can obviously modify the statement so that I do the lookup of the recipient\_id externally, and have a ? instead of r.recipient\_id, and don't select from the recipient table at all, but I'd prefer to do all this in 1 SQL statement.
Outter joins don't work "as expected" in that case because you have explicitly told Oracle you only want data if that criteria on that table matches. In that scenario, the outter join is rendered useless. A work-around ``` INSERT INTO account_type_standard (account_type_Standard_id, tax_status_id, recipient_id) VALUES( (SELECT account_type_standard_seq.nextval FROM DUAL), (SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?), (SELECT recipient_id FROM recipient WHERE recipient_code = ?) ) ``` [Edit] If you expect multiple rows from a sub-select, you can add ROWNUM=1 to each where clause OR use an aggregate such as MAX or MIN. This of course may not be the best solution for all cases. [Edit] Per comment, ``` (SELECT account_type_standard_seq.nextval FROM DUAL), ``` can be just ``` account_type_standard_seq.nextval, ```
131,179
<p>Trying to install the RMagick gem is failing with an error about being unable to find ImageMagick libraries, even though I'm sure they are installed.</p> <p>The pertinent output from gem install rmagick is:</p> <pre><code>checking for InitializeMagick() in -lMagick... no checking for InitializeMagick() in -lMagickCore... no checking for InitializeMagick() in -lMagick++... no Can't install RMagick 2.6.0. Can't find the ImageMagick library or one of the dependent libraries. Check the mkmf.log file for more detailed information. *** extconf.rb failed *** </code></pre> <p>And looking in mkmf.log reveals:</p> <pre><code>have_library: checking for InitializeMagick() in -lMagick... -------------------- no "/usr/local/bin/gcc -o conftest -I. -I/usr/local/lib/ruby/1.8/i386-solaris2.10 -I. -I/usr/local/include/ImageMagick -I/usr/local/include/ImageMagick conftest.c -L. - L/usr/local/lib -Wl,-R/usr/local/lib -L/usr/local/lib -L/usr/local/lib -R/usr/local/lib -lfreetype -lz -L/usr/local/lib -L/usr/local/lib -lMagickCore -lruby-static - lMagick -ldl -lcrypt -lm -lc" ld: fatal: library -lMagick: not found ld: fatal: File processing errors. No output written to conftest </code></pre> <p>This is on Solaris 10 x86 with ImageMagick version 6.4.3 and RMagick version 2.6.0</p> <p>If I need to add something to LDFLAGS, its not clear to me what that would be. I installed ImageMagick from source and it should be in the usual places. ie,</p> <pre><code># ls -l /usr/local/lib/ | grep -i magick drwxr-xr-x 5 root root 512 Sep 24 23:09 ImageMagick-6.4.3/ -rw-r--r-- 1 root root 10808764 Sep 25 02:09 libMagickCore.a -rwxr-xr-x 1 root root 1440 Sep 25 02:09 libMagickCore.la* -rw-r--r-- 1 root root 2327072 Sep 25 02:09 libMagickWand.a -rwxr-xr-x 1 root root 1472 Sep 25 02:09 libMagickWand.la* </code></pre> <p>ImageMagick-6.4.3/ contains nothing interesting and I can't find any other files that I might be able to point gem install at.</p> <p>Any advice would be much appreciated!! googling hasn't been too helpful.</p> <p>thanks -</p>
[ { "answer_id": 131194, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "<p>The linker cannot find libMagick in the standard places. Maybe you installed ImageMagick in a non standard place ...
2008/09/25
[ "https://Stackoverflow.com/questions/131179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8063/" ]
Trying to install the RMagick gem is failing with an error about being unable to find ImageMagick libraries, even though I'm sure they are installed. The pertinent output from gem install rmagick is: ``` checking for InitializeMagick() in -lMagick... no checking for InitializeMagick() in -lMagickCore... no checking for InitializeMagick() in -lMagick++... no Can't install RMagick 2.6.0. Can't find the ImageMagick library or one of the dependent libraries. Check the mkmf.log file for more detailed information. *** extconf.rb failed *** ``` And looking in mkmf.log reveals: ``` have_library: checking for InitializeMagick() in -lMagick... -------------------- no "/usr/local/bin/gcc -o conftest -I. -I/usr/local/lib/ruby/1.8/i386-solaris2.10 -I. -I/usr/local/include/ImageMagick -I/usr/local/include/ImageMagick conftest.c -L. - L/usr/local/lib -Wl,-R/usr/local/lib -L/usr/local/lib -L/usr/local/lib -R/usr/local/lib -lfreetype -lz -L/usr/local/lib -L/usr/local/lib -lMagickCore -lruby-static - lMagick -ldl -lcrypt -lm -lc" ld: fatal: library -lMagick: not found ld: fatal: File processing errors. No output written to conftest ``` This is on Solaris 10 x86 with ImageMagick version 6.4.3 and RMagick version 2.6.0 If I need to add something to LDFLAGS, its not clear to me what that would be. I installed ImageMagick from source and it should be in the usual places. ie, ``` # ls -l /usr/local/lib/ | grep -i magick drwxr-xr-x 5 root root 512 Sep 24 23:09 ImageMagick-6.4.3/ -rw-r--r-- 1 root root 10808764 Sep 25 02:09 libMagickCore.a -rwxr-xr-x 1 root root 1440 Sep 25 02:09 libMagickCore.la* -rw-r--r-- 1 root root 2327072 Sep 25 02:09 libMagickWand.a -rwxr-xr-x 1 root root 1472 Sep 25 02:09 libMagickWand.la* ``` ImageMagick-6.4.3/ contains nothing interesting and I can't find any other files that I might be able to point gem install at. Any advice would be much appreciated!! googling hasn't been too helpful. thanks -
problem solved. RMagick was unable to find ImageMagick because I neglected to build the shared objects (there were no .so files installed as you can see from the "ls" in the original question). The solution was to add `--with-shared` to my configure options. This however caused other problems. Most notably, `make` failing with "undefined symbol" messages for libiconv. This was solved by setting CFLAGS to point to libiconv: ``` export CFLAGS="-liconv" ``` Ultimately, my successful configure command was: ``` ./configure --disable-static --with-modules --without-perl --with-quantum-depth=8 --with-bzlib=no --with-libiconv ``` and after that, `make`, `make install`, and `gem install rmagick` all worked smoothly. thanks, R
131,217
<p>In one of our application im getting an exception that i can not seem to find or trap. </p> <pre><code>... Application.CreateForm(TFrmMain, FrmMain); outputdebugstring(pansichar('Application Run')); //this is printed Application.Run; outputdebugstring(pansichar('Application Run After')); //this is printed end. &lt;--- The Exception seems to be here </code></pre> <p>The Event log shows</p> <pre><code>&gt; ODS: Application Run &gt; //Various Application Messages &gt; ODS: Application Run After &gt; First Change Exception at $xxxxxxxx. ...etc </code></pre> <p>All i can think of is it is the finalization code of one of the units.</p> <p>(Delphi 7)</p>
[ { "answer_id": 131233, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 4, "selected": true, "text": "<p>Try installing <a href=\"http://www.madshi.net/\" rel=\"noreferrer\">MadExcept</a> - it should catch the exception and gi...
2008/09/25
[ "https://Stackoverflow.com/questions/131217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11016/" ]
In one of our application im getting an exception that i can not seem to find or trap. ``` ... Application.CreateForm(TFrmMain, FrmMain); outputdebugstring(pansichar('Application Run')); //this is printed Application.Run; outputdebugstring(pansichar('Application Run After')); //this is printed end. <--- The Exception seems to be here ``` The Event log shows ``` > ODS: Application Run > //Various Application Messages > ODS: Application Run After > First Change Exception at $xxxxxxxx. ...etc ``` All i can think of is it is the finalization code of one of the units. (Delphi 7)
Try installing [MadExcept](http://www.madshi.net/) - it should catch the exception and give you a stack-trace. It helped me when I had a similar issue.
131,238
<p>In Sharepoint designer's workflow editor I wish to retrieve the username/name of the work flow initiator (i.e. who kicked it off or triggered the workflow) - this is relatively easy to do using 3rd party products such as Nintex Workflow 2007 (where I would use something like {Common:Initiator}) - but I can't seem to find any way out of the box to do this using share point designer and MOSS 2007.</p> <p><strong>Update</strong></p> <p>It does not look like this rather obvious feature is supported OOTB, so I ended up writing a custom activity (as suggested by one of the answers). I have listed the activities code here for reference though I suspect there are probably a few instances of this floating around out there on blogs as it's a pretty trivial solution:</p> <pre><code>public partial class LookupInitiatorInfo : Activity { public static DependencyProperty __ActivationPropertiesProperty = DependencyProperty.Register("__ActivationProperties", typeof(Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties), typeof(LookupInitiatorInfo)); public static DependencyProperty __ContextProperty = DependencyProperty.Register("__Context", typeof (WorkflowContext), typeof (LookupInitiatorInfo)); public static DependencyProperty PropertyValueVariableProperty = DependencyProperty.Register("PropertyValueVariable", typeof (string), typeof(LookupInitiatorInfo)); public static DependencyProperty UserPropertyProperty = DependencyProperty.Register("UserProperty", typeof (string), typeof (LookupInitiatorInfo)); public LookupInitiatorInfo() { InitializeComponent(); } [Description("ActivationProperties")] [ValidationOption(ValidationOption.Required)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties __ActivationProperties { get { return ((Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties)(base.GetValue(__ActivationPropertiesProperty))); } set { base.SetValue(__ActivationPropertiesProperty, value); } } [Description("Context")] [ValidationOption(ValidationOption.Required)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public WorkflowContext __Context { get { return ((WorkflowContext)(base.GetValue(__ContextProperty))); } set { base.SetValue(__ContextProperty, value); } } [Description("UserProperty")] [ValidationOption(ValidationOption.Required)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public string UserProperty { get { return ((string) (base.GetValue(UserPropertyProperty))); } set { base.SetValue(UserPropertyProperty, value); } } [Description("PropertyValueVariable")] [ValidationOption(ValidationOption.Required)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public string PropertyValueVariable { get { return ((string) (base.GetValue(PropertyValueVariableProperty))); } set { base.SetValue(PropertyValueVariableProperty, value); } } protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { // value values for the UserProperty (in most cases you // would use LoginName or Name) //Sid //ID //LoginName //Name //IsDomainGroup //Email //RawSid //Notes try { string err = string.Empty; if (__ActivationProperties == null) { err = "__ActivationProperties was null"; } else { SPUser user = __ActivationProperties.OriginatorUser; if (user != null &amp;&amp; UserProperty != null) { PropertyInfo property = typeof (SPUser).GetProperty(UserProperty); if (property != null) { object value = property.GetValue(user, null); PropertyValueVariable = (value != null) ? value.ToString() : ""; } else { err = string.Format("no property found with the name \"{0}\"", UserProperty); } } else { err = "__ActivationProperties.OriginatorUser was null"; } } if (!string.IsNullOrEmpty(err)) Common.LogExceptionToWorkflowHistory(new ArgumentOutOfRangeException(err), executionContext, WorkflowInstanceId); } catch (Exception e) { Common.LogExceptionToWorkflowHistory(e, executionContext, WorkflowInstanceId); } return ActivityExecutionStatus.Closed; } } </code></pre> <p>And then wire it up with the following .action xml file:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;WorkflowInfo Language="en-us"&gt; &lt;Actions&gt; &lt;Action Name="Lookup initiator user property" ClassName="XXX.ActivityLibrary.LookupInitiatorInfo" Assembly="XXX.ActivityLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=XXX" AppliesTo="all" Category="WormaldWorkflow Custom Actions"&gt; &lt;RuleDesigner Sentence="Lookup initating users property named %1 and store in %2"&gt; &lt;FieldBind Field="UserProperty" DesignerType="TextArea" Id="1" Text="LoginName" /&gt; &lt;FieldBind Field="PropertyValueVariable" DesignerType="ParameterNames" Text="variable" Id="2"/&gt; &lt;/RuleDesigner&gt; &lt;Parameters&gt; &lt;Parameter Name="__Context" Type="Microsoft.Sharepoint.WorkflowActions.WorkflowContext, Microsoft.SharePoint.WorkflowActions" Direction="In"/&gt; &lt;Parameter Name="__ActivationProperties" Type="Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties, Microsoft.SharePoint" Direction="In"/&gt; &lt;Parameter Name="UserProperty" Type="System.String, mscorlib" Direction="In" /&gt; &lt;Parameter Name="PropertyValueVariable" Type="System.String, mscorlib" Direction="Out" /&gt; &lt;/Parameters&gt; &lt;/Action&gt; &lt;/Actions&gt; &lt;/WorkflowInfo&gt; </code></pre>
[ { "answer_id": 131999, "author": "Bryan Friedman", "author_id": 16985, "author_profile": "https://Stackoverflow.com/users/16985", "pm_score": 3, "selected": true, "text": "<p>I don't think this is possible to do in SharePoint Designer out of the box. You could probably write a custom ac...
2008/09/25
[ "https://Stackoverflow.com/questions/131238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4843/" ]
In Sharepoint designer's workflow editor I wish to retrieve the username/name of the work flow initiator (i.e. who kicked it off or triggered the workflow) - this is relatively easy to do using 3rd party products such as Nintex Workflow 2007 (where I would use something like {Common:Initiator}) - but I can't seem to find any way out of the box to do this using share point designer and MOSS 2007. **Update** It does not look like this rather obvious feature is supported OOTB, so I ended up writing a custom activity (as suggested by one of the answers). I have listed the activities code here for reference though I suspect there are probably a few instances of this floating around out there on blogs as it's a pretty trivial solution: ``` public partial class LookupInitiatorInfo : Activity { public static DependencyProperty __ActivationPropertiesProperty = DependencyProperty.Register("__ActivationProperties", typeof(Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties), typeof(LookupInitiatorInfo)); public static DependencyProperty __ContextProperty = DependencyProperty.Register("__Context", typeof (WorkflowContext), typeof (LookupInitiatorInfo)); public static DependencyProperty PropertyValueVariableProperty = DependencyProperty.Register("PropertyValueVariable", typeof (string), typeof(LookupInitiatorInfo)); public static DependencyProperty UserPropertyProperty = DependencyProperty.Register("UserProperty", typeof (string), typeof (LookupInitiatorInfo)); public LookupInitiatorInfo() { InitializeComponent(); } [Description("ActivationProperties")] [ValidationOption(ValidationOption.Required)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties __ActivationProperties { get { return ((Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties)(base.GetValue(__ActivationPropertiesProperty))); } set { base.SetValue(__ActivationPropertiesProperty, value); } } [Description("Context")] [ValidationOption(ValidationOption.Required)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public WorkflowContext __Context { get { return ((WorkflowContext)(base.GetValue(__ContextProperty))); } set { base.SetValue(__ContextProperty, value); } } [Description("UserProperty")] [ValidationOption(ValidationOption.Required)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public string UserProperty { get { return ((string) (base.GetValue(UserPropertyProperty))); } set { base.SetValue(UserPropertyProperty, value); } } [Description("PropertyValueVariable")] [ValidationOption(ValidationOption.Required)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public string PropertyValueVariable { get { return ((string) (base.GetValue(PropertyValueVariableProperty))); } set { base.SetValue(PropertyValueVariableProperty, value); } } protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { // value values for the UserProperty (in most cases you // would use LoginName or Name) //Sid //ID //LoginName //Name //IsDomainGroup //Email //RawSid //Notes try { string err = string.Empty; if (__ActivationProperties == null) { err = "__ActivationProperties was null"; } else { SPUser user = __ActivationProperties.OriginatorUser; if (user != null && UserProperty != null) { PropertyInfo property = typeof (SPUser).GetProperty(UserProperty); if (property != null) { object value = property.GetValue(user, null); PropertyValueVariable = (value != null) ? value.ToString() : ""; } else { err = string.Format("no property found with the name \"{0}\"", UserProperty); } } else { err = "__ActivationProperties.OriginatorUser was null"; } } if (!string.IsNullOrEmpty(err)) Common.LogExceptionToWorkflowHistory(new ArgumentOutOfRangeException(err), executionContext, WorkflowInstanceId); } catch (Exception e) { Common.LogExceptionToWorkflowHistory(e, executionContext, WorkflowInstanceId); } return ActivityExecutionStatus.Closed; } } ``` And then wire it up with the following .action xml file: ``` <?xml version="1.0" encoding="utf-8"?> <WorkflowInfo Language="en-us"> <Actions> <Action Name="Lookup initiator user property" ClassName="XXX.ActivityLibrary.LookupInitiatorInfo" Assembly="XXX.ActivityLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=XXX" AppliesTo="all" Category="WormaldWorkflow Custom Actions"> <RuleDesigner Sentence="Lookup initating users property named %1 and store in %2"> <FieldBind Field="UserProperty" DesignerType="TextArea" Id="1" Text="LoginName" /> <FieldBind Field="PropertyValueVariable" DesignerType="ParameterNames" Text="variable" Id="2"/> </RuleDesigner> <Parameters> <Parameter Name="__Context" Type="Microsoft.Sharepoint.WorkflowActions.WorkflowContext, Microsoft.SharePoint.WorkflowActions" Direction="In"/> <Parameter Name="__ActivationProperties" Type="Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties, Microsoft.SharePoint" Direction="In"/> <Parameter Name="UserProperty" Type="System.String, mscorlib" Direction="In" /> <Parameter Name="PropertyValueVariable" Type="System.String, mscorlib" Direction="Out" /> </Parameters> </Action> </Actions> </WorkflowInfo> ```
I don't think this is possible to do in SharePoint Designer out of the box. You could probably write a custom action to get the originator, but I don't believe it is exposed through the SPD workflow interface at all. The best you could probably do is get the user who created or modified the item in the list, but this wouldn't handle cases where the workflow was manually run.
131,241
<p>Take the following two lines of code:</p> <pre><code>for (int i = 0; i &lt; some_vector.size(); i++) { //do stuff } </code></pre> <p>And this:</p> <pre><code>for (some_iterator = some_vector.begin(); some_iterator != some_vector.end(); some_iterator++) { //do stuff } </code></pre> <p>I'm told that the second way is preferred. Why exactly is this?</p>
[ { "answer_id": 131253, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 6, "selected": false, "text": "<p>because you are not tying your code to the particular implementation of the some_vector list. if you use array indices, i...
2008/09/25
[ "https://Stackoverflow.com/questions/131241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
Take the following two lines of code: ``` for (int i = 0; i < some_vector.size(); i++) { //do stuff } ``` And this: ``` for (some_iterator = some_vector.begin(); some_iterator != some_vector.end(); some_iterator++) { //do stuff } ``` I'm told that the second way is preferred. Why exactly is this?
The first form is efficient only if vector.size() is a fast operation. This is true for vectors, but not for lists, for example. Also, what are you planning to do within the body of the loop? If you plan on accessing the elements as in ``` T elem = some_vector[i]; ``` then you're making the assumption that the container has `operator[](std::size_t)` defined. Again, this is true for vector but not for other containers. The use of iterators bring you closer to **container independence**. You're not making assumptions about random-access ability or fast `size()` operation, only that the container has iterator capabilities. You could enhance your code further by using standard algorithms. Depending on what it is you're trying to achieve, you may elect to use `std::for_each()`, `std::transform()` and so on. By using a standard algorithm rather than an explicit loop you're avoiding re-inventing the wheel. Your code is likely to be more efficient (given the right algorithm is chosen), correct and reusable.
131,303
<p>How do you measure the memory usage of an application or process in Linux?</p> <p>From the blog article of <em><a href="http://virtualthreads.blogspot.com/2006/02/understanding-memory-usage-on-linux.html" rel="noreferrer">Understanding memory usage on Linux</a></em>, <code>ps</code> is not an accurate tool to use for this intent.</p> <blockquote> <p><strong>Why <code>ps</code> is &quot;wrong&quot;</strong></p> <p>Depending on how you look at it, <code>ps</code> is not reporting the real memory usage of processes. What it is really doing is showing how much real memory each process would take up <strong>if it were the only process running</strong>. Of course, a typical Linux machine has several dozen processes running at any given time, which means that the VSZ and RSS numbers reported by <code>ps</code> are almost definitely <em>wrong</em>.</p> </blockquote> <p><sub>(Note: This question is covered <a href="https://stackoverflow.com/q/63166/15161">here</a> in great detail.)</sub></p>
[ { "answer_id": 131346, "author": "ypnos", "author_id": 21974, "author_profile": "https://Stackoverflow.com/users/21974", "pm_score": 10, "selected": true, "text": "<p>With <code>ps</code> or similar tools you will only get the amount of memory pages allocated by that process. This number...
2008/09/25
[ "https://Stackoverflow.com/questions/131303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16139/" ]
How do you measure the memory usage of an application or process in Linux? From the blog article of *[Understanding memory usage on Linux](http://virtualthreads.blogspot.com/2006/02/understanding-memory-usage-on-linux.html)*, `ps` is not an accurate tool to use for this intent. > > **Why `ps` is "wrong"** > > > Depending on how you look at it, `ps` is not reporting the real memory usage of processes. What it is really doing is showing how much real memory each process would take up **if it were the only process running**. Of course, a typical Linux machine has several dozen processes running at any given time, which means that the VSZ and RSS numbers reported by `ps` are almost definitely *wrong*. > > > (Note: This question is covered [here](https://stackoverflow.com/q/63166/15161) in great detail.)
With `ps` or similar tools you will only get the amount of memory pages allocated by that process. This number is correct, but: * does not reflect the actual amount of memory used by the application, only the amount of memory reserved for it * can be misleading if pages are shared, for example by several threads or by using dynamically linked libraries If you really want to know what amount of memory your application actually uses, you need to run it within a profiler. For example, [Valgrind](https://en.wikipedia.org/wiki/Valgrind) can give you insights about the amount of memory used, and, more importantly, about possible memory leaks in your program. The heap profiler tool of Valgrind is called 'massif': > > Massif is a heap profiler. It performs detailed heap profiling by taking regular snapshots of a program's heap. It produces a graph showing heap usage over time, including information about which parts of the program are responsible for the most memory allocations. The graph is supplemented by a text or HTML file that includes more information for determining where the most memory is being allocated. Massif runs programs about 20x slower than normal. As explained in the [Valgrind documentation](http://valgrind.org/docs/manual/ms-manual.html), you need to run the program through Valgrind: ``` valgrind --tool=massif <executable> <arguments> ``` Massif writes a dump of memory usage snapshots (e.g. `massif.out.12345`). These provide, (1) a timeline of memory usage, (2) for each snapshot, a record of where in your program memory was allocated. A great graphical tool for analyzing these files is [massif-visualizer](https://github.com/KDE/massif-visualizer). But I found `ms_print`, a simple text-based tool shipped with Valgrind, to be of great help already. To find memory leaks, use the (default) `memcheck` tool of valgrind.
131,326
<p>I'm looking for resources that can help me determine which approach to use in creating a 2d data structure with C#.</p>
[ { "answer_id": 131339, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>Do you mean multidimensional array? It's simple:</p>\n\n<pre><code>&lt;type&gt;[,] &lt;name&gt; = new &lt;type&gt;[&lt;first ...
2008/09/25
[ "https://Stackoverflow.com/questions/131326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm looking for resources that can help me determine which approach to use in creating a 2d data structure with C#.
Do you mean multidimensional array? It's simple: ``` <type>[,] <name> = new <type>[<first dimenison>,<second dimension>]; ``` Here is MSDN reference: [Multidimensional Arrays (C#)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays)
131,406
<p>There are several different methods for converting floating point numbers to Integers in JavaScript. My question is what method gives the best performance, is most compatible, or is considered the best practice?</p> <p>Here are a few methods that I know of:</p> <pre><code>var a = 2.5; window.parseInt(a); // 2 Math.floor(a); // 2 a | 0; // 2 </code></pre> <p>I'm sure there are others out there. Suggestions?</p>
[ { "answer_id": 131413, "author": "Jeff Hubbard", "author_id": 8844, "author_profile": "https://Stackoverflow.com/users/8844", "pm_score": -1, "selected": false, "text": "<p>parseInt() is probably the best one. <code>a | 0</code> doesn't do what you really want (it just assigns 0 if a is ...
2008/09/25
[ "https://Stackoverflow.com/questions/131406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10942/" ]
There are several different methods for converting floating point numbers to Integers in JavaScript. My question is what method gives the best performance, is most compatible, or is considered the best practice? Here are a few methods that I know of: ``` var a = 2.5; window.parseInt(a); // 2 Math.floor(a); // 2 a | 0; // 2 ``` I'm sure there are others out there. Suggestions?
According to [**this website**](http://www.jibbering.com/faq/faq_notes/type_convert.html#tcParseIn): > > parseInt is occasionally used as a means of turning a floating point number into an integer. It is very ill suited to that task because if its argument is of numeric type it will first be converted into a string and then parsed as a number... > > > For rounding numbers to integers one of Math.round, Math.ceil and Math.floor are preferable... > > >
131,439
<p>I want a C program to produce a core dump under certain circumstances. This is a program that runs in a production environment and isn't easily stopped and restarted to adjust other kinds of debugging code. Also, since it's in a production environment, I don't want to call abort(). The issues under investigation aren't easily replicated in a non-production environment. What I'd like is for the program, when it detects certain issues, to produce a core dump on its own, preferably with enough information to rename the file, and then continue.</p>
[ { "answer_id": 131461, "author": "Chris", "author_id": 15578, "author_profile": "https://Stackoverflow.com/users/15578", "pm_score": 2, "selected": false, "text": "<p>The source code to produce a core dump is in 'gcore', which is part of the gdb package.</p>\n\n<p>Also, the Sun has <a hr...
2008/09/25
[ "https://Stackoverflow.com/questions/131439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14732/" ]
I want a C program to produce a core dump under certain circumstances. This is a program that runs in a production environment and isn't easily stopped and restarted to adjust other kinds of debugging code. Also, since it's in a production environment, I don't want to call abort(). The issues under investigation aren't easily replicated in a non-production environment. What I'd like is for the program, when it detects certain issues, to produce a core dump on its own, preferably with enough information to rename the file, and then continue.
``` void create_dump(void) { if(!fork()) { // Crash the app in your favorite way here *((void*)0) = 42; } } ``` Fork the process then crash the child - it'll give you a snapshot whenever you want
131,449
<p>I have this code:</p> <pre><code>chars = #some list try: indx = chars.index(chars) except ValueError: #doSomething else: #doSomethingElse </code></pre> <p>I want to be able to do this because I don't like knowfully causing Exceptions:</p> <pre><code>chars = #some list indx = chars.index(chars) if indx == -1: #doSomething else: #doSomethingElse </code></pre> <p>Is there a way I can do this?</p>
[ { "answer_id": 131452, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 3, "selected": false, "text": "<pre><code>if element in mylist:\n index = mylist.index(element)\n # ... do something\nelse:\n # ... do something e...
2008/09/25
[ "https://Stackoverflow.com/questions/131449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
I have this code: ``` chars = #some list try: indx = chars.index(chars) except ValueError: #doSomething else: #doSomethingElse ``` I want to be able to do this because I don't like knowfully causing Exceptions: ``` chars = #some list indx = chars.index(chars) if indx == -1: #doSomething else: #doSomethingElse ``` Is there a way I can do this?
Note that the latter approach is going against the generally accepted "pythonic" philosophy of [EAFP, or "It is Easier to Ask for Forgiveness than Permission."](http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Exceptions), while the former follows it.
131,456
<p>How do I apply the MarshalAsAttribute to the return type of the code below?</p> <pre><code>public ISomething Foo() { return new MyFoo(); } </code></pre>
[ { "answer_id": 131467, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 6, "selected": true, "text": "<p>According to <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute.as...
2008/09/25
[ "https://Stackoverflow.com/questions/131456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21429/" ]
How do I apply the MarshalAsAttribute to the return type of the code below? ``` public ISomething Foo() { return new MyFoo(); } ```
According to <http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute.aspx>: ``` [return: MarshalAs(<your marshal type>)] public ISomething Foo() { return new MyFoo(); } ```
131,473
<p>G'day Stackoverflowers,</p> <p>I'm the author of Perl's <a href="http://search.cpan.org/perldoc?autodie" rel="nofollow noreferrer">autodie</a> pragma, which changes Perl's built-ins to throw exceptions on failure. It's similar to <a href="http://search.cpan.org/perldoc?Fatal" rel="nofollow noreferrer">Fatal</a>, but with lexical scope, an extensible exception model, more intelligent return checking, and much, much nicer error messages. It will be replacing the <code>Fatal</code> module in future releases of Perl (provisionally 5.10.1+), but can currently be downloaded from the CPAN for Perl 5.8.0 and above.</p> <p>The next release of <code>autodie</code> will add special handling for calls to <code>flock</code> with the <code>LOCK_NB</code> (non-blocking) option. While a failed <code>flock</code> call would normally result in an exception under <code>autodie</code>, a failed call to <code>flock</code> using <code>LOCK_NB</code> will merely return false if the returned errno (<code>$!</code>) is <code>EWOULDBLOCK</code>.</p> <p>The reason for this is so people can continue to write code like:</p> <pre><code>use Fcntl qw(:flock); use autodie; # All perl built-ins now succeed or die. open(my $fh, '&lt;', 'some_file.txt'); my $lock = flock($fh, LOCK_EX | LOCK_NB); # Lock the file if we can. if ($lock) { # Opportuntistically do something with the locked file. } </code></pre> <p>In the above code, a lock that fails because someone else has the file locked already (<code>EWOULDBLOCK</code>) is not considered to be a hard error, so autodying <code>flock</code> merely returns a false value. In the situation that we're working with a filesystem that doesn't support file-locks, or a network filesystem and the network just died, then autodying <code>flock</code> generates an appropriate exception when it sees that our errno is not <code>EWOULDBLOCK</code>.</p> <p>This works just fine in my dev version on Unix-flavoured systems, but it fails horribly under Windows. It appears that while Perl under Windows supports the <code>LOCK_NB</code> option, it doesn't define <code>EWOULDBLOCK</code>. Instead, the errno returned is 33 ("Domain error") when blocking would occur.</p> <p>Obviously I can hard-code this as a constant into <code>autodie</code>, but that's not what I want to do here, because it means that I'm screwed if the errno ever changes (or has changed). I would love to compare it to the Windows equivalent of <code>POSIX::EWOULDBLOCK</code>, but I can't for the life of me find where such a thing would be defined. If you can help, let me know.</p> <p>Answers I specifically don't want:</p> <ul> <li>Suggestions to hard-code it as a constant (or worse still, leave a magic number floating about).</li> <li>Not supporting <code>LOCK_NB</code> functionality at all under Windows.</li> <li>Assuming that any failure from a <code>LOCK_NB</code> call to <code>flock</code> should return merely false.</li> <li>Suggestions that I ask on p5p or <a href="http://perlmonks.org/" rel="nofollow noreferrer">perlmonks</a>. I already know about them.</li> <li>An explanation of how <code>flock</code>, or exceptions, or <code>Fatal</code> work. I already know. Intimately.</li> </ul>
[ { "answer_id": 131798, "author": "tye", "author_id": 21496, "author_profile": "https://Stackoverflow.com/users/21496", "pm_score": 5, "selected": true, "text": "<p>Under Win32 \"native\" Perl, note that $^E is more descriptive at 33, \"The process cannot access the file because another p...
2008/09/25
[ "https://Stackoverflow.com/questions/131473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19422/" ]
G'day Stackoverflowers, I'm the author of Perl's [autodie](http://search.cpan.org/perldoc?autodie) pragma, which changes Perl's built-ins to throw exceptions on failure. It's similar to [Fatal](http://search.cpan.org/perldoc?Fatal), but with lexical scope, an extensible exception model, more intelligent return checking, and much, much nicer error messages. It will be replacing the `Fatal` module in future releases of Perl (provisionally 5.10.1+), but can currently be downloaded from the CPAN for Perl 5.8.0 and above. The next release of `autodie` will add special handling for calls to `flock` with the `LOCK_NB` (non-blocking) option. While a failed `flock` call would normally result in an exception under `autodie`, a failed call to `flock` using `LOCK_NB` will merely return false if the returned errno (`$!`) is `EWOULDBLOCK`. The reason for this is so people can continue to write code like: ``` use Fcntl qw(:flock); use autodie; # All perl built-ins now succeed or die. open(my $fh, '<', 'some_file.txt'); my $lock = flock($fh, LOCK_EX | LOCK_NB); # Lock the file if we can. if ($lock) { # Opportuntistically do something with the locked file. } ``` In the above code, a lock that fails because someone else has the file locked already (`EWOULDBLOCK`) is not considered to be a hard error, so autodying `flock` merely returns a false value. In the situation that we're working with a filesystem that doesn't support file-locks, or a network filesystem and the network just died, then autodying `flock` generates an appropriate exception when it sees that our errno is not `EWOULDBLOCK`. This works just fine in my dev version on Unix-flavoured systems, but it fails horribly under Windows. It appears that while Perl under Windows supports the `LOCK_NB` option, it doesn't define `EWOULDBLOCK`. Instead, the errno returned is 33 ("Domain error") when blocking would occur. Obviously I can hard-code this as a constant into `autodie`, but that's not what I want to do here, because it means that I'm screwed if the errno ever changes (or has changed). I would love to compare it to the Windows equivalent of `POSIX::EWOULDBLOCK`, but I can't for the life of me find where such a thing would be defined. If you can help, let me know. Answers I specifically don't want: * Suggestions to hard-code it as a constant (or worse still, leave a magic number floating about). * Not supporting `LOCK_NB` functionality at all under Windows. * Assuming that any failure from a `LOCK_NB` call to `flock` should return merely false. * Suggestions that I ask on p5p or [perlmonks](http://perlmonks.org/). I already know about them. * An explanation of how `flock`, or exceptions, or `Fatal` work. I already know. Intimately.
Under Win32 "native" Perl, note that $^E is more descriptive at 33, "The process cannot access the file because another process locked a portion of the file" which is `ERROR_LOCK_VIOLATION` (available from [Win32::WinError](http://search.cpan.org/dist/Win32-WinError/)).
131,516
<p>I've got a BPG file that I've modified to use as a make file for our company's automated build server. In order to get it to work I had to change </p> <pre> Uses * Uses unit1 in 'unit1.pas' * unit1 unit2 in 'unit2.pas' * unit2 ... * ... </pre> <p>in the DPR file to get it to work without the compiler giving me some guff about unit1.pas not found. This is annoying because I want to use a BPG file to actually see the stuff in my project and every time I add a new unit, it auto-jacks that in 'unitx.pas' into my DPR file.<p></p> <p>I'm running <code>make -f [then some options]</code>, the DPR's that I'm compiling are not in the same directory as the make file, but I'm not certain that this matters. Everything compiles fine as long as the <code>in 'unit1.pas</code> is removed. <p></p>
[ { "answer_id": 131526, "author": "Peter Turner", "author_id": 1765, "author_profile": "https://Stackoverflow.com/users/1765", "pm_score": 1, "selected": false, "text": "<p>Well this work-around worked for me. </p>\n\n<pre>\n//{$define PACKAGE}\n{$ifdef PACKAGE}\n uses \n unit1 in 'unit1...
2008/09/25
[ "https://Stackoverflow.com/questions/131516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765/" ]
I've got a BPG file that I've modified to use as a make file for our company's automated build server. In order to get it to work I had to change ``` Uses * Uses unit1 in 'unit1.pas' * unit1 unit2 in 'unit2.pas' * unit2 ... * ... ``` in the DPR file to get it to work without the compiler giving me some guff about unit1.pas not found. This is annoying because I want to use a BPG file to actually see the stuff in my project and every time I add a new unit, it auto-jacks that in 'unitx.pas' into my DPR file. I'm running `make -f [then some options]`, the DPR's that I'm compiling are not in the same directory as the make file, but I'm not certain that this matters. Everything compiles fine as long as the `in 'unit1.pas` is removed.
It could come from the fact, that the search path in the IDE and the search path of the command line compiler are not the same. If you change the serach path of the command line compiler you might be able to use the exactely same source code as within the IDE. One possibility to configure the search path for the command-line compiler is to do it in a file called dcc32.cfg. Take a look at the help, there is a short description of dcc32.cfg in the IDE-help.
131,518
<p>In my ASP.Net 1.1 application, i've added the following to my Web.Config (within the System.Web tag section):</p> <pre><code>&lt;httpHandlers&gt; &lt;add verb="*" path="*.bcn" type="Internet2008.Beacon.BeaconHandler, Internet2008" /&gt; &lt;/httpHandlers&gt; </code></pre> <p>This works fine, and the HTTPHandler kicks in for files of type .bcn, and does its thing.. however for some reason all ASMX files stop working. Any idea why this would be the case?</p> <p>Cheers Greg</p>
[ { "answer_id": 131531, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": false, "text": "<p>It sounds like it as an inherant &lt;clear /&gt; in it although I don't know if I've seen this behaviour befor...
2008/09/25
[ "https://Stackoverflow.com/questions/131518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21969/" ]
In my ASP.Net 1.1 application, i've added the following to my Web.Config (within the System.Web tag section): ``` <httpHandlers> <add verb="*" path="*.bcn" type="Internet2008.Beacon.BeaconHandler, Internet2008" /> </httpHandlers> ``` This works fine, and the HTTPHandler kicks in for files of type .bcn, and does its thing.. however for some reason all ASMX files stop working. Any idea why this would be the case? Cheers Greg
It sounds like it as an inherant <clear /> in it although I don't know if I've seen this behaviour before, you could just add the general handler back, let me find you the code. ``` <add verb="*" path="*.asmx" type="System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services" validate="false"> ``` I think thats the right element, give it a shot. EDIT: That is odd, I don't have a copy of 2003 on this machine so I can't open a 1.1 but I thought that was the right declaration. You could try adding `validate="false"` into each element and see if that makes a difference.
131,559
<p>Is there a way to search for multiple strings simultaneously in Vim? I recall reading somewhere that it was possible but somehow forgot the technique.</p> <p>So for example, I have a text file and I want to search for "foo" and "bar" simultaneously (not necessarily as a single string, can be in different lines altogether).</p> <p>How do I achieve that?</p>
[ { "answer_id": 131563, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": -1, "selected": false, "text": "<pre><code>/(foo|bar)\n</code></pre>\n" }, { "answer_id": 131572, "author": "ChronoPositron", "author_id"...
2008/09/25
[ "https://Stackoverflow.com/questions/131559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17716/" ]
Is there a way to search for multiple strings simultaneously in Vim? I recall reading somewhere that it was possible but somehow forgot the technique. So for example, I have a text file and I want to search for "foo" and "bar" simultaneously (not necessarily as a single string, can be in different lines altogether). How do I achieve that?
``` /^joe.*fred.*bill/ : find joe AND fred AND Bill (Joe at start of line) /fred\|joe : Search for FRED OR JOE ```
131,605
<p>What version control systems have you used with MS Excel (2003/2007)? What would you recommend and Why? What limitations have you found with your top rated version control system?</p> <p>To put this in perspective, here are a couple of use cases:</p> <ol> <li>version control for VBA modules </li> <li>more than one person is working on a Excel spreadsheet and they may be making changes to the same worksheet, which they want to merge and integrate. This worksheet may have formulae, data, charts etc</li> <li>the users are not too technical and the fewer version control systems used the better</li> <li>Space constraint is a consideration. Ideally only incremental changes are saved rather than the entire Excel spreadsheet. </li> </ol>
[ { "answer_id": 131636, "author": "Dheer", "author_id": 17266, "author_profile": "https://Stackoverflow.com/users/17266", "pm_score": 1, "selected": false, "text": "<p>Use any of the standard version control tools like SVN or CVS. Limitations would depend on whats the objective. Apart fro...
2008/09/25
[ "https://Stackoverflow.com/questions/131605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20879/" ]
What version control systems have you used with MS Excel (2003/2007)? What would you recommend and Why? What limitations have you found with your top rated version control system? To put this in perspective, here are a couple of use cases: 1. version control for VBA modules 2. more than one person is working on a Excel spreadsheet and they may be making changes to the same worksheet, which they want to merge and integrate. This worksheet may have formulae, data, charts etc 3. the users are not too technical and the fewer version control systems used the better 4. Space constraint is a consideration. Ideally only incremental changes are saved rather than the entire Excel spreadsheet.
I've just setup a spreadsheet that uses Bazaar, with manual checkin/out via TortiseBZR. Given that the topic helped me with the save portion, I wanted to post my solution here. *The solution for me was to create a spreadsheet that exports all modules on save, and removes and re-imports the modules on open. Yes, this could be potentially dangerous for converting existing spreadsheets.* This allows me to edit the macros in the modules via **Emacs** (yes, emacs) or natively in Excel, and commit my BZR repository after major changes. Because all the modules are text files, the standard diff-style commands in BZR work for my sources except the Excel file itself. I've setup a directory for my BZR repository, X:\Data\MySheet. In the repo are MySheet.xls and one .vba file for each of my modules (ie: Module1Macros). In my spreadsheet I've added one module that is exempt from the export/import cycle called "VersionControl". Each module to be exported and re-imported must end in "Macros". **Contents of the "VersionControl" module:** ```vb Sub SaveCodeModules() 'This code Exports all VBA modules Dim i%, sName$ With ThisWorkbook.VBProject For i% = 1 To .VBComponents.Count If .VBComponents(i%).CodeModule.CountOfLines > 0 Then sName$ = .VBComponents(i%).CodeModule.Name .VBComponents(i%).Export "X:\Tools\MyExcelMacros\" & sName$ & ".vba" End If Next i End With End Sub Sub ImportCodeModules() With ThisWorkbook.VBProject For i% = 1 To .VBComponents.Count ModuleName = .VBComponents(i%).CodeModule.Name If ModuleName <> "VersionControl" Then If Right(ModuleName, 6) = "Macros" Then .VBComponents.Remove .VBComponents(ModuleName) .VBComponents.Import "X:\Data\MySheet\" & ModuleName & ".vba" End If End If Next i End With End Sub ``` Next, we have to setup event hooks for open / save to run these macros. In the code viewer, right click on "ThisWorkbook" and select "View Code". You may have to pull down the select box at the top of the code window to change from "(General)" view to "Workbook" view. **Contents of "Workbook" view:** ```vb Private Sub Workbook_Open() ImportCodeModules End Sub Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) SaveCodeModules End Sub ``` I'll be settling into this workflow over the next few weeks, and I'll post if I have any problems. Thanks for sharing the VBComponent code!
131,619
<h2>Question</h2> <p>Using XSLT 1.0, given a string with arbitrary characters how can I get back a string that meets the following rules.</p> <ol> <li>First character must be one of these: a-z, A-Z, colon, or underscore</li> <li>All other characters must be any of those above or 0-9, period, or hyphen</li> <li>If any character does not meet the above rules, replace it with an underscore</li> </ol> <h2>Background</h2> <p>In an XSLT I'm translating some attributes into elements, but I need to be sure the attribute doesn't contain any values that can't be used in an element name. I don't care much about the integrity of the attribute being converted to the name as long as it's being converted predictably. I also don't need to compensate for <em>every</em> valid character in an element name (there's a bunch).</p> <p>The problem I was having was with the attributes having spaces coming in, which the translate function can easily convert to underscores:</p> <pre><code>translate(@name,' ','_') </code></pre> <p>But soon after I found some of the attributes using slashes, so I have to add that now too. This will quickly get out of hand. I want to be able to define a whitelist of allowed characters, and replace any non-allowed characters with an underscore, but translate works as by replacing from a blacklist.</p>
[ { "answer_id": 131687, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 1, "selected": false, "text": "<p>As far as Im aware XSLT 1.0 doesnt have a builtin for this. XSLT 2.0 allows you to <a href=\"http://www.xml.com/pub/...
2008/09/25
[ "https://Stackoverflow.com/questions/131619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8507/" ]
Question -------- Using XSLT 1.0, given a string with arbitrary characters how can I get back a string that meets the following rules. 1. First character must be one of these: a-z, A-Z, colon, or underscore 2. All other characters must be any of those above or 0-9, period, or hyphen 3. If any character does not meet the above rules, replace it with an underscore Background ---------- In an XSLT I'm translating some attributes into elements, but I need to be sure the attribute doesn't contain any values that can't be used in an element name. I don't care much about the integrity of the attribute being converted to the name as long as it's being converted predictably. I also don't need to compensate for *every* valid character in an element name (there's a bunch). The problem I was having was with the attributes having spaces coming in, which the translate function can easily convert to underscores: ``` translate(@name,' ','_') ``` But soon after I found some of the attributes using slashes, so I have to add that now too. This will quickly get out of hand. I want to be able to define a whitelist of allowed characters, and replace any non-allowed characters with an underscore, but translate works as by replacing from a blacklist.
You *could* write a recursive template to do this, working through the characters in the string one by one, testing them and changing them if necessary. Something like: ``` <xsl:template name="normalizeName"> <xsl:param name="name" /> <xsl:param name="isFirst" select="true()" /> <xsl:if test="$name != ''"> <xsl:variable name="first" select="substring($name, 1, 1)" /> <xsl:variable name="rest" select="substring($name, 2)" /> <xsl:choose> <xsl:when test="contains('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ:_', $first) or (not($first) and contains('0123456789.-', $first))"> <xsl:value-of select="$first" /> </xsl:when> <xsl:otherwise> <xsl:text>_</xsl:text> </xsl:otherwise> </xsl:choose> <xsl:call-template name="normalizeName"> <xsl:with-param name="name" select="$rest" /> <xsl:with-param name="isFirst" select="false()" /> </xsl:call-template> </xsl:if> </xsl:template> ``` However, there is shorter way of doing this if you're prepared for some hackery. First declare some variables: ``` <xsl:variable name="underscores" select="'_______________________________________________________'" /> <xsl:variable name="initialNameChars" select="'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ:_'" /> <xsl:variable name="nameChars" select="concat($initialNameChars, '0123456789.-')" /> ``` Now the technique is to take the name and identify the characters that *aren't* legal by replacing all the characters in the name that *are* legal with nothing. You can do this with the `translate()` function. Once you've got the set of illegal characters that appear in the string, you can replace them with underscores using the `translate()` function again. Here's the template: ``` <xsl:template name="normalizeName"> <xsl:param name="name" /> <xsl:variable name="first" select="substring($name, 1, 1)" /> <xsl:variable name="rest" select="substring($name, 2)" /> <xsl:variable name="illegalFirst" select="translate($first, $initialNameChars, '')" /> <xsl:variable name="illegalRest" select="translate($rest, $nameChars, '')" /> <xsl:value-of select="concat(translate($first, $illegalFirst, $underscores), translate($rest, $illegalRest, $underscores))" /> </xsl:template> ``` The only thing you have to watch out for is that the string of underscores needs to be long enough to cover all the illegal characters that might appear within a single name. Making it the same length as the longest name you're likely to encounter will do the trick (though probably you could get away with it being a lot shorter). UPDATE: I wanted to add to this answer. In order to generate required length underscore string you can use this template. ``` <!--Generate string with given number of replacement--> <xsl:template name="gen-replacement"> <xsl:param name="n"/> <xsl:if test="$n > 0"> <xsl:call-template name="gen-replacement"> <xsl:with-param name="n" select="$n - 1"/> </xsl:call-template> <xsl:text>_</xsl:text> </xsl:if> </xsl:template> ``` And call it when you need to generate underscores: ``` <xsl:variable name="replacement"><xsl:call-template name="gen-replacement"><xsl:with-param name="n" select="string-length($value)"/></xsl:call-template></xsl:variable> ```
131,653
<p>I know that embedding CSS styles directly into the HTML tags they affect defeats much of the purpose of CSS, but sometimes it's useful for debugging purposes, as in:</p> <pre><code>&lt;p style="font-size: 24px"&gt;asdf&lt;/p&gt; </code></pre> <p>What's the syntax for embedding a rule like:</p> <pre><code>a:hover {text-decoration: underline;} </code></pre> <p>into the style attribute of an A tag? It's obviously not this...</p> <pre><code>&lt;a href="foo" style="text-decoration: underline"&gt;bar&lt;/a&gt; </code></pre> <p>...since that would apply all the time, as opposed to just during hover.</p>
[ { "answer_id": 131660, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 8, "selected": true, "text": "<p>I'm afraid it can't be done, the pseudo-class selectors can't be set in-line, you'll have to do it on the page or on ...
2008/09/25
[ "https://Stackoverflow.com/questions/131653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
I know that embedding CSS styles directly into the HTML tags they affect defeats much of the purpose of CSS, but sometimes it's useful for debugging purposes, as in: ``` <p style="font-size: 24px">asdf</p> ``` What's the syntax for embedding a rule like: ``` a:hover {text-decoration: underline;} ``` into the style attribute of an A tag? It's obviously not this... ``` <a href="foo" style="text-decoration: underline">bar</a> ``` ...since that would apply all the time, as opposed to just during hover.
I'm afraid it can't be done, the pseudo-class selectors can't be set in-line, you'll have to do it on the page or on a stylesheet. I should mention that *technically* you *should* be able to do it [according to the CSS spec](http://www.w3.org/TR/css-style-attr#cascading), but most browsers don't support it **Edit:** I just did a quick test with this: ``` <a href="test.html" style="{color: blue; background: white} :visited {color: green} :hover {background: yellow} :visited:hover {color: purple}">Test</a> ``` And it doesn't work in IE7, IE8 beta 2, Firefox or Chrome. Can anyone else test in any other browsers?
131,704
<p>Eclipse 3.4[.x] - also known as <a href="http://www.eclipse.org/downloads/packages/" rel="noreferrer">Ganymede</a> - comes with this new mechanism of provisioning called <strong>p2</strong>.</p> <p>"Provisioning" is the process allowing to discover and update on demand some parts of an application, as explained in general in this article on the <a href="http://developers.sun.com/mobility/midp/articles/ota" rel="noreferrer">Sun Web site</a>.</p> <p>Eclipse has an extended <a href="http://wiki.eclipse.org/Category:Equinox_p2" rel="noreferrer">wiki section</a> in which p2 details are presented. Specifically, it says in this wiki page that p2 will look for new components However after reading it.</p> <p>I suppose (but you may confirm that point by your own experience), that p2 can function file "file://" protocol, which would allow it to provision with <strong>local</strong> file (either on your computer or on an UNC path '\server\path'), as <a href="http://wiki.eclipse.org/Equinox_p2_PDE_Integration" rel="noreferrer">illustrated here</a>, but also by the files:</p> <ul> <li>[eclipse-SDK-3.4-win32]\eclipse\configuration\.settings\org.eclipse.equinox.p2.artifact.repository.prefs</li> <li>[eclipse-SDK-3.4-win32]\eclipse\configuration\.settings\org.eclipse.equinox.p2.metadata.repository.prefs</li> </ul> <p>p2 mechanism is used to update eclipse itself, through an <a href="http://download.eclipse.org/eclipse/updates/3.4" rel="noreferrer">eclipse 3.4 update site</a>, and reference in those '.prefs' files with line like:</p> <blockquote> <p>repositories/file:_C:_jv_eclipse_eclipse-SDK-3.4-win32_eclipse/url=file:/C:/jv/eclipse/eclipse-SDK-3.4-win32/eclipse/</p> </blockquote> <p>Now, how could I replicate the eclipse components present in that update site into a local directory and reference those components through the mentioned '.prefs' files, <strong>in order to have an upgrade process entirely run locally</strong>, without having to access the web?<br> I suppose that some p2 metadata files present in the distant 'update site' need to be replicated and changed as well.</p> <p>Do you have any thoughts/advice/tips on that ? (i.e. on how to discover and retrieve and update the complete structure needed for a full eclipse installation, in order to run that installation locally)</p>
[ { "answer_id": 182019, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 1, "selected": false, "text": "<p>It seems like you need to have one update work via the web which will mirror (download) what you need. But after...
2008/09/25
[ "https://Stackoverflow.com/questions/131704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6309/" ]
Eclipse 3.4[.x] - also known as [Ganymede](http://www.eclipse.org/downloads/packages/) - comes with this new mechanism of provisioning called **p2**. "Provisioning" is the process allowing to discover and update on demand some parts of an application, as explained in general in this article on the [Sun Web site](http://developers.sun.com/mobility/midp/articles/ota). Eclipse has an extended [wiki section](http://wiki.eclipse.org/Category:Equinox_p2) in which p2 details are presented. Specifically, it says in this wiki page that p2 will look for new components However after reading it. I suppose (but you may confirm that point by your own experience), that p2 can function file "file://" protocol, which would allow it to provision with **local** file (either on your computer or on an UNC path '\server\path'), as [illustrated here](http://wiki.eclipse.org/Equinox_p2_PDE_Integration), but also by the files: * [eclipse-SDK-3.4-win32]\eclipse\configuration\.settings\org.eclipse.equinox.p2.artifact.repository.prefs * [eclipse-SDK-3.4-win32]\eclipse\configuration\.settings\org.eclipse.equinox.p2.metadata.repository.prefs p2 mechanism is used to update eclipse itself, through an [eclipse 3.4 update site](http://download.eclipse.org/eclipse/updates/3.4), and reference in those '.prefs' files with line like: > > repositories/file:\_C:\_jv\_eclipse\_eclipse-SDK-3.4-win32\_eclipse/url=file:/C:/jv/eclipse/eclipse-SDK-3.4-win32/eclipse/ > > > Now, how could I replicate the eclipse components present in that update site into a local directory and reference those components through the mentioned '.prefs' files, **in order to have an upgrade process entirely run locally**, without having to access the web? I suppose that some p2 metadata files present in the distant 'update site' need to be replicated and changed as well. Do you have any thoughts/advice/tips on that ? (i.e. on how to discover and retrieve and update the complete structure needed for a full eclipse installation, in order to run that installation locally)
Yes, you can specify the repository locations if you use the p2.director this for example is a snippet of a script that I use to install eclipse (Ganymede) from a local copy of the Ganymede repository ``` ./eclipse\ -nosplash -consolelog -debug\ -vm "${VM}"\ -application org.eclipse.equinox.p2.director.app.application\ -metadataRepository file:${SHARED_REPOSITORY_DIR}\ -artifactRepository file:${SHARED_REPOSITORY_DIR}\ -installIU "${4-org.eclipse.sdk.ide}"\ -destination "${3}"\ -profile "${1}"\ -profileProperties org.eclipse.update.install.features=true\ -bundlepool ${SHARED_BUNDLEPOOL_DIR}\ -p2.os linux\ -p2.ws gtk\ -p2.arch "${2}"\ \ -vmargs\ -Xms64m -Xmx1024m -XX:MaxPermSize=256m\ -Declipse.p2.data.area=${SHARED_P2_DIR} ``` Here are some links to use the p2 director <http://eclipse.dzone.com/articles/understanding-eclipse-p2-provi> <http://wiki.eclipse.org/Equinox_p2_director_application>
131,718
<p>Is there a simple way to write a common function for each of the <code>CRUD (create, retreive, update, delete)</code> operations in <code>PHP</code> WITHOUT using any framework. For example I wish to have a single create function that takes the table name and field names as parameters and inserts data into a <code>mySQL database</code>. Another requirement is that the function should be able to support joins I.e. it should be able to insert data into multiple tables if required. </p> <p>I know that these tasks could be done by using a framework but because of various reasons - too lengthy to explain here - I cannot use them.</p>
[ { "answer_id": 131727, "author": "unexist", "author_id": 18179, "author_profile": "https://Stackoverflow.com/users/18179", "pm_score": 2, "selected": false, "text": "<p>Without any frameworks includes without any ORMs? Otherwise I would suggest to have a look at <a href=\"http://www.doct...
2008/09/25
[ "https://Stackoverflow.com/questions/131718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22009/" ]
Is there a simple way to write a common function for each of the `CRUD (create, retreive, update, delete)` operations in `PHP` WITHOUT using any framework. For example I wish to have a single create function that takes the table name and field names as parameters and inserts data into a `mySQL database`. Another requirement is that the function should be able to support joins I.e. it should be able to insert data into multiple tables if required. I know that these tasks could be done by using a framework but because of various reasons - too lengthy to explain here - I cannot use them.
I wrote this very thing, it's kind of a polished scaffold. It's basically a class the constructor of which takes the table to be used, an array containing field names and types, and an action. Based on this action the object calls a method on itself. For example: This is the array I pass: ``` $data = array(array('name' => 'id', 'type' => 'hidden') , array('name' => 'student', 'type' => 'text', 'title' => 'Student')); ``` Then I call the constructor: ``` new MyScaffold($table, 'edit', $data, $_GET['id']); ``` In the above case the constructor calls the 'edit' method which presents a form displaying data from the $table, but only fields I set up in my array. The record it uses is determined by the $\_GET method. In this example the 'student' field is presented as a text-box (hence the 'text' type). The 'title' is simply the label used. Being 'hidden' the ID field is not shown for editing but is available to the program for use. If I had passed 'delete' instead of 'edit' it would delete the record from the GET variable. If I passed only a table name it would default to a list of records with buttons for edit, delete, and new. It's just one class that contains all the CRUD with lots of customisability. You can make it as complicated or as simple as you wish. By making it a generic class I can drop it in to any project and just pass instructions, table information and configuration information. I might for one table not want to permit new records from being added through the scaffold, in this case I might set "newbutton" to be false in my parameters array. It's not a framework in the conventional sense. Just a standalone class that handles everything internally. There are some drawbacks to this. The key ones must be that all my tables must have a primary key called 'id', you could get away without this but it would complicate matters. Another being that a large array detailing information about each table to be managed must be prepared, but you need only do this once. For a tutorial on this idea see [here](http://www.shadow-fox.net/site/tutorial/39-Creating-A-Scaffold-like-Class-in-PHP-or-An-Automatic-CMS-For-a-Table)
131,728
<p>I'm using the Telerik RAD Controls RADEditor/WYSIWYG control as part of a Dynamic Data solution.</p> <p>I would like to be able to upload files using the Document Manager of this control.</p> <p>However, these files are larger than whatever the default setting is for maximum upload file size.</p> <p>Can anyone point me in the right direction to fix this?</p> <p><hr> Thanks Yaakov Ellis, see your answer + the answer I linked through a comment for the solution.</p>
[ { "answer_id": 131737, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 3, "selected": true, "text": "<p>The Telerik website has instructions <a href=\"http://www.telerik.com/help/aspnet-ajax/upload_uploadinglargefiles.html\" ...
2008/09/25
[ "https://Stackoverflow.com/questions/131728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
I'm using the Telerik RAD Controls RADEditor/WYSIWYG control as part of a Dynamic Data solution. I would like to be able to upload files using the Document Manager of this control. However, these files are larger than whatever the default setting is for maximum upload file size. Can anyone point me in the right direction to fix this? --- Thanks Yaakov Ellis, see your answer + the answer I linked through a comment for the solution.
The Telerik website has instructions [here](http://www.telerik.com/help/aspnet-ajax/upload_uploadinglargefiles.html). Short version: in Web.config set the maxRequestLength ``` <system.web> <httpRuntime maxRequestLength="102400" executionTimeout= "3600" /> </system.web> ```
131,788
<p>I'm writing a Perl script and I've come to a point where I need to parse a Java source file line by line checking for references to a fully qualified Java class name. I know the class I'm looking for up front; also the fully qualified name of the source file that is being searched (based on its path). </p> <p>For example find all valid references to foo.bar.Baz inside the com/bob/is/YourUncle.java file.</p> <p>At this moment the cases I can think of that it needs to account for are:</p> <ol> <li><p>The file being parsed is in the same package as the search class. </p> <p>find foo.bar.Baz references in foo/bar/Boing.java</p></li> <li><p>It should ignore comments.</p> <pre><code>// this is a comment saying this method returns a foo.bar.Baz or Baz instance // it shouldn't count /* a multiline comment as well this shouldn't count if I put foo.bar.Baz or Baz in here either */ </code></pre></li> <li><p>In-line fully qualified references.</p> <pre><code>foo.bar.Baz fb = new foo.bar.Baz(); </code></pre></li> <li><p>References based off an import statement.</p> <pre><code>import foo.bar.Baz; ... Baz b = new Baz(); </code></pre></li> </ol> <p>What would be the most efficient way to do this in Perl 5.8? Some fancy regex perhaps?</p> <pre><code>open F, $File::Find::name or die; # these three things are already known # $classToFind looking for references of this class # $pkgToFind the package of the class you're finding references of # $currentPkg package name of the file being parsed while(&lt;F&gt;){ # ... do work here } close F; # the results are availble here in some form </code></pre>
[ { "answer_id": 131869, "author": "Paul Wicks", "author_id": 85, "author_profile": "https://Stackoverflow.com/users/85", "pm_score": 3, "selected": false, "text": "<p>A Regex is probably the best solution for this, although I did find the following module in CPAN that you might be able to...
2008/09/25
[ "https://Stackoverflow.com/questions/131788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3636/" ]
I'm writing a Perl script and I've come to a point where I need to parse a Java source file line by line checking for references to a fully qualified Java class name. I know the class I'm looking for up front; also the fully qualified name of the source file that is being searched (based on its path). For example find all valid references to foo.bar.Baz inside the com/bob/is/YourUncle.java file. At this moment the cases I can think of that it needs to account for are: 1. The file being parsed is in the same package as the search class. find foo.bar.Baz references in foo/bar/Boing.java 2. It should ignore comments. ``` // this is a comment saying this method returns a foo.bar.Baz or Baz instance // it shouldn't count /* a multiline comment as well this shouldn't count if I put foo.bar.Baz or Baz in here either */ ``` 3. In-line fully qualified references. ``` foo.bar.Baz fb = new foo.bar.Baz(); ``` 4. References based off an import statement. ``` import foo.bar.Baz; ... Baz b = new Baz(); ``` What would be the most efficient way to do this in Perl 5.8? Some fancy regex perhaps? ``` open F, $File::Find::name or die; # these three things are already known # $classToFind looking for references of this class # $pkgToFind the package of the class you're finding references of # $currentPkg package name of the file being parsed while(<F>){ # ... do work here } close F; # the results are availble here in some form ```
You also need to skip quoted strings (you can't even skip comments correctly if you don't also deal with quoted strings). I'd probably write a fairly simple, efficient, and incomplete tokenizer very similar to the one I wrote in [node 566467](http://perlmonks.org/?node_id=566467). Based on that code I'd probably just dig through the non-comment/non-string chunks looking for `\bimport\b` and `\b\Q$toFind\E\b` matches. Perhaps similar to: ``` if( m[ \G (?: [^'"/]+ | /(?![/*]) )+ ]xgc ) { my $code = substr( $_, $-[0], $+[0] - $-[0] ); my $imported = 0; while( $code =~ /\b(import\s+)?\Q$package\E\b/g ) { if( $1 ) { ... # Found importing of package while( $code =~ /\b\Q$class\E\b/g ) { ... # Found mention of imported class } last; } ... # Found a package reference } } elsif( m[ \G ' (?: [^'\\]+ | \\. )* ' ]xgc || m[ \G " (?: [^"\\]+ | \\. )* " ]xgc ) { # skip quoted strings } elsif( m[\G//.*]g­c ) { # skip C++ comments ```
131,793
<p>I have an old Delphi codebase I have to maintain, lots of DLLs, some older than others. In some of these DLLs there is no version information in the Project Options dialog. The controls for adding a version are greyed out and I can't even add a version number by manually editing the .DOF file. How can I include a version number in these projects?</p>
[ { "answer_id": 131826, "author": "John Ferguson", "author_id": 8312, "author_profile": "https://Stackoverflow.com/users/8312", "pm_score": 4, "selected": true, "text": "<p>Check if the default .RES file exists in the project source location. Delphi includes the version number of the proj...
2008/09/25
[ "https://Stackoverflow.com/questions/131793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8312/" ]
I have an old Delphi codebase I have to maintain, lots of DLLs, some older than others. In some of these DLLs there is no version information in the Project Options dialog. The controls for adding a version are greyed out and I can't even add a version number by manually editing the .DOF file. How can I include a version number in these projects?
Check if the default .RES file exists in the project source location. Delphi includes the version number of the project in a .res file with the same name as the .dpr file. If the .RES file does not exist, the simplest way to recreate it is to add the {$R \*.RES} compiler directive to the .DPR file, immediately after the uses clause. ``` library foolib; uses foo in 'foo.pas', baz in 'baz.pas'; {$R *.RES} exports foofunc name 'foofunc'; end; ``` As soon as you add the {$R \*.RES} compiler directive Delphi will tell you it has recreated the foolib.res resource file.
131,805
<p>What is the SQL command to copy a table from one database to another database? I am using MySQL and I have two databases x and y. Suppose I have a table in x called a and I need to copy that table to y database. Sorry if the question is too novice.</p> <p>Thanks.</p>
[ { "answer_id": 131824, "author": "bzlm", "author_id": 7724, "author_profile": "https://Stackoverflow.com/users/7724", "pm_score": 1, "selected": false, "text": "<p>If you just want to copy the contents, you might be looking for <code>select into</code>:\n<a href=\"http://www.w3schools.co...
2008/09/25
[ "https://Stackoverflow.com/questions/131805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11193/" ]
What is the SQL command to copy a table from one database to another database? I am using MySQL and I have two databases x and y. Suppose I have a table in x called a and I need to copy that table to y database. Sorry if the question is too novice. Thanks.
If your two database are separated, the simplest thing to do would be to create a dump of your table and to load it into the second database. Refer to your database manual to see how a dump can be performed. Otherwise you can use the following syntax (for MySQL) ``` INSERT INTO database_b.table (SELECT * FROM database_a.table) ```
131,811
<p>Can someone explain why how the result for the following unpack is computed?</p> <pre><code>"aaa".unpack('h2H2') #=&gt; ["16", "61"] </code></pre> <p>In binary, 'a' = 0110 0001. I'm not sure how the 'h2' can become 16 (0001 0000) or 'H2' can become 61 (0011 1101).</p>
[ { "answer_id": 131850, "author": "Chris Bunch", "author_id": 422, "author_profile": "https://Stackoverflow.com/users/422", "pm_score": 3, "selected": false, "text": "<p>Check out the Programming Ruby <a href=\"http://www.ruby-doc.org/core-1.9.3/String.html#method-i-unpack\" rel=\"nofollo...
2008/09/25
[ "https://Stackoverflow.com/questions/131811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18432/" ]
Can someone explain why how the result for the following unpack is computed? ``` "aaa".unpack('h2H2') #=> ["16", "61"] ``` In binary, 'a' = 0110 0001. I'm not sure how the 'h2' can become 16 (0001 0000) or 'H2' can become 61 (0011 1101).
Not 16 - it is showing 1 and then 6. h is giving the hex value of each nibble, so you get 0110 (6), then 0001 (1), depending on whether its the high or low bit you're looking at. Use the high nibble first and you get 61, which is hex for 97 - the value of 'a'
131,847
<p>I have an ellipse centered at (0,0) and the bounding rectangle is x = [-5,5], y = [-6,6]. The ellipse intersects the rectangle at (-5,3),(-2.5,6),(2.5,-6),and (5,-3)</p> <p>I know nothing else about the ellipse, but the only thing I need to know is what angle the major axis is rotated at.</p> <p>seems like the answer must be really simple but I'm just not seeing it... thanks for the help!</p>
[ { "answer_id": 131876, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "<p>The gradient of the ellipse is identical to the gradient of the intersects with the bounding rectangle along one side...
2008/09/25
[ "https://Stackoverflow.com/questions/131847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an ellipse centered at (0,0) and the bounding rectangle is x = [-5,5], y = [-6,6]. The ellipse intersects the rectangle at (-5,3),(-2.5,6),(2.5,-6),and (5,-3) I know nothing else about the ellipse, but the only thing I need to know is what angle the major axis is rotated at. seems like the answer must be really simple but I'm just not seeing it... thanks for the help!
The gradient of the ellipse is identical to the gradient of the intersects with the bounding rectangle along one side of the ellipse. In your case, that's the line from (-2.5,6) to (5,-3), the top side of your ellipse. That line has a vertical drop of 9 and a horizontal run of 7.5. So we end up with the following right-angled triangle. ``` (-2.5,6) *----- |\x | \ | \ 9 | \ | \ | x\ +------* (5,-3) 7.5 ``` The angle we're looking for is x which is the same in both locations. We can calculate it as: ``` -1 tan (9/7.5) ``` which gives us an angle of -50.19 degrees
131,871
<p>I'd love to figure it out myself but I was wondering <strong>roughly what's the algorithm for converting a function with yield statements into a state machine for an enumerator?</strong> For example how does C# turn this:</p> <pre><code>IEnumerator&lt;string&gt; strings(IEnumerable&lt;string&gt; args) { IEnumerator&lt;string&gt; enumerator2 = getAnotherEnumerator(); foreach(var arg in arg) { enumerator2.MoveNext(); yield return arg+enumerator.Current; } } </code></pre> <p>into this:</p> <pre><code>bool MoveNext() { switch (this.state) { case 0: this.state = -1; this.enumerator2 = getAnotherEnumerator(); this.argsEnumerator = this.args.GetEnumerator(); this.state = 1; while (this.argsEnumerator.MoveNext()) { this.arg = this.argsEnumerator.Current; this.enumerator2.MoveNext(); this.current = this.arg + this.enumerator2.Current; this.state = 2; return true; state1: this.state = 1; } this.state = -1; if (this.argsEnumerator != null) this.argsEnumerator.Dispose(); break; case 2: goto state1; } return false; } </code></pre> <p>Of course the result can be completely different depending on the original code.</p>
[ { "answer_id": 131891, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 3, "selected": false, "text": "<p>Raymond Chen answers this <a href=\"https://devblogs.microsoft.com/oldnewthing/20080812-00/?p=21273\" rel=\"nofollow...
2008/09/25
[ "https://Stackoverflow.com/questions/131871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659/" ]
I'd love to figure it out myself but I was wondering **roughly what's the algorithm for converting a function with yield statements into a state machine for an enumerator?** For example how does C# turn this: ``` IEnumerator<string> strings(IEnumerable<string> args) { IEnumerator<string> enumerator2 = getAnotherEnumerator(); foreach(var arg in arg) { enumerator2.MoveNext(); yield return arg+enumerator.Current; } } ``` into this: ``` bool MoveNext() { switch (this.state) { case 0: this.state = -1; this.enumerator2 = getAnotherEnumerator(); this.argsEnumerator = this.args.GetEnumerator(); this.state = 1; while (this.argsEnumerator.MoveNext()) { this.arg = this.argsEnumerator.Current; this.enumerator2.MoveNext(); this.current = this.arg + this.enumerator2.Current; this.state = 2; return true; state1: this.state = 1; } this.state = -1; if (this.argsEnumerator != null) this.argsEnumerator.Dispose(); break; case 2: goto state1; } return false; } ``` Of course the result can be completely different depending on the original code.
The particular code sample you are looking at involves a series of transformations. Please note that this is an approximate description of the algorithm. The actual names used by the compiler and the exact code it generates may be different. The idea is the same, however. The first transformation is the "foreach" transformation, which transforms this code: ``` foreach (var x in y) { //body } ``` into this code: ``` var enumerator = y.GetEnumerator(); while (enumerator.MoveNext()) { var x = enumerator.Current; //body } if (y != null) { enumerator.Dispose(); } ``` The second transformation finds all the yield return statements in the function body, assigns a number to each (a state value), and creates a "goto label" right after the yield. The third transformation lifts all the local variables and function arguments in the method body into an object called a closure. Given the code in your example, that would look similar to this: ``` class ClosureEnumerable : IEnumerable<string> { private IEnumerable<string> args; private ClassType originalThis; public ClosureEnumerator(ClassType origThis, IEnumerable<string> args) { this.args = args; this.origianlThis = origThis; } public IEnumerator<string> GetEnumerator() { return new Closure(origThis, args); } } class Closure : IEnumerator<string> { public Closure(ClassType originalThis, IEnumerable<string> args) { state = 0; this.args = args; this.originalThis = originalThis; } private IEnumerable<string> args; private IEnumerator<string> enumerator2; private IEnumerator<string> argEnumerator; //- Here ClassType is the type of the object that contained the method // This may be optimized away if the method does not access any // class members private ClassType originalThis; //This holds the state value. private int state; //The current value to return private string currentValue; public string Current { get { return currentValue; } } } ``` The method body is then moved from the original method to a method inside "Closure" called MoveNext, which returns a bool, and implements IEnumerable.MoveNext. Any access to any locals is routed through "this", and any access to any class members are routed through this.originalThis. Any "yield return expr" is translated into: ``` currentValue = expr; state = //the state number of the yield statement; return true; ``` Any yield break statement is translated into: ``` state = -1; return false; ``` There is an "implicit" yield break statement at the end of the function. A switch statement is then introduced at the beginning of the procedure that looks at the state number and jumps to the associated label. The original method is then translated into something like this: ``` IEnumerator<string> strings(IEnumerable<string> args) { return new ClosureEnumerable(this,args); } ``` The fact that the state of the method is all pushed into an object and that the MoveNext method uses a switch statement / state variable is what allows the iterator to behave as if control is being passed back to the point immediately after the last "yield return" statement the next time "MoveNext" is called. It is important to point out, however, that the transformation used by the C# compiler is not the best way to do this. It suffers from poor performance when trying to use "yield" with recursive algorithms. There is a good paper that outlines a better way to do this here: <http://research.microsoft.com/en-us/projects/specsharp/iterators.pdf> It's worth a read if you haven't read it yet.
131,901
<p>I am trying to copy a file using the following code:</p> <pre><code>File targetFile = new File(targetPath + File.separator + filename); ... targetFile.createNewFile(); fileInputStream = new FileInputStream(fileToCopy); fileOutputStream = new FileOutputStream(targetFile); byte[] buffer = new byte[64*1024]; int i = 0; while((i = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, i); } </code></pre> <p>For some users the <code>targetFile.createNewFile</code> results in this exception:</p> <pre><code>java.io.IOException: The filename, directory name, or volume label syntax is incorrect at java.io.WinNTFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(File.java:850) </code></pre> <p>Filename and directory name seem to be correct. The directory <code>targetPath</code> is even checked for existence before the copy code is executed and the filename looks like this: <code>AB_timestamp.xml</code></p> <p>The user has write permissions to the <code>targetPath</code> and can copy the file without problems using the OS.</p> <p>As I don't have access to a machine this happens on yet and can't reproduce the problem on my own machine I turn to you for hints on the reason for this exception.</p>
[ { "answer_id": 131943, "author": "The Archetypal Paul", "author_id": 21755, "author_profile": "https://Stackoverflow.com/users/21755", "pm_score": 0, "selected": false, "text": "<p>Do you check that the targetPath is a directory, or just that something exists with that name? (I know you ...
2008/09/25
[ "https://Stackoverflow.com/questions/131901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5271/" ]
I am trying to copy a file using the following code: ``` File targetFile = new File(targetPath + File.separator + filename); ... targetFile.createNewFile(); fileInputStream = new FileInputStream(fileToCopy); fileOutputStream = new FileOutputStream(targetFile); byte[] buffer = new byte[64*1024]; int i = 0; while((i = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, i); } ``` For some users the `targetFile.createNewFile` results in this exception: ``` java.io.IOException: The filename, directory name, or volume label syntax is incorrect at java.io.WinNTFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(File.java:850) ``` Filename and directory name seem to be correct. The directory `targetPath` is even checked for existence before the copy code is executed and the filename looks like this: `AB_timestamp.xml` The user has write permissions to the `targetPath` and can copy the file without problems using the OS. As I don't have access to a machine this happens on yet and can't reproduce the problem on my own machine I turn to you for hints on the reason for this exception.
Try this, as it takes more care of adjusting directory separator characters in the path between targetPath and filename: ``` File targetFile = new File(targetPath, filename); ```
131,902
<p>I am wondering what security concerns there are to implementing a <code>PHP evaluator</code> like this:</p> <pre><code>&lt;?php eval($_POST['codeInput']); %&gt; </code></pre> <p>This is in the context of making a <code>PHP sandbox</code> so sanitising against <code>DB input</code> etc. isn't a massive issue.</p> <p>Users destroying the server the file is hosted on is.</p> <p>I've seen <code>Ruby simulators</code> so I was curious what's involved security wise (vague details at least).</p> <hr> <p>Thanks all. I'm not even sure on which answer to accept because they are all useful.</p> <p><a href="https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#131911">Owen's answer</a> summarises what I suspected (the server itself would be at risk).</p> <p><a href="https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137019">arin's answer</a> gives a great example of the potential problems.</p> <p><a href="https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137167">Geoff's answer</a> and <a href="https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137118">randy's answer</a> echo the general opinion that you would need to write your own evaluator to achieve simulation type capabilities.</p>
[ { "answer_id": 131911, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": false, "text": "<p>don't do that.</p>\n\n<p>they basically have access to anything you can do in PHP (look around the file system, get/set any ...
2008/09/25
[ "https://Stackoverflow.com/questions/131902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
I am wondering what security concerns there are to implementing a `PHP evaluator` like this: ``` <?php eval($_POST['codeInput']); %> ``` This is in the context of making a `PHP sandbox` so sanitising against `DB input` etc. isn't a massive issue. Users destroying the server the file is hosted on is. I've seen `Ruby simulators` so I was curious what's involved security wise (vague details at least). --- Thanks all. I'm not even sure on which answer to accept because they are all useful. [Owen's answer](https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#131911) summarises what I suspected (the server itself would be at risk). [arin's answer](https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137019) gives a great example of the potential problems. [Geoff's answer](https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137167) and [randy's answer](https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137118) echo the general opinion that you would need to write your own evaluator to achieve simulation type capabilities.
could potentially be in really big trouble if you `eval()`'d something like ``` <?php eval("shell_exec(\"rm -rf {$_SERVER['DOCUMENT_ROOT']}\");"); ?> ``` it's an extreme example but it that case your site would just get deleted. hopefully your permissions wouldn't allow it but, it helps illustrate the need for sanitization & checks.
131,923
<p>Here's my situation:</p> <ul> <li>Windows Server</li> <li>Apache</li> <li>CruiseControl</li> </ul> <p>The last step of my CruiseControl deploy scripts copies the build to Apache's htdocs folder, in a "demos" folder (I believe this is referred to as a "hot deploy"?)</p> <p>All is good and dandy, except that SOMETIMES (not common, but it happens enough that it bugs me), the demos folder doesn't contain the files I built! The old one is gone and the new one isn't there, just vanished.</p> <p>My gut feeling is that if I try to overwrite a file while someone on the web is downloading it, Apache just deletes it after the download is done? I don't know, it doesn't make any sense.</p> <p>I looked everywhere and couldn't find even a hint...let's see how good this StackOverflow community really is! :)</p> <p>Here's the "deploy" target in my ANT script:</p> <pre><code>&lt;target name="deploy" depends="revertVersionFile"&gt; &lt;copy todir="${deploy.dir}"&gt; &lt;fileset dir="${bin.dir}"/&gt; &lt;/copy&gt; &lt;copy todir="${deploy.dir}"&gt; &lt;fileset dir="${bin.dir}"/&gt; &lt;/copy&gt; &lt;available file="${deploy.dir}/MockupsLive.swf" property="mockupsFile"/&gt; &lt;fail unless="mockupsFile" message="MockupsLive doesn't exist!"/&gt; &lt;available file="${deploy.dir}/skins/sketch/sketch.swf" property="skinFile"/&gt; &lt;fail unless="skinFile" message="sketch.swf doesn't exist!"/&gt; &lt;/target&gt; </code></pre>
[ { "answer_id": 136751, "author": "hubbardr", "author_id": 22457, "author_profile": "https://Stackoverflow.com/users/22457", "pm_score": 0, "selected": false, "text": "<p>Apache won't delete the contents of the directory. Something in the script is removing the contents would be my guess....
2008/09/25
[ "https://Stackoverflow.com/questions/131923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199623/" ]
Here's my situation: * Windows Server * Apache * CruiseControl The last step of my CruiseControl deploy scripts copies the build to Apache's htdocs folder, in a "demos" folder (I believe this is referred to as a "hot deploy"?) All is good and dandy, except that SOMETIMES (not common, but it happens enough that it bugs me), the demos folder doesn't contain the files I built! The old one is gone and the new one isn't there, just vanished. My gut feeling is that if I try to overwrite a file while someone on the web is downloading it, Apache just deletes it after the download is done? I don't know, it doesn't make any sense. I looked everywhere and couldn't find even a hint...let's see how good this StackOverflow community really is! :) Here's the "deploy" target in my ANT script: ``` <target name="deploy" depends="revertVersionFile"> <copy todir="${deploy.dir}"> <fileset dir="${bin.dir}"/> </copy> <copy todir="${deploy.dir}"> <fileset dir="${bin.dir}"/> </copy> <available file="${deploy.dir}/MockupsLive.swf" property="mockupsFile"/> <fail unless="mockupsFile" message="MockupsLive doesn't exist!"/> <available file="${deploy.dir}/skins/sketch/sketch.swf" property="skinFile"/> <fail unless="skinFile" message="sketch.swf doesn't exist!"/> </target> ```
I would suggest creating a backup of the old files prior to copying the new files out. Name the old files with the timestamp for when they were replaced. Doing this and then seeing what is in the directory the next time it fails will most likely give you a clue as to where to look next.
131,944
<p>How do I read a time value and then insert it into a TimeSpan variables?</p>
[ { "answer_id": 131960, "author": "TraumaPony", "author_id": 18658, "author_profile": "https://Stackoverflow.com/users/18658", "pm_score": 1, "selected": false, "text": "<pre><code>TimeSpan span = new TimeSpan(days,hours,minutes,seconds,milliseonds);\n</code></pre>\n\n<p>Or, if you mean D...
2008/09/25
[ "https://Stackoverflow.com/questions/131944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I read a time value and then insert it into a TimeSpan variables?
If I understand you correctly you're trying to get some user input in the form of "08:00" and want to store the time in a timespan variable? So.. something like this? ``` string input = "08:00"; DateTime time; if (!DateTime.TryParse(input, out time)) { // invalid input return; } TimeSpan timeSpan = new TimeSpan(time.Hour, time.Minute, time.Second); ```
131,955
<p>Is there a keyboard shortcut for pasting the content of the clipboard into a command prompt window on Windows XP (instead of using the right mouse button)?</p> <p>The typical <kbd>Shift</kbd>+<kbd>Insert</kbd> does not seem to work here.</p>
[ { "answer_id": 131969, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 9, "selected": false, "text": "<p>Yes.. but awkward. <a href=\"https://learn.microsoft.com/en-gb/archive/blogs/adioltean/useful-copypaste-trick-in-cmd-exe...
2008/09/25
[ "https://Stackoverflow.com/questions/131955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4497/" ]
Is there a keyboard shortcut for pasting the content of the clipboard into a command prompt window on Windows XP (instead of using the right mouse button)? The typical `Shift`+`Insert` does not seem to work here.
I personally use a little [AutoHotkey](http://www.autohotkey.com/) script to remap certain keyboard functions, for the console window (CMD) I use: ``` ; Redefine only when the active window is a console window #IfWinActive ahk_class ConsoleWindowClass ; Close Command Window with Ctrl+w $^w:: WinGetTitle sTitle If (InStr(sTitle, "-")=0) { Send EXIT{Enter} } else { Send ^w } return ; Ctrl+up / Down to scroll command window back and forward ^Up:: Send {WheelUp} return ^Down:: Send {WheelDown} return ; Paste in command window ^V:: ; Spanish menu (Editar->Pegar, I suppose English version is the same, Edit->Paste) Send !{Space}ep return #IfWinActive ```
131,975
<p>I understand benefits of dependency injection itself. Let's take Spring for instance. I also understand benefits of other Spring featureslike AOP, helpers of different kinds, etc. I'm just wondering, what are the benefits of XML configuration such as:</p> <pre><code>&lt;bean id="Mary" class="foo.bar.Female"&gt; &lt;property name="age" value="23"/&gt; &lt;/bean&gt; &lt;bean id="John" class="foo.bar.Male"&gt; &lt;property name="girlfriend" ref="Mary"/&gt; &lt;/bean&gt; </code></pre> <p>compared to plain old java code such as:</p> <pre><code>Female mary = new Female(); mary.setAge(23); Male john = new Male(); john.setGirlfriend(mary); </code></pre> <p>which is easier debugged, compile time checked and can be understood by anyone who knows only java. So what is the main purpose of a dependency injection framework? (or a piece of code that shows its benefits.)</p> <hr> <p><strong>UPDATE:</strong><br/> In case of</p> <pre><code>IService myService;// ... public void doSomething() { myService.fetchData(); } </code></pre> <p>How can IoC framework guess which implementation of myService I want to be injected if there is more than one? If there is only one implementation of given interface, and I let IoC container automatically decide to use it, it will be broken after a second implementation appears. And if there is intentionally only one possible implementation of an interface then you do not need to inject it.</p> <p>It would be really interesting to see small piece of configuration for IoC which shows it's benefits. I've been using Spring for a while and I can not provide such example. And I can show single lines which demonstrate benefits of hibernate, dwr, and other frameworks which I use.</p> <hr> <p><strong>UPDATE 2:</strong><br/> I realize that IoC configuration can be changed without recompiling. Is it really such a good idea? I can understand when someone wants to change DB credentials without recompiling - he may be not developer. In your practice, how often someone else other than developer changes IoC configuration? I think that for developers there is no effort to recompile that particular class instead of changing configuration. And for non-developer you would probably want to make his life easier and provide some simpler configuration file.</p> <hr> <p><strong>UPDATE 3:</strong><br/></p> <blockquote> <p>External configuration of mapping between interfaces and their concrete implementations </p> </blockquote> <p>What is so good in making it extenal? You don't make all your code external, while you definitely can - just place it in ClassName.java.txt file, read and compile manually on the fly - wow, you avoided recompiling. Why should compiling be avoided?!</p> <blockquote> <p>You save coding time because you provide mappings declaratively, not in a procedural code </p> </blockquote> <p>I understand that sometimes declarative approach saves time. For example, I declare only once a mapping between a bean property and a DB column and hibernate uses this mapping while loading, saving, building SQL based on HSQL, etc. This is where the declarative approach works. In case of Spring (in my example), declaration had more lines and had the same expressiveness as corresponding code. If there is an example when such declaration is shorter than code - I would like to see it.</p> <blockquote> <p>Inversion of Control principle allows for easy unit testing because you can replace real implementations with fake ones (like replacing SQL database with an in-memory one)</p> </blockquote> <p>I do understand inversion of control benefits (I prefer to call the design pattern discussed here as Dependency Injection, because IoC is more general - there are many kinds of control, and we are inverting only one of them - control of initialization). I was asking why someone ever needs something other than a programming language for it. I definitely can replace real implementations with fake ones using code. And this code will express same thing as configuration - it will just initialize fields with fake values.</p> <pre><code>mary = new FakeFemale(); </code></pre> <p>I do understand benefits of DI. I do not understand what benefits are added by external XML configuration compared to configuring code that does the same. I do not think that compiling should be avoided - I compile every day and I'm still alive. I think configuration of DI is bad example of declarative approach. Declaration can be useful if is declared once AND is used many times in different ways - like hibernate cfg, where mapping between bean property and DB column is used for saving, loading, building search queries, etc. Spring DI configuration can be easily translated to configuring code, like in the beginning of this question, can it not? And it is used only for bean initialization, isn't it? Which means a declarative approach does not add anything here, does it?</p> <p>When I declare hibernate mapping, I just give hibernate some information, and it works based on it - I do not tell it what to do. In case of spring, my declaration tells spring exactly wht to do - so why declare it, why not just do it?</p> <hr> <p><strong>LAST UPDATE:</strong><br/> Guys, a lot of answers are telling me about dependency injection, which I KNOW IS GOOD. The question is about purpose of DI configuration instead of initializing code - I tend to think that initializing code is shorter and clearer. The only answer I got so far to my question, is that it avoids recompiling, when the configuration changes. I guess I should post another question, because it is a big secret for me, why compiling should be avoided in this case.</p>
[ { "answer_id": 131986, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 1, "selected": false, "text": "<p>In the .NET world, most of IoC frameworks provide both XML and Code configuration.</p>\n\n<p>StructureMap and Ninj...
2008/09/25
[ "https://Stackoverflow.com/questions/131975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5507/" ]
I understand benefits of dependency injection itself. Let's take Spring for instance. I also understand benefits of other Spring featureslike AOP, helpers of different kinds, etc. I'm just wondering, what are the benefits of XML configuration such as: ``` <bean id="Mary" class="foo.bar.Female"> <property name="age" value="23"/> </bean> <bean id="John" class="foo.bar.Male"> <property name="girlfriend" ref="Mary"/> </bean> ``` compared to plain old java code such as: ``` Female mary = new Female(); mary.setAge(23); Male john = new Male(); john.setGirlfriend(mary); ``` which is easier debugged, compile time checked and can be understood by anyone who knows only java. So what is the main purpose of a dependency injection framework? (or a piece of code that shows its benefits.) --- **UPDATE:** In case of ``` IService myService;// ... public void doSomething() { myService.fetchData(); } ``` How can IoC framework guess which implementation of myService I want to be injected if there is more than one? If there is only one implementation of given interface, and I let IoC container automatically decide to use it, it will be broken after a second implementation appears. And if there is intentionally only one possible implementation of an interface then you do not need to inject it. It would be really interesting to see small piece of configuration for IoC which shows it's benefits. I've been using Spring for a while and I can not provide such example. And I can show single lines which demonstrate benefits of hibernate, dwr, and other frameworks which I use. --- **UPDATE 2:** I realize that IoC configuration can be changed without recompiling. Is it really such a good idea? I can understand when someone wants to change DB credentials without recompiling - he may be not developer. In your practice, how often someone else other than developer changes IoC configuration? I think that for developers there is no effort to recompile that particular class instead of changing configuration. And for non-developer you would probably want to make his life easier and provide some simpler configuration file. --- **UPDATE 3:** > > External configuration of mapping between interfaces and their concrete implementations > > > What is so good in making it extenal? You don't make all your code external, while you definitely can - just place it in ClassName.java.txt file, read and compile manually on the fly - wow, you avoided recompiling. Why should compiling be avoided?! > > You save coding time because you provide mappings declaratively, not in a procedural code > > > I understand that sometimes declarative approach saves time. For example, I declare only once a mapping between a bean property and a DB column and hibernate uses this mapping while loading, saving, building SQL based on HSQL, etc. This is where the declarative approach works. In case of Spring (in my example), declaration had more lines and had the same expressiveness as corresponding code. If there is an example when such declaration is shorter than code - I would like to see it. > > Inversion of Control principle allows for easy unit testing because you can replace real implementations with fake ones (like replacing SQL database with an in-memory one) > > > I do understand inversion of control benefits (I prefer to call the design pattern discussed here as Dependency Injection, because IoC is more general - there are many kinds of control, and we are inverting only one of them - control of initialization). I was asking why someone ever needs something other than a programming language for it. I definitely can replace real implementations with fake ones using code. And this code will express same thing as configuration - it will just initialize fields with fake values. ``` mary = new FakeFemale(); ``` I do understand benefits of DI. I do not understand what benefits are added by external XML configuration compared to configuring code that does the same. I do not think that compiling should be avoided - I compile every day and I'm still alive. I think configuration of DI is bad example of declarative approach. Declaration can be useful if is declared once AND is used many times in different ways - like hibernate cfg, where mapping between bean property and DB column is used for saving, loading, building search queries, etc. Spring DI configuration can be easily translated to configuring code, like in the beginning of this question, can it not? And it is used only for bean initialization, isn't it? Which means a declarative approach does not add anything here, does it? When I declare hibernate mapping, I just give hibernate some information, and it works based on it - I do not tell it what to do. In case of spring, my declaration tells spring exactly wht to do - so why declare it, why not just do it? --- **LAST UPDATE:** Guys, a lot of answers are telling me about dependency injection, which I KNOW IS GOOD. The question is about purpose of DI configuration instead of initializing code - I tend to think that initializing code is shorter and clearer. The only answer I got so far to my question, is that it avoids recompiling, when the configuration changes. I guess I should post another question, because it is a big secret for me, why compiling should be avoided in this case.
For myself one of the main reasons to use an IoC (and make use of external configuration) is around the two areas of: * Testing * Production maintenance **Testing** If you split your testing into 3 scenarios (which is fairly normal in large scale development): 1. Unit testing 2. Integration testing 3. Black box testing What you will want to do is for the last two test scenarios (Integration & Black box), is not recompile any part of the application. If any of your test scenarios require you to change the configuration (ie: use another component to mimic a banking integration, or do a performance load), this can be easily handled (this does come under the benefits of configuring the DI side of an IoC though. Additionally if your app is used either at multiple sites (with different server and component configuration) or has a changing configuration on the live environment you can use the later stages of testing to verify that the app will handle those changes. **Production** As a developer you don't (and should not) have control of the production environment (in particular when your app is being distributed to multiple customers or seperate sites), this to me is the real benefit of using both an IoC and external configuration, as it is up to the infrastructure/production support to tweak and adjust the live environment without having to go back to developers and through test (higher cost when all they want to do is move a component). **Summary** The main benefits that external configuration of an IoC come from giving others (non-developers) the power to configure your application, in my experience this is only useful under a limited set of circumstances: * Application is distributed to multiple sites/clients where environments will differ. * Limited development control/input over the production environment and setup. * Testing scenarios. In practice I've found that even when developing something that you do have control over the environment it will be run on, over time it is better to give someone else the capabilities to change the configuration: * When developing you don't know when it will change (the app is so useful your company sells it to someone else). * I don't want to be stuck with changing the code every time a slight change is requested that could have been handled by setting up and using a good configuration model. *Note: Application refers to the complete solution (not just the executable), so all files required for the application to run*.
131,989
<p>I want to find out all the subdomains of a given domain. I found a hint which tells me to dig the authoritative Nameserver with the following option:</p> <pre><code>dig @ns1.foo.example example.com axfr </code></pre> <p>But this never works. Has anyone a better idea/approach</p>
[ { "answer_id": 131998, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 2, "selected": false, "text": "<p>If the DNS server is configured properly, you won't be able to get the entire domain. If for some reason is allows...
2008/09/25
[ "https://Stackoverflow.com/questions/131989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22029/" ]
I want to find out all the subdomains of a given domain. I found a hint which tells me to dig the authoritative Nameserver with the following option: ``` dig @ns1.foo.example example.com axfr ``` But this never works. Has anyone a better idea/approach
The hint (using axfr) only works if the NS you're querying (`ns1.foo.example` in your example) is configured to allow AXFR requests from the IP you're using; this is unlikely, unless your IP is configured as a secondary for the domain in question. Basically, there's no easy way to do it if you're not allowed to use axfr. This is intentional, so the only way around it would be via brute force (i.e. `dig a.example.com`, `dig b.example.com`, ...), which I can't recommend, as it could be viewed as a denial of service attack.
131,993
<p>Subversion is a great way to update our web applications on our servers. With a simple <code>svn update</code> all changed files get... well, changed.</p> <p>Except for the omnipresent configuration files such as <code>config.php</code> which hold the database access configuration, server paths etc. And are therefore different on my local development system and the remote server.</p> <p>With the <code>update</code> command, a file modified on the server won't get overwritten, but if I change the file locally and commit it, the server gets the wrong configuration file.</p> <p>But I don't want to set the <code>svn:ignore</code> property either, since the config file belongs to the project.</p> <p>Is there a Subversion-mechanism which will allow me to easily handle these kind of files? Or is the only way to solve this problem to make a system switch within the config file which will determine the executing system and sets the configuration accordingly?</p>
[ { "answer_id": 132002, "author": "xmjx", "author_id": 15259, "author_profile": "https://Stackoverflow.com/users/15259", "pm_score": 2, "selected": false, "text": "<p>Create a template for the file (e.g. config.php-default) and let the user copy the template. She can also do a diff to see...
2008/09/25
[ "https://Stackoverflow.com/questions/131993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6260/" ]
Subversion is a great way to update our web applications on our servers. With a simple `svn update` all changed files get... well, changed. Except for the omnipresent configuration files such as `config.php` which hold the database access configuration, server paths etc. And are therefore different on my local development system and the remote server. With the `update` command, a file modified on the server won't get overwritten, but if I change the file locally and commit it, the server gets the wrong configuration file. But I don't want to set the `svn:ignore` property either, since the config file belongs to the project. Is there a Subversion-mechanism which will allow me to easily handle these kind of files? Or is the only way to solve this problem to make a system switch within the config file which will determine the executing system and sets the configuration accordingly?
I find the easiest way is to switch on the machine's hostname. I have a .ini file with a general section that also overrides this for production, testing and development systems. ``` [general] info=misc db.password=secret db.host=localhost [production : general] info=only on production system db.password=secret1 [testing : general] info=only on test system db.password=secret2 [dev : general] info=only on dev system db.password=secret3 ``` So dev:db.password == 'secret3', but dev:db.host == 'localhost', from the original 'general' group. The 'production', 'testing' and 'dev' could be the machine hostnames, or they are aliases for them set from some other mechanism in a configuration control script.
132,030
<p>Right now I have a visual studio project which contains a custom content type that I made. It also contains all the necessary files for making a sharepoint solution (wsp) file and a script to generate this. </p> <p>Now, I would like to do 2 things. </p> <p>First, I'd like to create a custom display form for the content type and include it in my solution so that it is automatically deployed when I deploy my solution. How do I include this in my solution and make my content type use it?</p> <p>Secondly, you can query this type with the CQWP. I've thought about exporting it, adding more common view fields, and then modifying the XSL that is used to render it. How do I include this into my solution so that it is also deployed. I know i can export the CQWP webpart once it's all setup and include it in my project as a feature. But what abuot the XSL?</p> <p>Looking forward to see your suggestions, cheers.</p> <p>Did as described in the first answer. Worked like a charm.</p>
[ { "answer_id": 146879, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 2, "selected": true, "text": "<p>Use <a href=\"http://www.codeplex.com/stsdev\" rel=\"nofollow noreferrer\">STSDev</a> to create the solution package. \nThat...
2008/09/25
[ "https://Stackoverflow.com/questions/132030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17577/" ]
Right now I have a visual studio project which contains a custom content type that I made. It also contains all the necessary files for making a sharepoint solution (wsp) file and a script to generate this. Now, I would like to do 2 things. First, I'd like to create a custom display form for the content type and include it in my solution so that it is automatically deployed when I deploy my solution. How do I include this in my solution and make my content type use it? Secondly, you can query this type with the CQWP. I've thought about exporting it, adding more common view fields, and then modifying the XSL that is used to render it. How do I include this into my solution so that it is also deployed. I know i can export the CQWP webpart once it's all setup and include it in my project as a feature. But what abuot the XSL? Looking forward to see your suggestions, cheers. Did as described in the first answer. Worked like a charm.
Use [STSDev](http://www.codeplex.com/stsdev) to create the solution package. That should help with creating the WSP. The custom form, CQWP webpart and the .xls file should also be deployable within the project. To deploy the xslt, your feature will have an `<ElementManifest Location="mywebpartManifest.xml">` This then points to a files such as ``` <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <Module Name="Yourfile.xslt" Url="Style Library" Path="" RootWebOnly="TRUE"> <File Url="yourfile.xslt" Type="GhostableInLibrary" /> </Module> </Elements> ``` for the webpart: ``` <Module Name="myWebpart" List="113" Url="_catalogs/wp" RootWebOnly="FALSE"> <File Url="myWebpart.webpart" Type="GhostableInLibrary" /> </Module> ``` Now that file will need to be contained in the solution manifest.xml. This is done automatically from the STSDev project. e.g. ``` <Resources> <Resource Location="SimpleFeature\Feature.xml"/> ``` The actual schemas are: [Site](http://msdn.microsoft.com/en-us/library/aa544502.aspx) [Solution](http://msdn.microsoft.com/en-us/library/ms442108.aspx) [Feature](http://msdn.microsoft.com/en-us/library/ms414322.aspx) [and a link to someone else with the issue](http://social.msdn.microsoft.com/Forums/en-US/sharepointecm/thread/335399ea-f07f-43a5-a4e2-21d88ba2743e/)
132,038
<p>I am trying to implement in windows scripting host the same function as windows Send To/Mail Recipient does. Did not find anything usefull on google except steps to instantiate <code>Outlook.Application</code> and directly calling its methods.</p> <p>I need to go the same path as windows do, as there is a mix of Outlook and Lotus Notes installed, I don't see it good to perform some sort of testing and deciding which object to talk to...</p> <p>What I have found is that the actual work is done by <code>sendmail.dll</code>, there is a handler defined in registry under <code>HKEY_CLASSES_ROOT\CLSID\{9E56BE60-C50F-11CF-9A2C-00A0C90A90CE}</code>. I would like either to use this dll somehow or to simulate the same steps it does.</p> <p>Thanks for your input.</p>
[ { "answer_id": 146879, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 2, "selected": true, "text": "<p>Use <a href=\"http://www.codeplex.com/stsdev\" rel=\"nofollow noreferrer\">STSDev</a> to create the solution package. \nThat...
2008/09/25
[ "https://Stackoverflow.com/questions/132038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10560/" ]
I am trying to implement in windows scripting host the same function as windows Send To/Mail Recipient does. Did not find anything usefull on google except steps to instantiate `Outlook.Application` and directly calling its methods. I need to go the same path as windows do, as there is a mix of Outlook and Lotus Notes installed, I don't see it good to perform some sort of testing and deciding which object to talk to... What I have found is that the actual work is done by `sendmail.dll`, there is a handler defined in registry under `HKEY_CLASSES_ROOT\CLSID\{9E56BE60-C50F-11CF-9A2C-00A0C90A90CE}`. I would like either to use this dll somehow or to simulate the same steps it does. Thanks for your input.
Use [STSDev](http://www.codeplex.com/stsdev) to create the solution package. That should help with creating the WSP. The custom form, CQWP webpart and the .xls file should also be deployable within the project. To deploy the xslt, your feature will have an `<ElementManifest Location="mywebpartManifest.xml">` This then points to a files such as ``` <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <Module Name="Yourfile.xslt" Url="Style Library" Path="" RootWebOnly="TRUE"> <File Url="yourfile.xslt" Type="GhostableInLibrary" /> </Module> </Elements> ``` for the webpart: ``` <Module Name="myWebpart" List="113" Url="_catalogs/wp" RootWebOnly="FALSE"> <File Url="myWebpart.webpart" Type="GhostableInLibrary" /> </Module> ``` Now that file will need to be contained in the solution manifest.xml. This is done automatically from the STSDev project. e.g. ``` <Resources> <Resource Location="SimpleFeature\Feature.xml"/> ``` The actual schemas are: [Site](http://msdn.microsoft.com/en-us/library/aa544502.aspx) [Solution](http://msdn.microsoft.com/en-us/library/ms442108.aspx) [Feature](http://msdn.microsoft.com/en-us/library/ms414322.aspx) [and a link to someone else with the issue](http://social.msdn.microsoft.com/Forums/en-US/sharepointecm/thread/335399ea-f07f-43a5-a4e2-21d88ba2743e/)
132,052
<p>I deploy a webapp on two different containers (Tomcat and Jetty), but their default servlets for serving the static content have a different way of handling the URL structure I want to use (<a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=42411" rel="noreferrer">details</a>).</p> <p>I am therefore looking to include a small servlet in the webapp to serve its own static content (images, CSS, etc.). The servlet should have the following properties:</p> <ul> <li>No external dependencies</li> <li>Simple and reliable</li> <li>Support for <a href="http://www.freesoft.org/CIE/RFC/1945/58.htm" rel="noreferrer"><code>If-Modified-Since</code></a> header (i.e. custom <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServlet.html#getLastModified(javax.servlet.http.HttpServletRequest)" rel="noreferrer"><code>getLastModified</code></a> method)</li> <li>(Optional) support for gzip encoding, etags,...</li> </ul> <p>Is such a servlet available somewhere? The closest I can find is <a href="http://www.unix.org.ua/orelly/java-ent/servlet/ch04_04.htm#ch04-35758" rel="noreferrer">example 4-10</a> from the servlet book.</p> <p><strong>Update:</strong> The URL structure I want to use - in case you are wondering - is simply:</p> <pre class="lang-xml prettyprint-override"><code> &lt;servlet-mapping&gt; &lt;servlet-name&gt;main&lt;/servlet-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;default&lt;/servlet-name&gt; &lt;url-pattern&gt;/static/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre> <p>So all requests should be passed to the main servlet, unless they are for the <code>static</code> path. The problem is that Tomcat's default servlet does not take the ServletPath into account (so it looks for the static files in the main folder), while Jetty does (so it looks in the <code>static</code> folder).</p>
[ { "answer_id": 132103, "author": "Panagiotis Korros", "author_id": 19331, "author_profile": "https://Stackoverflow.com/users/19331", "pm_score": 4, "selected": false, "text": "<p>I had the same problem and I solved it by using the code of the 'default servlet' from the Tomcat codebase.</...
2008/09/25
[ "https://Stackoverflow.com/questions/132052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6918/" ]
I deploy a webapp on two different containers (Tomcat and Jetty), but their default servlets for serving the static content have a different way of handling the URL structure I want to use ([details](http://issues.apache.org/bugzilla/show_bug.cgi?id=42411)). I am therefore looking to include a small servlet in the webapp to serve its own static content (images, CSS, etc.). The servlet should have the following properties: * No external dependencies * Simple and reliable * Support for [`If-Modified-Since`](http://www.freesoft.org/CIE/RFC/1945/58.htm) header (i.e. custom [`getLastModified`](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServlet.html#getLastModified(javax.servlet.http.HttpServletRequest)) method) * (Optional) support for gzip encoding, etags,... Is such a servlet available somewhere? The closest I can find is [example 4-10](http://www.unix.org.ua/orelly/java-ent/servlet/ch04_04.htm#ch04-35758) from the servlet book. **Update:** The URL structure I want to use - in case you are wondering - is simply: ```xml <servlet-mapping> <servlet-name>main</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/static/*</url-pattern> </servlet-mapping> ``` So all requests should be passed to the main servlet, unless they are for the `static` path. The problem is that Tomcat's default servlet does not take the ServletPath into account (so it looks for the static files in the main folder), while Jetty does (so it looks in the `static` folder).
I ended up rolling my own `StaticServlet`. It supports `If-Modified-Since`, gzip encoding and it should be able to serve static files from war-files as well. It is not very difficult code, but it is not entirely trivial either. The code is available: [StaticServlet.java](http://bruno.defraine.net/StaticServlet.java). Feel free to comment. **Update:** Khurram asks about the `ServletUtils` class which is referenced in `StaticServlet`. It is simply a class with auxiliary methods that I used for my project. The only method you need is `coalesce` (which is identical to the SQL function [`COALESCE`](http://en.wikipedia.org/wiki/Null_(SQL)#COALESCE)). This is the code: ``` public static <T> T coalesce(T...ts) { for(T t: ts) if(t != null) return t; return null; } ```
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="https://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="https://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
[ { "answer_id": 132108, "author": "Gustavo Rubio", "author_id": 14533, "author_profile": "https://Stackoverflow.com/users/14533", "pm_score": 4, "selected": false, "text": "<p><em>python -dv yourscript.py</em></p>\n\n<p>That will make the interpreter to run in debug mode and to give you a...
2008/09/25
[ "https://Stackoverflow.com/questions/132058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/189/" ]
I have this Python application that gets stuck from time to time and I can't find out where. Is there any way to signal Python interpreter to show you the exact code that's running? Some kind of on-the-fly stacktrace? ***Related questions:*** * [Print current call stack from a method in Python code](https://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code) * [Check what a running process is doing: print stack trace of an uninstrumented Python program](https://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py)
I have module I use for situations like this - where a process will be running for a long time but gets stuck sometimes for unknown and irreproducible reasons. Its a bit hacky, and only works on unix (requires signals): ``` import code, traceback, signal def debug(sig, frame): """Interrupt running process, and provide a python prompt for interactive debugging.""" d={'_frame':frame} # Allow access to frame object. d.update(frame.f_globals) # Unless shadowed by global d.update(frame.f_locals) i = code.InteractiveConsole(d) message = "Signal received : entering python shell.\nTraceback:\n" message += ''.join(traceback.format_stack(frame)) i.interact(message) def listen(): signal.signal(signal.SIGUSR1, debug) # Register handler ``` To use, just call the listen() function at some point when your program starts up (You could even stick it in site.py to have all python programs use it), and let it run. At any point, send the process a SIGUSR1 signal, using kill, or in python: ``` os.kill(pid, signal.SIGUSR1) ``` This will cause the program to break to a python console at the point it is currently at, showing you the stack trace, and letting you manipulate the variables. Use control-d (EOF) to continue running (though note that you will probably interrupt any I/O etc at the point you signal, so it isn't fully non-intrusive. I've another script that does the same thing, except it communicates with the running process through a pipe (to allow for debugging backgrounded processes etc). Its a bit large to post here, but I've added it as a [python cookbook recipe](http://code.activestate.com/recipes/576515/).
132,070
<p>I have a really big database (running on PostgreSQL) containing a lot of tables with sophisticated relations between them (foreign keys, on delete cascade and so on). I need remove some data from a number of tables, but I'm not sure what amount of data will be really deleted from database due to cascade removals.</p> <p>How can I check that I'll not delete data that should not be deleted?</p> <p>I have a test database - just a copy of real one where I can do what I want :)</p> <p>The only idea I have is dump database before and after and check it. But it not looks comfortable. Another idea - dump part of database, that, as I think, should not be affected by my DELETE statements and check this part before and after data removal. But I see no simple ways to do it (there are hundreds of tables and removal should work with ~10 of them). Is there some way to do it?</p> <p>Any other ideas how to solve the problem?</p>
[ { "answer_id": 132080, "author": "DrStalker", "author_id": 17007, "author_profile": "https://Stackoverflow.com/users/17007", "pm_score": 0, "selected": false, "text": "<p>If the worry is keys left dangling (i.e.: pointing to a deleted record) then run the deletion on your test database, ...
2008/09/25
[ "https://Stackoverflow.com/questions/132070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19101/" ]
I have a really big database (running on PostgreSQL) containing a lot of tables with sophisticated relations between them (foreign keys, on delete cascade and so on). I need remove some data from a number of tables, but I'm not sure what amount of data will be really deleted from database due to cascade removals. How can I check that I'll not delete data that should not be deleted? I have a test database - just a copy of real one where I can do what I want :) The only idea I have is dump database before and after and check it. But it not looks comfortable. Another idea - dump part of database, that, as I think, should not be affected by my DELETE statements and check this part before and after data removal. But I see no simple ways to do it (there are hundreds of tables and removal should work with ~10 of them). Is there some way to do it? Any other ideas how to solve the problem?
You can query the information\_schema to draw yourself a picture on how the constraints are defined in the database. Then you'll know what is going to happen when you delete. This will be useful not only for this case, but always. Something like (for constraints) ``` select table_catalog,table_schema,table_name,column_name,rc.* from information_schema.constraint_column_usage ccu, information_schema.referential_constraints rc where ccu.constraint_name = rc.constraint_name ```
132,092
<p>I think everyone would agree that the MATLAB language is not pretty, or particularly consistent. But nevermind! We still have to use it to get things done.</p> <p>What are your favourite tricks for making things easier? Let's have one per answer so people can vote them up if they agree. Also, try to illustrate your answer with an example.</p>
[ { "answer_id": 132096, "author": "Matt", "author_id": 15368, "author_profile": "https://Stackoverflow.com/users/15368", "pm_score": 4, "selected": false, "text": "<p>Here's a quick example:</p>\n\n<p>I find the comma separated list syntax quite useful for building function calls:</p>\n\n...
2008/09/25
[ "https://Stackoverflow.com/questions/132092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15368/" ]
I think everyone would agree that the MATLAB language is not pretty, or particularly consistent. But nevermind! We still have to use it to get things done. What are your favourite tricks for making things easier? Let's have one per answer so people can vote them up if they agree. Also, try to illustrate your answer with an example.
Turn a matrix into a vector using a single colon. ``` x = rand(4,4); x(:) ```
132,118
<p>When you're using Tiles with Struts and do...</p> <pre><code>request.getRequestURL() </code></pre> <p>...you get the URL to e.g. <code>/WEB-INF/jsp/layout/newLayout.jsp</code> instead of the real URL that was entered/clicked by the user, something like <code>/context/action.do</code>.</p> <p>In newer Struts versions, 1.3.x and after, you can use the <a href="http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&amp;f=58&amp;t=012300" rel="nofollow noreferrer">solution mentioned on javaranch</a> and get the real URL using the request attribute <a href="http://struts.apache.org/1.x/apidocs/org/apache/struts/Globals.html#ORIGINAL_URI_KEY" rel="nofollow noreferrer"><code>ORIGINAL_URI_KEY</code></a>.</p> <p>But how to do this in Struts 1.2.x?</p>
[ { "answer_id": 135713, "author": "Mwanji Ezana", "author_id": 7288, "author_profile": "https://Stackoverflow.com/users/7288", "pm_score": 1, "selected": false, "text": "<p>I don't know if Struts 1.2.x has a similar Globals constant, but you could create your own in at least two ways:</p>...
2008/09/25
[ "https://Stackoverflow.com/questions/132118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When you're using Tiles with Struts and do... ``` request.getRequestURL() ``` ...you get the URL to e.g. `/WEB-INF/jsp/layout/newLayout.jsp` instead of the real URL that was entered/clicked by the user, something like `/context/action.do`. In newer Struts versions, 1.3.x and after, you can use the [solution mentioned on javaranch](http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=58&t=012300) and get the real URL using the request attribute [`ORIGINAL_URI_KEY`](http://struts.apache.org/1.x/apidocs/org/apache/struts/Globals.html#ORIGINAL_URI_KEY). But how to do this in Struts 1.2.x?
I use this, which also works on Spring: ``` <% out.println(request.getAttribute("javax.servlet.forward.request_uri")); %> ``` If you also need the query string (contributed by [matchew](https://stackoverflow.com/users/638649/matchew)): ``` <% out.println(request.getAttribute("javax.servlet.forward.query_string")); %> ```
132,136
<p>Does anyone know if IE6 ever misrenders pages with hidden <code>divs</code>? We currently have several <code>divs</code> which we display in the same space on the page, only showing one at a time and hiding all others.</p> <p>The problem is that the hidden <code>divs</code> components (specifically option menus) sometimes show through. If the page is scrolled, removing the components from view, and then scrolled back down, the should-be-hidden components then disappear.</p> <p>How do we fix this?</p>
[ { "answer_id": 132162, "author": "Santiago Cepas", "author_id": 6547, "author_profile": "https://Stackoverflow.com/users/6547", "pm_score": 2, "selected": false, "text": "<p>One hack you could use is to move your div outside the screen:</p>\n\n<pre><code>MyDiv.style.left = \"-1000px\";\n...
2008/09/25
[ "https://Stackoverflow.com/questions/132136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Does anyone know if IE6 ever misrenders pages with hidden `divs`? We currently have several `divs` which we display in the same space on the page, only showing one at a time and hiding all others. The problem is that the hidden `divs` components (specifically option menus) sometimes show through. If the page is scrolled, removing the components from view, and then scrolled back down, the should-be-hidden components then disappear. How do we fix this?
One hack you could use is to move your div outside the screen: ``` MyDiv.style.left = "-1000px"; ``` And then put it back on its original position when you want to show it.
132,164
<p>These <code>for</code>-loops are among the first basic examples of formal correctness proofs of algorithms. They have different but equivalent termination conditions:</p> <pre><code>1 for ( int i = 0; i != N; ++i ) 2 for ( int i = 0; i &lt; N; ++i ) </code></pre> <p>The difference becomes clear in the postconditions:</p> <ul> <li><p>The first one gives the strong guarantee that <code>i == N</code> after the loop terminates.</p></li> <li><p>The second one only gives the weak guarantee that <code>i &gt;= N</code> after the loop terminates, but you will be tempted to assume that <code>i == N</code>.</p></li> </ul> <p>If for any reason the increment <code>++i</code> is ever changed to something like <code>i += 2</code>, or if <code>i</code> gets modified inside the loop, or if <code>N</code> is negative, the program can fail:</p> <ul> <li><p>The first one may get stuck in an infinite loop. It fails early, in the loop that has the error. Debugging is easy.</p></li> <li><p>The second loop will terminate, and at some later time the program may fail because of your incorrect assumption of <code>i == N</code>. It can fail far away from the loop that caused the bug, making it hard to trace back. Or it can silently continue doing something unexpected, which is even worse.</p></li> </ul> <p>Which termination condition do you prefer, and why? Are there other considerations? Why do many programmers who know this, refuse to apply it?</p>
[ { "answer_id": 132175, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "<p>In C++, using the <code>!=</code> test is preferred for generality. Iterators in C++ have various concepts, like <a href=...
2008/09/25
[ "https://Stackoverflow.com/questions/132164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2686/" ]
These `for`-loops are among the first basic examples of formal correctness proofs of algorithms. They have different but equivalent termination conditions: ``` 1 for ( int i = 0; i != N; ++i ) 2 for ( int i = 0; i < N; ++i ) ``` The difference becomes clear in the postconditions: * The first one gives the strong guarantee that `i == N` after the loop terminates. * The second one only gives the weak guarantee that `i >= N` after the loop terminates, but you will be tempted to assume that `i == N`. If for any reason the increment `++i` is ever changed to something like `i += 2`, or if `i` gets modified inside the loop, or if `N` is negative, the program can fail: * The first one may get stuck in an infinite loop. It fails early, in the loop that has the error. Debugging is easy. * The second loop will terminate, and at some later time the program may fail because of your incorrect assumption of `i == N`. It can fail far away from the loop that caused the bug, making it hard to trace back. Or it can silently continue doing something unexpected, which is even worse. Which termination condition do you prefer, and why? Are there other considerations? Why do many programmers who know this, refuse to apply it?
We shouldn't look at the counter in isolation - if for any reason someone changed the way the counter is incremented they would change the termination conditions and the resulting logic if it's required for i==N. I would prefer the the second condition since it's more standard and will not result in endless loop.
132,186
<p>I wish to test a function that will generate <code>lorem ipsum</code> text, but it does so within html tags. So I cant know in advance the textual content, but i know the html structure. That is what I want to test. And maybe that the length of the texts are within certain limits. So what I am wondering is if the assertTags can do this in a way paraphrased bellow:</p> <pre><code>Result = "&lt;p&gt;Some text&lt;/p&gt;"; Expected = array( '&lt;p' , 'regex', '/p' ); assertTags(resutl, expected) </code></pre> <p>I am using SimpleTest with CakePHP, but I think it should be a general question.</p>
[ { "answer_id": 132420, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 0, "selected": false, "text": "<p>Extend the SimpleExpectation class and then use your new Expectation class in the assert statement</p>\n\n<p>see: <a href=\...
2008/09/25
[ "https://Stackoverflow.com/questions/132186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4013/" ]
I wish to test a function that will generate `lorem ipsum` text, but it does so within html tags. So I cant know in advance the textual content, but i know the html structure. That is what I want to test. And maybe that the length of the texts are within certain limits. So what I am wondering is if the assertTags can do this in a way paraphrased bellow: ``` Result = "<p>Some text</p>"; Expected = array( '<p' , 'regex', '/p' ); assertTags(resutl, expected) ``` I am using SimpleTest with CakePHP, but I think it should be a general question.
``` $expected = array( '<p', 'preg:/[A-Za-z\.\s\,]+/', '/p' ); ```
132,231
<p>When I'm writing a Spring command line application which parses command line arguments, how do I pass them to Spring? Would I want to have my main() structured so that it first parses the command line args and then inits Spring? Even so, how would it pass the object holding the parsed args to Spring?</p>
[ { "answer_id": 132546, "author": "Bradley Beddoes", "author_id": 22087, "author_profile": "https://Stackoverflow.com/users/22087", "pm_score": 1, "selected": false, "text": "<p>Here is an example to boot strap spring for a Main method, simply grab the passed params as normal then make th...
2008/09/25
[ "https://Stackoverflow.com/questions/132231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22063/" ]
When I'm writing a Spring command line application which parses command line arguments, how do I pass them to Spring? Would I want to have my main() structured so that it first parses the command line args and then inits Spring? Even so, how would it pass the object holding the parsed args to Spring?
Two possibilities I can think of. 1) Set a static reference. (A static variable, although typically frowned upon, is OK in this case, because there can only be 1 command line invocation). ``` public class MyApp { public static String[] ARGS; public static void main(String[] args) { ARGS = args; // create context } } ``` You can then reference the command line arguments in Spring via: ``` <util:constant static-field="MyApp.ARGS"/> ``` Alternatively (if you are completely opposed to static variables), you can: 2) Programmatically add the args to the application context: ``` public class MyApp2 { public static void main(String[] args) { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); // Define a bean and register it BeanDefinition beanDefinition = BeanDefinitionBuilder. rootBeanDefinition(Arrays.class, "asList") .addConstructorArgValue(args).getBeanDefinition(); beanFactory.registerBeanDefinition("args", beanDefinition); GenericApplicationContext cmdArgCxt = new GenericApplicationContext(beanFactory); // Must call refresh to initialize context cmdArgCxt.refresh(); // Create application context, passing command line context as parent ApplicationContext mainContext = new ClassPathXmlApplicationContext(CONFIG_LOCATIONS, cmdArgCxt); // See if it's in the context System.out.println("Args: " + mainContext.getBean("args")); } private static String[] CONFIG_LOCATIONS = new String[] { "applicationContext.xml" }; } ``` Parsing the command line arguments is left as an exercise to the reader.
132,242
<p>Consider this case:</p> <pre><code>dll = LoadDLL() dll-&gt;do() ... void do() { char *a = malloc(1024); } ... UnloadDLL(dll); </code></pre> <p>At this point, will the 1k allocated in the call to malloc() be available to the host process again? The DLL is statically linking to the CRT.</p>
[ { "answer_id": 132308, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": -1, "selected": true, "text": "<p>No, you do not leak. </p>\n\n<p>If you mix dll models (static, dynamic) then you can end up with a memory error if you...
2008/09/25
[ "https://Stackoverflow.com/questions/132242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17424/" ]
Consider this case: ``` dll = LoadDLL() dll->do() ... void do() { char *a = malloc(1024); } ... UnloadDLL(dll); ``` At this point, will the 1k allocated in the call to malloc() be available to the host process again? The DLL is statically linking to the CRT.
No, you do not leak. If you mix dll models (static, dynamic) then you can end up with a memory error if you allocate memory in a dll, that you free in a different one (or freed in the exe) This means that the heap created by the statically-linked CRT is not the same heap as a different dll's CRT. If you'd linked with the dynamic version of the CRT, then you'd have a leak as the heap is shared amongst all dynamically-linked CRTs. It means you should always design your apps to use the dynamic CRTs, or ensure you never manage memory across a dll boundary (ie if you allocate memory in a dll, always provide a routine to free it in the same dll)
132,245
<p>The simple demo below captures what I am trying to do. In the real program, I have to use the object initialiser block since it is reading a list in a LINQ to SQL select expression, and there is a value that that I want to read off the database and store on the object, but the object doesn't have a simple property that I can set for that value. Instead it has an XML data store.</p> <p>It looks like I can't call an extension method in the object initialiser block, and that I can't attach a property using extension methods.</p> <p>So am I out of luck with this approach? The only alternative seems to be to persuade the owner of the base class to modify it for this scenario.</p> <p>I have an existing solution where I subclass BaseDataObject, but this has problems too that don't show up in this simple example. The objects are persisted and restored as BaseDataObject - the casts and tests would get complex.</p> <pre><code>public class BaseDataObject { // internal data store private Dictionary&lt;string, object&gt; attachedData = new Dictionary&lt;string, object&gt;(); public void SetData(string key, object value) { attachedData[key] = value; } public object GetData(string key) { return attachedData[key]; } public int SomeValue { get; set; } public int SomeOtherValue { get; set; } } public static class Extensions { public static void SetBarValue(this BaseDataObject dataObject, int barValue) { /// Cannot attach a property to BaseDataObject? dataObject.SetData("bar", barValue); } } public class TestDemo { public void CreateTest() { // this works BaseDataObject test1 = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 }; // this does not work - it does not compile // cannot use extension method in the initialiser block // cannot make an exension property BaseDataObject test2 = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4, SetBarValue(5) }; } } </code></pre> <p>One of the answers (from mattlant) suggests using a fluent interface style extension method. e.g.:</p> <pre><code>// fluent interface style public static BaseDataObject SetBarValueWithReturn(this BaseDataObject dataObject, int barValue) { dataObject.SetData("bar", barValue); return dataObject; } // this works BaseDataObject test3 = (new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 }).SetBarValueWithReturn(5); </code></pre> <p>But will this work in a LINQ query?</p>
[ { "answer_id": 132275, "author": "Tigraine", "author_id": 21699, "author_profile": "https://Stackoverflow.com/users/21699", "pm_score": 3, "selected": false, "text": "<p>Object Initializers are just syntactic sugar that requires a clever compiler, and as of the current implementation you...
2008/09/25
[ "https://Stackoverflow.com/questions/132245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5599/" ]
The simple demo below captures what I am trying to do. In the real program, I have to use the object initialiser block since it is reading a list in a LINQ to SQL select expression, and there is a value that that I want to read off the database and store on the object, but the object doesn't have a simple property that I can set for that value. Instead it has an XML data store. It looks like I can't call an extension method in the object initialiser block, and that I can't attach a property using extension methods. So am I out of luck with this approach? The only alternative seems to be to persuade the owner of the base class to modify it for this scenario. I have an existing solution where I subclass BaseDataObject, but this has problems too that don't show up in this simple example. The objects are persisted and restored as BaseDataObject - the casts and tests would get complex. ``` public class BaseDataObject { // internal data store private Dictionary<string, object> attachedData = new Dictionary<string, object>(); public void SetData(string key, object value) { attachedData[key] = value; } public object GetData(string key) { return attachedData[key]; } public int SomeValue { get; set; } public int SomeOtherValue { get; set; } } public static class Extensions { public static void SetBarValue(this BaseDataObject dataObject, int barValue) { /// Cannot attach a property to BaseDataObject? dataObject.SetData("bar", barValue); } } public class TestDemo { public void CreateTest() { // this works BaseDataObject test1 = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 }; // this does not work - it does not compile // cannot use extension method in the initialiser block // cannot make an exension property BaseDataObject test2 = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4, SetBarValue(5) }; } } ``` One of the answers (from mattlant) suggests using a fluent interface style extension method. e.g.: ``` // fluent interface style public static BaseDataObject SetBarValueWithReturn(this BaseDataObject dataObject, int barValue) { dataObject.SetData("bar", barValue); return dataObject; } // this works BaseDataObject test3 = (new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 }).SetBarValueWithReturn(5); ``` But will this work in a LINQ query?
Even better: ``` public static T SetBarValue<T>(this T dataObject, int barValue) where T : BaseDataObject { dataObject.SetData("bar", barValue); return dataObject; } ``` and you can use this extension method for derived types of BaseDataObject to chain methods without casts and preserve the real type when inferred into a var field or anonymous type.