input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Amazon S3 Url rewrite <p>How can I change the Amazon S3 url from <a href="http://bucket.amazons3.com/imagepath.jpg" rel="nofollow">http://bucket.amazons3.com/imagepath.jpg</a> to <a href="http://image.mydomain.com/imagepath.jpg" rel="nofollow">http://image.mydomain.com/imagepath.jpg</a> </p>
<p>EDIT:
Basically the whole reason for this is to hide the amazon s3 url from my users.</p>
<p>I was thinking about a HttpModule that would redirect the request from image.mydomain.com to bucket.amazons3.com. But that would require all requests to be handled by my servers first then forwarded.</p>
| <p>If I understand, you need to specify your domain name instead of S3. To do this, you need to write a handler which will act as a proxy to the amazon server.</p>
<p>But, that would actually double your bandwidth as you need to send the image to the client as well fetch the image for S3. </p>
<p>I am not sure is there any S3 specific way to handle this.</p>
<p>Below is Amazon S3 specific way taken from <a href="http://5thirtyone.com/archives/1763" rel="nofollow">Amazon S3, CNAME record</a></p>
<blockquote>
<p>The average user may sign up for
Amazon S3 hosting and begin uploading
files - accepting the default URL
structure for hosted files:</p>
<p><a href="http://s3.amazonaws.com/your-bucket/some-file.txt" rel="nofollow">http://s3.amazonaws.com/your-bucket/some-file.txt</a>
If you plan on using S3 to host media
files - more specifically Flash files
- youâll run into Adobeâs cross domain security policy. The fix requires
mapping your hosted S3 files to look
as though they are being served from
your own domain - virtual hosting. The
easiest and most attractive method
would be a hosted file URL that like
this:</p>
<p><a href="http://s3.your-site.com/some-file.txt" rel="nofollow">http://s3.your-site.com/some-file.txt</a>
To get started, create a bucket on S3
that you want as the root for your
hosted files. For this example, your
S3 bucket would be:</p>
<p>s3.your-site.com The most important
step is adding the appropriate CNAME
record to your DNS settings.</p>
<p>Name Type Data
s3.your-site.com CNAME s3.amazonaws.com.
Expect your new DNS settings to take
up to 24-48 hours to resolve.</p>
</blockquote>
|
Populate a constant values table <p>In a Rails application, I need a table in my database to contain constant data. </p>
<p>This table content is not intended to change for the moment but I do not want to put the content in the code, to be able to change it whenever needed.</p>
<p>I tried filling this table in the migration that created it, but this does not seem to work with the test environment and breaks my unit tests. In test environment, my model is never able to return any value while it is ok in my development environment.</p>
<p>Is there a way to fill that database correctly even in test environment ? Is there another way of handling these kind of data that should not be in code ?</p>
<p><strong>edit</strong></p>
<p>Thanks all for your answers and especially Vlad R for explaining the problem.</p>
<p>I now understand why my data are not loaded in test. This is because the test environment uses the <code>db:load</code> rake command which directly loads the schema instead of running the migrations. Having put my values in the migration only and not in the schema, these values are not loaded for test.</p>
| <p>What you are probably observing is that the test framework is not running the migrations (db:migrate), but loading db/schema.rb directly (db:load) instead.</p>
<p>You have two options:</p>
<ol>
<li>continue to use the migration for production and development; for the test environment, add your constant data to the corresponding yml files in db/fixtures</li>
<li>leave the existing db/fixtures files untouched, and create another set of yml files (containing the constant data) in the same vein as db/fixtures, but usable by both test and production/development environments when doing a rake db:load schema initialization</li>
</ol>
<p>To cover those scenarios that use db:load (instead of db:migrate - e.g. test, bringing up a new database on a new development machine using the faster db:load instead of db:migrate, etc.) is create a drop-in rakefile in RAILS_APP/lib/tasks to augment the db:load task by loading your constant intialization data from "seed" yml files (one for each model) into the database.</p>
<p>Use the db:seed rake task as an example. Put your seed data in db/seeds/.yml</p>
<pre><code>#the command is: rake:db:load
namespace :db do
desc 'Initialize data from YAML.'
task :load => :environment do
require 'active_record/fixtures'
Dir.glob(RAILS_ROOT + '/db/seeds/*.yml').each do |file|
Fixtures.create_fixtures('db/seeds', File.basename(file, '.*'))
end
end
end
</code></pre>
<p>To cover the incremental scenarios (db:migrate), define <strong>one</strong> migration that does the same thing as the task defined above.</p>
<p>If your seed data ever changes, you will need to add another migration to remove the old seed data and load the new one instead, which may be non-trivial in case of foreign-key dependencies etc.</p>
|
How to debug JavaScript/jQuery event bindings with Firebug (or similar tool) <p>I need to debug a web application that uses jQuery to do some fairly complex and messy <a href="http://en.wikipedia.org/wiki/Document_Object_Model">DOM</a> manipulation. At one point, some of the events that were bound to particular elements, are not fired and simply stop working.</p>
<p>If I had a capability to edit the application source, I would drill down and add a bunch of <a href="http://en.wikipedia.org/wiki/Firebug_%28software%29">Firebug</a> <code>console.log()</code> statements and comment/uncomment pieces of code to try to pinpoint the problem. But let's assume I cannot edit the application code and need to work entirely in Firefox using Firebug or similar tools.</p>
<p>Firebug is very good at letting me navigate and manipulate the DOM. So far, though, I have not been able to figure out how to do event debugging with Firebug. Specifically, I just want to see a list of event handlers bound to a particular element at a given time (using Firebug JavaScript breakpoints to trace the changes). But either Firebug does not have the capability to see bound events, or I'm too dumb to find it. :-)</p>
<p>Any recommendations or ideas? Ideally, I would just like to see and edit events bound to elements, similarly to how I can edit DOM today.</p>
| <p>See <a href="http://stackoverflow.com/questions/446892/how-to-find-event-listeners-on-a-dom-node/447106#447106">How to find event listeners on a DOM node</a>.</p>
<p>In a nutshell, assuming at some point an event handler is attached to your element (eg): <code>$('#foo').click(function() { console.log('clicked!') });</code></p>
<p>You inspect it like so:</p>
<ul>
<li><p>jQuery 1.3.x</p>
<pre><code>var clickEvents = $('#foo').data("events").click;
jQuery.each(clickEvents, function(key, value) {
console.log(value) // prints "function() { console.log('clicked!') }"
})
</code></pre></li>
<li><p>jQuery 1.4.x</p>
<pre><code>var clickEvents = $('#foo').data("events").click;
jQuery.each(clickEvents, function(key, handlerObj) {
console.log(handlerObj.handler) // prints "function() { console.log('clicked!') }"
})
</code></pre></li>
</ul>
<p>See <a href="http://docs.jquery.com/Core/data#name"><code>jQuery.fn.data</code></a> (where jQuery stores your handler internally).</p>
<ul>
<li><p>jQuery 1.8.x</p>
<pre><code>var clickEvents = $._data($('#foo')[0], "events").click;
jQuery.each(clickEvents, function(key, handlerObj) {
console.log(handlerObj.handler) // prints "function() { console.log('clicked!') }"
})
</code></pre></li>
</ul>
|
Can you build ASP.net User controls as assemblies? <p>Is there some setting in VS2K8 or some command line utility that can compile my user controls as .net assemblies? Is it even possible?</p>
| <p>There is no settings provided by default to support this. But there is a hack and is explained here <a href="http://www.cmswire.com/cms/tips-tricks/aspnet-reusing-web-user-controls-and-forms-000915.php" rel="nofollow">ASP.NET: Reusing Web User Controls and Forms</a></p>
|
How do I read the standard output from a child process in VB6? <p>When creating a process in VB6 (related to <a href="http://stackoverflow.com/questions/570295/can-i-spawn-a-synchronous-process-in-vb6-and-retrieve-its-return-value">this</a> question:), I'm using the following struct:</p>
<pre><code>Private Type STARTUPINFO
cb As Long
lpReserved As String
lpDesktop As String
lpTitle As String
dwX As Long
dwY As Long
dwXSize As Long
dwYSize As Long
dwXCountChars As Long
dwYCountChars As Long
dwFillAttribute As Long
dwFlags As Long
wShowWindow As Integer
cbReserved2 As Integer
lpReserved2 As Long
hStdInput As Long
hStdOutput As Long
hStdError As Long
End Type
</code></pre>
<p>Before I start my process, what needs to happen to STARTUPINFO.hStdOutput in order for my VB6 app to read the output of my hosted process?</p>
<p>Thanks!!</p>
| <p>Following up <a href="http://stackoverflow.com/questions/570295/can-i-spawn-a-synchronous-process-in-vb6-and-retrieve-its-return-value">this other question by the OP</a>, I post an alternative method to execute a command and get hold of stdout:</p>
<pre><code>' References: "Windows Script Host Shell Object Model" '
Public Declare Sub Sleep Lib "kernel32" Alias "Sleep" ( _
ByVal dwMilliseconds As Long)
Function ExecuteCommand(cmd As String, ExpectedResult as Long) As String
Dim shell As New IWshRuntimeLibrary.WshShell
Dim exec As IWshRuntimeLibrary.WshExec
Set exec = shell.Exec(cmd)
While exec.Status = 0
Sleep 100
Wend
If exec.ExitCode = ExpectedResult Then
ExecuteCommand = exec.StdOut.ReadAll
Else
ExecuteCommand = vbNullString ' or whatever '
End
End Function
</code></pre>
|
Is there Java CAPS equivalent from .NET <p>I am looking for an integration framework for building and managing SOA composite applications consist of exposing web services, calling 3rd party web services, performing business logic and invoking database.</p>
<p>It is similar to Sun Java Composite Application Platform Suite (Java CAPS).</p>
| <p>It sounds like you may be looking for BizTalk from Microsoft. </p>
<p>However, depending on how heavy-duty your needs are, you may find that they are served by the basics of WCF (the Microsoft platform for developing web services and clients for them), plus the features of Windows Workflow Foundation (WF). One can easily use WF to create programs that consume one or more web services. You can also expose a WF workflow as a service itself.</p>
<p>Where the composite application is focused on a process like an ETL, you can do a lot with SQL Server Integration Services, which can consume web services as part of an overall ETL task.</p>
<p>See the <a href="http://msdn.microsoft.com/wcf/" rel="nofollow">WCF Developer Center</a> and the <a href="http://msdn.microsoft.com/wf/" rel="nofollow">WF Developer Centers</a> on MSDN .</p>
|
jQuery tabs interfering with SimpleModal in IE <p>I have a page that has two tabs created using jQuery, and I am also using Eric Martin's SimpleModal plugin. However when I am in IE7, the SimpleModal overlay is appearing completely opaque, and not the 50% opacity I wanted. If I remove the tabbing, the modals appear just fine. I looked at the overlay style info in IE Dev Toolbar and it shows the overlay style as 50%, even though it is not showing that way.</p>
| <p>Without more code it's tough to tell.</p>
<p>I would recommend using the <a href="http://docs.jquery.com/UI/Dialog" rel="nofollow">jQuery UI Dialog</a> if you can. They're both made by the UI team and should work fine together.</p>
|
import csv or sql thru phpmyadmin and skip PK? <p>Is it possible to have phpmyadmin or other tool to import a csv or sql backup into an existing DB and skip the primary key or is this a manual, table by table process of inserting with queries and manually removing the primary key?</p>
| <p>Many ways lead to Rome:
1 way:</p>
<pre><code>LOAD DATA LOCAL INFILE 'file.txt'
INTO TABLE t1 (column1, column2, column3);
</code></pre>
<p>another way:</p>
<pre><code>CREATE TABLE `import` (
`column1` int(11) NOT NULL,
`column2` varchar(128) NOT NULL,
`column3` varchar(128) NOT NULL
) ENGINE=MyISAM CHARSET=utf8;
LOAD DATA LOCAL INFILE 'file.txt'
INTO TABLE import
(column1, column2, column3);
INSERT INTO destination_table (columnA,columnB,columnC)
SELECT column3, column1, column2 FROM import;
</code></pre>
|
How do I suppress the results from a stored procedure from within a stored procedure? <p>I've got a stored procedure (we'll call it A) that calls another stored procedure (we'll call this one B). B includes a SELECT that I do not want to send back to the caller of A.</p>
<p>Here is some really rough pseudocode, but it should get the idea across.</p>
<pre><code>PROCEDURE A
CURSOR
CALL B -- I WANT TO SUPPRESS THE RESULTS FROM B
END
SELECT *
END
PROCEDURE B
Do some interesting things
SELECT *
END
</code></pre>
<p>As you can see above, A calls B and B does some things that I want and returns results that I don't care about. Once A is done, it returns it's own set of results.</p>
<p>How do I suppress the results from B in A? I'm using SQL Server 2005. I would prefer not to make changes to B because it is working and more complex than I want to mess with.</p>
| <p>You can try something like this:</p>
<pre><code>/* Assume this table matches the output of your procedure */
DECLARE @tmpNewValue TABLE (newvalue int)
INSERT INTO @tmpNewValue
EXEC ProcedureB
</code></pre>
|
Writing video frames with variable framerate <p>I'm using the <a href="http://www.codeproject.com/KB/audio-video/avifilewrapper.aspx" rel="nofollow">AVIFile Wrapper</a> to create video from my WPF app. I'm using CompositionTarget to grab an image for each frame but I'm having problems with framerate. As my app slows down with heavy data load, the CompositionTarget frame rate drops. With less video frames, when I play back these parts appear as fast forward.</p>
<p>Is there a video format/library that will allow me to work with variable framerates, or can I fix the WPF framerate so I don't drop frames?</p>
<p>Edit -> the frames within an AVI don't have a time codes associated with them, which other video format does? Is there a standard way of do this?</p>
| <p>The standard way to do this with AVI files is to write out a zero-size video frame for each skipped sample.</p>
|
Make SQL Server faster at manipulating data - turn off transaction logging? <p>I use SQL Server 2005 as a data store for a lot of data I do analytic work on. This is not a transactional database as I am not hitting it with updates or capturing real time data. I get a few gigs of data from my clients, load them into SQL Server and do a series of manipulations. I then grab bits of this data and pull them into R where I do most of my analysis. I then push a little data into tables in SQL Server and maybe do a join or two. </p>
<p>I have a heck of a time with the logs in SQL Server getting big and I assume it takes some degree of overhead to create these. How can I configure SQL Server so that it runs with little or no logging? If things get corrupt I am happy to just start from the beginning. Any ideas how to make this all faster?</p>
<p>BTW, no need to tell me how to shrink logs, I'm already doing that. But I wish I didn't have to make the logs in the first place. I'm only using the DB to house the data because its too big to fit into memory in R. </p>
<p>Should I be using a more simple DB than Sql Server? Feel free to tell me I am killing an ant with a sledgehammer. But please recommend a more appropriate sized hammer. :)</p>
| <blockquote>
<p>How can I configure SQL Server so that it runs with little or no logging? I</p>
</blockquote>
<p>I don't believe you can.</p>
<p>However if you configure the database (each database on a server can be different) for simple backups the log file won't grow until you back it up. This is done by setting the recovery mode to "simple".</p>
<p>With simple backups the log is only used to hold the state of transactions until they are fully written into the main database.</p>
|
Adding elements to python generators <p>Is it possible to append elements to a python generator?</p>
<p>I'm currently trying to get all images from a set of disorganized folders and write them to a new directory. To get the files, I'm using os.walk() which returns a list of image files in a single directory. While I can make a generator out of this single list, I don't know how to combine all these lists into one single generator. Any help would be much appreciated.</p>
<p>Related:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| <p>You are looking for <a href="http://docs.python.org/library/itertools.html"><code>itertools.chain</code></a>. It will combine multiple iterables into a single one, like this:</p>
<pre><code>>>> for i in itertools.chain([1,2,3], [4,5,6]):
... print i
...
1
2
3
4
5
6
</code></pre>
|
container for quick name lookup <p>I want to store strings and issue each with a unique ID number (an index would be fine). I would only need one copy of each string and I require quick lookup. I check if the string exist in the table often enough that i notice a performance hit. Whats the best container to use for this and how do i lookup if the string exist?</p>
| <p>I would suggest tr1::unordered_map. It is implemented as a hashmap so it has an expected complexity of O(1) for lookups and a worst case of O(n). There is also a boost implementation if your compiler doesn't support tr1.</p>
<pre><code>#include <string>
#include <iostream>
#include <tr1/unordered_map>
using namespace std;
int main()
{
tr1::unordered_map<string, int> table;
table["One"] = 1;
table["Two"] = 2;
cout << "find(\"One\") == " << boolalpha << (table.find("One") != table.end()) << endl;
cout << "find(\"Three\") == " << boolalpha << (table.find("Three") != table.end()) << endl;
return 0;
}
</code></pre>
|
Is there a vr (vertical rule) in html? <p>I know there is a hr (horizontal rule) in html, but I don't believe there is a vr (vertical rule). Am I wrong and if not, why isn't there a vertical rule?</p>
| <p>No, there is no vertical rule.</p>
<p>It does not make logical sense to have one. HTML is parsed sequentially, meaning you lay out your HTML code from top to bottom, left to right how you want it to appear from top to bottom, left to right (generally)</p>
<p>A vr tag does not follow that paradigm.</p>
<p>This is easy to do using CSS, however. Ex:</p>
<pre><code><div style="border-left:1px solid #000;height:500px"></div>
</code></pre>
<p>Note that you need to specify a height or fill the container with content.</p>
|
Why is Java EE scalable? <p>I heard from various sources that Java EE is highly scalable, but to me it seems that you could never scale a Java EE application to the level of the google search engine or any other large website. </p>
<p>I would like to hear the technical reasons why it is so scalable.</p>
| <p>Java EE is considered scalable because if you consider the EJB architecture and run on an appropriate application server, it includes facilities to transparently cluster and allow the use of multiple instances of the EJB to serve requests. </p>
<p>If you managed things manually in plain-old-java, you would have to figure out all of this yourself, for example by opening ports, synchronizing states, etc.</p>
<p>I am not sure you could define Google as a "large website". That would be like likening the internet to your office LAN. Java EE was not meant to scale to the global level, which is why sites like Amazon and Google use their own technologies (e.g., with use of MapReduce).</p>
<p>There are many papers discussing the efficiency of Java EE scalability.
For example <a href="http://portal.acm.org/citation.cfm?id=974040">this</a></p>
|
How do I create a Setup And Deployment project that can run any number of times on a machine without requiring an uninstall? <p>How do I create a Setup And Deployment project that can run any number of times on a machine without requiring an uninstall?</p>
<p>I've created an installer to install a WCF service to an IIS directory. It does more than just xcopy, it asks the users questions to correctly setup web.config.</p>
<p>The problem is when it can only be installed once per server without requesting an uninstall.</p>
<p>"Another version of this product is already installed...."</p>
<p>Typically the service will have 10-15 separate instances per server (each instance pointing most likely to a separate database, or a different security context)</p>
<p>I can't figure out how to set up the installer to do this.</p>
| <p>Ok, I've got this working, I figured I'd answer it.</p>
<ol>
<li>I downloaded the Orca windows installer editing tool (Part of the Windows SDK) </li>
<li><p>In the InstallExecuteSequence table, changed the following values to 0</p>
<p><strong>RegisterUser
RegisterProduct
PublishFeatures
PublishProduct</strong></p></li>
</ol>
<p>This should allow the installer to run over and over without uninstalling.</p>
|
Can someone explain in detail how the clear works in this code? <p>I am new to CSS. I have a Top, Right, and Content div. I want it to look like this:</p>
<pre><code>Top Right
Content
</code></pre>
<p>However, it is showing up like this:</p>
<pre><code>Top Content Right
</code></pre>
<p>I know I need a clear somewhere, but I am not sure where because I am unclear on how clears actually work, so can someone please explain the html code below on where I would apply the clear and what type of clear I would choose (left, right, or both). Here is the stripped down html code:</p>
<pre><code><div style="float:left; width:600px; height:100px;
border:1px solid black;">Top</div>
<div style="float:right; width:200px; height:800px;
border:1px solid red;">Right</div>
<div style="width:500px; height:600px;
border:1px solid blue;">Content</div>
</code></pre>
| <p>Put the <code>clear</code> on the Content <code><div></code>:</p>
<pre><code><div style="float:left; width:600px; height:100px;
border:1px solid black;">Top</div>
<div style="float:right; width:200px; height:800px;
border:1px solid red;">Right</div>
<div style="width:500px; height:600px; clear: both;
border:1px solid blue;">Content</div>
</code></pre>
<p>This pushes the Content <code><div></code> so that it is below any floating elements (from the left <em>or</em> the right).</p>
<p>A side note: you probably should use CSS classes or the <code>id</code> attribute for convenience instead of inlining using <code>style</code>.</p>
|
Disabling Log4J Output in Java <p>How can one quickly turn off all Log4J output using a log4j.properties file?</p>
| <p>Set level to OFF
(instead of DEBUG, INFO, ....)</p>
|
Is there chemistry in you development team? <p>I've had two intership at the same company and one things that bothered me is the fact that everyone was in their own world doing their stuff and listening to music. I knew I would not want to work there after I graduate even though they would offer me a job if i'm interested. I just didn't like the atmosphere, I like to interact with people anb there was none.</p>
<p>It is a small company, we were about 12 developers. At first, it seems that smaller team should be closer together, have more fun together, but I didn't feel that. So now I've been hired by a much larger company and I wonder if it will be the same thing. I really hope not.</p>
<p>I don't mean to put music on to keep me motivate during my work, but all day long? No, I need to talk with people! The office was so quiet.</p>
<p>So what about you? Are you the type to cut yourself from the outside world? Is your team member more individual? Does that bother you?</p>
| <p>There's an awful lot of converting oxygen to carbon dioxide. In fact, for some that seems to be their primary (and arguably only) skill. On the other hand from some team members we have some conversion of carbon dioxide to oxygen so I guess that balances out.</p>
|
NSColor with calibrated values works differently than regular color? <p>I'm using a method in my view to set a color, and in awakeFromNib I pass it a color using
[NSColor colorWithCalibratedRed: green: blue: alpha:]</p>
<p>The application kept crashing, with the error with "[NSCFNumber set] unrecognized selector."
After inserting a breakpoint, I found it was defining my variable as an "NSCalibratedRGBColor." The application worked when I defined the color with one of the convenience methods (blueColor, whiteColor, etc.). I thought those were just a shortcut for setting RGB values. I have no idea why I haven't run into this problem before, I've used colors like this a lot. Why does it handle this differently, and can I make it interpret it as a regular color?</p>
<p>EDIT:
The code is: [self setLineColor:[NSColor colorWithCalibratedRed:green:blue:alpha]; in my awakeFromNib. I've also discovered that it is a non-1 alpha value that causes the color to be defined "NSCalibratedRGBColor."
Alpha values of 1, like the convenience methods, cause the color to be defined "NSCachedRGBColor" in the debug, which works completely fine.</p>
| <blockquote>
<p>The application kept crashing, with the error with "[NSCFNumber set] unrecognized selector."</p>
</blockquote>
<p>That means that you over-released the color, and then another object (in this case, an NSNumber) got allocated to the same pointer. Then you sent the <code>set</code> message to the object that you thought was your color, but it was actually now an NSNumber object. Result: That error. It had nothing to do with your use of a calibrated vs. uncalibrated color space.</p>
<p>All the colors support the same NSColor interface. The NS[snip]Color classes you're seeing are private subclasses of NSColor; they all support all of NSColor's methods. As far as you're concerned, they are all just NSColors.</p>
|
Destroy session variables in another application <p>I have two applications, one is the front end application, another is the backend one. </p>
<p>Each application has their own copy of identical user database. When a user logs into the front end application, I will also simultaneously log int the backend application using the web services provided by the backend application. </p>
<p>The question now is is it possible for me to destroy the backend session from front end application? The backend uses $_Session super global array to store all the session information. If yes, how?</p>
| <p>Yes it is.</p>
<p>I asume that you are using the same session ID name for both front and back. I think the default is PHP_SESSID. If this is the case, then all the session details will be being stored in the one location. </p>
<p>I am also asuming that the domain of front and back end is teh same.. if it is different, then it wont work, as web browsers will not share session information between different domains.</p>
<p>if you use different session ID names for front and back end, then you will have to get tricky. (the session ID for both will be in the request data, you will just have to load up both sessions and destroy them both.)</p>
<p>use:</p>
<pre><code>session_destroy();
</code></pre>
|
MultiLine Regular Expression and outputting to a file in windows <p>I have an log file that I need to extract specific patterns from. I need to find and then process them into a new file. grep on Linux would usually do the trick but the regular expression spans multiple lines, which I understand grep does not do.</p>
<p>here is an example from my log/debug file:</p>
<p><hr /></p>
<pre><code>Da:
1.328 0.5045
Db:
0.6415 0.1192
Lambda:
0.4429 -0.35
-0.0461 -0.02421
seps:
0.714272
</code></pre>
<p><hr /></p>
<p>I'm looking for <code>/Lambda:\n([-\d\.]+)\s+([\-\d\.]+)\s+\n([\-\d\.]+)\s+([\-\d\.]+)/</code> I then want to output the lines to a new file removing the lambda and rearrange the numbers onto the same line so output <code>\1\s\2\s\3\s\4\n</code></p>
<p>So I have actually two questions:</p>
<ol>
<li>Is there an easy utility to accomplish this, on any system?</li>
<li>Is there a way to do this specifically on windows?</li>
</ol>
<p>I'm hoping there is a simple solution to this that has escaped me. I would rather stay in windows but if I have to go to Linux I will to get this done.</p>
| <p>This is a good candidate for <code>awk</code>, <code>perl</code> and the like <em>stateful parsing</em> (these will run in both Windows's <code>CMD.EXE</code>, provided you have <code>perl</code> and/or <code>awk/sed</code> in your <code>PATH</code>, as well as, of course, on Linux and other unices):</p>
<p><code>awk "/^Lambda/ { in_lambda=1 ; next } in_lambda && /^ *$/ { in_lambda=0 ; printf \"\n\" ; next } in_lambda { printf \"%s \", $0 }" input_file >output_file</code></p>
<p><em>or</em></p>
<p><code>perl -ne "chomp; if (/^Lambda/) { $in_lambda = 1 } elsif ($in_lambda && /^ *$/) { $in_lambda=0 ; printf \"\n\" } elsif ($in_lambda) { printf \"%s \", $_ }" input_file >output_file</code></p>
<hr>
<p>You can perform a second pass to normalize whitespace (and trim whitespace at the end of the lines) if needed. </p>
<p><code>awk "/^Lambda/ { in_lambda=1 ; next } in_lambda && /^ *$/ { in_lambda=0 ; printf \"\n\" ; next } in_lambda { printf \"%s \", $0 }" input_file</code><strong><code>| sed -e "s: *: :g" -e "s: *$::" >output_file</code></strong></p>
<p><em>or</em></p>
<p><code>perl -ne "chomp; if (/^Lambda/) { $in_lambda = 1 } elsif ($in_lambda && /^ *$/) { $in_lambda=0 ; printf \"\n\" } elsif ($in_lambda) { printf \"%s \", $_ }" input_file</code><strong><code>| perl -ne "s/ +/ /g; s/ +$//g; print" >output_file</code></strong></p>
|
Perl regex: How to grab the part that is the same <p>I'm creating a ladder system for some games and I've encountered a problem regarding the clan base system. You see, every player who joins are parsed and put into a players table. Like this:</p>
<pre><code>chelsea | gordon
chelsea | jim
chelsea | brad
</code></pre>
<p>OR...</p>
<pre><code>CLANTAG|> jenna
CLANTAG|> jackson
CLANTAG|> irene
</code></pre>
<p>So, what I want: I wanna grab the CLANTAG, which is at the same place and identical in every players name, which are on that team. But, the separator could be anything from whitespace to nothing (clan player1, clan player2 OR clanplayer1, clanplayer2). </p>
<p>Any ideas on how to do this?</p>
<p>Thanks in advance.</p>
| <p>Here's a shot:</p>
<pre><code>use strict;
use warnings;
my($strip) = shift || 0;
print FindTeamName("TEAMJimBob", "TEAMJoeBob", "TEAMBillyBob"), "\n";
print FindTeamName("TEAM|JimBob", "TEAM|JoeBob", "TEAM|BillyBob"), "\n";
print FindTeamName("TEAM | JimBob", "TEAM | JoeBob", "TEAM | BillyBob"), "\n";
print FindTeamName("TEAMJimBob", "TEAM|JoeBob", "TEAM - BillyBob"), "\n";
sub FindTeamName
{
my(@players) = @_;
my($team) = shift;
foreach my $player (@players) {
$team = FindCommonString($team, $player);
}
$team =~ s{\W+$}{} if $strip;
$team;
}
sub FindCommonString
{
my($str1, $str2) = @_;
my(@arr1) = split(//, $str1);
my(@arr2) = split(//, $str2);
my($common) = "";
while (@arr1 && @arr2) {
my($letter1) = shift(@arr1);
my($letter2) = shift(@arr2);
if ($letter1 eq $letter2) {
$common .= $letter1;
}
else {
last;
}
}
$common;
}
</code></pre>
<p>which gives the following:</p>
<pre><code>C:\temp>perl test.pl
TEAM
TEAM|
TEAM |
TEAM
C:\temp>perl test.pl 1
TEAM
TEAM
TEAM
TEAM
C:\temp>
</code></pre>
|
About DPI issue <p>I have a WIN32 SW which the UI was designed in 96 DPI, so when user changes the windows DPI from 96 to 120 or bigger, the UI will be wrong. I want to know if there is API to force my SW to display the UI with 96DPI.</p>
| <p>Starting with Windows Vista, scaling for DPI is supposed to happen automatically. I don't have any direct experience to know how well it works, but here's the page that explains how to turn it off:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms701681(VS.85).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms701681(VS.85).aspx</a></p>
|
is a great memory a requirement for great programming <p>Do you think having a great memory is REQUIRED to be a great programmer? </p>
<p>I don't consider myself a great programmer but I do think I am decent. But my memory is REALLY bad so I find myself always having to remind myself how to do things. I mean I "know where to look" but sometimes it makes me feel like I am just a crappy programmer. What makes it even worse is that I am always forgetting where things are in my source code or what algorithm I used for certain situations.</p>
<p>Think back on the great programmers you have encountered in your life, didn't all of them seem to have amazing memories?</p>
| <p>Surely apocrapful, but here's <a href="http://weblogs.macromedia.com/jd/archives/2005/12/search_user_mut.html">Einstein's number</a>:</p>
<blockquote>
<p>A reporter interviewed Albert
Einstein. At the end of the interview,
the reporter asked if he could have
Einstein's phone number so he could
call if he had further questions.</p>
<p>âCertainlyâ replied Einstein. He
picked up the phone directory and
looked up his phone number, then wrote
it on a slip of paper and handed it to
the reporter.</p>
<p>Dumbfounded, the reporter said, "You
are considered to be the smartest man
in the world and you can't remember
your own phone number?â</p>
<p>Einstein replied, âWhy should I
memorize something when I know where
to find it?â</p>
</blockquote>
|
Avoiding conflicts while using git-svn <p>Folks I'm facing repeated code conflicts while pulling from the shared git repo in the following scenario:</p>
<ol>
<li><p>There is a common svn repository</p></li>
<li><p>There are several developers who track/sync this common svn repo with their own local git repos using git-svn bridge(via git svn rebase/dcommit)</p></li>
<li><p>From time to time these developers using git need to share their changes without affecting the svn repository. For this purpose they setup a shared git repo and exchange their work using pull/push commands</p></li>
<li><p>It turns out these developers may face conflict problems due to usage of âgit svn rebaseâ for syncing with the main svn repo. This happens because rebase operation rewrites history of the local git branch and it becomes impossible to push into the shared git repo and pulling from it often leads to conflicts.</p></li>
</ol>
<p>Anybody having the same problem?</p>
| <p><a href="http://git-scm.com/docs/git-svn">git-svn(1)</a> says:</p>
<blockquote>
<p>For the sake of simplicity and
interoperating with a less-capable
system (SVN), it is recommended that
all git-svn users clone, fetch and
dcommit directly from the SVN server,
and avoid all
git-clone/pull/merge/push operations
between git repositories and branches.
The recommended method of exchanging
code between git branches and users is
git-format-patch and git-am, or just
'dcommit'ing to the SVN repository.</p>
</blockquote>
<p>If your situation allows it, you can use branches (i.e. subdirectories) in the SVN repository to isolate your work from the other developers.</p>
|
Libtool slowness, double building? <p>In my project, modules are organized in subdirs for tidiness.</p>
<p><strong>My project dir hierarchy:</strong></p>
<pre><code>$ ls -R
.: configure.in Makefile.am Makefile.cvs src
./src: log Makefile.am main.cpp
./src/log: log.cpp Makefile.am
</code></pre>
<p><strong>configure.in:</strong></p>
<pre><code>AC_INIT(configure.in)
AM_CONFIG_HEADER(config.h)
AM_INIT_AUTOMAKE(myapp, 0.1)
AC_LANG_CPLUSPLUS
AC_PROG_CXX
AM_PROG_LIBTOOL
AC_OUTPUT(Makefile src/Makefile src/log/Makefile)
</code></pre>
<p><strong>Makefile.am:</strong></p>
<pre><code>AUTOMAKE_OPTIONS = foreign
SUBDIRS = src
</code></pre>
<p><strong>Makefile.cvs:</strong></p>
<pre><code>default:
aclocal
libtoolize --force --copy
autoheader
automake --add-missing --copy
autoconf
</code></pre>
<p><strong>src/Makefile.am</strong></p>
<pre><code>bin_PROGRAMS = myapp
myapp_SOURCES = main.cpp
SUBDIRS = log
myapp_LDADD = $(top_builddir)/src/log/liblog.la
</code></pre>
<p><strong>src/log/Makefile.am:</strong></p>
<pre><code>INCLUDES = $(all_includes)
METASOURCES = AUTO
noinst_LTLIBRARIES = liblog.la
liblog_la_SOURCES = log.cpp
</code></pre>
<p><strong>src/main.cpp:</strong> contains <code>int main(){}</code>, <strong>src/log/log.cpp</strong> contains <code>void f(){}</code>.</p>
<p>Invoking <code>make</code> produces (edited for brevity):</p>
<pre><code>libtool --mode=compile g++ -MT log.lo -MD -MP -MF .deps/log.Tpo -c -o log.lo log.cpp
libtool: compile: g++ -MT log.lo -MD -MP -MF .deps/log.Tpo -c log.cpp -fPIC -DPIC -o .libs/log.o
libtool: compile: g++ -MT log.lo -MD -MP -MF .deps/log.Tpo -c log.cpp -o log.o >/dev/null 2>&1
mv -f .deps/log.Tpo .deps/log.Plo
libtool --mode=link g++ -o liblog.la log.lo
libtool: link: ar cru .libs/liblog.a .libs/log.o
libtool: link: ranlib .libs/liblog.a
libtool: link: ( cd ".libs" && rm -f "liblog.la" && ln -s "../liblog.la" "liblog.la" )
g++ -MT main.o -MD -MP -MF .deps/main.Tpo -c -o main.o main.cpp
mv -f .deps/main.Tpo .deps/main.Po
libtool --mode=link g++ -o myapp main.o ../src/log/liblog.la
libtool: link: g++ -o myapp main.o ../src/log/.libs/liblog.a
</code></pre>
<p>The problem is the first three lines: <strong>log.cpp is compiled twice!</strong></p>
<p>The question: <strong>why isn't it just compiled once -- taking half the time?</strong></p>
<p><strong>note:</strong> I have no idea what I'm doing -- autotools is black magic to me, but we have to use it in our place. The docs are incomprehensible to me.</p>
| <p>By default Libtool creates two types of libraries: static and shared. (aka libfoo.a and libfoo.so)</p>
<p>Static and shard require different compilation flags. Dynamic libraries -- shared objects
use Position Independent Code with following gcc flags:</p>
<pre><code>-fPIC -DPIC
</code></pre>
<p>Static are not. You can force build only one type by specifing </p>
<pre><code>./configure --disable-shared
</code></pre>
<p>or</p>
<pre><code>./configure --disable-static
</code></pre>
<p><strong>Rationale</strong></p>
<p>Usually when library is provided for user it provide in two setups -- static for development that allows create pure static builds and dynamic for use by most
of programs that use this library. So, usually when you install library in the system
you only install shared object. (aka libfoo_XYZ.deb)</p>
<p>When you add development version (aka libfoo-dev_XYZ.deb) you add headers and statically
build version of the library that allows users make staic builds if they whant.</p>
<p>This is common practice for shipping libraries in UNIX. Thus libtool does this for
you automatically.</p>
|
CPython internal structures <p>GAE has various limitations, one of which is size of biggest allocatable block of memory amounting to 1Mb (now 10 times more, but that doesn't change the question). The limitation means that one cannot put more then some number of items in list() as CPython would try to allocate contiguous memory block for element pointers. Having huge list()s can be considered bad programming practice, but even if no huge structure is created in program itself, CPython maintains some behind the scenes.</p>
<p>It appears that CPython is maintaining single global list of objects or something. I.e. application that has many small objects tend to allocate bigger and bigger single blocks of memory.</p>
<p>First idea was gc, and disabling it changes application behavior a bit but still some structures are maintained.</p>
<p>A simplest short application that experience the issue is:</p>
<pre><code>a = b = []
number_of_lists = 8000000
for i in xrange(number_of_lists):
b.append([])
b = b[0]
</code></pre>
<p>Can anyone enlighten me how to prevent CPython from allocating huge internal structures when having many objects in application?</p>
| <p>On a 32-bit system, each of the 8000000 lists you create will allocate 20 bytes for the list object itself, plus 16 bytes for a vector of list elements. So you are trying to allocate at least (20+16) * 8000000 = 20168000000 bytes, about 20 GB. And that's in the best case, if the system malloc only allocates exactly as much memory as requested.</p>
<p>I calculated the size of the list object as follows:</p>
<ul>
<li>2 Pointers in the <code>PyListObject</code> structure itself (see <a href="http://svn.python.org/view/python/branches/release26-maint/Include/listobject.h?view=markup">listobject.h</a>)</li>
<li>1 Pointer and one <code>Py_ssize_t</code> for the <code>PyObject_HEAD</code> part of the list object (see <a href="http://svn.python.org/view/python/branches/release26-maint/Include/object.h?view=markup">object.h</a>)</li>
<li>one <code>Py_ssize_t</code> for the <code>PyObject_VAR_HEAD</code> (also in object.h)</li>
</ul>
<p>The vector of list elements is slightly overallocated to avoid having to resize it at each append - see list_resize in <a href="http://svn.python.org/view/python/branches/release26-maint/Objects/listobject.c?view=markup">listobject.c</a>. The sizes are 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... Thus, your one-element lists will allocate room for 4 elements.</p>
<p>Your data structure is a somewhat pathological example, paying the price of a variable-sized list object without utilizing it - all your lists have only a single element. You could avoid the 12 bytes overallocation by using tuples instead of lists, but to further reduce the memory consumption, you will have to use a different data structure that uses fewer objects. It's hard to be more specific, as I don't know what you are trying to accomplish.</p>
|
Looking for particular alert box behavior <p>I'm interested in alert boxes such as,</p>
<p><a href="http://www.visual-blast.com/javascript/nice-alert-box-with-jquery-impromptu/" rel="nofollow">http://www.visual-blast.com/javascript/nice-alert-box-with-jquery-impromptu/</a></p>
<p>and</p>
<p><a href="http://woork.blogspot.com/2008/08/design-stunning-alert-box-using.html" rel="nofollow">http://woork.blogspot.com/2008/08/design-stunning-alert-box-using.html</a></p>
<p>but with a different functionality, the user should be able to interact with the page even with the alert box present, so it needs to be movable and not obscure the underlying page, as in this example,</p>
<p><a href="http://www.open-lab.com/mb.ideas/index.html" rel="nofollow">http://www.open-lab.com/mb.ideas/index.html</a></p>
<p>Alert box should be generated automatically on page view plus the title and message of the alert box should change with each page refresh from expandable library.</p>
<p>Is there anything out there like this?</p>
<p>Thanks</p>
| <p>Sounds like the jQuery UI dialog widget might do what you need?</p>
<p><a href="http://jqueryui.com/demos/dialog/" rel="nofollow">http://jqueryui.com/demos/dialog/</a></p>
|
C# Scaling UserControl content to match users Dpi/Font Size <p>How do I get my OwnerDrawn UserControl to respect the users dpi (96/120/xxx) and/or font-size (normal, large, extra large)?</p>
<p>Some people suggest to use the DpiX and DpiY properties on a Graphics object, but that doesn't seem to to anything in my control (i.e. they are always set to 96, regardless of which font-size or dpi I choose).</p>
<p>There is another similar question here on StackOverflow where it suggests to use the AutoScale properties, but the suggested solutions don't really do anything either.</p>
<p>Is there no way of doing this in .NET except for relying on WPF?</p>
| <p>You would need to set the AutoScaleMode property of the UserControl to AutoScaleMode.Dpi, and <strong>not</strong> set the AutoScale property to true. If you do, it will reset the AutoScaleMode back to None. The AutoScale property is obsolete and is there only for backwards compatibility (see the <em>Important Note</em> in this <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.autoscalemode.aspx" rel="nofollow">MSDN article</a>).</p>
<p>Also, in Windows Vista/7, unless you explicitly specify that your application is DPI-aware, Windows will emulate a default DPI environment so that your application renders with 96 DPI, then scale the resulting bitmap to the appropriate size. To avoid that, you can alter your application manifest to inform Windows that you are in fact DPI aware - see the <em>Using manifest to declare DPI awareness</em> section in <a href="http://www.rw-designer.com/DPI-aware" rel="nofollow">this article</a>.</p>
|
Store text in BLOB? <p>I'm making a little forum for my clans website. I'm wondering if I should store the thread text in TEXT or BLOB? Whats the difference? I've seen that phpBB does that.</p>
<p>What is BLOB anyway? cant find much about it on Google.</p>
| <p>A blob is just a bunch of bytes. An arbitrary number of bytes, nothing more.</p>
<p>If you were to store text as a blob, you'd have to worry about encoding (the process of translating text to bytes). But if you store things as text whatever database transport your using will make sure that the text stored in the database is properly encoded and decoded for both efficient storage and easy use.</p>
<p>If you're planning to store text, you should store text.</p>
<p>phpBB could implement text encoding and decoding themselves and that could be one reason to use blob instead of text. It's unlikely but sometimes text data types have a maximum length, the blob might be a work around for phpBB in this particular instance.</p>
|
How to retrieve the pre edited value of the cell of a datagrid to an itemeditor in a flex <p>I wrote a custom item editor for a datagrid in flex. My question is how to retrieve the pre-edited value of the datagrid cell after the item editor initializes and also in the custom item editors code. </p>
| <p>I don't think it is possible to get the old value once you are in the item editor. I would do this manually by listening to the "itemEditBeginning" event and keeping a variable with the value of the cell. You can then reference that value through the "parent", "parentDocument" or "outerDocument" properties in the item editor, depending on whether you are using an inline item editor or a separate class.</p>
|
javascript pointer function <p>if I have:</p>
<pre><code>function init(t,y,u)
{
alert(t + " " + y + " " + u);
}
// String.prototype.add = init(5, 6, 7); // 1)
// window.onload = init(5,6,7); // 2)
</code></pre>
<p>in the 1) <code>init</code> will be executed and then it pointer assegned to <code>String.prototype.add</code>
but in the 2) the function is only executed one time... but why not two times also
when the <code>onload</code> event is raised?</p>
<p>Thanks</p>
| <blockquote>
<p>in the 1) init will be executed and then it pointer assegned to String.prototype.add</p>
</blockquote>
<p>No it won't. The function will simply be executed and its return value (<code>undefined</code>) will be assigned to <code>String.prototype.add</code>. No function pointer will be assigned. To do this, you need to <em>return</em> a function!</p>
<pre><code>function init(t,y,u) {
alert(t + " " + y + " " + u);
return function () { alert('function call!'); };
}
</code></pre>
|
Change the values of _Session in another application <p>Is it possible to modify the values inside the super global array <a href="http://www.php.net/session" rel="nofollow">_Session</a> in PhP? Assume that the _Session is writing to files. </p>
<p>The reason I ask this is because I have two application, the front end and the back end. The backend uses some variables inside the _Session object, and the front end must be able to modify those values so that it can communicate with the backend.</p>
| <p>If the two application are sharing a PHP session, then each can happily modify <code>$_SESSION</code>.</p>
<p>For this to happen you will need to make sure both applications are storing the sessions in the same place and either:</p>
<ul>
<li>Both are on the same domain and the
cookie path has not been changed e.g. using <code>session_set_cookie_params()</code>.</li>
</ul>
<p>or</p>
<ul>
<li>You know the sessionid of the 'back
end' application and in your
'front end' application call
<code>session_id('back-end SessionId
here')</code> before calling
<code>session_start()</code>. The two
applications should then have the
same session. The front-end application would then lose any data it had already stored up to this point in its original session.</li>
</ul>
<p>Either way, two applications communicating by sharing session data doesn't seem a great solution</p>
|
Convert characters to HTML Entities in Cocoa <p>I am currently trying to put together an URL where I specify some GET parameters. But I want to use japanese or other characters too in this URL.</p>
<p>Is there a way to convert a NSString to a string containing the HTML entities for the 'special' characters in my NSString?</p>
<p>I am currently using the following code, which seems to work, except for 'special characters' like chinese and japanese:</p>
<pre><code>NSString* url = @"/translate_a/t?client=t&sl=auto&tl=";
url = [url stringByAppendingString:destinationLanguage];
url = [url stringByAppendingString:@"&text="];
url = [url stringByAppendingString:text];
NSURL* nsurl = [[NSURL alloc] initWithScheme:@"http" host:@"translate.google.com" path:url];
NSError* error;
NSString* returnValue = [[NSString alloc] initWithContentsOfURL:nsurl encoding:NSUTF8StringEncoding error:&error];
</code></pre>
| <p>To properly URL encode your parameters, you need to convert each name and value to UTF-8, then URL encode each name and value separately, then join names with values using '=' and name-value pairs using '&'.</p>
<p>I generally find it easier to put all the parameters in an NSDictionary, then build the query string from the dictionary. Here's a category that I use for doing that:</p>
<pre><code>// file NSDictionary+UrlEncoding.h
#import <Cocoa/Cocoa.h>
@interface NSDictionary (UrlEncoding)
-(NSString*) urlEncodedString;
@end
// file NSDictionary+UrlEncoding.m
#import "NSDictionary+UrlEncoding.h"
// private helper function to convert any object to its string representation
static NSString *toString(id object) {
return [NSString stringWithFormat: @"%@", object];
}
// private helper function to convert string to UTF-8 and URL encode it
static NSString *urlEncode(id object) {
NSString *string = toString(object);
return [string stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
}
@implementation NSDictionary (UrlEncoding)
-(NSString*) urlEncodedString {
NSMutableArray *parts = [NSMutableArray array];
for (id key in self) {
id value = [self objectForKey: key];
NSString *part = [NSString stringWithFormat: @"%@=%@",
urlEncode(key), urlEncode(value)];
[parts addObject: part];
}
return [parts componentsJoinedByString: @"&"];
}
@end
</code></pre>
<p>The method build an array of name-value pairs called <code>parts</code> by URL encoding each key and value, then joining them together with '='. Then the parts in the <code>parts</code> array are joined together with '&' characters.</p>
<p>So for your example:</p>
<pre><code>#import "NSDictionary+UrlEncoding.h"
// ...
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
[parameters setValue: @"t" forKey: @"client"];
[parameters setValue: @"auto" forKey: @"sl"];
[parameters setValue: destinationLanguage forKey: @"tl"];
[parameters setValue: text forKey: @"text"];
NSString *urlString = [@"/translate_a/t?" stringByAppendingString: [parameters urlEncodedString]];
</code></pre>
|
Can't use WPF designer in VS2008 SP1 <p>i searched several hours four solution and nothing found. If I open WPF Designer in my VS2008 Team Suite SP1 I become following error:</p>
<blockquote>
<p>Loading this assembly would produce a
different grant set from other
instances. (Exception from HRESULT:
0x80131401) at
System.RuntimeTypeHandle.CreateInstance(RuntimeType
type, Boolean publicOnly, Boolean
noCheck, Boolean& canBeCached,
RuntimeMethodHandle& ctor, Boolean&
bNeedSecurityCheck) at
System.RuntimeType.CreateInstanceSlow(Boolean
publicOnly, Boolean fillCache) at
System.RuntimeType.CreateInstanceImpl(Boolean
publicOnly, Boolean
skipVisibilityChecks, Boolean
fillCache) at
System.Activator.CreateInstance(Type
type, Boolean nonPublic) at
System.RuntimeType.CreateInstanceImpl(BindingFlags
bindingAttr, Binder binder, Object[]
args, CultureInfo culture, Object[]
activationAttributes) at
System.Activator.CreateInstance(Type
type, BindingFlags bindingAttr, Binder
binder, Object[] args, CultureInfo
culture, Object[]
activationAttributes) at
System.Activator.CreateInstance(String
assemblyName, String typeName, Boolean
ignoreCase, BindingFlags bindingAttr,
Binder binder, Object[] args,
CultureInfo culture, Object[]
activationAttributes, Evidence
securityInfo, StackCrawlMark&
stackMark) at
System.Activator.CreateInstance(String
assemblyName, String typeName) at
System.AppDomain.CreateInstance(String
assemblyName, String typeName) at
System.AppDomain.CreateInstanceAndUnwrap(String
assemblyName, String typeName) at
System.AppDomain.CreateInstanceAndUnwrap(String
assemblyName, String typeName) at
MS.Internal.Package.VSIsolationProviderService.CreateIsolationProvider(String
identity, AssemblyReferenceProvider
assemblyReferences, IEnumerable`1
assemblyFolders) at
MS.Internal.Providers.VSDesignerContext.GetIsolationProvider(IServiceProvider
provider, IVsHierarchy hierarchy,
AssemblyReferenceProvider
assemblyReferences, Boolean
isSilverlightProject) at
MS.Internal.Providers.VSDesignerContext.GetIsolationProvider(IServiceProvider
provider, IVsHierarchy hierarchy,
AssemblyReferenceProvider
assemblyReferences) at
MS.Internal.Providers.VSDesignerContext.Initialize(IServiceProvider
provider, IVsHierarchy hierarchy,
UInt32 itemid, Object docDataObj)<br />
at
MS.Internal.Providers.VSDesignerContext..ctor(IServiceProvider
provider, IVsWindowFrame frame, Object
docDataObj) at
MS.Internal.Providers.VSDesignerContext.GetContext(IServiceProvider
services, IVsWindowFrame frame,
Boolean createIfNotExist) at
MS.Internal.Designer.DesignerPane.InitializeDesigner()</p>
</blockquote>
<p>What I tried to this moment:</p>
<ul>
<li>Reset all settings in Visual Studio</li>
<li>Closed any open XAML files in project, closed Visual Studio, re-opened VS, opened XAML file</li>
<li>Create new user in operating system and try open solution with them</li>
<li>Completed uninstallation/reinstallation of VS 2008 SP1 + MSDN, .NET 3.5 Framework SP1, Silverlight SDK, WPF Toolkit - January 2009</li>
</ul>
<p>I run on Windows Vista SP1 32bit Business Edition.</p>
<p>Do any have a idea how can I solve it before I would try reinstalling operation system?</p>
<p>Regards
Anton Kalcik</p>
<p>UPDATE: Also I tried to disable all add-ons.</p>
| <p>First of all not only you receive this error so may be you should <a href="http://www.google.com/search?q=Loading+this+assembly+would+produce+a+different+grant+set+from+other+instances&ie=utf-8&oe=utf-8" rel="nofollow">google it first</a>? As you can see there are many behaviors of this problem and we are not able to figure out what is wrong in your case because it's hard to reproduce the problem. Also you may try to repair you VS or <a href="http://social.msdn.microsoft.com/Forums/en-US/vswpfdesigner/thread/40e2b0a8-8131-4b50-a290-654f657c1d8e/" rel="nofollow">disable all your addins</a></p>
|
How To Do Performance Profiling in Visual Studio 2008 "Pro" <p>Microsoft make this piece of software called "Visual Studio 2008 Professional". I have found that there doesn't appear to be an application performance profiler or something similar in it, making it seem not so "professional" to me. </p>
<p>If Microsoft don't include a profiler, what are your third party options for time profiling for Visual Studio 2008? Free would be preferable, as this is for uni student purposes :P</p>
| <p>There are a couple of free profilers, not as complete or polished as the commercial ones, but they can definately help a lot:</p>
<p><a href="http://www.eqatec.com/tools/profiler?gclid=CM_xvqDx7ZgCFRxNagod_Xic1Q" rel="nofollow">Eqatec</a> - This was designed for Windows CE, but works just fine for normal applications.</p>
<p><a href="http://www.softprodigy.net/products" rel="nofollow">Soft Prodigy Profile Sharp</a> - This is actually an open source project written in c#, so you can tinker with it if you want.</p>
|
Why CSS files not loading when compressing HTTP response using GZipStream? <p>I am developing an application using asp.net 2.0 (C#), in which I am trying to implement the compression of my files, so that performance of my website will improve.</p>
<p>For that I have added a code in my Global.asax file to compress all requests (.aspx, .js, .css) But when I am running my application it works well for first time then the CSS is not loading and web page is not rendering properly. </p>
<p>Why its happening??</p>
<p><strong>Edited (added my compression code)</strong> </p>
<p>My compression code of Global.asax file is as follows:</p>
<pre><code>void Application_BeginRequest()
{
HttpContext incoming = HttpContext.Current;
string oldpath = incoming.Request.Path.ToLower();
incoming.Response.Filter = new GZipStream(incoming.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;
}
</code></pre>
<p>Also please let me know if there is any other better way to do the same, using the Global.asax file, because I don't have access of IIS Settings and also I don't have permission to implement the HttpModule, that is why I am using Global.asax file.</p>
<p>Thanks</p>
| <p>For static files, you can configure IIS to do the compression for you, no need to implement it yourself.</p>
<p>In IIS6 this is a global setting (properties of the "Web Sites" node in IIS manager, service tab).</p>
<p>In IIS7 this is set on a per folder basis, and it will also compress dynamic content for you. It can either be set in IIS Manager or in the <a href="http://www.iis.net/ConfigReference/system.webServer/urlCompression" rel="nofollow" title="iis.net">web.config</a> file:</p>
<pre><code><configuration>
<system.webServer>
<urlCompression doDynamicCompression="true" doStaticCompression="true" />
</system.webServer>
</configuration>
</code></pre>
|
Can I embed a sqlite database in an Air application? <p>Is it always necessary to create a database for the user in an adobe air application or can you ship an empty database as part of the distributed app?</p>
| <p>Look up the section 'Distributing a pre-populated database' in Flex 3.0 documentation. From the documentation:</p>
<blockquote>
<p>[...]As an alternative to creating the database, structure, and data programmatically, you can distribute a pre-populated database with your application. To distribute a predefined database, include the database file in the application's AIR package.</p>
<p>Like all files that are included in an AIR package, a bundled database file is installed in the application directory (the directory represented by the File.applicationDirectory property). However, files in that directory are read-only. Use the file from the AIR package as a "template" database. The first time a user runs the application, copy the original database file into the user's application storage directory (or another location), and use that database within the application.</p>
</blockquote>
<p>So, the answer to your question:</p>
<blockquote>
<p>can you ship an empty database as part of the distributed app?</p>
</blockquote>
<p>is yes!</p>
|
Include header path change from Windows to Linux <p>I'm porting an application written in C++ from Windows to Linux. I have a problem with the header files path. Windows uses <code>\</code> and Linux uses <code>/</code>. I am finding it cumbersome to change this in each and every source and header file. Is there some work around?</p>
| <p>Always use forward slashes in #include paths. It is the compiler's job to map the path to whatever slash/directory scheme the underlying OS supports.</p>
|
How to reference Resources folder in code <p>I'm porting a c++ Qt application from Windows to OSX and cannot wrap my head around the .app bundle concept. I hope someone can help me understand.</p>
<p>My executable lives here: MyProgram.app/Content/MacOS/MyProgram.exe</p>
<p>My resource folder lives here: MyProgram.app/Content/Resources/</p>
<p>In my code I use a relative path to reference items in the resource folder:</p>
<p>"../Resources/something.png"</p>
<p>This works great if I open the .app bundle and run the .exe directly. </p>
<p>But that is not how the .app bundle is meant to work. The user is supposed to click on the .app bundle in the Finder to run the program. But in that case my relative path no longer works, and this is what I don't understand.</p>
<p>Does anyone understand my problem and how I can fix it?</p>
| <pre><code>QApplication::applicationDirPath()
</code></pre>
<p><a href="http://doc.qt.io/qt-5/qcoreapplication.html#applicationDirPath" rel="nofollow">http://doc.qt.io/qt-5/qcoreapplication.html#applicationDirPath</a></p>
|
Domain Specific Language for Business Objects? <p>I'm thinking of writing a domain specific language (DSL) to model business objects. The DSL will not be executed, instead it will be used by a template based code generator (probably CodeSmith) to generate the .NET & SQL.</p>
<p>The DSL will need to support the definition of the following elements:</p>
<ul>
<li>Classes (name & description)</li>
<li>Properties (name, friendly name, type, null/not null)</li>
<li>Simple validation (required, regex, range, etc..)</li>
<li>Relationships between classes (1 to 1, 1 to many, many to many)</li>
<li>Inheritance (ok, maybe in version 2)</li>
</ul>
<p>Here's a simple example of what the DSL code might look like:</p>
<pre><code>Class: Insured
Desc: "Represents a person covered by an insurance policy"
Prop: FirstName, "First Name", String(20), not null
Prop: LastName, "Last Name", String(20), not null
Prop: MailAddress, "Mailing Address", Address, not null
Prop: SSN, "Social Security Number", String(9), null
Rule: RegEx, SSN, ^\d{9}$
Class: Address
Prop: Line1, "Line 1", String(30), not null
Prop: City, "City", String(30), not null
Prop: State, "State", String(2), not null
...
</code></pre>
<p>For the sake of keeping the DSL simple the more complex validation rules will be coded in the target language. The current plan is to make the generated code off limits and add the more complex rules to subclasses. </p>
<p>Has anyone written something similar to this? Can you provide any tips or links to similar solutions?</p>
| <p>It's fairly easy to automatically convert the structure you present into XML. From there, I imagine it's possible to write some sort of transformation via XSLT or XQuery into whatever end result you desire. I wrote a Visual Studio add-in called <a href="http://code.google.com/p/codegenutils" rel="nofollow">CodeGenUtils</a> to facilitate doing the transformations.</p>
<p>If you really feel like writing your own parser, I would suggest looking at existing textual DSL solutions such as, e.g., <a href="http://www.jetbrains.com/mps/index.html" rel="nofollow">JetBrains MPS</a>.</p>
|
How do I define HAVE_STDIO_H in VC++ 2005? <p>I just built an updated version of SDL.dll, an open-source C DLL that my Delphi project uses, with the Express edition of Visual C++ 2005. I dropped it in the folder with my EXE and tried to run it, but it won't load:</p>
<pre><code>The procedure entry point SDL_RWFromFP could not be located in the dynamic
link library SDL.dll.
</code></pre>
<p>Now C never was my strong point, but I remember enough of it from college to try and track this one down. I went poking around in the source code to see what had happened to this function, and I found it grayed out, beneath a preprocessor directive:</p>
<pre><code>#ifdef HAVE_STDIO_H
</code></pre>
<p>IIRC, STDIO is the standard C I/O library. I assume this means that it's not available. Anyone know why that would be and how to fix it? Is this a Visual C++ issue or an SDL one?</p>
| <p>Most often in the Unix/Linux world, names like <code>HAVE_STDIO_H</code> indicate that the code has been 'autoconfiscated' (which is the official term used to describe the state of having been made to work with the 'autotools' such as 'autoconf'). In such a set up, the configure process would determine whether <code><stdio.h></code> was available and would set <code>#define HAVE_STDIO_H 1</code> in the <code>config.h</code> file that it generates. The compilation would then discover that the platform has <code><stdio.h></code> and would compile the matching code (the stuff that is currently greyed out).</p>
<p>Adapting to your Windows environment, somewhat less than 100% confidently since there could be some other significance to <code>HAVE_STDIO_H</code> on Windows, you might decide that it would be OK to include <code>-DHAVE_STDIO_H</code> in the command line options when you run the compiler. Or you might create the config file by hand, and define <code>-DHAVE_CONFIG_H</code> (which is the normal way to indicate that configuration settings are in the file 'config.h'). In the 'config.h' file, you'd have <code>#define HAVE_STDIO_H 1</code> as mentioned above.</p>
<p><hr></p>
<p>Note: on Unix, you normally find a shell script called 'configure' which you run to create the config.h file. If you have Cygwin, there's an outside chance that you can use that script on Windows - I've just checked that an autoconfiscated package I created on Solaris was configurable on Windows under Cygwin and it mostly worked - all except some network handling. I'd not guarantee that it will always fail (but it's software - guaranteeing anything is pretty dangerous). I should add that the problem is in my auto-configuration code (the tests for the network functionality clearly aren't quite correct), and not in Cygwin per se. If I'd done the job properly, it would have worked. (Someone said "There is no portable code; there is only code that has been ported". That applies here.)</p>
<p>You do need a good simulation of a Unix environment. MingW might also work.</p>
|
How to get started on Information Extraction? <p>Could you recommend a training path to start and become very good in Information Extraction. I started reading about it to do one of my hobby project and soon realized that I would have to be good at math (Algebra, Stats, Prob). I have read some of the introductory books on different math topics (and its so much fun). Looking for some guidance. Please help.</p>
<p>Update: Just to answer one of the comment. I am more interested in Text Information Extraction.</p>
| <blockquote>
<p>Just to answer one of the comment. I
am more interested in Text Information
Extraction.</p>
</blockquote>
<p>Depending on the nature of your project, <a href="http://en.wikipedia.org/wiki/Natural_language_processing">Natural language processing</a>, and <a href="http://en.wikipedia.org/wiki/Computational_linguistics">Computational linguistics</a> can both come in handy -they provide tools to measure, and extract features from textual information, and apply training, scoring, or classification. Good introductionary books include <a href="http://rads.stackoverflow.com/amzn/click/0596529325">OReilly's Programming Collective Intelligence</a> (chapters on "searching, and ranking", Document filtering, and maybe decision trees).</p>
<p>Suggested projects utilizing this knowledge: POS (part-of-speech) tagging, and named entity recognition (ability to recognize names, places, and dates from plain text). You can use Wikipedia as a training corpus, since most of the target information is already extracted in infoboxes -this might provide you with some limited amount of measurement feedback.</p>
<p>The other big hammer in IE is search, a field not to be underestimated. Again, OReilly's book provides some introduction in basic ranking; once you have a large corpus of indexed text, you can do some really IE tasks with it. Check out <a href="http://www.youtube.com/watch?v=nU8DcBF-qo4">Peter Norvig: Theorizing from data</a> as a starting point, and very good motivator -maybe you could reimplement some of their results as a learning exercise.</p>
<p>As a fore-warning, I think I'm obligated to tell you, that information extraction is <em>hard</em>. The first 80% of any given task are usually trivial; however, the difficulty of each additional percentage for IE tasks are usually growing exponentially -in development, and research time. It's also quite underdocumented -most of the high quality info is currently in obscure white papers (<a href="http://scholar.google.com/">Google scholar</a> is your friend) -do check them out once you've got your hand burned a couple of times. But most importantly, do not let these obstacles throw you off -there are certainly big opportunities to make progress in this area.</p>
|
Which algorithm for assigning shifts (discrete optimization problem) <p>I'm developing an application that optimally assigns shifts to nurses in a hospital. I believe this is a <a href="http://en.wikipedia.org/wiki/Linear_programming#Integer_unknowns">linear programming</a> problem with discrete variables, and therefore probably NP-hard:</p>
<ul>
<li>For each day, each nurse (ca. 15-20) is assigned a shift</li>
<li>There is a small number (ca. 6) of different shifts</li>
<li>There is a considerable number of constraints and optimization criteria, either concerning a day, or concerning an emplyoee, e.g.:
<ul>
<li>There must be a minimum number of people assigned to each shift every day</li>
<li>Some shifts overlap so that it's OK to have one less person in early shift if there's someone doing intermediate shift</li>
<li>Some people prefer early shift, some prefer late shift, but a minimum of shift changes is required to still get the higher shift-work pay.</li>
<li>It's not allowed for one person to work late shift one day and early shift the next day (due to minimum resting time regulations)</li>
<li>Meeting assigned working week lengths (different for different people)</li>
<li>...</li>
</ul></li>
</ul>
<p>So basically there is a large number (aout 20*30 = 600) variables that each can take a small number of discrete values.</p>
<p>Currently, my plan is to use a modified <a href="http://en.wikipedia.org/wiki/Min_conflicts_algorithm">Min-conflicts algorithm</a> </p>
<ul>
<li>start with random assignments </li>
<li>have a fitness function for each person and each day</li>
<li>select the person or day with the worst fitness value</li>
<li>select at random one of the assignments for that day/person and set it to the value that results in the optimal fitness value</li>
<li>repeat until either a maximum number of iteration is reached or no improvement can be found for the selected day/person</li>
</ul>
<p>Any better ideas? I am somewhat worried that it will get stuck in a local optimum. Should I use some form of <a href="http://en.wikipedia.org/wiki/Simulated_annealing">simulated annealing</a>? Or consider not only changes in one variable at a time, but specifically switches of shifts between two people (the main component in the current manual algorithm)? I want to avoid tailoring the algorithm to the current constraints since those might change.</p>
<p><strong>Edit:</strong> it's not necessary to find a strictly optimal solution; the roster is currently done manual, and I'm pretty sure the result is considerably sub-optimal most of the time - shouldn't be hard to beat that. Short-term adjustments and manual overrides will also definitely be necessary, but I don't believe this will be a problem; Marking past and manual assignments as "fixed" should actually simplify the task by reducing the solution space.</p>
| <p>This is a difficult problem to solve well. There has been many academic papers on this subject particularly in the <a href="http://en.wikipedia.org/wiki/Operations_research">Operations Research</a> field - see for example <a href="http://www.asap.cs.nott.ac.uk/watt/resources/NR_2008_REFS.pdf">nurse rostering papers 2007-2008</a> or just google "nurse rostering operations research". The complexity also depends on aspects such as: how many days to solve; what type of "requests" can the nurse's make; is the roster "cyclic"; is it a long term plan or does it need to handle short term rostering "repair" such as sickness and swaps etc etc.</p>
<p>The algorithm you describe is a <a href="http://en.wikipedia.org/wiki/Heuristic_(computer_science)">heuristic</a> approach.
You may find you can tweak it to work well for one particular instance of the problem but as soon as "something" is changed it may not work so well (e.g. local optima, poor convergence). </p>
<p>However, such an approach may be adequate depending your particular business needs - e.g. how important is it to get the <strong>optimal</strong> solution, is the problem outline you describe expected to stay the same, what is the potential savings (money and resources), how important is the nurse's perception of the quality of their rosters, what is the budget for this work etc. </p>
|
Import data from Google Checkout into Quickbooks? <p>Is there any way to import data from Google Checkout into Quickbooks? (Or another accounting package)?</p>
| <p>Yep - you can export CSV from Google and import that into Quickbooks (and presumably into other accounting packages):</p>
<p><a href="http://checkout.google.com/support/sell/bin/answer.py?answer=134476&topic=8951" rel="nofollow">Google Checkout - Reporting and reconciliation</a></p>
<p><a href="http://support.quickbooks.intuit.com/support/Pages/KnowledgeBaseArticle/1005472" rel="nofollow">QuickBooks - Tools for importing Excel and CSV files</a></p>
|
Howto print java class garbage collection events? <pre>
java version "1.5.0_14"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_14-b03)
Java HotSpot(TM) Server VM (build 1.5.0_14-b03, mixed mode)
</pre>
<p>I'm trying to debug a NullPointerException I'm getting for passing a reference to statically defined field. To be more specific, I'm setting a global on a Drools3 working memory instance.</p>
<pre><code>workingMemory.setGlobal("log", workingMemorieslog);
</code></pre>
<p>My assumption is that the Class where the field is statically defined is being garbage collected. (The receiving class must be using WeakReference or something like that, I don't really know)</p>
<p>How would you suggest to debug this?
I think that if I could know exactly when JVM's GC unloads a class / instance of a class then I could narrow down on the cause of the buggy behavior. (If not the exact time of the event at least getting an indication that something did happened).</p>
<p>Thank you,
Maxim.</p>
| <p>To trace GC activity add this to java command:</p>
<blockquote>
<p>-verbose:gc
-XX:+PrintGCTimeStamps
-XX:+PrintGCDetails</p>
</blockquote>
<p>NPE that you are getting is probably you passing null value.</p>
|
Drupal: how to change taxonomy header on page with items? <p>I have a menu item like
<a href="http://localhost/drupal/?q=category/articles/php" rel="nofollow">http://localhost/drupal/?q=category/articles/php</a></p>
<p>It's supposed to output all stories about PHP,
But in resulting page header (with term name (PHP) ) doesn't look very well.
How can I remove header or change its CSS style?</p>
| <p>Your best bet for customizing the page is to use the Views Module and activate the taxonomy_term view. Then, you can add to the header field or even create a new template just for that view. </p>
<p>The Drupal Handbook has a lot of great resources for theming and building views:
<a href="http://drupal.org/node/352970" rel="nofollow">http://drupal.org/node/352970</a></p>
|
C++ Vector <p>Look this code(and forgive the miss of knowlegde).It outputs errors that I couldnot solve.I need to declare a vector of elements of struct C,but I need the number of elements be i(a input of type int).I also tried others aproachs but in all of them I recieved an error(cannot convert C to int,etc).How can I do this?</p>
<pre><code># include < iostream >
using std::cout;
using std::cin;
using std::endl;
# include < vector >
using std::vector;
struct C{
int cor;
vector<int>cores;
};
void LerVector( vector< C> &array ) ;
int main ()
{
int n;
bool done=false;
bool don=false;
vector<C>cidade;
int i;
while(!done){
cout<<"Entre o número de cidades "<<endl;
cin>>n;
if(n>500)
{
cout<<endl;
cout<<"O número máximo é 500"<<endl;
}
else
done=true;
}
n--;
while(!don){
cout<<"Entre o número de confederações"<<endl;
cin>>i;
if(i>100){
cout<<endl;
cout<<"Número máximo de 100 cidades"<<endl;
}
else {
LerVector( cidade) ;
don=true;
}
}
cin.get();
return 0;
}
//resolve...
void LerVector( vector< C> &array )
{
for ( size_t i = 0; i < array.size(); i++ )
cin>>array[i];
} // end function inputVector
</code></pre>
| <p>Let's try with an explanation :)</p>
<pre><code>cin >> array[i];
</code></pre>
<p>That tries to extract from <code>cin</code> into an object of struct C. Well, so it needs an operator>> that actually does that work:</p>
<pre><code>istream & operator>>(istream &is, C &c) {
is >> c.cor; // or into whatever member
return is;
}
</code></pre>
<p>In addition, as another one mentioned, you have to actually add the elements to the vector first:</p>
<pre><code>while(!don){
cout<<"Entre o número de confederações"<<endl;
....
} else {
cidade.resize(i); // resize to i elements
LerVector(cidade);
don = true;
}
</code></pre>
<p>For the next time, please format the text (correct indent it). It was hard for me to step through it :)</p>
|
Application.DoEvents(); <p>How do I keep my C# form that, lets say is in a for-loop, from locking up? Do I call Application.DoEvents(); before the loop or after? From what I've heard using the DoEvents method will keep my app from locking.</p>
| <p>You should not use Application.DoEvents() in order to keep your application responsive. </p>
<p>Calling this method will allow any waiting windows messages to be dispatched. This means if a user clicks on a button (or performs any other user interaction) that action will be processed. This can therefore cause reentrancy. If they press the same button as the one that caused the loop you are processing you will end up having the routine called again before you have finished!</p>
<p>Instead you should use a <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" rel="nofollow">BackgroundWorker</a> thread to perform the long process and then once the action is completed perform whatever additional actions are required. For example, once a button is pressed you would start the worker thread and then disable you button so it cannot be pressed again. Once the worker thread completes you would enable the button again.</p>
|
One view ( frontpage ) for many controllers (sub views) <p><em>Notes:</em> Cannot use Javascript or iframes. In fact I can't trust the client browser to do just about anything but the ultra basics.</p>
<p>I'm rebuilding a legacy PHP4 app as a MVC application, with most of my research currently focused with the Pylon's framework.</p>
<p>One of the first weird issues I've run into and one I've solved in the past by using iframes or better yet javascript is displaying a dynamic collection of "widgets" that are like digest views of a typical controller's index view.</p>
<p>Best way to visualize my problem would be to look at Google's personalized homepage. They solve the problem with Javascript, but for my scenario javascript and pretty much anything above basic XHTML is not possible.</p>
<p>One idea I started working on was to have my Frontpage controller poll a database or other service for the currently activated widgets, then taking a list of tuples/dicts, dynamically instantiate each controller and build a list/dict of render sub-views and pass that to the frontpage view and let it figure things out.</p>
<p>So with peusudo code:</p>
<pre><code>Get request goes to WSGI
WSGI calls pylons
Pylons routes to Frontpage.index()
Frontpage.index()
myViews = list()
for WidgetController in ActiveWidegets():
myViews.append(subRender(WidgetController, widgetView))
c.subviews = myViews
render(frontpage.mako)
</code></pre>
<p>Weird bits about subRender</p>
<ul>
<li>Dynamically imports controllers via <code>__import__</code> (currently hardcoded to project's namespace :( )</li>
<li>Has a potential to be very expensive (most widget calls can be cached, but one is a user panel)</li>
</ul>
<p>I feel like there has to be a better way or perhaps a mechanism already implemented in WSGI or better yet Pylons to do this, but so far the closest I've found is this utility method: <a href="http://www.pylonshq.com/docs/en/0.9.7/modules/controllers_util/#pylons.controllers.util.forward" rel="nofollow">http://www.pylonshq.com/docs/en/0.9.7/modules/controllers_util/#pylons.controllers.util.forward</a> but it seems a little crazy to build <code>N</code> instances of pylons on top of pylons just to get a collection views.</p>
| <p>While in most cases I'd recommend what you originally stated, using Javascript to load each widget, since that isn't an option I think you'll need to do something a little different.</p>
<p>In addition to using the approach of trying to have a single front controller go through all the widgets needed and building them, an alternative you might want to consider is making more powerful use of the templating in Mako.</p>
<p>You can actually define small blocks as Mako def's, which of course have full Python power. To avoid polluting your Mako templates with domain logic, make sure to keep that all in your models, and just make calls to the model instances in the Mako def's as needed for that component of the page to build itself.</p>
<p>A huge advantage of this approach is that since Mako def's support cache args, you can actually have components of the page decide how to cache themselves. Maybe the sidebar should be cached for 5 mins, but the top bar changes every hit for example. Also, since the component is triggering the db hit, you'll save db hits when the component caches itself.</p>
<p>ToscaWidgets doesn't have the performance to make it a very feasible option on a larger scale, so I'd stay away from trying that out.</p>
<p>As for some tweaks to your existing idea, make sure not to actually use Pylons controllers for 'widgets', as they do much more as needed to support WSGI that you don't need for building a page up of widgets.</p>
<p>I'd consider having all Widget classes work like so:</p>
<pre><code>class Widget(object):
def process(self):
# Determine if this widget should process a POST aimed at it
# ie, one of the POST args is a widget id indicating the widget
# to handle the POST
def prepare(self):
# Load data from the database if needed in prep for the render
def render(self):
# return the rendered content
def __call__(self):
self.process()
self.prepare()
return self.render()
</code></pre>
<p>Then just have your main Mako template iterate through the widget instances, and call them to render them out.</p>
|
Apache2 isn't serving index.php <p>My server is fairly old (based on SuSE 9), and while I try to go through the pain of updating to the latest Apache2, PHP5 and MySQL, I ran into this problem with one of my hosted domains.</p>
<p>The site has an index.php, and if I browse to their site example.org/index.php it displays fine.</p>
<p>But if I navigate to <a href="http://example.org" rel="nofollow">http://example.org</a> or <a href="http://example.org/" rel="nofollow">http://example.org/</a> , Firefox pops up a dialog asking if I want to save the file or view it in a program. The downloaded file is a copy of the unprocessed index.php file.</p>
<p>The config file for the domain has not changed, but clearly I messed up something. In the config file is "DirectoryIndex index.php". In the DocumentRoot is a .htaccess file with only "XBitHack on".</p>
<p>Confusing the matter is that I have another hosted domain with a Wordpress install that also uses index.php, and navigating there works just fine.</p>
<p>Here's the site: <a href="http://www.sjbridge.org" rel="nofollow">http://www.sjbridge.org</a> or <a href="http://www.sjbridge.org/index.php" rel="nofollow">http://www.sjbridge.org/index.php</a></p>
<p>Mojo</p>
<p>Here's some more information: When I navigate to <a href="http://www.sjbridge.org" rel="nofollow">http://www.sjbridge.org</a>, Firefox presents the file as "application/x-httpd-php" in the content-type, but for /index.php the content-type is, of course, text/html.</p>
| <p>Ugh, I cleared the cache in my browser and the problem went away. Let me say "Never mind."</p>
|
Is there an advantage to use a Synchronized Method instead of a Synchronized Block? <p>Can any one tell me the advantage of synchronized method over synchronized block with an example?</p>
| <blockquote>
<p><em>Can any one tell me the advantage of synchronized method over synchronized block with an example?Thanks.</em></p>
</blockquote>
<p>There is not a clear advantage of using synchronized method over block. </p>
<p>Perhaps the only one ( but I wouldn't call it advantage ) is you don't need to include the object reference <code>this</code>.</p>
<p>Method:</p>
<pre><code>public synchronized void method() { // blocks "this" from here....
...
...
...
} // to here
</code></pre>
<p>Block:</p>
<pre><code>public void method() {
synchronized( this ) { // blocks "this" from here ....
....
....
....
} // to here...
}
</code></pre>
<p>See? No advantage at all. </p>
<p>Blocks <strong>do</strong> have advantages over methods, most of all in flexibility because you can use other object as lock whereas syncing the method would lock the complete class.</p>
<p>Compare: </p>
<pre><code>// locks the whole object
...
private synchronized void someInputRelatedWork() {
...
}
private synchronized void someOutputRelatedWork() {
...
}
</code></pre>
<p>Vs. </p>
<pre><code>// Using specific locks
Object inputLock = new Object();
Object outputLock = new Object();
private void someInputRelatedWork() {
synchronize(inputLock) {
...
}
}
private void someOutputRelatedWork() {
synchronize(outputLock) {
...
}
}
</code></pre>
<p>Also if the method grows you can still keep the synchronized section separated:</p>
<pre><code> private void method() {
... code here
... code here
... code here
synchronized( lock ) {
... very few lines of code here
}
... code here
... code here
... code here
... code here
}
</code></pre>
|
What does the operator '=>' mean in C#? <p>What does the '=>' in this statement signify?</p>
<pre><code>del = new SomeDelegate(() => SomeAction());
</code></pre>
<p>Is the above declaration the same as this one?</p>
<pre><code>del = new SomeDelegate(this.SomeAction);
</code></pre>
<p>Thanks.</p>
| <p>Basically it's specifying an anonymous function, that takes no parameters that calls SomeAction. So yes, they are functionally equivalent. Though not equal. Using the lambda is more equivalent to:</p>
<pre><code>del = new SomeDelegate(this.CallSomeAction);
</code></pre>
<p>where CallSomeAction is defined as:</p>
<pre><code>public void CallSomeAction()
{
this.SomeAction();
}
</code></pre>
<p>Hope that helps!</p>
|
Transferring files with metadata <p>I am writing a client windows app which will allow files and respective metadata to be uploaded to a server. For example gear.stl (original file) and gear.stl.xml (metadata). I am trying to figure out the correct protcol to use to transfer the files. </p>
<p>I was thinking about using ftp since it is widely used and a proven method to transfer files, except that I would have to transfer 2 files for every actual file (.stl and .stl.xml). However, another thought had also crossed my mind ... What if I create an object and wrap the file, metadata and the directory I needed to tranfer it to, serialize the object and then submit a request to a webservice, to transfer the file. </p>
<p>Original file size would range from 100k to 10MB. Metadata size would probably be less than 200k</p>
<p>The webservice call seems like an easier process to me to deserialize the object and distribute the file and respective metadata accordingly. However I'm not sure if this is a sound idea or if there is a better way to transfer this data other than the two methods I have mentioned. </p>
<p>If someone can point me in the right direction it would be much appreciated.</p>
| <p>You could wrap it in a zip file like the "new" office document format does. You might even be able to use their classes to package it all up.</p>
<p><strong>Edit:</strong> </p>
<p>Take a look at the <a href="http://msdn.microsoft.com/en-us/library/system.io.packaging.package.aspx" rel="nofollow" title="System.IO.Packaging.Package">System.IO.Packaging.Package</a> class. It seems to be what you need. This class resides in the WindowsBase.dll assembly and became available in .NET 3.0. </p>
<p>PS: Remember that even though it is a zip file, it doesn't need to be compressed. If you have very large files, it may be better to keep them uncompressed. It all depends on how they're going to be used and if the transport size is an issue.</p>
|
IE 7 error: "An outgoing call cannot be made since the application is dispatching an input-synchronous call" <p>I am getting this error (see post title) from time to time as I interact with a web application I created. The application uses Ajax to communicate with a server, but doesn't do anything fancy specific to IE. I don't get this error, or any other error, when running the same application on Firefox or Safari.</p>
<p>Have you seen this error message before, know what can cause this, or have any recommendation on how to deal with this?</p>
| <p>This is a generic COM error. What is happening is that the AJAX component, XmlHttpRequest is a COM object, and therefore follow the rules for COM. What is likely happening here is that XmlHttpRequest is dispatching an incoming event. In the response to this event, there's probably code that calls out to a different COM object in another apartment which ultimately will cause deadlock. COM detects this and prevents this from happening. </p>
<p>The general recommendation is to break this type of application into using queues. Instead of responding to events immediately, save the event into a queue and return immediately. Then process the events asynchronously using a timer.</p>
|
How to Design Data Transfer Objects in Business Logic Layer <h2>DTO</h2>
<p>I'm building a Web application I would like to scale to many users. Also, I need to expose functionality to trusted third parties via Web Services.</p>
<p>I'm using LLBLGen to generate the data access layer (using SQL Server 2008). The goal is to build a business logic layer that shields the Web App from the details of DAL and, of course, to provide an extra level of validation beyond the DAL. Also, as far as I can tell right now, the Web Service will essentially be a thin wrapper over the BLL. </p>
<p>The DAL, of course, has its own set of entity objects, for instance, CustomerEntity, ProductEntity, and so forth. However, I don't want the presentation layer to have access to these objects directly, as they contain DAL specific methods and the assembly is specific to the DAL and so on. So, the idea is to create Data Transfer Objects (DTO). The idea is that these will be, essentially, plain old C#/.NET objects that have all the fields of, say, a CustomerEntity that are actually the database table Customer but none of the other stuff, except maybe some IsChanged/IsDirty properties. So, there would be CustomerDTO, ProductDTO, etc. I assume these would inherit from a base DTO class. I believe I can generate these with some template for LLBLGen, but I'm not sure about it yet.</p>
<p>So, the idea is that the BLL will expose its functionality by accepting and returning these DTO objects. I think the Web Service will handle converting these objects to XML for the third parties using it, many may not be using .NET (also, some things will be script callable from AJAX calls on the Web App, using JSON).</p>
<p>I'm not sure the best way to design this and exactly how to go forward. Here are some issues:</p>
<p>1) How should this be exposed to the clients (The presentation tier and to the Web Service code)</p>
<p>I was thinking that there would be one public class that has these methods, every call would be be an atomic operation:</p>
<p>InsertDTO, UpdateDTO, DeleteDTO, GetProducts, GetProductByCustomer, and so forth ...</p>
<p>Then the clients would just call these methods and pass in the appropriate arguments, typically a DTO.</p>
<p>Is this a good, workable approach?</p>
<p>2) What to return from these methods? Obviously, the Get/Fetch sort of methods will return DTO. But what about Inserts? Part of the signature could be:</p>
<pre><code>InsertDTO(DTO dto)
</code></pre>
<p>However, when inserting what should be returned? I want to be notified of errors. However, I use autoincrementing primary keys for some tables (However, a few tables have natural keys, particularly many-to-many ones).</p>
<p>One option I thought about was a Result class:</p>
<pre><code>class Result
{
public Exception Error {get; set;}
public DTO AffectedObject {get; set;}
}
</code></pre>
<p>So, on an insert, the DTO would get its get ID (like CustomerDTO.CustomerID) property set and then put in this result object. The client will know if there is an error if Result.Error != null and then it would know the ID from the Result.AffectedObject property.</p>
<p>Is this a good approach? One problem is that it seems like it is passing a lot of data back and forth that is redundant (when it's just the ID). I don't think adding a "int NewID" property would be clean because some inserts will not have a autoincrementing key like that. Another issue is that I don't think Web Services would handle this well? I believe they would just return the base DTO for AffectedObject in the Result class, rather than the derived DTO. I suppose I could solve this by having a LOT of the different kinds of Result objects (maybe derived from a base Result and inherit the Error property) but that doesn't seem very clean.</p>
<p>All right, I hope this isn't too wordy but I want to be clear.</p>
| <p>1: That is a pretty standard approach, that lends itself well to a "repository" implementation for the best unit-testable approach.</p>
<p>2: Exceptions (which should be declared as "faults" on the WCF boundary, btw) will get raised automatically. You don't need to handle that directly. For data - there are three common approaches:</p>
<ul>
<li>use <code>ref</code> on the contract (not very pretty)</li>
<li>return the (updated) object - i.e. <code>public DTO SomeOperation(DTO item);</code></li>
<li>return just the updated identity information (primary-key / timestamp / etc)</li>
</ul>
<p>One thing about all of these is that it doesn't necessitate a different type per operation (contrast your <code>Result</code> class, which would need to be duplicated per DTO).</p>
|
Jquery append using multiline <p>I have been working on a project that dynamically creates a javascript file using ASP.NET which is called from another site.</p>
<p>This jquery javascript file appends a div and fills it with a rather large HTML segment and in order to do that I need to turn the segment into a string like so:</p>
<pre><code>$(document).ready(function(){
var html = "Giving this magazine such a lofty epithet may seem a bit presumptuous, but for a non scientifically trained outsider this magazine offers a fresh and challenging look at the fast paced world of science that doesn't shy away from humor and the use of terms and ideas that may require its readers to go online and define a term. And in some cases it may inspire the reader to pick up a book on science by such greats as Hawking and Greene in order to better grasp some of the concepts dealing with time, space and atoms. This magazine isn't dumbed down. It includes well placed and efficient illustrations to help explain some of the more abstract points. It is not designed in the way popular magazinea are, in so much as they only touch upon a topic in the simplest manner and then move on before the audience is lost. Yet this magazine keeps the attention of the reader by combining explanatory notes that help people with no background knowledge have some grasp of the topic and by using humor and well written articles to clearly make their points. <br />For a magazine with a serious and well researched list of topics having small cartoons the likes of the New Yorker shows how comfortable this magazine is with itself. From the moment I picked up this magazine for the first time I felt like every word I read mattered and was worth my time to read. (Not true of many other magazines) American Scientist may not have the audience of Discover or National Geographic, nor is it as accessible as said titles, but for those with a true interest in science willing to challenge themselves and commit to real learning this magazine may be a perfect fit. At $4.95 it is certainly worth it to pick a copy on the news stand and try it out."
$("#divname").append(html);
});
</code></pre>
<p>As you can see the segment will be pretty large and I have no way of knowing how big as it is generated dynamically from my database depending on the reviewID which is defined by the user in their request.</p>
<p>The html to be inserted into the div is a list of reviews and is generated using asp.net MVC by a repeater which loops through a list. (if that helps give you an idea of what I am doing).</p>
<p>Is there any way to turn this large segment into one string which can be inserted into the append script?</p>
<p>Thank You</p>
| <p>Some ideas:</p>
<ul>
<li>You can replace new lines with spaces and create a huge line. There shouldn't be a problem with it.</li>
<li><p>Use string concatenation. Split the string and lines and do:</p>
<p>var html = line1 +
line2 +
...
linen;</p></li>
<li><p>Make an Ajax call to fill the div:</p>
<p>$("#divname").load(service_url);</p></li>
</ul>
<p>You need to create a service that will return the string.</p>
<p>In my opinion the 3rd option is better than the other ones.</p>
|
Add fields to ActiveRecord model dynamically in Rails 2.2.2? <p>Say I wanted to allow an administrative user to add a field to an ActiveRecord Model via an interface in the Rails app. I believe the normal ActiveRecord::Migration code would be adequate for modifying the AR Model's table structure (something that would not be wise for many applications - I know). Of course, only certain types of fields could be added...in theory.</p>
<p>Obviously, the forms that add (or edit) records to this newly modified ActiveRecord Model would need to be build dynamically at run-time. A common form_for approach won't do. This discussion suggests this can only be accomplished with JavaScript.</p>
<p><a href="http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/fc0b55fd4b2438a5" rel="nofollow">http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/fc0b55fd4b2438a5</a></p>
<p>I've used Ruby in the past to query an object for it's available methods. I seem to remember it was insanely slow. I'm too green with Ruby and Rails to know an elegant way to approach this. I hope someone here may. I'm also open to entirely different approaches to this problem that don't involve modifying the database.</p>
| <p>To access the columns which are currently defined for a model, use the <a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002239" rel="nofollow">columns</a> method - it will give you, for each column, its name, type and other information (such as whether it is a primary key, etc.)</p>
<p>However, modifying the schema at runtime is delicate.</p>
<p>The schema is pre-loaded (and cached, from the DB driver) by each model class when it is first loaded. In <code>production</code> mode, Rails only does this <em>once</em> per model, around startup.</p>
<ol>
<li>In order to force Rails to refresh its cached schema following your modification, you should force Ruby to reload the affected model's class (pretty much what Rails does for you automatically, after each request, when running in <code>development</code> mode - see <a href="http://hildolfur.wordpress.com/2006/10/29/class-reloading-in-ruby/" rel="nofollow">how to reload a class using <code>remove_const</code> followed by <code>load</code></a>.)</li>
<li>If you have a Mongrel cluster, you also have to inform the other processes in the cluster, which run in their own separate memory space, to also reload their model's classes (some clusters will allow you to create a 'restart.txt' file, which will cause an automatic soft-restart of all processes in your cluster with no additional work required on your behalf.)</li>
</ol>
<p>Now, these having been said, depending on the actual problem that you need to solve you may not need to dynamically alter the schema after all. Instead of adding, say, columns <code>col1</code>, <code>col2</code> and <code>col3</code> to some table <code>entries</code> (model <code>Entry</code>), you can use a table called <code>dyn_attribs</code>, where Entry <code>has_many :dyn_attribs</code>, and where <code>dyn_attribs</code> has both a <code>key</code> column (which in this case can have values <code>col1</code>, <code>col2</code> or <code>col3</code>) and a <code>value</code> column (which lists the corresponding values for <code>col1</code>, <code>col2</code> etc.)</p>
<p>Thus, instead of:</p>
<pre><code>my_entry = Entry.find(123)
col1 = my_entry.col1
#do something with col1
</code></pre>
<p>you would use:</p>
<pre><code>my_entry = Entry.find(123, :include => :dyn_attribs)
dyn_attribs = my_entry.dyn_attribs.inject(HashWithIndifferentAccess.new) { |s,a|
s[a.key] = a.value ; s
}
col1 = dyn_attribs[:col1]
#do something with col1
</code></pre>
<p>The above <code>inject</code> call can be factored away into the model, or even into a base class inherited from by all models that may require additional, dynamic columns/attributes (see <a href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html" rel="nofollow">Polymorphic associations</a> on how to make several models share the same <code>dyn_attribs</code> table for dynamic attributes.)</p>
<p><hr /></p>
<p><strong>UPDATE</strong></p>
<p>Adding or renaming a column via a regular HTML form.</p>
<p>Assume that you have a <code>DynAttrTable</code> model representing a table with dynamic attributes, as well as a <code>DynAttrDef</code> defining the dynamic attribute names for a given table.</p>
<p>Run:</p>
<pre><code>script/generate scaffold_resource DynAttrTable name:string
script/generate scaffold_resource DynAttrDef name:string
rake db:migrate
</code></pre>
<p>Then edit the generated models:</p>
<pre><code>class DynAttrTable < ActiveRecord::Base
has_many :dyn_attr_defs
end
class DynAttrDef < ActiveRecord::Base
belongs_to :dyn_attr_table
end
</code></pre>
<p>You may continue to edit the controllers and the views <a href="http://ariejan.net/2007/01/23/rails-nested-resource-scaffold/" rel="nofollow">like in this tutorial</a>, replacing <code>Recipe</code> with <code>DynAttrTable</code>, and <code>Ingredient</code> with <code>DynAttrDef</code>.</p>
<p><strong>Alternatively</strong>, use one of the plugins <a href="http://www.joesniff.co.uk/critique/rails-admins-plugins-review.html" rel="nofollow">reviewed here</a> to automatically put the <code>dyn_attr_tables</code> and <code>dyn_attr_defs</code> tables under management by an automated interface (with all its bells and whistles), with virtually zero implementation effort on your behalf.</p>
<p>This should get you going.</p>
|
Core Animation - Sheet-like Window Sliding <p>How difficult would it be to use core animation to make an NSView slide in an out of view like a sheet? Generally speaking, what would be involved in accomplishing this? I've been reading through the CA documentation, but it's been hard for me to pinpoint which parts are relevant to what I want to do since I have no experience with the framework.</p>
<p>Any tips at all would be much appreciated.</p>
<p>Thanks.</p>
| <p>Since you're talking of a NSView, you're probably using Cocoa's animation support, not CA directly. In this case, you just need to set the view's frame through the view's animator object:</p>
<pre><code>[theView setFrame:offscreenFrame];
[[theView animator] setFrame:finalFrame];
</code></pre>
<p>Unfortunately, Cocoa view animation interacts badly with the more advanced features of CA, like setting an easing. You might have more luck using NSViewAnimation instead, which is not Core Animation-backed and allows for a little more flexibility.</p>
|
Sharing PHP-CGI between Apache and NGINX <p>I've been running most of my PHP apps on my website on a fastcgi backend, served by NGINX. I have a new application which seems pretty well integrated with Apache; it's heavily dependent on dynamically written .htaccess files, for example. I'm working on modifying it to work natively with NGINX, but that's not yet ready. In the meantime, I was going to have NGINX proxy all connections to that path straight to Apache, and let Apache handle it.</p>
<p>However, I'm on a memory limited VPS, and I'd rather not run one set of PHP-CGI processes for NGINX (with their own APC cache) and another for Apache (using more memory for <em>their</em> APC cache). Has anyone had any luck sharing PHP between the two?</p>
<p>mod_ fcgid doesn't appear to support using already running servers, so I tried mod_ fastcgi. This seemed to work at first, but was sucking up quite a lot of memory (committed -- it was growing, not just static). Worse, I couldn't get the DirectoryIndex line in my apache configs to work with mod_fastcgi! </p>
<p>I added</p>
<pre>
AddHandler php5-fastcgi .php
FastCgiExternalServer /var/www -host 127.0.0.1:9000
</pre>
<p>to my Apache config, and all .php pages are processed, but a path like <a href="http://example.com/foo/" rel="nofollow">http://example.com/foo/</a> doesn't server /foo/index.php! If I remove FastCgiExternalServer, then it does find the index.php, but of course just shows it as text. </p>
<p>I'm assuming it's because DirectoryIndex is processed after FastCgiExternalServer, but I have no idea how this can be changed. </p>
| <p>Problem solved. The trick was to use the following lines</p>
<pre>
FastCGIExternalServer /var/www/fast-cgi-fake-handler -host 127.0.0.1:9000
AddType application/x-httpd-fastphp5 .php
Action application/x-httpd-fastphp5 /fast-cgi-fake-handler
</pre>
<p>The relative path in Action + the full path in FastCGIExternalServer did it!</p>
|
Python: How to ignore an exception and proceed? <p>I have a try...except block in my code and When an exception is throw. I really just want to continue with the code because in that case, everything is still able to run just fine. The problem is if you leave the except: block empty or with a #do nothing, it gives you a syntax error. I can't use continue because its not in a loop. Is there a keyword i can use that tells the code to just keep going?</p>
| <pre><code>except:
pass
</code></pre>
|
How do I add/remove a class in a <div> when it already has classes <p>How do I add/remove a class from a div when it already has one or more classes?</p>
<pre><code><div class="class1 class2" id="id1">some text</div>
$("#id1").toggleClass("class3"); // doesn't work
$("#id1").toggleClass(" class3"); // doesn't work
</code></pre>
<p>Do I have to parse the string?</p>
| <p>Your code should definitely work. In fact, the <a href="http://docs.jquery.com/Attributes/toggleClass" rel="nofollow"><code>toggleClass</code> example</a> <em>uses</em> multiple class names!</p>
|
How to keep special characters when running ./mysqldump? <p>How do you keep the special characters when you run mysqldump?</p>
<p>On the database it appears correctly when i do a query. But on the file after i export, all special characters look like this:</p>
<pre><code>'R. Antââ¥nio Lt1, 1¬⫠Dt¬â«'
</code></pre>
| <p>Use the correct character set by either setting it in your editor or (better) force one you like (such as UTF8) on dumping (this also helps avoiding all those problems moving database dumps across servers).</p>
<p><code>mysqldump --default-character-set=UTF8</code></p>
|
Need well formatted data for testing <p>Sometimes you need data for tests, like <a href="http://www.youtube.com/watch?v=d9IjZJ0D_bo" rel="nofollow">Adobe Thermo</a> has prewritten "sets" of data, like 1-word strings, 3-word strings, etc for use in populating data controls.</p>
<p>I need:</p>
<ul>
<li>Continuous text, no newlines</li>
<li>CSV Numbers, Integers</li>
<li>CSV Numbers, Decimals</li>
<li>URL encoded strings</li>
</ul>
<p>Any ideas on how to get any of those?</p>
| <p><a href="http://www.generatedata.com/#about" rel="nofollow">GenerateData.com</a> is a free, open source script written in JavaScript, PHP and MySQL that lets you quickly generate large volumes of custom data in a variety of formats for use in testing software, populating databases.</p>
<ul>
<li>JS-enabled and browser-friendly.</li>
<li>Many data types: names, phone numbers, email addresses, cities, states, provinces, counties, dates, street addresses, number ranges, alphanumeric strings, lorem ipsum text and more.</li>
<li>Option to generate data in XML, Excel, HTML, CSV or SQL.</li>
<li>Country specific data (state / province / county) for Canada, US, Netherlands and UK.</li>
<li>Saves your data generation forms for later use</li>
</ul>
|
64-bit linux, Assembly Language, Issues? <p>I'm currently in the process of learning assembly language.
I'm using <a href="http://en.wikipedia.org/wiki/GNU%5FAssembler" rel="nofollow">Gas</a> on <a href="http://en.wikipedia.org/wiki/Linux%5FMint" rel="nofollow">Linux Mint</a> (32-bit). Using this book:
<a href="http://savannah.nongnu.org/projects/pgubook/" rel="nofollow">Programming from the Ground Up</a>.</p>
<p>The machine I'm using has an <a href="http://en.wikipedia.org/wiki/AMD%5FTurion" rel="nofollow">AMD Turion 64 bit</a> processor, but I'm limited to 2 GB of RAM.
I'm thinking of upgrading my Linux installation to the 64-bit version of Linux Mint, but I'm worried that because the book is targeted at 32-bit x86 architecture that the code examples won't work.</p>
<p>So two questions:</p>
<ol>
<li>Is there likely to be any problems with the code samples?</li>
<li>Has anyone here noticed any benefits in general in using 64-bit Linux over 32-bit (I've seen some threads on Stack Overflow about this but they are mostly related to Windows Vista vs. Windows XP.)</li>
</ol>
| <p>Your code examples should all still work. 64-bit processors and operating systems can still run 32-bit code in a sort of "compatability mode". Your assembly examples are no different. You may have to provide an extra line of assembly or two (such as .BITS 32) but that's all.</p>
<p>In general, using a 64-bit OS will be faster than using a 32-bit OS. x86_64 has more registers than i386. Since you're working on assembly, you already know what registers are used for... Having more of them means less stuff has to be moved on and off the stack (and other temporary memory) thus your program spends less time managing data and more time working on that data.</p>
<p><strong>Edit</strong>: To compile 32-bit code on 64-bit linux using gas, you just use the commandline argument "--32", as noted in <a href="http://sourceware.org/binutils/docs-2.19/as/i386_002dOptions.html#i386_002dOptions" rel="nofollow">the GAS manual</a></p>
|
How can you have folds for a LaTeX file in XEmacs? <p>I would like to have automatic folds for comments in my AquaEmacs.</p>
| <p>have a look at <a href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Hideshow.html" rel="nofollow"><code>hs-minor-mode</code></a>. it's not automatic though. for a more automatic approach, i guess you could customize the hideshow mode the following way:</p>
<ol>
<li>hide comments via <code>hs-hide-comments-when-hiding-all</code></li>
<li>assign a function which hides nothing to <code>hs-hide-all-non-comment-function</code> and then </li>
<li>use <code>hs-hide-all</code> to hide all comments.</li>
</ol>
<p>have not tried it. just an idea.</p>
<p>check out the <a href="http://www.emacswiki.org/cgi-bin/wiki/HideShow" rel="nofollow">hideshow mode page at emacswiki</a> as well.</p>
|
Setting a timeout on ifstream in C++? <p>We're trying to read data from 2 usb mice connected to a linux box (this data is used for odometry/localization on a robot). So we need to continuously read from each mouse how much it moved. The problem is that when a mouse is not moving, it doesn't send any data, so the file stream from which we get the data blocks execution and therefore the program can't do the odometry calculations (which involve time measurement for speed).</p>
<p>Is there a way to set a timeout on the input stream (we're using ifstream in C++ and read from /dev/input/mouse), so that we're able to know when the mouse doesn't move, instead of waiting for an event to be received? Or do we need to mess up with threads (arggh...)? Any other suggestions are welcome!</p>
<p>Thanks in advance!</p>
| <p>A common way to read from multiple file descriptors in linux is to use select(). I suggest starting with the <a href="http://linux.die.net/man/2/select">manpage</a>. The basic system flow is as follows:</p>
<p>1) Initialize devices<Br>
2) Obtain list of device file descriptors<br>
3) Setup the time out<br>
4) Call select with file descriptors and timeout as parameters - it will block until there is data on one of the file descriptors or the time out is reached<br>
5) Determine why select returned and act accordingly (i.e. call read() on the file descriptor that has data). You may need to internally buffer the result of read until an entire data gram is obtained.<br>
6) loop back to 4.</p>
<p>This can become your programs main loop. If you already have a different main loop you, can run the above without looping, but your will need to insure that the function is called frequently enough such that you do not lose data on the serial ports. You should also insure that your update rate (i.e. 1/timeout) is fast enough for your primary task.</p>
<p>Select can operate on any file descriptor such network sockets and anything else that exposes an interface through a file descriptor.</p>
|
How to solve TPTP Monitor error ( IWAT0435E ) in Eclipse, on Debian-based Linux? <p>After installing Test & Performance Tools Platform in Eclipse Ganymede on, whenever I tried to profile a Java application, I was confronted by the launch configuration dialogue which contained an error along the lines of:</p>
<pre><code>Error IWAT0435E could not connect to host
</code></pre>
<p>How is this problem fixed?</p>
| <p>After searching for a while I found the solution in a couple of blogs, so thanks to
<a href="http://goodenoughjava.blogspot.com/2008/10/profiling-with-eclipse-tptp-problem.html" rel="nofollow">Pablo</a> and <a href="http://myjavanotebook.blogspot.com/2008/04/libstdc210-glibc22-on-ubuntu-hardy-804.html" rel="nofollow">Shimi</a>. These contain a more detailed background if you're interested.</p>
<p>The problem related to something called the Agent Controller being linked to an old version of libstdc++. To solve it you can run the following two commands: </p>
<pre><code>wget mirrors.kernel.org/ubuntu/pool/universe/g/gcc-2.95/libstdc++2.10-glibc2.2_2.95.4-24_i386.deb
sudo dpkg --install libstdc++2.10-glibc2.2_2.95.4-24_i386.deb
</code></pre>
<p>Though your mileage may vary depending on distro version etc.</p>
<p>You should then be able to profile successfully in Eclipse, I found that I didn't even need to restart Eclipse.</p>
|
Objective-C use of #import and inheritance <p>I have a hypothetical UIViewController class named "foo". foo inherits from class bar and class bar #import's "Class A", a class which foo uses extensively. The problem is, when I'm using an instance of class A in foo, I don't get any compiler errors, but I do get a warning for instance, that an instance of Class A does not respond to a particular method. Do I have to explicitly #import ClassA.h into class 'foo'? even though class foo extends extends bar, which already imports it?</p>
<p>Hope that's not too confusing. Let me know if I need to clear anything up.</p>
| <p>It sounds like you have a circular dependency issue. In order to resolve it, yes, each imlementation file (<code>.m</code>) needs to <code>#import</code> the proper header file. However, if you try to have the <em>header</em> files <code>#import</code> each other, you'll run into problems.</p>
<p>In order to use inheritance, you need to know the size of the superclass, which means you need to <code>#import</code> it. For other things, though, such as member variables which are pointers, or methods which take as a parameter or return the other type, you don't actually need the class definition, so you can use a <strong>forward reference</strong> to resolve the compiler errors.</p>
<pre><code>// bar.h
@class A; // forward declaration of class A -- do not to #import it here
@interface bar : UIViewController
{
A *member; // ok
}
- (A) method:(A)parameter; // also ok
@end
// bar.m
#import "bar.h"
#import "A.h"
// can now use bar & A without any errors or warnings
</code></pre>
|
Is there an in-memory provider for Entity Framework? <p>I am unit testing code written against the ADO .NET Entity Framework. I would like to populate an in-memory database with rows, and make sure that my code retrieves them properly.</p>
<p>I can mock the Entity Framework using Rhino Mocks, but that would not be sufficient. I would be telling the query what entities to return to me. This would neither test the where clause nor the .Include() statements. I want to be sure that my where clause matches only the rows I intend, and no others. I want to be sure that I have asked for the entities that I need, and none that I don't.</p>
<p>For example:</p>
<pre><code>class CustomerService
{
ObjectQuery<Customer> _customerSource;
public CustomerService(ObjectQuery<Customer> customerSource)
{
_customerSource = customerSource;
}
public Customer GetCustomerById(int customerId)
{
var customers = from c in _customerSource.Include("Order")
where c.CustomerID == customerId
select c;
return customers.FirstOrDefault();
}
}
</code></pre>
<p>If I mock the ObjectQuery to return a known customer populated with orders, how do I know that CustomerService has the right where clause and Include? I would rather insert some customer rows and some order rows, then assert that the right customer was selected and the orders are populated.</p>
| <p>An InMemory provider is included in <strong>EF7</strong> (pre-release).</p>
<p>You can use either the <a href="http://www.nuget.org/packages/EntityFramework.InMemory" rel="nofollow">NuGet package</a>, or read about it in the <a href="https://github.com/aspnet/EntityFramework/wiki/Using-EF7-in-Traditional-.NET-Applications#install-entity-framework-and-providers" rel="nofollow">EF repo</a> on GitHub (<a href="https://github.com/aspnet/EntityFramework/tree/dev/src/EntityFramework.InMemory" rel="nofollow">view source</a>).</p>
|
Use of @synthesize/@property in Objective-C inheritance <p>If you have Class A with an instance var "foo" which has a @property/@synthesize directive, and Class B inherits from Class A, does it also need to @property/@synthesize "foo"? The reason I ask is because when I try to use Class B's "foo", the calling class says that "foo" is not something of a structured union or a member, which makes me believe it needs to be explicitly synthesized.</p>
| <p>No, you don't. Synthesized properties are added to class A and its subclasses automatically.</p>
|
How can I generate scaffolding as code in CakePHP? <p>I have a cakephp app with some controllers using scaffolding for the logic and views... How can I make cake actually generate those as files and functions in my project that I can then modify and take ownership of... </p>
<p>It's nice to have this stuff as a starting point, but it can't be true that I need to start basically from scratch if I want to change the model properties that are exposed on the scaffold generated list page.</p>
| <p>You can bake the code using the cake console script. It's all explained in <a href="http://book.cakephp.org/view/113/Code-Generation-with-Bake" rel="nofollow">the cookbook</a></p>
|
Which browsers claim to support HTTP compression but are actually flaky? <p>Are there any known issues with older/buggy browsers that claim to support gzip/deflate compression but don't handle it very well? I'm obviously only turning it on for browsers that claim to support it, but for the best user experience, I want to know if there are any browsers I should blacklist. </p>
<p>For some reason, I remember hearing problems about IE6 and gzip, but I'm not sure what the details were. </p>
| <p>Here are some links to documents that name some browsers that donât support compression though claiming it:</p>
<ul>
<li><a href="http://httpd.apache.org/docs/2.2/mod/mod_deflate.html#recommended">Apacheâs sample configuration in the mod_deflate module documentation</a></li>
<li><a href="http://schroepl.net/projekte/mod_gzip/browser.htm">Which browsers can handle <code>Content-Encoding: gzip</code>?</a></li>
</ul>
|
Optimizing the speed of insertion in java.util.Map/Set <p>is there a way to optimize the speed of the insertions in a java.util.Collection by specifying the order of the items ?</p>
<p>For example</p>
<pre><code>java.util.Set<String> set = java.util.TreeSet<String>();
</code></pre>
<p>will this solution:</p>
<pre><code>set.add("A");
set.add("B");
set.add("C");
set.add("D");
set.add("E");
</code></pre>
<p>be faster than this one (random order) ?</p>
<pre><code>set.add("E");
set.add("D");
set.add("C");
set.add("A");
set.add("B");
</code></pre>
<p>(and the same question for the other collections: HashMap, hastable...)</p>
<p>Thanks</p>
| <p>The easy answer is "time it and see". </p>
<p>The other answer is "it won't matter". This seems to be a micro-optimization that is hardly worth the effort. I think it falls into the category of <a href="http://www.codinghorror.com/blog/archives/001218.html" rel="nofollow">"The Sad Tragedy of Micro-Optimization Theater"</a>.</p>
|
Why can't gcc find the random() interface when -std=c99 is set? <p>I do <code>"#include <stdlib.h>"</code> at the top of the source.</p>
<p>Example compilation:</p>
<pre><code>/usr/bin/colorgcc -std=c99 -fgnu89-inline -g -Wall -I/usr/include -I./ -I../ -I../../ -I../../../ -I../../../../ -O3 -o f8 f8.c
In file included from f8.c:7:
ctype-cmp.c: In function ârandomizedâ:
ctype-cmp.c:48: warning: implicit declaration of function ârandomâ
ctype-cmp.c: In function âmainâ:
ctype-cmp.c:153: warning: implicit declaration of function âsrandomâ
ais@xcalibur:t$
</code></pre>
<p>When I turn off -std=c99, the function isfinite() can not be found. So I do want to use -std=c99 for this and other reasons. Is there some trick I'm missing?</p>
| <p><code>man srandom</code> says that the function is <em>not</em> part of C99 but part of POSIX. </p>
<p>Activate <code>_BSD_SOURCE</code> or <code>_XOPEN_SOURCE >= 500</code> or any other suitable feature test macro that declares the srandom/random function (see <code>man feature_test_macros</code> and <code>man srandom</code>). </p>
<p>This one has good chances, but you need to figure out the macros that are defined/not defined implicitly thereby too by reading the manpages above.</p>
<pre><code>/usr/bin/colorgcc -std=c99 -D_XOPEN_SOURCE=600 -fgnu89-inline -g -Wall
-I/usr/include -I./ -I../ -I../../ -I../../../ -I../../../../ -O3 -o f8 f8.c
</code></pre>
|
Update .NET Compact Framework - when? <p>As many of you know, in Barcelona last week at the Mobile World Congress, Microsoft presented a "beta" of Windows Mobile 6.5 which will probably be launched later on this year.</p>
<p>I have been reading a lot of articles on the web about this congress and the new features of Windows Mobile 6.5 but nowhere have I found any indications if the .NET Compact Framework (currently at 3.5) will be updated as well. </p>
<p>Does anyone of you have any news/updates in this regard which you would like to share?</p>
| <p>My guess is that you shouldn't hold your breath. I really don't think there's anything new for 6.5 concerning .NET CF, but for 7.0 I'd say that a new .NET CF will be in ROM.</p>
|
URL Encoding using C# <p>I have an application which I've developed for a friend. It sends a POST request to the VB forum software and logs someone in (with out setting cookies or anything).</p>
<p>Once the user is logged in I create a variable that creates a path on their local machine.</p>
<p>c:\tempfolder\date\username</p>
<p>The problem is that some usernames are throwing "Illegal chars" exception. For example if my username was <code>mas|fenix</code> it would throw an exception..</p>
<pre><code>Path.Combine( _
Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData), _
DateTime.Now.ToString("ddMMyyhhmm") + "-" + form1.username)
</code></pre>
<p>I don't want to remove it from the string, but a folder with their username is created through FTP on a server. And this leads to my second question. If I am creating a folder on the server can I leave the "illegal chars" in? I only ask this because the server is Linux based, and I am not sure if Linux accepts it or not..</p>
<p><strong>EDIT: It seems that URL encode is NOT what I want.. Here's what I want to do:</strong></p>
<pre><code>old username = mas|fenix
new username = mas%xxfenix
</code></pre>
<p>Where %xx is the ASCII value or any other value that would easily identify the character.</p>
| <p>I've been experimenting with the various methods .NET provide for URL encoding. Perhaps the following table will be useful (as output from a test app I wrote):</p>
<pre><code>Unencoded UrlEncoded UrlEncodedUnicode UrlPathEncoded EscapedDataString EscapedUriString HtmlEncoded HtmlAttributeEncoded HexEscaped
A A A A A A A A %41
B B B B B B B B %42
C C C C C C C C %43
D D D D D D D D %44
a a a a a a a a %61
b b b b b b b b %62
c c c c c c c c %63
d d d d d d d d %64
0 0 0 0 0 0 0 0 %30
1 1 1 1 1 1 1 1 %31
2 2 2 2 2 2 2 2 %32
3 3 3 3 3 3 3 3 %33
[space] + + %20 %20 %20 [space] [space] %20
! ! ! ! ! ! ! ! %21
" %22 %22 " %22 %22 &quot; &quot; %22
# %23 %23 # %23 # # # %23
$ %24 %24 $ %24 $ $ $ %24
% %25 %25 % %25 %25 % % %25
& %26 %26 & %26 & &amp; &amp; %26
' %27 %27 ' ' ' &#39; &#39; %27
( ( ( ( ( ( ( ( %28
) ) ) ) ) ) ) ) %29
* * * * * * * * %2A
+ %2b %2b + %2B + + + %2B
, %2c %2c , %2C , , , %2C
- - - - - - - - %2D
. . . . . . . . %2E
/ %2f %2f / %2F / / / %2F
: %3a %3a : %3A : : : %3A
; %3b %3b ; %3B ; ; ; %3B
< %3c %3c < %3C %3C &lt; &lt; %3C
= %3d %3d = %3D = = = %3D
> %3e %3e > %3E %3E &gt; > %3E
? %3f %3f ? %3F ? ? ? %3F
@ %40 %40 @ %40 @ @ @ %40
[ %5b %5b [ %5B %5B [ [ %5B
\ %5c %5c \ %5C %5C \ \ %5C
] %5d %5d ] %5D %5D ] ] %5D
^ %5e %5e ^ %5E %5E ^ ^ %5E
_ _ _ _ _ _ _ _ %5F
` %60 %60 ` %60 %60 ` ` %60
{ %7b %7b { %7B %7B { { %7B
| %7c %7c | %7C %7C | | %7C
} %7d %7d } %7D %7D } } %7D
~ %7e %7e ~ ~ ~ ~ ~ %7E
Ä %c4%80 %u0100 %c4%80 %C4%80 %C4%80 Ä Ä [OoR]
Ä %c4%81 %u0101 %c4%81 %C4%81 %C4%81 Ä Ä [OoR]
Ä %c4%92 %u0112 %c4%92 %C4%92 %C4%92 Ä Ä [OoR]
Ä %c4%93 %u0113 %c4%93 %C4%93 %C4%93 Ä Ä [OoR]
Ī %c4%aa %u012a %c4%aa %C4%AA %C4%AA Ī Ī [OoR]
Ä« %c4%ab %u012b %c4%ab %C4%AB %C4%AB Ä« Ä« [OoR]
Å %c5%8c %u014c %c5%8c %C5%8C %C5%8C Å Å [OoR]
Å %c5%8d %u014d %c5%8d %C5%8D %C5%8D Å Å [OoR]
Ū %c5%aa %u016a %c5%aa %C5%AA %C5%AA Ū Ū [OoR]
Å« %c5%ab %u016b %c5%ab %C5%AB %C5%AB Å« Å« [OoR]
</code></pre>
<p>The columns represent encodings as follows:</p>
<p>UrlEncoded: HttpUtility.UrlEncode</p>
<p>UrlEncodedUnicode: HttpUtility.UrlEncodeUnicode</p>
<p>UrlPathEncoded: HttpUtility.UrlPathEncode</p>
<p>EscapedDataString: Uri.EscapeDataString</p>
<p>EscapedUriString: Uri.EscapeUriString</p>
<p>HtmlEncoded: HttpUtility.HtmlEncode</p>
<p>HtmlAttributeEncoded: HttpUtility.HtmlAttributeEncode</p>
<p>HexEscaped: Uri.HexEscape</p>
<p><strong>NOTES:</strong> </p>
<ol>
<li><p>HexEscape can only handle the first 255 characters. Therefore it throws an ArgumentOutOfRange exception for the Latin A-Extended characters (eg Ä).</p></li>
<li><p>This table was generated in .NET 4.0 (see Levi Botelho's comment below that says the encoding in .NET 4.5 is slightly different).</p></li>
</ol>
<p><strong>EDIT:</strong></p>
<p>I've added a second table with the encodings for .NET 4.5. See this answer: <a href="http://stackoverflow.com/a/21771206/216440">http://stackoverflow.com/a/21771206/216440</a></p>
<p><strong>EDIT 2:</strong></p>
<p>Since people seem to appreciate these tables, I thought you might like the source code that generates the table, so you can play around yourselves. It's a simple C# console application, which can target either .NET 4.0 or 4.5:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
// Need to add a Reference to the System.Web assembly.
using System.Web;
namespace UriEncodingDEMO2
{
class Program
{
static void Main(string[] args)
{
EncodeStrings();
Console.WriteLine();
Console.WriteLine("Press any key to continue...");
Console.Read();
}
public static void EncodeStrings()
{
string stringToEncode = "ABCD" + "abcd"
+ "0123" + " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" + "ÄÄÄÄĪīÅÅŪū";
// Need to set the console encoding to display non-ASCII characters correctly (eg the
// Latin A-Extended characters such as ÄÄÄÄ...).
Console.OutputEncoding = Encoding.UTF8;
// Will also need to set the console font (in the console Properties dialog) to a font
// that displays the extended character set correctly.
// The following fonts all display the extended characters correctly:
// Consolas
// DejaVu Sana Mono
// Lucida Console
// Also, in the console Properties, set the Screen Buffer Size and the Window Size
// Width properties to at least 140 characters, to display the full width of the
// table that is generated.
Dictionary<string, Func<string, string>> columnDetails =
new Dictionary<string, Func<string, string>>();
columnDetails.Add("Unencoded", (unencodedString => unencodedString));
columnDetails.Add("UrlEncoded",
(unencodedString => HttpUtility.UrlEncode(unencodedString)));
columnDetails.Add("UrlEncodedUnicode",
(unencodedString => HttpUtility.UrlEncodeUnicode(unencodedString)));
columnDetails.Add("UrlPathEncoded",
(unencodedString => HttpUtility.UrlPathEncode(unencodedString)));
columnDetails.Add("EscapedDataString",
(unencodedString => Uri.EscapeDataString(unencodedString)));
columnDetails.Add("EscapedUriString",
(unencodedString => Uri.EscapeUriString(unencodedString)));
columnDetails.Add("HtmlEncoded",
(unencodedString => HttpUtility.HtmlEncode(unencodedString)));
columnDetails.Add("HtmlAttributeEncoded",
(unencodedString => HttpUtility.HtmlAttributeEncode(unencodedString)));
columnDetails.Add("HexEscaped",
(unencodedString
=>
{
// Uri.HexEscape can only handle the first 255 characters so for the
// Latin A-Extended characters, such as A, it will throw an
// ArgumentOutOfRange exception.
try
{
return Uri.HexEscape(unencodedString.ToCharArray()[0]);
}
catch
{
return "[OoR]";
}
}));
char[] charactersToEncode = stringToEncode.ToCharArray();
string[] stringCharactersToEncode = Array.ConvertAll<char, string>(charactersToEncode,
(character => character.ToString()));
DisplayCharacterTable<string>(stringCharactersToEncode, columnDetails);
}
private static void DisplayCharacterTable<TUnencoded>(TUnencoded[] unencodedArray,
Dictionary<string, Func<TUnencoded, string>> mappings)
{
foreach (string key in mappings.Keys)
{
Console.Write(key.Replace(" ", "[space]") + " ");
}
Console.WriteLine();
foreach (TUnencoded unencodedObject in unencodedArray)
{
string stringCharToEncode = unencodedObject.ToString();
foreach (string columnHeader in mappings.Keys)
{
int columnWidth = columnHeader.Length + 1;
Func<TUnencoded, string> encoder = mappings[columnHeader];
string encodedString = encoder(unencodedObject);
// ASSUMPTION: Column header will always be wider than encoded string.
Console.Write(encodedString.Replace(" ", "[space]").PadRight(columnWidth));
}
Console.WriteLine();
}
}
}
}
</code></pre>
|
Where to place a primary key <p>To my knowledge SQL Server 2008 will only allow one clustered index per table. For the sake of this question let's say I have a list of user-submitted stories that contains the following columns.</p>
<p>ID (int, primary key)<br />
Title (nvarchar)<br />
Url (nvarchar)<br />
UniqueName (nvarchar) This is the url slug (blah-blah-blah)<br />
CategoryID (int, FK to Category table)</p>
<p>Most of the time stories will never be queried by ID. Most of the queries will be done either by the CategoryID or by the UniqueName.</p>
<p>I'm new to indexing so I assumed that it would be best to place 2 nonclustered indexes on this table. One on UniqueName and one on CategoryID. After doing some reading about indexes it seems like haivng a clustered index on UniqueName would be very beneficial. Considering UniqueName is... unique would it be advantageous to place the primary key on UniuqeName and get rid of the ID field? As for CategoryID I assume a nonclustered index will do just fine.</p>
<p>Thanks.</p>
| <p>In the first place you can put the clustered index on unique name, it doesn't have to be onthe id field. If you do little or no joining to this table you could get rid of the id. In any event I would put a unique index on the unique name field (you may find in doing so that it isn't as unique as you thought it would be!).</p>
<p>If you do a lot of joining though, I would keep the id field, it is smaller and more efficient to join on. </p>
<p>Since you say you are new at indexing, I will point out that while primary keys have an index created automatically when they are defined, foreign keys do not. You almost always want to index your foreign key fields.</p>
|
PHP Lexical and Syntax analyzer written in C/C++ <p>I'm writing a PHP IDE in Qt4 for my Master's project. I am trying to duplicate a lot of the functionality of Eclipse or Visual Studio without all the bloat and the overhead. I'm trying to do some code completion but I need to do some syntax analyzing to have intelligent code completion. I've looked at the PHP source code and thought about just compiling the Zend engine in my code (and give credit where credit is due), but even after staring at the code for a couple of days I'm not sure where to start with that.</p>
<p>Does anyone know some C++ code that already accomplishes this, or have used the Zend engine for their own purposes, or have some advice about writing my own?</p>
| <p>PHP does not have anything even <em>remotely</em> close to a formal LALR(1) or LL(k) grammar that you could use to implement this in a manner suitable for academia. Zend's parser is not context-aware and is full of ad-hoc disambiguations from what I've seen.</p>
<p>That is not to say you cannot write something that does simple syntax highlighting. Take for example <a href="http://marijn.haverbeke.nl/codemirror/contrib/php/" rel="nofollow">this javascript implementation</a>. The code for their tokenizer is <a href="http://marijn.haverbeke.nl/codemirror/contrib/php/js/tokenizephp.js" rel="nofollow">here</a> and an active thread about the project is <a href="http://groups.google.com/group/codemirror/browse_thread/thread/20cd864c74753db8?pli=1" rel="nofollow">here</a>.</p>
|
Associative arrays in javascript <p>I have this object:</p>
<pre><code>function formBuddy()
{
var fields = new Array();
var labels = new Array();
var rules = new Array();
var count=0;
this.addField = function(field, label, rule)
{
fields[count] = field;
labels[field] = label;
rules[field] = rule;
count = ++count;
}
}
</code></pre>
<p>Its used in this way:</p>
<pre><code>var cForm=new formBuddy();
cForm.addField("c_first_name","First Name","required");
cForm.addField("c_last_name","Last Name","required");
</code></pre>
<p>The problem is, in the <code>addField()</code> function the <code>fields</code> array is being set correct (perhaps because a numerical index is being used to refer to it) but the other 2 arrays (<code>labels</code> and <code>rules</code>) aren't being touched at all. Doing a <code>console.log</code> shows them as empty in firebug.</p>
<p>What do I need to change to make them work? I'd still like to refer to the rules and labels by the string index of the field.</p>
| <p>Use objects instead:</p>
<pre><code>function formBuddy()
{
var fields = {};
var labels = {};
var rules = {};
var count = 0;
this.addField = function(field, label, rule)
{
fields[count] = field;
labels[field] = label;
rules[field] = rule;
count++;
}
}
</code></pre>
<p><hr /></p>
<p>But as <a href="http://stackoverflow.com/revisions/575533/list#spacer-762632">Christoph already mentioned</a>, I would store this information in a single data structure too. For example:</p>
<pre><code>function formBuddy() {
var fields = {};
this.addField = function(name, label, rule) {
fields[name] = {
name: name,
label: label,
rule: rule
};
};
this.getField = function(name) {
return fields[name];
};
}
var cForm=new formBuddy();
cForm.addField("c_first_name","First Name","required");
cForm.addField("c_last_name","Last Name","required");
alert(cForm.getField("c_last_name").label);
</code></pre>
|
What's the difference between grep and map in Perl? <p>In Perl both <code>grep</code> and <code>map</code> take an expression and a list, and evaluate the expression for each element of the list.</p>
<p>What is the difference between the two?</p>
| <p><code>grep</code> returns those elements of the original list that match the expression, while <code>map</code> returns the result of the expression applied to each element of the original list.</p>
<pre><code>$ perl -le 'print join " ", grep $_ & 1, (1, 2, 3, 4, 5)'
1 3 5
$ perl -le 'print join " ", map $_ & 1, (1, 2, 3, 4, 5)'
1 0 1 0 1
</code></pre>
<p>The first example prints all the odd elements of the list, while the second example prints a 0 or 1 depending on whether the corresponding element is odd or not.</p>
|
Java Regex - reduce spaces in a string <p>I don't have time to get my head around regex and I need a quick answer. Platform is Java.</p>
<p>I need the string </p>
<pre><code>"Some text with spaces"
</code></pre>
<p>...to be converted to</p>
<pre><code>"Some text with spaces"
</code></pre>
<p>i.e., 2 or more consecutive spaces to be changed to 1 space.</p>
| <pre><code>String a = "Some text with spaces";
String b = a.replaceAll("\\s+", " ");
assert b.equals("Some text with spaces");
</code></pre>
|
In NHibernate, can I use factory to build complex aggregate object (Entity)? <p>In NHibernate, can I use factory to build complex aggregate object (Entity)?
If yes then how?
If not.. then what is your approach?</p>
| <p>Yes. If you can make the object as a POCO, you can map in to your database with NHibernate.</p>
<p>However, you don't actually understand exactly what you need, so please post clearer requirements and I'll be able to help you better.</p>
|
Confusion about streamwriters and how compression works <p>Before I begin, is it possible to write a .doc file with mixed content using a streamwriter? For example, I may have a .doc file with images and text - would a streamwriter be suitable for this? I assume a textwriter is for writing a text only document.</p>
<p>What I am trying to do is compress a file (format not known), which is easy enough. But what I am confused about is why would I call decompress? This will make the size its normal and larger value, so what is the point? If I want to compress a file and send it to a network drive, should I compress it, copy it to the network location, and decompress that to a new file? This app will be a windows service, so I will need to use Windows Impersonation, right?</p>
<p>Thanks</p>
| <p>I think you are confused about compression in general.</p>
<p>You "compress" any data to reduce its size. But by reducing it size the structure of the data must also be changed.</p>
<p>So if you save an MS Word document a .doc file, you will get MS Word document structure in the .doc file.</p>
<p>But if you then compress the .doc file, the file will gets smaller by the magic of the compression algorithms... but it will <em>no longer</em> contains MS Word document structure.</p>
<p>So how can MS Word reads the alien structure it gets? It can't!</p>
<p>That's why you have to "decompress", to restore any structure of the data it has before being compacted so it become useful again.</p>
<p>For example, suppose you have the sentence "Woah .NET rocks", a certain compression algorithm might replace each word with a page in an English dictionary and produce the string "77 69 84" instead.</p>
<pre><code>Woah -> 77
.NET -> 69
rocks -> 84
</code></pre>
<p>So how do you make sense of the string "77 69 84"?</p>
<p>It doesn't make sense of course! Because it has been compressed.</p>
<p>To make sense of it again, you'll have to decompress it, which goes like this:</p>
<pre><code>77 -> Woah
69 -> .NET
84 -> rocks
</code></pre>
<p>So basically, you are taking "other people"'s data structure and compress them. And after compression, the data would not have a sensible meaning to them because it is in compacted form. Thus you must "decompress" it so that "other people" could read it again."</p>
<p>I'm I understanding your question correctly?</p>
|
Is the Content folder sacred in asp.net mvc? <p>Is the Content folder special to the underlying framework of MVC? I can't find any reference to it in routing code or configuration.</p>
<p>I'm just wondering if static content can be handled in different ways.</p>
<p>On a related note, stackoverflow's script and css content seems to be retrieved by version number in the querystring: </p>
<pre><code><link href="/Content/all.min.css?v=2516" rel="stylesheet" type="text/css" />
</code></pre>
<p>Care to speculate how this might work and why this would be important?</p>
| <p>No magic, the System.Web.Routing.RouteCollection class has a property RouteExistingFiles which controls the behavior.</p>
<p>The default is false, which means ASP Routing should not route the URL, but just return the default content. In this case the "/Content/all.min.css?v=251" skips the MVC routing rules entirely.</p>
<p>if you want to add a routing rule for the content folder, you need to add the rule, and set RouteExistingFiles to true.</p>
|
How to obtain the keycodes in Python <p>I have to know what key is pressed, but not need the code of the Character, i want to know when someone press the 'A' key even if the key obtained is 'a' or 'A', and so with all other keys.</p>
<p>I can't use PyGame or any other library (including Tkinter). Only Python Standard Library. And this have to be done in a terminal, not a graphical interface.</p>
<p>NOT NEED THE CHARACTER CODE. I NEED TO KNOW THE KEY CODE.</p>
<p>Ex:</p>
<pre><code>ord('a') != ord('A') # 97 != 65
someFunction('a') == someFunction('A') # a_code == A_code
</code></pre>
| <p>See <a href="http://docs.python.org/library/tty.html">tty</a> standard module. It allows switching from default line-oriented (cooked) mode into char-oriented (cbreak) mode with <a href="http://docs.python.org/library/tty.html#tty.setcbreak">tty.setcbreak(sys.stdin)</a>. Reading single char from sys.stdin will result into next pressed keyboard key (if it generates code): </p>
<pre><code>import sys
import tty
tty.setcbreak(sys.stdin)
while True:
print ord(sys.stdin.read(1))
</code></pre>
<p><em>Note: solution is Unix (including Linux) only.</em></p>
<p>Edit: On Windows try <a href="http://docs.python.org/library/msvcrt.html#msvcrt.getche">msvcrt.getche()</a>/<a href="http://docs.python.org/library/msvcrt.html#msvcrt.getwche">getwche()</a>. /me has nowhere to try...</p>
<p><hr/></p>
<p>Edit 2: Utilize win32 low-level console API via <a href="http://docs.python.org/library/ctypes.html">ctypes.windll</a> (see <a href="http://stackoverflow.com/questions/239020/how-can-i-call-a-dll-from-a-scripting-language">example at SO</a>) with <code>ReadConsoleInput</code> function. You should filter out keypresses - <code>e.EventType==KEY_EVENT</code> and look for <code>e.Event.KeyEvent.wVirtualKeyCode</code> value. Example of application (not in Python, just to get an idea) can be found at <a href="http://www.benryves.com/tutorials/?t=winconsole&c=4">http://www.benryves.com/tutorials/?t=winconsole&c=4</a>.</p>
|
How do I access the original method of a monkeypatched method in Perl? <p>I'm trying to <a href="http://en.wikipedia.org/wiki/Monkey_patch" rel="nofollow">monkey patch</a> a Perl class: I want to change the behavior of an existing method. </p>
<p><a href="http://www.perlmonks.org/?node_id=694332" rel="nofollow">This node on perlmonks</a> shows how to <em>add</em> a function to an existing class. I found that this pattern can also be used to provide a new implementation for an existing function.</p>
<p>However, I'd like to know how to call the original function.</p>
<p>I'm looking for something like this:</p>
<pre><code>use ExistingClass;
# TODO: Somehow rename existingFunction() to oldExistingFunction().
sub ExistingClass::existingFunction {
my $self = shift;
# New behavior goes here.
$self->oldExistingFunction(@_); # Call old behavior.
# More new behavior here.
}
</code></pre>
| <h2>Typeglob assignment</h2>
<pre><code>*ExistingClass::oldExistingFunction = *ExistingClass::existingFunction;
</code></pre>
<p>Quick and dirty. This aliases all <code>existingFunction</code> symbols to <code>oldExistingFunction</code>. This includes the sub you're interested in, but also any scalars, arrays, hashes, handles that might happen to have the same name.</p>
<ul>
<li>Advantages: no thinking, it just works. "quick"</li>
<li>Disadvantages: "dirty"</li>
</ul>
<h2>Coderef assignment</h2>
<pre><code>*ExistingClass::oldExistingFunction = \&ExistingClass::existingFunction;
# or something using *ExistingClass::symbol{CODE}
</code></pre>
<p>That one only aliases the sub. It's still done in the package stash, so the <code>oldExistingFunction</code> symbol is globally visible, which might or might not be what you want. Probably not.</p>
<ul>
<li>Advantages: that aliasing doesn't 'leak' to other variable types.</li>
<li>Disadvantages: more thinking, more typing. A lot more thinking if going for the *...{CODE} syntax (I personnally don't use it every day)</li>
</ul>
<h2>Lexical coderef</h2>
<pre><code>my $oldFunction = \&ExistingClass::existingFunction;
</code></pre>
<p>Using <code>my</code> keeps a reference to the old function that is only visible to the currrent block/file. There is no way for external code to get hold of it without your help anymore. Mind the calling convention:</p>
<pre><code>$self->$oldFunction(@args);
$oldFunction->($self, @args);
</code></pre>
<ul>
<li>Advantages: no visibility issues anymore</li>
<li>Disadvantages: harder to get right</li>
</ul>
<h2>Moose</h2>
<p>See <a href="http://stackoverflow.com/questions/575710/monkey-patching-in-perl-how-to-access-original-method/576425#576425">jrockway's answer</a>. It's got to be The Right Way, since there's no mucking around with globs and/or references anymore, but I don't know it enough to explain it.</p>
|
Set default values for a global variable in a custom class? <p>I have a custom class that has quite a few accessor methods for customizing it. My question is, if a programmer uses this class and doesn't bother to assign values for ALL of these methods because he doesn't know about them or doesn't want to bother, how can I make the class assume a default view? I can't use awakeFromNib, because that would override purposeful customization in, say, an AppController awakeFromNib.</p>
<p>Any simple way to do this?</p>
<p>EDIT:</p>
<p>The class in an NSView, and the customization methods just modify an instance variable then tell the view to redraw (background color, etc.). When I don't explicitly tell the object somewhere to assign values for ALL of these customizations, it sets them to zero. I need to change this to where they assume usable default values. </p>
| <p>I'm confused about what you're trying to do. If you want to set default values for class members, just assign to them in your <code>init</code> method(s):</p>
<pre><code>- (id) init
{
if((self = [super init]))
{
member1 = member1default;
member2 = member2default; // etc.
}
return self;
}
- (id) initWithCoder:(NSCoder *)encoder // this is called for objects constructed from a NIB
{
if((self = [super initWithCoder:encoder]))
{
member1 = member1default;
member2 = member2default; // etc.
}
return self;
}
</code></pre>
|
Are Denormalized Updates Possible With NHibernate Without Using a Stored Procedure? <p>I'm pondering the use of NHibernate on a project that has a database with some degree of planned denormalization (planned by the DBAs). Reading from one set of tables and mapping one column to one property is not a problem. However when updating I'd have to map one property back to the original column in the original table plus update a few copies of that column in the denormalized tables. Is it possible to do this with NHibernate without using stored procedures?</p>
<p>EDIT: Although I tend to agree with NXC's answer, this question is about how to solve the problem with NHibernate as opposed to solving it in the database. </p>
| <p>Yes, you can register an event listener inheriting from DefaultSaveOrUpdateEventListener, override OnSaveOrUpdate and update the other entities.</p>
<p>Here are some blog posts about event listeners:</p>
<ul>
<li><a href="http://nhforge.org/blogs/nhibernate/archive/2008/09/06/soft-deletes.aspx" rel="nofollow">http://nhforge.org/blogs/nhibernate/archive/2008/09/06/soft-deletes.aspx</a></li>
<li><a href="http://darioquintana.com.ar/blogging/?p=9" rel="nofollow">http://darioquintana.com.ar/blogging/?p=9</a></li>
<li><a href="http://www.codinginstinct.com/2008/04/nhibernate-20-events-and-listeners.html" rel="nofollow">http://www.codinginstinct.com/2008/04/nhibernate-20-events-and-listeners.html</a></li>
</ul>
|
Which C Compiler do you recommend for windows <p>Which C Compiler do you recommend for Windows (Not C++, C ANSI)</p>
<p>Related:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/116368/c-compiler-for-windows">c compiler for windows</a></li>
<li><a href="http://stackoverflow.com/questions/397377/c-c-compiler-for-windows">C/C++ Compiler for windows</a></li>
</ul>
| <p><a href="http://www.mingw.org">Mingw</a></p>
<p>Free. Open source. GNU. Compiles native windows binaries. Can't get much better than that.</p>
|
Is a Ruby module equivalent to a Java Interface? <p>As I understand it, an interface is Java is intended to enforce a design by laying out methods for classes implementing the interface to fill in. Is this the idea with a Ruby module also? I see that just like with Interfaces in Java, you can't instantiate a module in Ruby.</p>
| <p>The short answer is no.</p>
<p>Here's the reasoning, a Java/C# interface defines the method signatures an implementing class will provide at minimum. </p>
<p>Additionally:</p>
<ul>
<li>With ruby modules there is no such contract because of the duck-typing. </li>
<li>Modules are just a way to extract out common functionality for easy re-use. The closest relation is C# extension methods, but those aren't an exact match since they exist in a static context. </li>
<li>Modules can add state to an existing class.</li>
<li>Modules can have static methods</li>
<li>Modules can act as namespaces</li>
</ul>
<p>Example: </p>
<pre><code>module SimpleConversation
class NamespacedExample
def poke
puts "ouch"
end
end
attr_accessor :partner_name
def converse
partner_name ||= "Slowpoke"
speak + "\n#{partner_name}: Yes they are"
end
def self.yay
puts "yay"
end
end
class Foo
include SimpleConversation
attr_accessor :name
def speak
name ||= "Speedy"
"#{name}: tacos are yummy"
end
end
x = Foo.new
x.name = "Joe"
x.partner_name = "Max"
puts x.speak
puts x.converse
y = SimpleConversation::NamespacedExample.new
y.poke
SimpleConversation.yay
</code></pre>
|
Property-values database <p>I have a number of objects, each one have an arbitrary number of shared, and distinct property-value pairs (more specifically: files, and their related properties -such as width, and height values for images, album/artist/length for music files, etc). I'd like to be able to search for objects having specific property/values (such as: by album), group by property, etc.</p>
<p>What kind of database would you suggest for this scenario? Due to modularity (ability to add more properties on-the-fly), as well as the fact of common properties are <20% of all properties, the standard SQL with normalized tables wouldn't really cut it. I have already tried to approach the problem using a "<a href="http://philip.greenspun.com/seia/user-registration-and-management" rel="nofollow">skinny data model</a>"; however I have faced with serious scalability issues.</p>
<p>Are there any specialized databases tuned for this scenario (BSD-licensed solutions preferred)? Or any alternative way to tweak standard RDBMs for this?</p>
| <p>Searching for an object having some properties makes me think about a RDF datastore. Have a look a a RDF API (see JENA , sesame, virtuoso ).</p>
<p>Or BerkeleyDB ?</p>
|
NSTimeInterval to readable NSNumber <p>NSTimeInterval == double; (e.g. 169.12345666663)</p>
<p>How can I round up this double so that there are only 2 digits left after the "dot"?<br />
It would be very good if the result is a NSNumber.</p>
| <p>If this is for display purposes, take a look at <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/Reference/Reference.html">NSNumberFormatter</a>.</p>
<p>If you really want to round the double in your calculations for some reason, you can use the standard C <code>round()</code> function.</p>
|
How can I unobtrusively disable submit buttons with Javascript and Prototype? <p>So I found <a href="http://stackoverflow.com/questions/326919/disabling-button-with-javascript-ff-vs-ie/327152#327152">this</a> recommendation, but I can't quite seem to figure out how.</p>
<p>This is the code I originally started with:</p>
<pre><code> function greySubmits(e) {
var value = e.srcElement.defaultValue;
// This doesn't work, but it needs to
$(e).insert('<input type="hidden" name="commit" value="' + value + '" />');
// This causes IE to not submit at all
$$("input[type='submit']").each(function(v) {v.disabled = true;})
}
// This works fine
Event.observe(window, 'load', function() {
$$("input[type='submit']").each(function(e) {
Event.observe(e, 'click', greySubmits);
});
});
</code></pre>
<p>Anyway, I am pretty close, but I can't seem to get any further.</p>
<p>Thanks for any help at all!</p>
<p><strong>Update</strong>: Sorry, I guess I wasn't entirely clear. I'd like to disable all of the submit buttons when someone clicks a submit button. But I <strong>do</strong> need to send along the value of the submit button so the server knows which button I clicked, hence the insert call. (Note: insert does <a href="http://www.prototypejs.org/api/element/insert" rel="nofollow"><strong>not</strong></a> create a child of the element you call it on.) And then after disabling the submit buttons I need to call the containing form of the submit buttons submit call, as IE will not submit after you disable the button. Does that make sense?</p>
| <p>You need to do exactly what the answer says :</p>
<p>"Do not disable the button in its "onclick", but save it, and do it in form's onsubmit."</p>
<p>So in greySubmits() keep the line that sets the hidden value, but remove the line that disables all the submit buttons.</p>
<p>Then add another event handler in your online - to the form, not the submit buttons - that does the disabling.</p>
<pre><code> function reallyGreySubmits(e) {
// This causes IE to not submit at all
$$("input[type='submit']").each(function(v) {v.disabled = true;})
}
Event.observe(window, 'load', function() {
$$("input[type='submit']").each(function(e) {
Event.observe(e, 'click', greySubmits);
});
$$("form").each(function(e) {
Event.observe(e, 'submit', reallyGreySubmits);
});
});
</code></pre>
<p>Another option, which I've used is to not disable the submits but to swap visibility between two elements. On click, mark the submits hidden, and then make visible a div or some other element that displays as "disabled" in their place.</p>
|
Changing an IIS6 website directory remotely <p>First, the prior situation: We have this project with a one-click build script. It's cobbled together with TFS Deployer + PowerShell + VB Script. TFS Deployer sits on the production machine, copies the new website files into a brand new directory, and then calls a VB Script that changes the IIS website to the new directory. </p>
<p>Now, I'm moving the team away from the horror that is TFS/MSBuild. I have a TeamCity build agent on a dedicated build server. A simple NANT script deploys the build artifacts from the build server to the production server through a shared folder. Simple, quick, and effective.</p>
<p>However, I haven't found either a way a) to run the VB Script remotely b) update the IIS site remotely with a different mechanisms (programmatically within the 1-click build). Windows Server 2003/IIS6. Any ideas?</p>
<p>Update: I solved this by creating another vbs that remotely called the old vbs I had through WMI. Thanks everyone!</p>
| <p>Could you change the vbscript file into an ASP file in a different website on the same server? This would allow you to call it remotely.</p>
|
What's the best way to diff two database backup files with MS Sql Server 2005? <p>I have two database backup files. I would like to know if there is any difference between the two. I could go row by row, field by field and do a diff (I'm not looking for differences in schema but rather data, although I expect the schema to remain the same).</p>
<p>Can I run some sort of checksum on the files, or do I have to go through the data itself to be 100% certain?</p>
| <p>Restore both backups to temporary database (might need to use 'WITH MOVE' to rename logical name), and then use a tool like RedGate's Data Compare.</p>
|
Asynchronous Webrequest best practices <p>What is the best practice for getting a webrequest asynchronously?</p>
<p>I want to download a page from the internet (doesn't matter what)
and avoid blocking a thread as much as possible.</p>
<p>Previously I believed that it was enough to just use the 'BeginGetResponse' and 'EndGetResponse' pair. But on closer inspection I also see that there is the option of using 'BeginGetRequestStream' </p>
<p><strong>[UPDATE]</strong> GetRequestStream is used for POST operations</p>
<p>And then to add to the confusion, Should I be using stream.BeginRead and EndRead?</p>
<p><strong>[UPDATE]</strong> this <a href="http://tomasp.net/blog/csharp-async.aspx">article</a> suggests it is even better to process the HttpResponse.GetResponseStream asynchronously using Stream.BeginRead</p>
<p>What a mess!</p>
<p>Can someone point me in the right direction?</p>
<p>What is the Best Practice?</p>
| <p>You could code this all yourself or you could just use WebClient which does a lot of the grunt work for you. For example, to download file as a string you would call DownloadStringAsync() which eventually will trigger the OnDowloadStringCompleted event. If the file is binary you might try using DownloadDataAsync() instead.</p>
|
Lock android app after a certain amount of idle time <p>My android application requires a password to be entered in the first activity. I want to be able to automatically send the application back to the password entry screen after the application has been idle for a fixed amount of time.</p>
<p>The application has multiple activities, but I would like the timeout to be global for all activities. So, it wouldn't be sufficient to create a timer thread in the <code>onPause()</code> method of an <code>Activity</code>.</p>
<p>I'm not sure what the best definition for the application being idle is, but no activities being active would be sufficient.</p>
| <p>I know another answer is accepted already, but I came across this working on a similar problem and think I'm going to try an alternate much simpler approach that I figured I may as well document if anyone else wants to try to go down the same path.enter code here</p>
<p>The general idea is just to track the system clock time in a SharedPreference whenever any Activity pauses - sounds simple enough, but alas, there's a security hole if that's all you use, since that clock resets on reboot. To work around that:</p>
<ul>
<li>Have an <code>Application</code> subclass or shared static singleton class with a global unlocked-since-boot state (initially false). This value should live as long as your Application's process.</li>
<li>Save the system time (<a href="http://developer.android.com/reference/android/os/SystemClock.html#elapsedRealtime%28%29">realtime</a> since boot) in every relevant <code>Activity</code>'s <code>onPause</code> into a <code>SharedPreference</code> if the current app state is unlocked.</li>
<li>If the appwide unlocked-since-boot state is false (clean app start - either the app or the phone restarted), show the lock screen. Otherwise, check the <code>SharedPreference</code>'s value at the lockable activity's onResume; if it's nonexistent or greater than the <code>SharedPreference</code> value + the timeout interval, also show the lock screen.</li>
<li>When the app is unlocked, set the appwide unlocked-since-boot state to true.</li>
</ul>
<p>Besides the timeout, this approach will also automatically lock your app if your app is killed and restarts or if your phone restarts, but I don't think that's an especially bad problem for most apps. It's a little over-safe and may lock unecessarily on users who task switch a lot, but I think it's a worthwhile tradeoff for reduced code and complexity by a total removal of any background process / wakelock concerns (no services, alarms, or receivers necessary). </p>
<p>To work around process-killing locking the app regardless of time, instead of sharing an appwide singleton for unlocked-since-boot, you could use a SharedPreference and register a listener for the system boot broadcast intent to set that Preference to false. That re-adds some of the complexity of the initial solution with the benefit being a little more convenience in the case that the app's process is killed while backgrounded within the timeout interval, although for most apps it's probably overkill.</p>
|
Which is better code for converting BSTR parameters to ANSI in C/C++? <p>So far I've discovered I can convert incoming BSTRs to ANSI in two (of many?) ways, and I'm curious to know whether one is "better" than the other with respect to speed / efficiency etc.</p>
<p>The way I've been using for a while is use the <code>USES_CONVERSION</code> and <code>W2A</code> macros, e.g.</p>
<pre><code>BSTR __stdcall F(BSTR p1, BSTR p2 ) {
USES_CONVERSION;
LPSTR sNum1 = W2A( p1 );
LPSTR sNum2 = W2A( p2 );
</code></pre>
<p>Recently, however, I came across another technique:</p>
<pre><code>BSTR __stdcall F(BSTR p1, BSTR p2 ) {
long amt = wcstombs( NULL, p1, 1 );
sNum1 = (char *) malloc( amt );
wcstombs( sNum1, p1, amt );
*(sNum1 + amt) = '\0';
amt = wcstombs( NULL, p2, 1 );
sNum2 = (char *) malloc( amt );
wcstombs( sNum2, p2, amt );
*(sNum2 + amt) = '\0';
</code></pre>
<p>Now I grant you, it's wordier, and has two calls to <code>wcstombs</code> but for all I know the <code>USES_CONVERSION</code> and <code>W2A</code> macros may be hiding all sorts of fun and games.</p>
<p>Which is the more efficient / faster code? Or, is there another technique I could use that would do the job better?</p>
| <p>From <a href="http://msdn.microsoft.com/en-us/library/87zae4a3(vs.71).aspx" rel="nofollow">MSDN</a>:</p>
<blockquote>
<p>[...]The recommended way of converting to and from BSTR strings is to use the <a href="http://msdn.microsoft.com/en-us/library/zh7x9w3f(VS.71).aspx" rel="nofollow">CComBSTR</a> class. To convert to a BSTR, pass the existing string to the constructor of CComBSTR. To convert from a BSTR, use COLE2[C]DestinationType[EX], such as COLE2T.</p>
</blockquote>
<p>From the CComBSTR page:</p>
<blockquote>
<p>[...]The CComBSTR class provides a number of members (constructors, assignment operators, and comparison operators) that take either ANSI or Unicode strings as arguments. The ANSI versions of these functions are less efficient than their Unicode counterparts because temporary Unicode strings are often created internally. For efficiency, use the Unicode versions where possible.</p>
</blockquote>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.