instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>When obtaining the DPI for the screen under Windows (by using ::GetDeviceCaps) will the horizontal value always be the same as the vertical? For example:</p>
<pre><code>HDC dc = ::GetDC(NULL);
const int xDPI = ::GetDeviceCaps(dc, LOGPIXELSX);
const int yDPI - ::GetDeviceCaps(dc, LOGPIXELSY);
assert(xDPI == yDPI);
::ReleaseDC(NULL, dc);
</code></pre>
<p>Are these values ever different?</p>
|
<p>It's possible for it to be different, but that generally only applies to printers. It can be safely assumed that the screen will always have identical horizontal and vertical DPIs.</p>
|
<p>I've never seen a case where they're different, but the fact that there are two separate calls for it strongly suggests that they might be sometimes.</p>
| 40,585
|
<p>I'm currently using a UIImageView with an array of images to create a small looping animation sequence with about 20 images in there (at 320x480). Whilst this works okay for 20 - 30 images, any more and the app quits on the iphone. There is nothing else in my test app at the moment so I know it's just down to the animationImages sequence.</p>
<p>Has anyone come across any samples of doing this type of thing through Core Animation to achieve better performance and allow many more images? From what I've read it sounds like its possible to set up a ton of CALayers and put an image in each, and then create the animation by manipulating the layers on and off in sequence. Is this a good way to do it?</p>
<p>Or, alternatively, as I'm basically after the effect of a looping movie, is there a way to use the moviecontroller to achieve the effect without it fading in and out at the start and at the end?</p>
<p>I'd be grateful for any pointers. Many thanks.</p>
|
<p>This could be a simple memory issue. 20 images (320x480) is about 3 MB of memory, assuming 8bpp (if they're higher color, obviously even more). You might try loading and unloading as needed (though, of course, that'll mean rolling your own animation, rather than using UIImageView). </p>
|
<p>Sounds like a simple memory issue.</p>
<p>You could load one or two frames at a time, or actually play a movie instead.</p>
| 32,372
|
<p>I am trying to have one one layer, and center images within. I.E., if I have 3 images and want 3 links beneath them, is there a way to do this without using a separate div tag for each link and image? To automatically make the links be centered under the images, and the images to be spaced evenly within a layer? </p>
<p>I was also wondering how I would make the div show behind standard html if that is possible. I.E. if I have some text and a div over the text, the div will default show over the text, when I would like it to be behind. Is this only possible by using another layer?</p>
|
<p>Yes, you'll have to put a container element, such as a div, around each image and its caption to keep them together.</p>
<pre><code><div class="pictureBox">
<div>
<img />
caption caption
</div>
<div>
<img />
more caption
</div>
</div>
--------
.pictureBox div {
text-align: center;
/* whatever width/height/positioning you want */
}
</code></pre>
<p>for the second part of the question, regarding putting it behind the other text, take a look at <a href="http://www.w3schools.com/css/pr_pos_z-index.asp" rel="nofollow noreferrer">CSS z-index</a>, though I think that only applies to absolutely positioned elements.</p>
|
<p>nickf is right, z-index only applies to absolutely positioned elements.</p>
<p>You could make the containing element position:relative, then give both the image and link position:absolute to affect their stacking order.</p>
| 37,794
|
<p>I can't find any post regarding the cache on logout so I'm going to ask this question. If there is a similar question. Please let me know.</p>
<p>I have a Logout page that basically call FormAuthentications signout method then redirect the user to the login page. It work fine but the problem is user can click on the browser's back button and get the cached page. I tried to set the no-cache header on my master page but that doesn't work.</p>
<p>Can someone point me to a article or tutorial or post some tips on how you handle this situation?</p>
<p>thank</p>
|
<p>Depending on your requirements a possible solution might be to set the Cache-Control header to "no-cache" on every authenticated page. This will prevent pages from being cached downstream. It could be achieved by writing a custom <a href="http://msdn.microsoft.com/en-us/library/system.web.ihttpmodule.aspx" rel="nofollow noreferrer">HttpModule</a> that will <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcachepolicy.setnostore.aspx" rel="nofollow noreferrer">set the header</a>:</p>
<pre><code>// Prevent the browser from caching the ASPX page
Response.Cache.SetNoStore();
</code></pre>
<p>You can also set this in your page's HEAD section by adding the following line of code:</p>
<pre><code><meta http-equiv="Cache-Control" content="no-cache" />
</code></pre>
<p>By doing that if a user clicks the Back button once he's been signed out, he will be redirected to the login form instead of seeing a cached version of his last page which could be a problem if he is using a public computer.</p>
|
<p>There's no foolproof way to accomplish this. The user ultimately has control over the cache settings and no-cache headers can't override these.</p>
<p>Is there a particular concern you are trying to address here (security?), or are you just trying to ensure that users aren't seeing stale data?</p>
| 49,091
|
<p>I have a basically sql select question that people gave me different answers over the years. Say I have a couple of tables designed each with over 40 columns and potentially will hold ten and thousands of row, I'm using SqlServer2005.</p>
<p>On joining these tables, in the where clause if I have things like</p>
<pre><code>select * from t1, t2
where t1.UserID = 5
and t1.SomeID = t2.SomeOtherID
</code></pre>
<p>some people say you should alwasys have the constant "t1.UserID = 5" up front rather than after the "t1.SomeID = t2.SomeOtherID", it boosts the select performance. While others say it doesn't matter.</p>
<p>What is the correct answer?</p>
<p>Also, if I use ADO.NET Entity Framework to implement my DAL, will modeling tables that have over 40 columns and doing CRUD operations be a performance issue to it?</p>
<p>Thank you,</p>
<p>Ray.</p>
|
<p>In general, with database optimization, you should write SQL which is conceptually correct first, and then tweak performance if profiling shows it to be necessary. When doing an inner join, it is better to use SQL-92, explicit INNER JOINs than Cartesian products. So I would begin by writing your SQL as follows:</p>
<pre><code>SELECT *
FROM t1
INNER JOIN t2
ON t1.SomeID = t2.SomeOtherID
WHERE
t1.UserID = 5
</code></pre>
<p>The t1.SomeID = t2.SomeOtherID that goes in the ON part of the INNER JOIN, because it expresses the relationship between the two tables. The UserID that goes in the WHERE clause because it is a filter to limit the result set. Writing your SQL in this way gives more information to the database optimizer, because it expresses your intentions about the join versus the filtering.</p>
<p>Now IF you are not getting acceptable performance with this syntax in a real-world database, then do feel free to experiment with moving bits around. But like I said, start with something which is conceptually correct.</p>
<p>With regards to the second part of your question, the most obvious performance implication is that when you select a collection of entities, the Entity Framework needs to bring back all properties for the entities it is materializing. So if you have 40 columns, then you will be pulling that data back over the wire, if you materialize them as entities. It is, however, possible to write LINQ queries which return anonymous types containing only the columns you need. However, to do full CRUD, you will need to return entities.</p>
|
<p>Firstly, construct the query using an explicit JOIN syntax, rather than the cartesian product. It probably won't make any difference performance-wise for any modern optimiser, but it does make the information on how the JOINs work more accessible for the programmers.</p>
<pre><code>
SELECT Player.Name, Game.Date
FROM Player
INNER JOIN Game ON Game.WinnerPlayerID = Player.PlayerID
WHERE Game.WinnerFrags > Game.TotalFrags/2
ORDER BY Player.Name
</code></pre>
<p>Which will give us all the players sorted by name who have take more frags in a game than all the other players in the game put together, and the dates of the games. Putting both the conditions are in the JOIN probably won't affect performance either, since the optimiser is likely do the filtering as part of the JOIN anyway. It does start to matter for LEFT JOINs though. Lets say we're looking for how many games the week's top ten players have ever won by the margin described above. Since it is possible that some of them have never one this spectacularly, we'll need LEFT JOIN.</p>
<pre><code>
SELECT Player.WeekRank, Player.Name, COUNT(Game.*) AS WhitewashCount
FROM Player
LEFT JOIN Game ON Game.WinnerPlayerID = Player.PlayerID
WHERE Player.WeekRank >= 10
AND Game.WinnerFrags > Game.TotalFrags/2
GROUP BY Player.WeekRank, Player.Name
ORDER BY Player.WeekRank
</code></pre>
<p>Well, not quite. The JOIN will return records for each game played by a player, or the player data and NULL game data if the player has played no games. These results will get filtered, during or after the JOIN depending on the optimiser's decision, based on the frag criteria. This will eliminate all the records that don't meet the frag criteria. So there will be no records to group for players who have never had such a spectacular win. Effectively creating an INNER JOIN .... FAIL.</p>
<pre><code>
SELECT Player.WeekRank, Player.Name, COUNT(Game.*) AS WhitewashCount
FROM Player
LEFT JOIN Game ON Game.WinnerPlayerID = Player.PlayerID
AND Game.WinnerFrags > Game.TotalFrags/2
WHERE Player.WeekRank >= 10
GROUP BY Player.WeekRank, Player.Name
ORDER BY Player.WeekRank
</code></pre>
<p>Once we move the frag criteria into the JOIN the query will behave correctly, returning records for all players in the week's top ten, irrespective of whether they've achieved a whitewash.</p>
<p>After all of that, the short answer is:</p>
<p>For INNER JOIN situations it probably doesn't make a to performance difference where you put the conditions. The queries are more readable if you separate the the join and filtering conditions though. And getting a condition in the wrong place can seriously mess up the results of a LEFT JOIN.</p>
| 49,247
|
<p>How do I create a view dynamically in SQL Server using C#?</p>
|
<p>Something like this, obviously your connection code will be different (better):</p>
<pre><code>SqlConnection conn = null;
conn = new SqlConnection("yourConnectionString");
conn.Open();
string strSQLCommand = "CREATE VIEW vw_YourView AS SELECT YOurColumn FROM YourTable";
SqlCommand command = new SqlCommand(strSQLCommand, conn);
string returnvalue = (string)command.ExecuteScalar();
conn.Close();
</code></pre>
|
<p>You can use the following code to write the query for a view:</p>
<pre><code>query = " Create View [Viewname] Select ....";
</code></pre>
<p>Execute the query.</p>
| 43,681
|
<p>How do you usually go about <strong>separating your codebase and associated unit tests</strong>? I know people who create a separate project for unit tests, which I personally find confusing and difficult to maintain. On the other hand, if you mix up code and its tests in a single project, you end up with binaries related to your unit test framework (be it NUnit, MbUnit or whatever else) and your own binaries side by side.</p>
<p>This is fine for debugging, but once I build a <strong>release version</strong>, I really do not want my code to <strong>reference the unit testing framework</strong> any more.</p>
<p>One solution I found is to enclose all your unit tests within #if DEBUG -- #endif directives: when no code references an unit testing assembly, the compiler is clever enough to omit the reference in the compiled code.</p>
<p>Are there any other (possibly more comfortable) options to achieve a similar goal?</p>
|
<p>I definitely advocate separating your tests out to a separate project. It's the only way to go in my opinion.</p>
<p>Yes, as <a href="https://stackoverflow.com/users/6369/garry-shutler">Gary</a> says, it also forces you to test behavior through public methods rather than playing about with the innards of your classes</p>
|
<p>I definitely agree with everyone else that you should separate the tests from your production code. If you insist on not, however, you should define a conditional comiplation constant called TEST, and wrap all of your unit test classes with a </p>
<pre><code>#if TEST
#endif
</code></pre>
<p>first to ensure that the test code does not compile in a production scenario. Once that is done, you should either be able to exclude the test dlls from your production deployment, or even better (but higher maintenance), create an NAnt or MSBuild for production that compiles without the references to the test dlls.</p>
| 10,752
|
<p>I've got a program that tends to crash quite often while I'm asleep and I need to keep it running. So I thought I might writeup a vb6 application that monitors the process list, if something disappears it will relaunch it. Anyone know of an easy way?</p>
|
<p>Use <a href="http://en.wikipedia.org/wiki/Windows_Management_Instrumentation" rel="nofollow noreferrer">WMI</a>.<br/><br/>
If you're stuck with VB6, search the web for WMI+VB6.<br/>
Otherwise, interfacing c# and WMI is much easier.</p>
|
<p>I've used scheduled task (running at each 10 min), starting cmd file with next content:</p>
<pre><code>tasklist |find "myapp.exe" >nul || c:\mypath\myapp.exe
</code></pre>
<p>You can execute such command file from VB6 Shell or just use Task Scheduler :)</p>
| 41,137
|
<p>I want to check if an app is alredy installed through launch conditions.If yes i want to exit the installer,if no the installation should continue.Could anyone tell how to achive this in c# installer?.</p>
<p>Regards,
Harsh Suman</p>
|
<p>Put an entry in the registry on install. If, when the installer runs, the entry is there, then the program is already installed (or your user has hacked the registry to make the installer think it has been). If it's not, then you haven't installed it yet.</p>
|
<p>If you don't want to put anything in the registry (due to admin rights or anything like that), you can simply check to see if the folders or files you install are present. Yes, this assumes you install to the same folder every time, but it's an option.</p>
| 25,942
|
<p>There are numerous times you have an interface that accepts similar type arguments that have a separate domain logic meaning:</p>
<pre><code>public static class Database
{
public static bool HasAccess(string userId, string documentId) { return true; }
}
</code></pre>
<p>Now it's quite easy to have someone key documentId instead of userId and vice versa. One could prevent that by abstracting the data type of the arguments:</p>
<pre><code>public class UserId
{
public string Value { get; internal set; }
public static implicit operator string(UserId id) { return id.Value; }
}
public class DocumentId
{
public string Value { get; internal set; }
public static implicit operator string(DocumentId id) { return id.Value; }
}
public static class Database
{
public static bool HasAccess(UserId userId, DocumentId documentId) { return true; }
}
</code></pre>
<p>This way you get a nice compiler warning if you type in arguments out of order:</p>
<pre><code>UserId e = new UserId() { Value = "a" };
DocumentId d = new DocumentId() { Value = "b" };
Database.HasAccess(d, e);
</code></pre>
<p>You also get the ability to change abstracted type in without affecting the rest of the system but that's not very likely. Would abstracting type be a good idea to get more type safety?</p>
<p>The question relates to C# solutions but short descriptions in other languages is welcome.</p>
<p>EDIT: Removed the implicit cast from string and pointing finger at the C# tag.</p>
|
<p>I think you answered your own question - better data integrity and validation, better system</p>
|
<p>Yes, it is sometimes a good idea. But if you get too obsessed with this you become an architecture astronaut.</p>
<p>As regards the type safety argument - it does increase type safety but lots of languages manage fine without it.</p>
<p>In my opinion the best way to go is leave it as a String to start with, and then when you find yourself reusing the interface, make the refactoring to a more abstract type at that point.</p>
<p>Predicting the future is too hard to waste time trying. </p>
| 20,966
|
<p>Suddenly my Flex Apps can no longer connect to salesforce.com via its API, I am getting a security sandbox violation. Login credentials are correct, I have tried them via a different means, and I have obfuscated them below.</p>
<p>This was working fine earlier today and I have not been coding since then.</p>
<p>Anyone else come across this or know what's going on?</p>
<p>Here is the exception returned to my app</p>
<pre><code>Method name is: login
'A997F86A-36E9-DDDC-EC6B-BBEE23101466' producer connected.
'A997F86A-36E9-DDDC-EC6B-BBEE23101466' producer sending message 'B89E5879-D7F7-E91E-2082-BBEE231054DD'
'direct_http_channel' channel sending message:
(mx.messaging.messages::HTTPRequestMessage)#0
body = "<se:Envelope xmlns:se="http://schemas.xmlsoap.org/soap/envelope/"><se:Header xmlns:sfns="urn:partner.soap.sforce.com"/><se:Body><login xmlns="urn:partner.soap.sforce.com" xmlns:ns1="sobject.partner.soap.sforce.com"><username>simon.palmer@***.com</username><password>***</password></login></se:Body></se:Envelope>"
clientId = (null)
contentType = "text/xml; charset=UTF-8"
destination = "DefaultHTTPS"
headers = (Object)#1
httpHeaders = (Object)#2
Accept = "text/xml"
SOAPAction = """"
X-Salesforce-No-500-SC = "true"
messageId = "B89E5879-D7F7-E91E-2082-BBEE231054DD"
method = "POST"
recordHeaders = false
timestamp = 0
timeToLive = 0
url = "https://www.salesforce.com/services/Soap/u/11.0"
Method name is: login
*** Security Sandbox Violation ***
Connection to https://www.salesforce.com/services/Soap/u/11.0 halted - not permitted from https://localhost/pm_server/pm/pm-debug.swf
'A997F86A-36E9-DDDC-EC6B-BBEE23101466' producer acknowledge of 'B89E5879-D7F7-E91E-2082-BBEE231054DD'.
'A997F86A-36E9-DDDC-EC6B-BBEE23101466' producer fault for 'B89E5879-D7F7-E91E-2082-BBEE231054DD'.
Comunication Error : Channel.Security.Error : Security error accessing url : Destination: DefaultHTTPS
Error: Request for resource at https://www.salesforce.com/services/Soap/u/11.0 by requestor from https://localhost/pm_server/pm/pm-debug.swf is denied due to lack of policy file permissions.
</code></pre>
|
<p>You have to make sure to load the policy from the /services tree, the default policy at the root won't help you. You need to load this policy <a href="https://www.salesforce.com/services/crossdomain.xml" rel="nofollow noreferrer">https://www.salesforce.com/services/crossdomain.xml</a></p>
|
<p>Did you recently upgrade to flash player 10? Flash player 10 changes the way policy files work to some degree, and the crossdomain.xml file needs to be updated to address this. In short, Salesforce.com probably isn't prepared for users upgrading to Flash Player 10 yet.</p>
| 39,510
|
<p>I am looking for a tool/framework to (automatically) generate a Swing user interface to perform CRUD operations on an underlying database.</p>
<p>I would also like to configure the database fields that should be exposed. Something like django (via <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms" rel="nofollow noreferrer">modelforms</a>) or ruby on rails features, but in a Java desktop environment.</p>
|
<p>NetBeans does seem like an obvious answer. These guys make a NetBeans plugin that does just that:
<a href="http://www.morelisland.com/java_services/netbeans_tutorial/midbmetadata_se.htm" rel="nofollow noreferrer">http://www.morelisland.com/java_services/netbeans_tutorial/midbmetadata_se.htm</a></p>
<p>I've heard jgoodies does something similar:
<a href="http://www.jgoodies.com/products/index.html" rel="nofollow noreferrer">http://www.jgoodies.com/products/index.html</a></p>
<p>And more specifically their sub-project, Binding:
<a href="https://binding.dev.java.net/" rel="nofollow noreferrer">https://binding.dev.java.net/</a></p>
<p>I know less about the SwingLabs databinding project, but it looks worth looking into:
<a href="https://databinding.dev.java.net/" rel="nofollow noreferrer">https://databinding.dev.java.net/</a></p>
|
<p>I'm using Netbeans (latest). I guess it's far from Django (haven't tried it, but as far as I understand it is kind of rails/symfony-like,) but it does reverse engineer the database and give you a basic application including a master/detail view.</p>
| 46,979
|
<p>I'm writing a lightweight game engine and while doing some research for it I've come across a number of compelling articles advocating the implementation of Game Objects through a "collection of components" model rather than an "inheiritance from concrete classes" model. There are lots of advantages:</p>
<ul>
<li>objects can be composed using data
driven design techniques, allowing
designers to come up with new
objects without involving a
programmer;</li>
<li>there tend to be fewer source file
dependencies, allowing code to be
compiled faster;</li>
<li>the engine as a whole becomes more
general;</li>
<li>unforseen consequences of having to
change concrete classes high up the
inheiritance hierarchy can be
avoided;</li>
<li>and so on.</li>
</ul>
<p>But there are parts of the system that remain opaque. Primarily among these is how components of the same object communicate with each other. For example, let's say an object that models a bullet in game is implemented in terms of these components:</p>
<ul>
<li>a bit of geometry for visual
representation</li>
<li>a position in the world</li>
<li>a volume used for collision with
other objects</li>
<li>other things</li>
</ul>
<p>At render time the geometry has to know its position in the world in order to display correctly, but how does it find that position among all its sibling components in the object? And at update time, how does the collision volume find the object's position in the world in order to test for its intersection with other objects?</p>
<p>I guess my question can be boiled down to this: Okay, we have objects that are composed of a number of components that each implement a bit of functionality. What is the best way for this to work at runtime?</p>
|
<p>Composable architectures usually rely on interfaces. A component then is implementation+data, enabling designers to re-use available implementations with different data. e.g. using the rocket code once with a rocket graphic and once with an arrow graphic. The flexibility comes from being able to "configure" such combinations outside of the actual run-time.</p>
<p>Within the run-time, the objects receive and provide the necessary information via the interfaces. For example, an object would receive an origin and a reference direction to position itself in the world. For actually drawing stuff I'd presume that a kind of graphical context would be passed around and the infrastructure takes care of aligning the default offset/projection appropriately for the current object. </p>
|
<p>It sounds a little over-engineered; what do you gain by making location an abstract component of an object instead of a fundamental property?</p>
<p>But if you really want to do it that way, I guess you could set up a dependancy-graph where everything's explicitly connected. So the (eg) collision-volume has a location input that's hooked up to the position-component's output. Take a look at the internals of Maya to get an idea of how this can work.</p>
<p>But again, IMHO this looks a lot like overkill.</p>
| 24,710
|
<p>I have a team lead who seems to think that business logic is very subjective, to the point that if my stored procedure has a <code>WHERE ID = @ID</code> — he would call this <em>“business logic”</em></p>
<p>What approach should I take to define <em>“business logic”</em> in a very objective way without offending my team lead?</p>
|
<p>I really think you just need to agree on a clear definition of what you mean when you say "business logic". If you need to be "politically sensitive", you could even craft the definition around your team lead's understanding, then come up with another term ("domain rules"?) that defines what you want to talk about.</p>
<p>Words and terms are relatively subjective -- of course, once you leave that company you will need to 're-learn' industry standards, so it's always better to stick with them if you can, but the main goal is to communicate clearly and get work done.</p>
|
<p>You could try to argue your point with a timed example, run a sql select against an indexed table and then run a loop to find exactly the same item in the same set but this time in code. The code will be much slower.</p>
<p>Let the database do what it was designed to do, select sets and subsets of data :) I think realistically though, all you can do is get your team together to build a set of standards which you will all code to, democracy rules!</p>
| 7,633
|
<p>So I'm basically a beginner when it comes to Vim, nonetheless I do know the basic things (open files, edit, move around, basic grep, .vimrc, etc)</p>
<p>I would submit this link first</p>
<p><a href="http://weblog.jamisbuck.org/2008/11/17/vim-follow-up" rel="nofollow noreferrer">http://weblog.jamisbuck.org/2008/11/17/vim-follow-up</a></p>
<p>If you scroll down to where it says "NERD___tree", it explains what it is and gives a link to the home page. I have already gotten NERD_tree installed, so far so good.</p>
<p>Only thing is, this guy (JamisBuck) adds a line to the .vimrc file to streamline it's usage (I'm guessing to toggle between NERD_tree and the actual file, because as far as I can tell, there is no quick way to do it other than typing in:</p>
<pre><code>:NERDTree
</code></pre>
<p>Every time which is less than desirable. The follwing is the code he adds to the .vimrc file:</p>
<pre><code>map <leader>d :execute 'NERDTreeToggle ' . getcwd()<CR>
</code></pre>
<p>He doesn't explain exactly what is is and/or how to use it, so If someone could give me a short explanation and/or point me towards a resource to learn more about this, that would be appreciated.</p>
|
<p>I'd say <code>:help leader</code> will give you what you need, is an anti-slash by default.</p>
<p>Thus, <code>map <leader>d</code> will be launched when you do <code>\d</code>.</p>
|
<p>In addition to what others have said (d mapped to the command), the command, itself:</p>
<pre><code>:execute 'NERDTreeToggle ' . getcwd()<CR>
</code></pre>
<p>Is simply executing the NERDTreeToggle command with the first argument as the current working directory. The at the end is a carriage return, and is just simulating a press of the enter key.</p>
<p>This means that when NERD tree opens, it will be in the current working directory.</p>
| 45,570
|
<p>I have a <code>Rakefile</code> with a Rake task that I would normally call from the command line:</p>
<pre><code>rake blog:post Title
</code></pre>
<p>I'd like to write a Ruby script that calls that Rake task multiple times, but the only solution I see is shelling out using `` (backticks) or <code>system</code>.</p>
<p>What's the right way to do this?</p>
|
<p>from <a href="http://web.archive.org/web/20090412040557/http://timocracy.com:80/articles/2008/02/21/calling-invoking-rails-rake-tasks-from-within-ruby-for-testing-try-2" rel="nofollow noreferrer">timocracy.com</a>:</p>
<pre><code>require 'rake'
def capture_stdout
s = StringIO.new
oldstdout = $stdout
$stdout = s
yield
s.string
ensure
$stdout = oldstdout
end
Rake.application.rake_require 'metric_fetcher', ['../../lib/tasks']
results = capture_stdout {Rake.application['metric_fetcher'].invoke}
</code></pre>
|
<p>In a script with Rails loaded (e.g. <code>rails runner script.rb</code>)</p>
<pre><code>def rake(*tasks)
tasks.each do |task|
Rake.application[task].tap(&:invoke).tap(&:reenable)
end
end
rake('db:migrate', 'cache:clear', 'cache:warmup')
</code></pre>
| 2,563
|
<p>A python script is running two parallel python processes ( created via os.fork() ) each of which eventually tries to check out a subversion repository leaf into the same working copy dir.</p>
<p>Before running 'svn co ...' command in a sub-process ( via python subprocess module ) the parent python code checks if the working copy dir already exists. </p>
<pre><code> if os.path.isdir(checkout_dir):
# working copy dir already exists
return checkout_dir
</code></pre>
<p>So that if it does there shouldn't be any 'svn co' running, but rather immediate return from the parent function.</p>
<p>Nevertheless some collision happened and one of the python processes failed on 'svn co ..' with the following error.</p>
<pre><code>checked-out failed: svn: Working copy '/tmp/qm_23683' locked
svn: run 'svn cleanup' to remove locks (type 'svn help cleanup' for details)**
</code></pre>
<p>So the first question is why the working copy dir existence check didn't work and the second - is there a way to find out that a working copy dir is locked by svn and loop until it is unlocked?</p>
<p>Thanks.</p>
|
<p>This sounds like a potential race condition, in that something like the following can happen:</p>
<ol>
<li>Process A checks to see if the directory exists (it doesn't yet).</li>
<li>Process B checks to see if the directory exists (it doesn't yet).</li>
<li>Process A invokes <code>svn</code>, which creates the directory.</li>
<li>Process B invokes <code>svn</code>, which subsequently fails.</li>
</ol>
<p>An easy way to avoid this is to have each process attempt to <em>create</em> the directory rather than checking for its existence. If the other process has already created the directory, the other process is guaranteed to get a well-defined error code under a very wide variety of platforms and filesystems. For instance, this is one of the only reliable ways to do synchronization on many implementations of NFS. Luckily, <code>svn</code> won't care if the working directory already exists.</p>
<p>The Python code would look something like this:</p>
<pre><code>import os, errno
# ...
try:
os.mkdir(dirName)
except OSError, e:
if e.errno != errno.EEXIST: raise # some other error
print 'Directory already exists.'
else:
print 'Successfully created new directory.'
</code></pre>
<p>This technique is easy to implement, very reliable, and useful in a wide variety of situations.</p>
|
<p>Within the directory, there should be a directory called '.svn'. Within this, a file named 'locked' indicates that the directory is locked.</p>
| 23,947
|
<p>currently I have only seen products from smartertools for email servers that run on windows boxes.</p>
<p>what are you guys running? Is there any other options? </p>
<p>It gets expensive when you have multiple servers requiring their software.</p>
|
<p>Imail Server works well for small organizations.
<a href="http://www.imailserver.com/" rel="nofollow noreferrer">http://www.imailserver.com/</a></p>
|
<p>We use <a href="http://www.kerio.com/kms_home.html" rel="nofollow noreferrer">Kerio Email Server</a>. It works well for us.</p>
| 32,380
|
<p>While working on SVG implementation for Internet Explorer to be based on its own VML format I came to a problem of translation of an SVG elliptical arc to an VML elliptical arc.</p>
<p>In VML an arc is given by: two angles for two points on ellipse and lengths of radiuses,
In SVG an arc is given by: two pairs of coordinates for two points on ellipse and sizes of ellipse boundary box</p>
<p>So, the question is: How to express angles of two points on ellipse to two pairs of their coordinates.
An intermediate question could be: How to find the center of an ellipse by coordinates of a pair of points on its curve.</p>
<p><b>Update</b>: Let's have a precondition saying that an ellipse is normally placed (its radiuses are parallel to linear coordinate system axis), thus no rotation is applied.</p>
<p><b>Update</b>: This question is not related to svg:ellipse element, rather to "a" elliptical arc command in svg:path element (<a href="http://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands" rel="noreferrer">SVG Paths: The elliptical arc curve commands</a>)</p>
|
<p>So the solution is here:</p>
<p>The parametrized formula of an ellipse:</p>
<pre>
x = x0 + a * cos(t)
y = y0 + b * sin(t)
</pre>
<p>Let's put known coordinates of two points to it:</p>
<pre>
x1 = x0 + a * cos(t1)
x2 = x0 + a * cos(t2)
y1 = y0 + b * sin(t1)
y2 = y0 + b * sin(t2)
</pre>
<p>Now we have a system of equations with 4 variables: center of ellipse (x0/y0) and two angles t1, t2</p>
<p>Let's subtract equations in order to get rid of center coordinates:</p>
<pre>
x1 - x2 = a * (cos(t1) - cos(t2))
y1 - y2 = b * (sin(t1) - sin(t2))
</pre>
<p>This can be rewritten (with product-to-sum identities formulas) as:</p>
<pre>
(x1 - x2) / (2 * a) = sin((t1 + t2) / 2) * sin((t1 - t2) / 2)
(y2 - y1) / (2 * b) = cos((t1 + t2) / 2) * sin((t1 - t2) / 2)
</pre>
<p>Let's replace some of the equations:</p>
<pre>
r1: (x1 - x2) / (2 * a)
r2: (y2 - y1) / (2 * b)
a1: (t1 + t2) / 2
a2: (t1 - t2) / 2
</pre>
<p>Then we get simple equations system:</p>
<pre>
r1 = sin(a1) * sin(a2)
r2 = cos(a1) * sin(a2)
</pre>
<p>Dividing first equation by second produces:</p>
<pre>
a1 = arctan(r1/r2)
</pre>
<p>Adding this result to the first equation gives:</p>
<pre>
a2 = arcsin(r2 / cos(arctan(r1/r2)))
</pre>
<p>Or, simple (using compositions of trig and inverse trig functions):</p>
<pre>
a2 = arcsin(r2 / (1 / sqrt(1 + (r1/r2)^2)))
</pre>
<p>or even more simple:</p>
<pre>
a2 = arcsin(sqrt(r1^2 + r2^2))
</pre>
<p>Now the initial four-equations system can be resolved with easy and all angles as well as eclipse center coordinates can be found.</p>
|
<p>TypeScript implementation based on the answer from Rikki. </p>
<p>Default DOMMatrix and DOMPoint are used for the calculations (Tested in the latest Chrome v.80) instead of the external library.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> ellipseCenter(
x1: number,
y1: number,
rx: number,
ry: number,
rotateDeg: number,
fa: number,
fs: number,
x2: number,
y2: number
): DOMPoint {
const phi = ((rotateDeg % 360) * Math.PI) / 180;
const m = new DOMMatrix([
Math.cos(phi),
-Math.sin(phi),
Math.sin(phi),
Math.cos(phi),
0,
0,
]);
let v = new DOMPoint((x1 - x2) / 2, (y1 - y2) / 2).matrixTransform(m);
const x1p = v.x;
const y1p = v.y;
rx = Math.abs(rx);
ry = Math.abs(ry);
const lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
if (lambda > 1) {
rx = Math.sqrt(lambda) * rx;
ry = Math.sqrt(lambda) * ry;
}
const sign = fa === fs ? -1 : 1;
const div =
(rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p) /
(rx * rx * y1p * y1p + ry * ry * x1p * x1p);
const co = sign * Math.sqrt(Math.abs(div));
// inverse matrix b and c
m.b *= -1;
m.c *= -1;
v = new DOMPoint(
((rx * y1p) / ry) * co,
((-ry * x1p) / rx) * co
).matrixTransform(m);
v.x += (x1 + x2) / 2;
v.y += (y1 + y2) / 2;
return v;
}</code></pre>
</div>
</div>
</p>
| 24,050
|
<p>Is there a tool out there which can convert SQL syntax to LINQ syntax? </p>
<p>I just want to rewrite basic queries with join, etc., to <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query" rel="noreferrer">LINQ</a>. It would save me a lot of time.</p>
|
<p>Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.</p>
<p>[<strong>Linqer</strong>] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.</p>
<p>Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.</p>
|
<p>I know that this isn't what you asked for but <a href="http://en.wikipedia.org/wiki/LINQPad" rel="noreferrer">LINQPad</a> is a really great tool to teach yourself <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query" rel="noreferrer">LINQ</a> (and it's free :o).</p>
<p>When time isn't critical, I have been using it for the last week or so instead or a query window in <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="noreferrer">SQL Server</a> and my LINQ skills are getting better and better.</p>
<p>It's also a nice little code snippet tool. Its only downside is that the free version doesn't have <a href="https://en.wikipedia.org/wiki/Intelli-sense" rel="noreferrer">IntelliSense</a>.</p>
| 37,982
|
<p>How can I have it so Visual Studio doesn't keep re-creating this folder that I never use. It's annoying ot keep looking and unnecessary.</p>
|
<p>Add a trailing slash to the default projects location:</p>
<p><a href="http://rerrify.wordpress.com/2012/03/22/get-rid-of-the-annoying-vsmacros80-folder-5/" rel="nofollow">Get Rid of the Annoying VSMacros80 Folder</a></p>
|
<pre><code>Tools->Options->Addin/Macro Security
</code></pre>
<p>Change Paths there.</p>
| 4,771
|
<p>I need to conduct a survey of 3 questions:</p>
<ul>
<li><p>The first question will be Yes/No.</p></li>
<li><p>The second will have multiple answers, in which you can select multiple answers for just that question, as well as an "other" box that you can use to fill in an answer.</p></li>
<li><p>The last question will be a textarea in which the user can enter general comments/suggestions.</p></li>
</ul>
<p>I would love for this survey app to have an administration end so I can export results to a standard format and/or be able to view the stats via the interface.</p>
<p>One I did find was <a href="http://www.limesurvey.org/" rel="nofollow noreferrer">this</a>. Are there any others like this?</p>
<p>EDIT: PHP/MySQL based.</p>
|
<p>I looked into this a few years ago. Surveymonkey is a web service that appears to be widely used, especially by non-computer literate. If you want to modify, serve and count yourself (possible for free), see <a href="http://websurveytoolbox.org/FeatureTable.html" rel="nofollow noreferrer" title="this comparison chart">this comparison chart</a>.</p>
|
<p><a href="http://www.surveymonkey.com" rel="nofollow noreferrer">http://www.surveymonkey.com</a> works well in my experience.</p>
| 31,658
|
<p>I want to create visuals along the lines of CNN's "red-state, blue-state" shadings of the states in the U.S. for my project. I'm planning to do something fancier than just shading the state's shape in a color. Are there open source libraries of state shapes/polygons (or - if not open source - others) that I can import into Word, Excel, etc. that I can use to show complicated graphs based on states?</p>
<p>I have Map Point, but haven't been able to figure out how to shade the states in a complex way.</p>
|
<p>you could try google charts, it looks like <a href="http://www.woot.com" rel="nofollow noreferrer">http://www.woot.com</a> is doing something similar to what you need</p>
|
<p>There might be a couple parts to the question you are asking, but to address the first part "Are there open source libraries of state shapes/polygons...", here's a resource to check out:</p>
<p><a href="http://commons.wikimedia.org/wiki/Category:SVG_maps_of_the_United_States" rel="nofollow noreferrer">http://commons.wikimedia.org/wiki/Category:SVG_maps_of_the_United_States</a></p>
<p>It's a list of various SVG(scalable vector graphics) files which can be imported into a number of applications. Basically a giant xml representation of lines and endpoints. This can be directly converted to XAML, if you're into a more programmatic way of charting(ie, C# w/ Silverlight).</p>
<p>However, to address the second part regarding MS Office, Visio can import SVG files for manipulation as well. I'm unsure what type of graphs you were looking for, but I hope this can assist in some small way on your path to awesomeness ;)</p>
| 27,712
|
<p>What is <a href="http://docs.oracle.com/javase/6/docs/api/java/awt/Component.html#getName%28%29" rel="noreferrer"><code>java.awt.Component.getName()</code></a> used for? It always seems to be <code>null</code> in the applications I build with NetBeans. I'm thinking of storing some help text per component in it -- I don't want to use the tooltip, I have another panel where I'll show the help text.</p>
|
<p>Component.setName(..) is used in the JDK mostly by the look and feel implementation classes to set ID-like strings for each component, e.g. BasicOptionPaneUI might call it on a button component to set its name to "OptionPane.button".</p>
<p>The getName() is used in toString() methods, when setting the names of child components inside a Composite/parent Component and in AWT and Swing debug logging code.
I suspect strongly that the getName() method is also used by some AWT/Swing testing frameworks. </p>
<p>So if you're not dependent on any of the above uses of getName(), you might try using it for your help messages, though I would not recommend it. </p>
<p>Maybe you should reconsider your design? Use the name to do some lookup in a hashmap that loads the help text from a resource bundle?</p>
|
<p>I have searched many answers for getting name
and i think this is the only easy solution </p>
<pre><code>public static void main(String[] args) {
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
String name = actionEvent.getSource().toString();
UserReaction(ObjectName.getComponentVariableName(name), "null");
}
};
Button calculate_btn = new Button("Calculate");
calculate_btn.setName("Calculate");
calculate_btn.addActionListener(actionListener);
}
private static void UserReaction(String objectName) {
if (objectName.equals("Calculate")) {
//do something;
}
}static public String getComponentVariableName(String name) {
String res = (name.substring(name.indexOf("[") + 1));
res = res.split(",")[0];
return res;
}
</code></pre>
| 28,106
|
<p>I've been tasked with implementing a Date/Time selector for several areas of our web project, and instructed to use a control that another developer created as part of it. The control I'm working on is supposed to allow the user to choose a date from a calendar, choose a format for the display of that date (from several pre-defined formats, or with a simple text override) and optionally a time string (which is really just freeform text).</p>
<p>The control I was instructed to use is documented here: <a href="http://www.west-wind.com/WebLog/posts/213015.aspx" rel="nofollow noreferrer">http://www.west-wind.com/WebLog/posts/213015.aspx</a>, and uses the DatePicker from jQuery.</p>
<p>After I implemented my control and tested it, I began integrating it into the pages which needed Date and/or time inputs. In my testing of those implementations, I discovered a bug: when I include multiple copies of my control on a page, only the first one gets the jQuery calendar. The others are not tied to it.</p>
<p>I have tried some of the methods suggested in a seemingly-related question (titled 'duplicating jquery datepicker'), such as calling the '.datepicker()' function on the west-wind control (which renders a textbox) via the $("css-selector").datepicker() syntax, and ASP.NET is guaranteeing unique IDs for all the text boxes.</p>
<p>So, in summation, it looks like this:</p>
<pre><code><page>
<mycontrol>
<west-windjQuerycontrol />
</mycontrol>
<mycontrol>
<west-windjQuerycontrol />
</mycontrol>
</page>
</code></pre>
<p>Now, the strange part: When there are multiple copies of the west-wind control on the page, without the other user control containing them, they work correctly. Other than the jQuery control, my control has nothing unusual about it: simply labels, textboxes, panels, and dropdowns. Something about bundling the West-Wind jQuery control into a user control seems to be breaking it.</p>
<p>Any advice? I've been banging my head against this for a while, hampered by my poor javascript skills and limited exposure to jQuery.</p>
<p>As pointed out below, it's hard to say without the HTML. I've included it below.</p>
<pre><code><form name="form1" method="post" action="ControlTest.aspx" id="form1">
<div>
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__LASTFOCUS" id="__LASTFOCUS" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTU4NjEzMDEwOQ9kFgICAw9kFgQCAw9kFgRmD2QWAgIDD2QWAgIDDxBkZBYBZmQCAg9kFgICAw9kFgICAQ8QZGQWAWZkAgUPZBYEZg9kFgICAw9kFgICAw8QZGQWAWZkAgIPZBYCAgMPZBYCAgEPEGRkFgFmZGRDjfLpdb+XxaVaQYP2XkPil2Galw==" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<script src="/SSO/DE/WebResource.axd?d=jMPpL-KK8_mPj_ssZzGblw2&amp;t=633481894229838141" type="text/javascript"></script>
<script src="/SSO/DE/ScriptResource.axd?d=8KwRIGaNAD3hi2Loz3YV-uxgrdZpGe8nnwH5E3gxLW_lQpnYjRbyIYThTnHtD9rt0&amp;t=633613004148118290" type="text/javascript"></script>
<script src="/SSO/DE/ScriptResource.axd?d=8KwRIGaNAD3hi2Loz3YV-uxgrdZpGe8nnwH5E3gxLW-K0Kuw-pGK1O3mE_r1y3sjKmhHtQjSXeMtYSim0bjyGA2&amp;t=633613004148118290" type="text/javascript"></script>
<script src="/SSO/DE/ScriptResource.axd?d=Id5yAacLMZHF7TWlkgrrid30ZStmsXuLHcF6WQ404YLySP4Itj4qxv2wi9ffbsWQA86oLdnZPWkwDnu4NKxfG1Ue7qdGG1SbOfb4ooHVs7M1&amp;t=633481957084709567" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>
<script src="/SSO/DE/ScriptResource.axd?d=Id5yAacLMZHF7TWlkgrrid30ZStmsXuLHcF6WQ404YLySP4Itj4qxv2wi9ffbsWQhT3MFELBAa2rFJZXnSlYAZIN7RT1npcBxJRsWGjJWIwTF0Es1m0vOd-xYnFqWJKz0&amp;t=633481957084709567" type="text/javascript"></script>
<div style="margin:25px 10px;width:100%;">
<script type="text/javascript">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('stupidThing', document.getElementById('form1'));
Sys.WebForms.PageRequestManager.getInstance()._updateControls([], [], [], 90);
//]]>
</script>
<div id="datePicker_Div0" class="AdminRowOdd DERow">
<div id="datePicker_Div1" class="DELabel">
<span id="datePicker_DateLabel">Date</span>
</div>
<div id="datePicker_Div2" class="DEInput datePicker">
<input name="datePicker$DateSelector" type="text" onchange="javascript:setTimeout('__doPostBack(\'datePicker$DateSelector\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="datePicker_DateSelector" style="width:80px;" />
<select name="datePicker$languageSelector" onchange="javascript:setTimeout('__doPostBack(\'datePicker$languageSelector\',\'\')', 0)" id="datePicker_languageSelector">
<option selected="selected" value="en-US">en-US</option>
<option value="fr-CA">fr-CA</option>
<option value="fr-FR">fr-FR</option>
<option value="es-ES">es-ES</option>
<option value="es-MX">es-MX</option>
</select>
</div>
</div>
<div id="datePicker_Div3" class="AdminRowEven DERow">
<div id="datePicker_Div4" class="DELabel">
<span id="datePicker_FormatChoiceLabel">Choose your display format: </span>
</div>
<div id="datePicker_Div5" class="DEInput">
<select name="datePicker$DateFormatSelector" onchange="javascript:setTimeout('__doPostBack(\'datePicker$DateFormatSelector\',\'\')', 0)" id="datePicker_DateFormatSelector">
<option selected="selected" value="Choose a date first">Choose a date first</option>
</select>
</div>
</div>
<div id="datePicker_Div6" class="AdminRowOdd DERow">
<div id="datePicker_Div7" class="DELabel">
<span id="datePicker_FormatOverrideLabel">Or enter your own text</span>
</div>
<div id="datePicker_Div8" class="DEInput">
<input name="datePicker$DateFormatOverride" type="text" onchange="javascript:setTimeout('__doPostBack(\'datePicker$DateFormatOverride\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="datePicker_DateFormatOverride" />
</div>
</div>
<br />
<div id="date1_Div0" class="AdminRowOdd DERow">
<div id="date1_Div1" class="DELabel">
<span id="date1_DateLabel">Date</span>
</div>
<div id="date1_Div2" class="DEInput datePicker">
<input name="date1$DateSelector" type="text" onchange="javascript:setTimeout('__doPostBack(\'date1$DateSelector\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="date1_DateSelector" style="width:80px;" />
<select name="date1$languageSelector" onchange="javascript:setTimeout('__doPostBack(\'date1$languageSelector\',\'\')', 0)" id="date1_languageSelector">
<option selected="selected" value="en-US">en-US</option>
<option value="fr-CA">fr-CA</option>
<option value="fr-FR">fr-FR</option>
<option value="es-ES">es-ES</option>
<option value="es-MX">es-MX</option>
</select>
</div>
</div>
<div id="date1_Div3" class="AdminRowEven DERow">
<div id="date1_Div4" class="DELabel">
<span id="date1_FormatChoiceLabel">Choose your display format:</span>
</div>
<div id="date1_Div5" class="DEInput">
<select name="date1$DateFormatSelector" onchange="javascript:setTimeout('__doPostBack(\'date1$DateFormatSelector\',\'\')', 0)" id="date1_DateFormatSelector">
<option selected="selected" value="Choose a date first">Choose a date first</option>
</select>
</div>
</div>
<div id="date1_Div6" class="AdminRowOdd DERow">
<div id="date1_Div7" class="DELabel">
<span id="date1_FormatOverrideLabel">Or enter your own text</span>
</div>
<div id="date1_Div8" class="DEInput">
<input name="date1$DateFormatOverride" type="text" onchange="javascript:setTimeout('__doPostBack(\'date1$DateFormatOverride\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="date1_DateFormatOverride" />
</div>
</div>
</div>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWFQLr6MeTCwKb1Zr0AwKVt6utCQKIwaTjAQKdwYzzBwLiwsDhDQKIwdCLBAKHwbCtCgLRr42cCQKi9vj4DgK2lM6kBQLLrsUtAsaboRMC2+2u3QgCzu2GzQ4Cse7K3wQC2+3atQ0C1O26kwMCpdTivwwC1o2X2wsCoubqnQk8I1BK30Q/iVw/rExUww2Cs4bicw==" />
</div>
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready( function() {
var cal = jQuery('#datePicker_DateSelector').datepicker({yearRange: '-1500:+100',dateFormat: 'm/d/yy'});
} );
Sys.Application.initialize();
//]]>
</script>
</form>
</code></pre>
|
<p>Why would you start a thread and then join against it immediately?</p>
<p>I'd normally do something like this:</p>
<pre><code>List<Thread> threads = new List<Thread>();
foreach (string item in items)
{
string copy = item; // Important due to variable capture
ThreadStart ts = () => DoWork(copy); // Strongly typed :)
Thread t = new Thread(ts);
t.Start();
threads.Add(t);
}
foreach (Thread t in threads)
{
t.Join();
}
</code></pre>
|
<p>Why not have your parameters be part of the class, make them properties, and have the get/set methods lock around them? If you have enough parameters, make the parameter object itself a property of the object, and then lock that parameter block. As in:</p>
<pre><code>class GonnaDoSomeThreading {
private Object mBlockLock = new Object();
private MyParameterBlock mBlock;
public MyParameterBlock Block {
get {
MyParameterBlock tmp;
lock (mBlockLock){
tmp = new MyParameterBlock(mBlock); //or some other cloning
}
return tmp; //use a tmp in order to make sure that modifications done
//do not modify the block directly, but that modifications must
//be 'committed' through the set function
}
set { lock (mBlockLock){ mBlock = value; } }
}
}
</code></pre>
<p>And then do your thread pool as already suggested. That way, you've got locks around the data access, so that if all of your threads need it, they can wait on one another.</p>
<p>If you're doing this for something like image processing (where a lot of parallel objects can be done at once), then it might be better to break up your data into individualized chunks. IE, say you want to run some convolution over a largish image, and so want to break it up into two halves. Then, you can have a 'Fragmentimage' function which creates the image blocks that you're going to work on individually, and then a 'MergeFragments' function call to join all the results. So your fragment could look like:</p>
<pre><code>class ThreadWorkFragment {
<image type, like ushort>[] mDataArray;
bool mDone;
}
</code></pre>
<p>Put a lock around that fragment (ie, a list of objects and fragments, with each having a lock and so forth), so that when the thread accesses it's fragment, it can eventually state that it's 'done', release the lock, and then you can have a final merge function which just waits for those done booleans to be flagged. That way, if one of the threads dies before setting done, and you know the thread's dead, then you also know that the thread didn't finish its work and you need to do some error recovery; if you just wait for a join to happen, the thread could still have messed up its fragment.</p>
<p>But there's a lot of those kinds of specific ideas to implement, based on the problem you're trying to solve.</p>
| 31,824
|
<p>What are the benefits of Perforce?</p>
<p>I'd love to have some insight as to how Perforce can work better in a given situation than, say, Subversion.</p>
<p>If you have experience with both Perforce and Subversion and you don't believe that there are any advantages, or believe that svn has advantages over Perforce, I'd like to know why, as well.</p>
|
<p>I've worked with Perforce for years, as well as Clearcase, Sourcesafe, RCS, PVCS, CVS and Subversion. More recently I've started using GIT too.</p>
<p>From this experience my opinion is that, for most purposes, Perforce is the best version control system for commercial environments. While not as simple, initially, as Subversion, it has a number of more powerful features, especially around branching and merging. The "lock by default" approach is generally more suited to this environment.</p>
<p>For personal stuff, small collaborative projects, small start-ups, or open source projects I find Subversion is better suited in many cases. They have different approaches, different ways of working. You can't just line them up on a scale and say which is best.</p>
<p>That said I hate ClearCase. ClearCase is usually forced down from above (ie a management decision).</p>
<p>For many of the cases where Subversion trumps Perforce many people seem to prefer the distributed systems like GIT, Bazaar, Mercurial, these days. From what I have seen of GIT they may well be right and I'm sure other posters will bear that out.</p>
|
<p>A Perforce server can <b>read and write arbitrary files on the client, and thus execute arbitrary code.</b> The Perforce configuration is all server-side, so the server could simply treat the entire hard disc of the clients' computer as a repository, and do <b>whatever it wanted to it.</b></p>
<p>Never run Perforce except in an SELinux sandbox.</p>
<p><b>Remember: The Perforce client is the server's puppet.</b> You must use the operating system's security features to prevent it from doing something you don't want it to do. <b>ALWAYS treat the Perforce client as hostile.</b></p>
| 31,028
|
<p>My end goal is getting high quality dash footage from a 6 month road trip I'm going on. From my research, very few dash cams support 4k 30fps filming, and the ones that do overwrite their own footage really quick, so instead of that I'd like to use my iPhone. I have a wide angle lens for it, and I figure I can mount it to my windshield, behind the rear-view mirror.</p>
<p>But here's the problem: <strong>there are no windshield phone mounts that allow for the angle I need.</strong> They're all designed to point the phone screen at the driver, and the little ball joints that let you set the angle just don't work to point the camera straight ahead. I've tried like 5 different ones, and they all have this problem.</p>
<p>What I need is a solid thing that sticks to my windshield and holds my phone in the correct direction. Once stuck, it never needs to be adjusted. I think I could use 3M strips to stick something to the glass, so the only remaining part of the mystery is this: <strong>A piece of plastic the exact right shape to hold my phone and point it at a specific angle.</strong></p>
<p>My question is: <strong>Is this a good use case for 3D printing?</strong> And if so, how would a complete amateur get started on this?</p>
<p>A few more requirements that I'm not sure if 3D printing can meet:</p>
<ul>
<li>It would need to withstand heat, as it would be left in the car on hot days in the south.</li>
<li>It can't be too brittle, as speed bumps and dirt roads will knock it around a fair bit, and it has to support a large phone with an added lens.</li>
</ul>
|
<p>You'd <a href="https://3dprinting.stackexchange.com/questions/6119/can-you-put-pla-parts-in-your-car-in-the-sun">need to print in a heat resistant material</a> - ASA for example - and design the part for your needs, but this project is certainly feasible and doable with 3D printing. If that isn't enough for you, you could drill a hole to the internal cavity (it's best to have an infill pattern that does not split the internal cavity into several ones. Gyroid is one of these) and fill it with resin to make it even more sturdy.</p>
<p>With the right design, you could also go for SLA/DLP aks resin printing, but I am not well versed in the properties of printed resins but that they have some of the best inter-layer bonds.</p>
<p>If you don't want to get a 3D printer yourself, order the part printed, which usually comes cheaper than an entry-level printer with better quality for a one-off project as you won't have to learn the ins and outs of your printer and how to ensure the quality in the material you choose. Some print services also provide really exotic materials.</p>
|
<p>Why not try a GoPro camera? They now have 4K, image stabilized camera with all kinds of accessory mounts.</p>
<p><a href="https://shop.gopro.com/cameras/hero7-silver/CHDHC-601-master.html" rel="nofollow noreferrer">https://shop.gopro.com/cameras/hero7-silver/CHDHC-601-master.html</a></p>
| 1,398
|
<p>the problem I have is that I have two sets of values in a drop down list. If type 'A' is selected I want a text box to be populated with a value from the database and be read only. If Type 'B' is selected the box is to be empty and editable.</p>
<p>My original code is written in jsp/struts and I have sort of achieved this by using </p>
<p><code>onchange="javascript:submit()"</code> to reload the page, but this has the obvious drawback of saving any changes you have made which means you can't really cancel.</p>
<p>I also have other problems with the serverside validation due to this method.</p>
<p>Is there a way of making a jsp page reload on change, that way I could write javascript to change the way the page looks according to the values held in the session. That way the save/submit function will only be called when the page has properly been filled out and the server side validation will work as designed.</p>
<p>I know that this is something that AJAX is good at doing but I am trying to avoid it if possible.</p>
|
<p>AJAX is your only other option my friend, unless on the original page load you load all the other possible values of the Text Box so you don't need to go back to the database. Well, you could try putting the text box in an IFRAME, but you will probably run into more problems with that approach than just going with AJAX.</p>
|
<p>Without AJAX what you are asking is going to be difficult. Another option (which is ugly) is to write out all possible values for the second list box into a data structure like an array or dictionary.</p>
<p>Then write some javascript to get the values from the data structure when the user selects from the first list box. The amount of javascript you will have to write to get this done and to do it correctly in a cross browser way will be much more difficult than simply using AJAX.</p>
| 35,176
|
<p>I was looking into the best encryption for a license key for an application, and someone said that someone can easily decompile the application and then just skip the test for the license key.</p>
<p>how would someone go about doing that practically speaking? So they have my .dll, they have to decompile it somehow, then comment out the function call to check the license, then recompile it? The decompiler has to be really good such that the code still compiles!</p>
|
<p>Try opening your application with <a href="http://www.red-gate.com/products/reflector/" rel="noreferrer">Reflector</a>. You will probably be surprised :-)</p>
<p>And once a cracker has located the right location in your code, they can use a combination of <a href="http://msdn.microsoft.com/en-us/library/f7dy01k1(VS.80).aspx" rel="noreferrer">ildasm</a>/<a href="http://msdn.microsoft.com/en-us/library/496e4ekx(VS.80).aspx" rel="noreferrer">ilasm</a> to remove the check from your application - even if the code Reflector generates won't compile.</p>
|
<p>Even without Reflector, people have been doing this for ages. Basically you watch the app with a debugger - something like WinDBG will do - and then find out when the license check happens. You watch the return value, and then you simply patch the application to jump directly to the "all good" check. </p>
<p>I'd recommend everything that people have posted above. You just have to realize that it is a cat and mouse game, and if your return on investment is going to be worth it. If you have users that aren't trying to game the system, then something simple may do. If you have something where cracking is rampant, then you will have to look at different strategies and go from there.</p>
<p>You don't have to recompile the application to patch it - plenty of binary patch tools exist out there. And it won't stop your most determined crackers if there is enough money to be made.</p>
| 33,245
|
<p>I've used all three of these when making local programmatic connections to databases. Is there any real difference between them?</p>
|
<p>The final result is the same. The difference is: </p>
<ul>
<li>'localhost' resolves at the TCP/IP level and is equivalent to the IP address 127.0.0.1</li>
<li>Depending on the application "(local)" could be just an alias for 'localhost'. In SQLServer, '(local)' and '.' mean that the connection will be made using the named pipes (shared memory) protocol within the same machine (doesn't need to go through the TCP/IP stack). </li>
</ul>
<p>That's the theory. In practice, I don't think there is substantial difference in performance or features if you use either one of them.</p>
|
<p>As far as I know the dot <strong><em>"."</em></strong> and <strong><em>"local"</em></strong> are windows application terms, not a "standard" term, <strong><em>localhost</em></strong> resolves to <strong><em>127.0.0.1</em></strong> in the TCP/IP level so if you want to make sure you are "compatible" across platforms you should use either localhost or 127.0.0.1</p>
| 18,839
|
<p>In jQuery, how do you select the <code><a></code> which href is pointing to the current URL</p>
<p>For example:<br>
URL = <a href="http://server/dir/script.aspx?id=1" rel="nofollow noreferrer">http://server/dir/script.aspx?id=1</a></p>
<p>I want to select this <code><a></code><br>
<code><a href="/dir/script.aspx">...</a></code></p>
<p>I tried this but it doesn't work:</p>
<pre><code>var url = window.location.href;
$('#ulTopMenu a["'+url+'"*=href]').addClass("selected");
</code></pre>
<p>Probably wrong syntax. Anyone know the right way of doing it?</p>
<p>Thanks in advance</p>
|
<p>It sounds like you're trying to solve the selected tab 'pattern'. I've found I can solve this myself with the following code:</p>
<pre><code>var nav = location.pathname.substr(1).split('/', 2)[0] || '/';
if (nav) {
$('#ulTopMenu a[href$="' + nav + '"]').parent().addClass('selected');
}
</code></pre>
<p>This basically says add the class of selected if the URL ends with the same ending as the current URL. Though you have to watch out for 'similar' urls - but if you have a lot of urls that are actually similar, you should probably consider a server side solution.</p>
<p>(I posted an article a while back on this technique - if it's actually what you're trying to do: <a href="http://leftlogic.com/lounge/articles/auto-selecting_navigation/" rel="nofollow noreferrer">http://leftlogic.com/lounge/articles/auto-selecting_navigation/</a>)</p>
|
<p>I do not know the answer to your question but is that selector syntax valid?</p>
<pre><code>'#ulTopMenu a["http://www.foo.com"*=href]'
</code></pre>
<p>I'd imagine if such a thing is possible it'd be written as</p>
<pre><code>'#ulTopMenu a[href*="http://www.foo.com"]'
</code></pre>
| 41,760
|
<p>I'm not familiar with shell scripting, so I'm not sure how to do it or if it is possible. If you can give me links or advice, that would be great.</p>
<p>What I want to do is:</p>
<ul>
<li><p>Create a file, simple text file
EX:</p>
<p>param1 (RANDOMVALUE)</p>
<p>Where randomvalue is a random number generated.</p>
</li>
<li><p>run a program with that file we just created and output to a file</p>
<p>./program filewejustcreated > A</p>
</li>
</ul>
<p>The program has already been created and it takes a filename as a parameter, no need to worry about that stuff.</p>
<ul>
<li>run another program with the file we just created, the program already exists and out put it to a file</li>
</ul>
<p>./Anotherprogram filewejustcreated > B</p>
<ul>
<li><p>run a diff comamand on A, B</p>
<p>diff A B</p>
</li>
</ul>
<p>Display what diff returns...</p>
<p>Thanks</p>
<p>[Edit] I am using shell: tcsh</p>
|
<p>You have almost written the script already. The only missing thing is the random number; I'll do it with Perl. Here is a quick & dirty solution in sh (or bash; I'm presuming you're on a Linux/Unix system):</p>
<pre><code>#!/bin/sh
perl -e 'print "TheWord (", int(rand(1000)), ")\n"' > tempfile
./program tempfile > A
./Anotherprogram tempfile > B
# rm tempfile # this would delete 'tempfile' if uncommented
diff A B
</code></pre>
<p>Now save this in a file (say, script.sh) and in a shell execute:</p>
<pre><code>chmod +x script.sh
</code></pre>
<p>to make it executable, and</p>
<pre><code>./script.sh
</code></pre>
<p>to run it.</p>
|
<p>Shell scripting is mostly just putting together different programs in ways that get the job done. There are a lot of programs that do just one simple thing and can be combined to accomplish larger tasks that you will learn of as you get into the shell scripting world.
An example of a large shell script is <a href="http://public.activestate.com/cgi-bin/perlbrowse/f/Configure" rel="nofollow noreferrer">perl's Configure script</a>. In the first bit you see (along with some humorous comments) cat, true, sh, rm, test, sed, uname, and grep used.</p>
| 42,764
|
<p>If I want to bind a collection to a some form of listing control in Silverlight. Is the only way to do it so make the underlying objects in the collection implement INotifyPropertyChanged and for the collection to be an Observablecollection?</p>
<p>If I was using some sort of third party object, for example that returned by a web service, I would have to wrap it or map it to something that implements INotifyPropertyChanged ?</p>
|
<p>No, once you add a service reference to your silverlight project in Visual Studio, you can right click it and configure it such that it uses an ObservableCollection (which is the default setting anyway)</p>
<p>Also, the Service Reference will by default ensure that the service's returned types already implement INotifyPropertyChanged.</p>
|
<p>Just to be clear, you can <strong>OneTime</strong> bind to any object. If you want to <strong>OneWay</strong> or <strong>TwoWay</strong> bind you will ned an object supports one of those interfaces. As mentioned, creating the Service Reference does this for you for objects delivered via webservice. However, if for some reason, you still need to produce a Bindable object from a legacy class, you could implement a Converter that implements IValueConverter and then use it to "wrap" your legacy object in a Bindable one live this:</p>
<pre><code><UserControl>
<UserControl.Resources>
<local:FooToBindableFooConverter x:Key="BindableFooConverter"/>
</UserControl.Resources>
<TextBlock Text="{Binding FooInstance, Converter={StaticResource BindableFooConverter}}"/>
</UserControl>
</code></pre>
<p>Converters are very powerful and can solve lots of "I need X but I have Y" problems. </p>
| 14,785
|
<p>What is a realistic use for VB.Net's MyClass keyword?</p>
<p>I understand the <a href="http://msdn.microsoft.com/en-us/library/b3b35kyk.aspx" rel="noreferrer">technical usage of MyClass</a>; I don't understand the practical usage of it in the real world.</p>
<p>Using MyClass only makes sense if you have any virtual (overridable) members. But it also means that you want to ignore the overridden implementations in sub classes. It appears to be self-contradicting.</p>
<p>I can think of some contrived examples, but they are simply bad design rather than practical usage.</p>
|
<p><code>MyClass</code>, from a compiler's perspective, is a way to omit a <code>callvirt</code> instruction in favor of a <code>call</code> instruction. Essentially when you call a method with the virtual semantics (<code>callvirt</code>), you're indicating that you want to use the most derived variation. In cases where you wish to omit the derived variations you utilize <code>MyClass</code> (<code>call</code>). While you've stated you understand the basic concept, I figured it might help to describe it from a functional viewpoint, rather than an implicit understanding. It's functionally identical to <code>MyBase</code> with the caveat of scope being base type with <code>MyBase</code>, instead of the active type with <code>MyClass</code>.</p>
<p>Overriding virtual call semantics, at the current point in the hierarchy, is typically a bad design choice, the only times it is valid is when you must rely on a specific piece of functionality within your object's hierarchy, and can't rely on the inheritor to call your variation through a base invocation in their implementation. It could also rely on you as a designer deciding that it's the only alternative since you overrode the functionality further in the object hierarchy and you must ensure that in this corner case that this specific method, at the current level of the inheritance tree, must be called.</p>
<p>It's all about design, understanding the overall design and corner cases. There's likely a reason C♯ doesn't include such functionality since on those corner cases you could separate the method into a private variation the current level in the hierarchy invokes, and just refer to that private implementation when necessary. It's my personal view that utilizing the segmentation approach is the ideal means to an end since it's explicit about your design choice, and is easier to follow (and it's also the only <em>valid</em> means in languages without a functional equivalent to <code>MyClass</code>.)</p>
|
<p>I guess the only case I could see a use for it, would be if you want the base condition, and an inherited condition at the same time? I.E. where you want to be able to inherit a member, but you want the ability to access a value for that member that hasn't been changed by inheritance?</p>
| 18,854
|
<p>What's the best / simplest / most accurate way to detect the browser of a user?</p>
<p>Ease of extendability and implementation is a plus.</p>
<p>The less technologies used, the better.</p>
<p>The solution can be server side, client side, or both. The results should eventually end up at the server, though.</p>
<p>The solution can be framework agnostic.</p>
<p>The solution will only be used for reporting purposes.</p>
|
<p>On the server you're pretty much limited to the UserAgent string the browser provides (which is fraught with problems, have a read about the <a href="http://www.webaim.org/blog/user-agent-string-history/" rel="noreferrer">UserAgent string's history</a>).</p>
<p>On the client (ie in Javascript), you have more options. But the best option is to not actually worry about working out which browser it is. Simply check to make sure whatever feature you want to use actually exists.</p>
<p>For example, you might want to use setCapture, which only MSIE provides:</p>
<pre><code>if (element.setCapture) element.setCapture()
</code></pre>
<p>Rather than working out what the browser is, and then inferring its capabilities, we're simply seeing if it supports something before using it - who knows what browsers will support what in the future, do you really want to have to go back and update your scripts if Safari decides to support setCapture?</p>
|
<p>For internet explorer and Style sheets you can use the following syntax:</p>
<pre><code><!--[if lte IE 6]><link href="/style.css" rel="stylesheet" type="text/css" /><![endif]-->
</code></pre>
<p>This applys to IE 6 or earlier.
You can change the IE version and also have:</p>
<pre><code><!--[if eq IE 7]> = Equal too IE 7
<!--[if gt IE 6]> = Greater than IE 6
</code></pre>
<p>Im not sure if this works with other parts of the page but works when placed within the <code><head></code> tag. See this <a href="http://www.quirksmode.org/css/condcom.html" rel="nofollow noreferrer">example</a> for more information</p>
| 12,619
|
<p>I've got a big file on which I'm opening a FileInputStream. This file contains some files each having an offset from the beginning and a size. Furthermore, I've got a parser that should evaluate such a contained file.</p>
<pre><code>File file = ...; // the big file
long offset = 1734; // a contained file's offset
long size = 256; // a contained file's size
FileInputStream fis = new FileInputStream(file );
fis.skip(offset);
parse(fis, size);
public void parse(InputStream is, long size) {
// parse stream data and insure we don't read more than size bytes
is.close();
}
</code></pre>
<p>I feel like this is no good practice. Is there a better way to do this, maybe using buffering?</p>
<p>Furthermore, I feel like the skip() method slows the reading process a lot.</p>
|
<p>It sounds like what you really want is a sort of "partial" input stream - one a bit like the ZipInputStream, where you've got a stream within a stream.</p>
<p>You could write this yourself, proxying all InputStream methods to the original input stream making suitable adjustments for offset and checking for reading past the end of the subfile.</p>
<p>Is that the sort of thing you're talking about?</p>
|
<p>You could use a wrapper class on a RandomAccessFile - try <a href="http://www-mipl.jpl.nasa.gov/vicar/vicar290/html/javadoc/jpl/mipl/io/streams/RandomAccessFileInputStream.html" rel="nofollow noreferrer">this</a> </p>
<p>You could also try wrapping that in a BufferedInputStream and see if the performance improves.</p>
| 47,888
|
<p>I'm trying to create routes which follow the structure of a tree navigation system, i.e I want to include the entire path in the tree in my route. So if I had a tree which looked like this</p>
<ul>
<li>Computers
<ul>
<li>Software
<ul>
<li>Development</li>
<li>Graphics</li>
</ul></li>
<li>Hardware
<ul>
<li>CPU</li>
<li>Graphics cards</li>
</ul></li>
</ul></li>
</ul>
<p>Then I would like to be able to have routes that looks like this</p>
<ul>
<li>site.com/catalog/computers/software/graphics</li>
</ul>
<p>This, on it's own is not hard and can be caught by a route which looks like this</p>
<ul>
<li>catalog/{*categories}</li>
</ul>
<p>However I want to be able to add the product information at the end of that URL, something like this</p>
<ul>
<li>site.com/catalog/computers/software/graphics/title=Photoshop</li>
</ul>
<p>Which would mean I would requite routes that were defined like the following examples</p>
<ul>
<li>site.com/{*categories}/title={name}</li>
<li>site.com/{*categories}</li>
</ul>
<p>However the first of these routes are invalid since nothing else can appear after a greedy parameter such as {*categories} so I'm a bit stuck. I've been thinking of implementing regex routes or perhaps use IRouteContraint to work my way around this but I can't think of a decent solution that would enable me to also use the <strong>Html.ActionLink(...)</strong> method to generate outbount URLs which filled in both {*categories} and {name}</p>
<p>Any advice is greatly apprechiated!</p>
<p><em>Some of you may have seen a similar question by me yesterday but that was deleted, by me, since I've since given it more thought and the old question contained incomplete descriptions of my problem</em></p>
<p><strong>UPDATE 2008/11/26</strong> I posted the solution at <a href="http://thecodejunkie.blogspot.com/2008/11/supporting-complex-route-patterns-with.html" rel="nofollow noreferrer">http://thecodejunkie.blogspot.com/2008/11/supporting-complex-route-patterns-with.html</a></p>
|
<p>Routes ignore query string parameters. But at the same time, query string parameters are passed in to an action method as long as there isn't a route URL parameter of the same name. So I would use just the second route, and pass in title via the query string.</p>
<p>Another option is more complicated. You write a custom route that derives from Route and override the GetRouteData method so that it parses the value of "categories" (something like RouteData.Values["categories"] and then add the parsed data to the route value dictionary (RouteData.Values["title"] = parsedTitle. </p>
|
<h2>Greedy segment anywhere in the URL</h2>
<p>I've written <code>GreedyRoute</code> class that supports greedy (catch all) segment anywhere in the URL. It's been a while since you needed it, but it may be useful to others in the future.</p>
<p>It supports any of the following patterns:</p>
<ul>
<li><code>{segment}/{segment}/{*greedy}</code> - this is already supported with default <code>Route</code> class</li>
<li><code>{segment}/{*greedy}/{segment}</code> - <strong>greedy in the middle</strong></li>
<li><code>{*greedy}/{segment}/{segment}</code> - <strong>greedy at the beginning</strong></li>
</ul>
<p>You can read all the details <a href="http://erraticdev.blogspot.com/2011/01/custom-aspnet-mvc-route-class-with.html" rel="nofollow">on my blog post</a> and get the code as well.</p>
| 38,631
|
<p>It sounds like Mozilla is having good luck improving JavaScript performance with <a href="http://weblogs.mozillazine.org/roadmap/archives/2008/08/tracemonkey_javascript_lightsp.html" rel="noreferrer">TraceMonkey</a>. See also Andreas Gal's <a href="http://www.ics.uci.edu/~franz/Site/pubs-pdf/ICS-TR-06-16.pdf" rel="noreferrer">paper on Trace Trees</a>.</p>
<p>Are these improvements available to other interpreters/compilers and if so, does this mean we'll see a cascade of improvements in other interpreted languages?</p>
|
<p>There's a research JVM by Andreas Gal called <a href="http://HotPath.Org/" rel="nofollow noreferrer">HotPath</a>, and some people from his team are currently working on adding nested trace tree based JITting to <a href="http://Research.Sun.Com/projects/maxine/" rel="nofollow noreferrer">Maxine</a> (Sun's new research JVM written in Java) and HotSpot. So, at least it is showing up in other VMs for other languages as well.</p>
<p>Also, the new <a href="http://PyPy.Org/" rel="nofollow noreferrer">PyPy</a> JIT compiler (currently being prototyped in Prolog) uses some kind of tracing technique, although I don't know how closely related that is to Gal/Franz style nested trace trees.</p>
<p>The <a href="http://Rubini.us/" rel="nofollow noreferrer">Rubinius</a> guys are definitely aware of this work, and very open to experimentation. I wouldn't be surprised, if some advanced compilation techniques start showing up there, soon.</p>
<p>BTW: there is a Ruby VM written in JavaScript, called <a href="http://HotRuby.Accelart.Jp/" rel="nofollow noreferrer">HotRuby</a>. If you run that on TraceMonkey, you get trace tree based Ruby for free :-)</p>
|
<p>The only possible answer to this is: <strong>Hopefully!</strong></p>
| 16,970
|
<p>I prefer to use jQuery with my ASP.NET MVC apps than the Microsoft Ajax library. I have been adding a parameter called "mode" to my actions, which I set in my ajax calls. If it is provided, I return a JsonViewResult. If it isn't supplied, I assume it was a standard Http post and I return a ViewResult.</p>
<p>I'd like to be able to use something similar to the IsMvcAjaxRequest in my controllers when using jQuery so I could eliminate the extra parameter in my Actions.</p>
<p>Is there anything out there that would provide this capability within my controllers or some simple way to accomplish it? I don't want to go crazy writing code since adding a single parameter works, it just isn't ideal.</p>
|
<p>Here's an except from MVC RC1 release notes - Jan 2009</p>
<p><strong>IsMvcAjaxRequest Renamed to IsAjaxRequest</strong></p>
<blockquote>
<p>The IsMvcAjaxRequest method been
renamed to IsAjaxRequest. As part of
this change, the IsAjaxRequest method
was updated to recognize the
X-Requested-With HTTP header. This is
a well known header sent by the major
JavaScript libraries such as
Prototype.js, jQuery, and Dojo.</p>
<p>The ASP.NET AJAX helpers were updated to send this header in
requests. However, they continue to
also send it in the body of the form
post in order to work around the issue
of firewalls that strip unknown
headers.</p>
</blockquote>
<p>In other words - it was specifically renamed to be more 'compatible' with other libraries.</p>
<p>In addition, for anyone who hasnt read the <a href="http://go.microsoft.com/fwlink/?LinkID=137661&clcid=0x409" rel="nofollow noreferrer">full release notes</a> but has been using previous versions - even as recent as the beta - I <strong>STRONGLY</strong> recommend you read them in full. It will save you time in future and most likely excite you with some of the new features. Its quite surprising how much new stuff is in there.</p>
<p><strong>Important note:</strong> You will need to make sure you upgrade the .js file for MicrosoftAjax.MVC (not the exact name) if upgrading to RC1 from the Beta - otherwise this method won't work. It isn't listed in the release notes as a required task for upgrading so don't forget to.</p>
|
<p>Ok, I have taken this one step farther and modified my jQuery file to load the additional parameter into the post data, so I don't have to repeat the "__JQUERYASYNCPOST: true" for every call to post. For anybody that's interested, here's what my new definition for $.post looks like:</p>
<pre><code>post: function(url, data, callback, type) {
var postIdentifier = {};
if (jQuery.isFunction(data)) {
callback = data;
data = {};
}
else {
postIdentifier = { __JQUERYASYNCPOST: true };
jQuery.extend(data, postIdentifier);
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
}
</code></pre>
<p>I added the "postIdentifier" variable as well as the call to jQuery.extend. Now the Helper explained in spoon16's response works without having to add any thing special to my page-level jQuery code.</p>
| 36,808
|
<p>What is the best way to close a browser window of an AJAX ASP.NET application after the server-side has been executed.</p>
<p>I found this <a href="https://stackoverflow.com/questions/250450/aspnet-ajax-close-window-after-ajax-call">solution</a>, but it seems a little complex for what I want to accomplish. Or is this the best way to accomplish my task.</p>
<p><b>UPDATE:</b> I have to close the window after the button is pressed</p>
<p><b>UPDATE 1:</b> I tried the solution from the other SO question, and it did not work for me.</p>
<pre><code><asp:Button ID="btnMyButton" runat="server" onClick="btnMyButton_Click" />
protected void btnMyButton_Click(object sender, EventArgs e)
{
}
</code></pre>
<hr>
<p>I used the following code in my page, but the "The webpage you are viewing is trying to close the windows" module window pops up.</p>
<pre><code>if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
ScriptManager.RegisterStartupScript(upApproveRequest, typeof(string), "closeWindow", "window.close();", true);
</code></pre>
<p>Any way to prevent this?</p>
|
<p>No, there is no way to close a browser window without the user's consent. You can log them out of their application, but you can't forcibly close the browser window. </p>
|
<p>That's pretty much it. You can just use <code>ScriptManager.RegisterStartupScript(...)</code></p>
| 46,202
|
<p>I am writing an application that if the user hits back, it may resend the same information and mess up the flow and integrity of data. How do I disable it for users who are with and without javascript on?</p>
|
<p>It's not possible, sadly. However, consider your applications navigation model. Are you using Post/Redirect/Get PRG Model? <a href="http://en.wikipedia.org/wiki/Post/Redirect/Get" rel="noreferrer">http://en.wikipedia.org/wiki/Post/Redirect/Get</a>?</p>
<p>This model is more back button friendly than the Postback model.</p>
|
<p>You could post the data on each form to a _NEW window. This will disable the back button on each window, but without javascript it might be difficult to force the old one closed.</p>
| 11,300
|
<p>Is there any way to include the SVN repository revision number in the version string of a .NET assembly? Something like Major.Minor.SVNRev</p>
<p>I've seen mention of doing this with something like CC.NET (although on ASP.NET actually), but is there any way to do it without any extra software? I've done similar things in C/C++ before using build batch scripts, but in was accomplished by reading the version number, then having the script write out a file called "ver.h" everytime with something to the effect of:</p>
<pre><code>#define MAJORVER 4
#define MINORVER 23
#define SOURCEVER 965
</code></pre>
<p>We would then use these defines to generate the version string.</p>
<p>Is something like this possible for .NET?</p>
|
<p>Here's and C# example for updating the revision info in the assembly automatically. It is based on the answer by Will Dean, which is not very elaborate.</p>
<p>Example :</p>
<ol>
<li>Copy AssemblyInfo.cs to AssemblyInfoTemplate.cs in the project's
folder <em>Properties</em>.</li>
<li>Change the <em>Build Action</em> to <em>None</em> for AssemblyInfoTemplate.cs.</li>
<li><p>Modify the line with the AssemblyFileVersion to: </p>
<p><code>[assembly: AssemblyFileVersion("1.0.0.$WCREV$")]</code></p></li>
<li><p>Consider adding: </p>
<p><code>[assembly: AssemblyInformationalVersion("Build date: $WCNOW=%Y-%m-%d %H:%M:%S$; Revision date: $WCDATE=%Y-%m-%d %H:%M:%S$; Revision(s) in working copy: $WCRANGE$$WCMODS?; WARNING working copy had uncommitted modifications:$.")]</code>, </p>
<p>which will give details about the revision status of the source the assembly was build from.</p></li>
<li><p>Add the following Pre-build event to the project file properties:</p>
<p><code>subwcrev "$(SolutionDir)." "$(ProjectDir)Properties\AssemblyInfoTemplate.cs" "$(ProjectDir)Properties\AssemblyInfo.cs" -f</code></p></li>
<li><p>Consider adding AssemblyInfo.cs to the svn ignore list. Substituted revision numbers and dates will modify the file, which results in insignificant changes and revisions and $WCMODS$ will evaluate to true. AssemblyInfo.cs must, of course, be included in the project.</p></li>
</ol>
<p>In response to the objections by Wim Coenen, I noticed that, in contrast to what was suggested by Darryl, the AssemblyFileVersion also does <strong>not</strong> support numbers above 2^16. The build will complete, but the property <em>File Version</em> in the actual assembly will be AssemblyFileVersion modulo 65536. Thus, 1.0.0.65536 as well as 1.0.0.131072 will yield 1.0.0.0, etc. In this example, there is always the true revision number in the AssemblyInformationalVersion property. You could leave out step 3, if you consider this a significant issue.</p>
<p>Edit: some additional info after having used this solution for a while.</p>
<ol>
<li>It now use AssemblyInfo.cst rather than AssemblyInfoTemplate.cs, because it will automatically have <em>Build Action</em> option <em>None</em>, and it will not clutter you Error list, but you'll loose syntax highlighting.</li>
<li><p>I've added two tests to my AssemblyInfo.cst files:</p>
<pre><code>#if(!DEBUG)
$WCMODS?#error Working copy has uncommitted modifications, please commit all modifications before creating a release build.:$
#endif
#if(!DEBUG)
$WCMIXED?#error Working copy has multiple revisions, please update to the latest revision before creating a release build.:$
#endif
</code></pre>
<p>Using this, you will normally have to perform a complete SVN Update, after a commit and before you can do a successful release build. Otherwise, $WCMIXED will be true. This seems to be caused by the fact that the committed files re at head revision after the commit, but other files not.</p></li>
<li>I have had some doubts whether the first parameter to subwcrev, "$(SolutionDir)", which sets the scope for checking svn version info, does always work as desired. Maybe, it should be $(ProjectDir), if you are content if each individual assembly is in a consistent revision.</li>
</ol>
<p><strong>Addition</strong>
<em>To answer the comment by @tommylux.</em></p>
<p>SubWcRev can be used for any file in you project. If you want to display revision info in a web page, you could use this VersionInfo template:</p>
<pre><code>public class VersionInfo
{
public const int RevisionNumber = $WCREV$;
public const string BuildDate = "$WCNOW=%Y-%m-%d %H:%M:%S$";
public const string RevisionDate = "$WCDATE=%Y-%m-%d %H:%M:%S$";
public const string RevisionsInWorkingCopy = "$WCRANGE$";
public const bool UncommitedModification = $WCMODS?true:false$;
}
</code></pre>
<p>Add a pre-build event just like the one for AssemblyInfo.cst and you will have easy access to all relevant SubVersion info.</p>
|
<p>You can use a shared Assembly Version file that you can reference in all of your projects.</p>
<p><a href="http://uppercut.googlecode.com" rel="nofollow noreferrer">UppercuT</a> does this - <a href="http://ferventcoder.com/archive/2009/05/21/uppercut---automated-builds---versionbuilder.aspx" rel="nofollow noreferrer">http://ferventcoder.com/archive/2009/05/21/uppercut---automated-builds---versionbuilder.aspx</a></p>
<p>This will give you an idea of what you can do to get versions in your assemblies.</p>
| 3,327
|
<p>I have written a windows service using the Apache.NMS and Apcahe.NMS.ActiveMQ (version 1.0) libraries. The service consumes messages from ActiveMQ from a vendor server.</p>
<p>The service spins up a connection and listens for messages (I handle the OnMessage event)</p>
<p>The connection is a transacted connection so I call commit after each message.</p>
<p>When the service starts up, everything works very well and does so for a while. However, after it has run for a while, it will no longer consume messages. Even if I reset the service. It usually takes a restart of my service AND the vendor server (tomcat) to get things going again. The vendor insists that nothing is wrong on their side.</p>
<p>No exceptions are thrown on either side (client or server) - it's just 'stuck'.</p>
<p>Should I consider using Spring.Messaging.Nms? </p>
|
<p>I have discovered the problem. After establishing the connection and the message listener the service went into a loop with Thread.Sleep(500). Dumb. I refactored the service to start everything up in OnStart and dispose of it in OnStop.</p>
<p>Since doing that, everything is running perfectly.</p>
<p>Classic ID-10-T error occurring between keyboard and chair.</p>
|
<p>we have just come across exactly the same issue using a .Net service talking to ActiveMQ, but ours locks up after only about 10-20 messages being delivered.</p>
<p>Have tried it with and without the spring framework and it's slightly better without (unless I'm imagining things).</p>
<p>Would you mind checking over this code and letting me know if it bears any resemblance to your own?</p>
<pre><code>ConnectionFactory connectionFactory = new ConnectionFactory("tcp://activemq:61616");
Connection connection = (Connection)connectionFactory.CreateConnection();
connection.Start();
Session session = (Session)connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
IDestination queue = session.GetQueue("test.queue");
MessageConsumer consumer = (MessageConsumer)session.CreateConsumer(queue);
for (int i = 0; i < 1000; i++)
{
IMessage msg = consumer.Receive();
if (msg != null)
Console.WriteLine((msg as ITextMessage).Text);
}
</code></pre>
| 33,832
|
<p>Enterprise Architect has a way to generate the documentation in HTML/RTF/etc. that you could publish, but you have to use its GUI to do that manually. When you have your *.eap files in a CVS/Subversion server, it would be useful to have a script that would check out daily the latest version and publish it in a web server. As long as I know, EA doesn't have a command line utility for this purpose. I found that you can automate almost anything using its COM interface, but that means it's necessary to write a small program to do that. Any ideas about the easiest/cleanest way to do that (without having to write code, if possible)?</p>
|
<p>I think that you might run into concurrency and contention problems no matter what configuration you use as long as you are attempting to have two different processes log to the same file.</p>
<p>You should look into sending log events from both processes to a third, centralized location - take a look at <a href="http://logging.apache.org/log4net/release/sdk/log4net.Appender.RemotingAppender.html" rel="nofollow noreferrer">RemotingAppender</a> in log4net, I assume log4cxx has something similar.</p>
|
<p>Even if the question is quite old (and marked as answered) and you're probably already finished with your project:</p>
<p>log4net and log4cxx are distinct logging framworks that don't know of each other so you can't configure them to write to the same file. Only one of the framworks will have the file open for writing, whichever was first.</p>
<p>What I have done in a similar situation (a legacy c++ application with custom logging an a new c# module using log4net) is <a href="http://www.google.com/search?hl=en&q=log4net+custom+appender&btnG=Google+Search&cts=1234823516335&aq=0&oq=log4net+custom" rel="nofollow noreferrer">create a custom log4net appender</a> that forwards traces into the old logging framework. In the project where I was involved the old C++ code had a Windows COM Interface for writing log messages which the custom appender used.</p>
<p>Another way would be using C++/CLI to create the custom appender.</p>
| 27,327
|
<p>I have a client sending me requests without HTTP chunking (they use content-length). When my server responds, chunking is enabled, and the client can't handle this - even though they should be able to as they are using HTTP 1.1..... </p>
<p>I have tried to disable chunking by removing the entry below from the axis2 config file (axis2.xml) but the response is still going back chunked.</p>
<p>chunked</p>
<p>So the question is, is there somewhere else that the chunking is being enabled that is over-riding the axis2 setting? In tomcat setting perhaps?</p>
<p>Webserver details - tomcat 6.0.16, axis2 2.1.3</p>
<p>Thanks
Mike</p>
|
<p>you can disable Chunking programatically as follows:</p>
<p>Options options = new Options();
[...]
options.setProperty(HTTPConstants.CHUNKED, "false");</p>
<p>Source: <a href="http://jcesarperez.blogspot.com/2008/10/resolviendo-problemas-de.html" rel="noreferrer">http://jcesarperez.blogspot.com/2008/10/resolviendo-problemas-de.html</a></p>
|
<p>If you created a stub for your web service, just do this:</p>
<p><code>myStub._getServiceClient().getOptions().setProperty(HTTPConstants.CHUNKED, false);</code></p>
| 34,170
|
<p>Is there a way to configure an assembly in GAC? I want to add a custom configuration to my assembly with System.Configuration.</p>
<p>Mher</p>
|
<p>If I understand your question right, no, there is no way to do this.</p>
<p>An assembly uses the configuration file of the application that loads it.</p>
|
<p>Depending on what scenario you are trying to achieve, you could include your App.config file as an embedded resource and when required extract to somewhere on disk and load using the advice given to <a href="https://stackoverflow.com/questions/163803/how-do-i-select-a-net-application-configuration-file-from-a-command-line-parame">this question</a>.</p>
<p>Obviously this removes the ability to actually <em>change</em> the config without recompiling, so kind of defeats the purpose.</p>
<p>Another option might be to have the config file intalled into either the <code>Application Data</code> or <code>Common Application Data</code> folder, and use the same technique as above.</p>
| 20,078
|
<p>Is there anyone using Subsonic with asp.net mvc framework? If so, can you tell us something about your experience. Are there tips and tricks that can be shared?</p>
|
<p>If you're planning on doing database first design, and you don't need any mapping (i.e. you're in control of your db naming) then SubSonic is a decent option.</p>
<p>It's straight-forward, doesn't hide a lot from you. On the same token, for advanced scenarios I have to side-step it a lot and execute raw sql (or a sproc).</p>
<p>If you're looking for a better object abstraction over the database, something that more closely matches your problem domain, then I'd look at NHibernate or Castle ActiveRecord. This gives you a lot more flexibility in how you want your object model to look, and you have a powerful query API at your disposal.</p>
<p>None of this really has to do with ASP.NET MVC, other than you just use your objects in your web project. I'd suggest putting the entities inside of a separate class library project anyway.</p>
|
<p>I totally agree with Ben <em>SubSonic</em> is an <em>ORM</em> and works well with the MVC concept but doesn't have anything that ties it with <em>MVC</em>.</p>
<p>For small projects or for projects that you already have a Database and don't really care to much about the domain then <em>SubSonic</em> is great and will get you up and running very fast.</p>
<p>But if your project is a bit bigger or more specificity your DB is an after thought then you should go with a tool like <em>NHibernate</em>.</p>
<p>FYI <a href="http://www.summerofnhibernate.com/" rel="nofollow noreferrer">Summer of <em>NHibernate</em></a> is a great Screencast Series on getting started with <em>NHibernate</em></p>
| 16,038
|
<p>How do I convert text between multi-byte text strings, for example Simplified Chinese GB 2312, into UTF8 using c++ ?</p>
|
<p>On unix systems you'd best use the iconv library.</p>
<p>See <a href="http://www.manpagez.com/man/3/iconv_open/" rel="nofollow noreferrer">iconv_open</a>, <a href="http://www.manpagez.com/man/3/iconv/" rel="nofollow noreferrer">iconv</a>, <a href="http://www.manpagez.com/man/3/iconv_close/" rel="nofollow noreferrer">iconv_close</a></p>
<p>You'd have to know the character encoding of course (EUC-CN, HZ).</p>
<p>If not on a unix system, search for some support in the OS, doing character conversions by hand is very hard to get right.</p>
|
<p>WinAPI: <a href="http://msdn.microsoft.com/en-us/library/ms776413(VS.85).aspx" rel="nofollow noreferrer">MultiByteToWideChar</a> and vice versa, <a href="http://msdn.microsoft.com/en-us/library/ms776420(VS.85).aspx" rel="nofollow noreferrer">WideCharToMultiByte</a>.
I can post a sample later.</p>
<p>However, UTF-8 is rather tricky to represent and more specifically, to use, in applications. The MultiByteToWideChar function converts a string to <a href="http://en.wikipedia.org/wiki/UTF-16/UCS-2" rel="nofollow noreferrer">UTF-16 (UCS2)</a>. I suggest you use this format in your software internally, and only convert it to UTF-8 using WideCharToMultiByte if your program needs to produce such output. This is the standard way of doing internationalization/unicode on Windows & OS X.</p>
| 27,262
|
<p>Basically I have the following class:</p>
<pre><code>class StateMachine {
...
StateMethod stateA();
StateMethod stateB();
...
};
</code></pre>
<p>The methods stateA() and stateB() should be able return pointers to stateA() and stateB().
How to typedef the StateMethod?</p>
|
<p><a href="http://www.gotw.ca/gotw/057.htm" rel="noreferrer">GotW #57</a> says to use a proxy class with an implicit conversion for this very purpose.</p>
<pre><code>struct StateMethod;
typedef StateMethod (StateMachine:: *FuncPtr)();
struct StateMethod
{
StateMethod( FuncPtr pp ) : p( pp ) { }
operator FuncPtr() { return p; }
FuncPtr p;
};
class StateMachine {
StateMethod stateA();
StateMethod stateB();
};
int main()
{
StateMachine *fsm = new StateMachine();
FuncPtr a = fsm->stateA(); // natural usage syntax
return 0;
}
StateMethod StateMachine::stateA
{
return stateA; // natural return syntax
}
StateMethod StateMachine::stateB
{
return stateB;
}
</code></pre>
<blockquote>
<p>This solution has three main
strengths:</p>
<ol>
<li><p>It solves the problem as required. Better still, it's type-safe and
portable.</p></li>
<li><p>Its machinery is transparent: You get natural syntax for the
caller/user, and natural syntax for
the function's own "return stateA;"
statement.</p></li>
<li><p>It probably has zero overhead: On modern compilers, the proxy class,
with its storage and functions, should
inline and optimize away to nothing.</p></li>
</ol>
</blockquote>
|
<p>I can never remember the horrible C++ function declspec, so whenever I have to find out the syntax that describes a member function, for example, I just induce an intentional compiler error which usually displays the correct syntax for me.</p>
<p>So given:</p>
<pre><code>class StateMachine {
bool stateA(int someArg);
};
</code></pre>
<p>What's the syntax for stateA's typedef? No idea.. so let's try to assign to it something unrelated and see what the compiler says:</p>
<pre><code>char c = StateMachine::stateA
</code></pre>
<p>Compiler says: </p>
<pre><code>error: a value of type "bool (StateMachine::*)(int)" cannot be used to initialize
an entity of type "char"
</code></pre>
<p>There it is: "bool (StateMachine::*)(int)" is our typedef.</p>
| 19,457
|
<p>I thought that I had the latest CTP of PowerShell 2 but when I try the command:</p>
<p><code>invoke-expression –computername Server01 –command 'get-process PowerShell'</code></p>
<p>I get an error message:<br>
<strong>A parameter cannot be found that matches parameter name 'computername'.</strong></p>
<p>So the question is: How can I tell which version of PowerShell I have installed? And what the latest version is?</p>
|
<p><code>$host.version.tostring()</code> will return the version number.</p>
<p>RTM of v1 is 1.0.0.0</p>
<p>Couldn't honestly tell you what the latest version of the previews are because I haven't had a chance to play yet.</p>
|
<p>I'm guessing that this is a change to the cmdlet made during the configuration process Configure-Wsman.ps1. I don't have an environment setup to test right now, but I'm guessing something went wrong with the configuration. I can verify that on XP the parameter is not available (duh). I'd assume that you will find the same on Vista/08 without the configuration completed.</p>
| 3,352
|
<p>I'm building an open source project that uses python and c++ in Windows.
I came to the following error message:</p>
<pre><code> ImportError: No module named win32con
</code></pre>
<p>The same happened in a "prebuilt" code that it's working ( except in my computer :P ) </p>
<p>I think this is kind of "popular" module in python because I've saw several messages in other forums but none that could help me.</p>
<p>I have Python2.6, should I have that module already installed?
Is that something of VC++?</p>
<p>Thank you for the help.</p>
<p>I got this url <a href="http://sourceforge.net/projects/pywin32/" rel="noreferrer">http://sourceforge.net/projects/pywin32/</a> but I'm not sure what to do with the executable :S</p>
|
<p>This module contains constants related to Win32 programming. It is not part of the Python 2.6 release, but should be part of the download of the pywin32 project.</p>
<p><strong>Edit:</strong> I imagine that the executable is an installation program, though the last time I downloaded pywin32 it was just a zip file.</p>
|
<p>navigate to: C:\Python27\Lib\site-packages\win32\lib and copy the win32con.py file into your project directory.</p>
| 28,207
|
<p>What would be the best method to implement extra functionality in a database layer that uses Linq-to-SQL? Currently I'm looking at implementing functions for adding information based on presets and similar tasks?</p>
<p>Inserts, updates and deletes requires access to the <code>DataContext</code> and in the <code>Table</code> classes you don't have access to the context. I've seen solutions that uses Singletons but it seems like a hack and I wonder if anyone else has run into this problem and what your solutions were? Is there a better way all together to implement similar functionality.</p>
<p>The reason for me looking to add this functionality to the database layer is that I have several applications that all use the same database objects and I want to be able to use these functions from all applications so I don't have to rewrite a lot of code.</p>
<hr>
<p>That's not quite what I meant. I want to be able to do complex actions like updating one table and adding a record to another table based on information from the first one.</p>
<p>Say I have selected a Customer record and I want to update this with information, and when this happens I want it to add another record to the "Updates" table to keep track of when updates happened and who did them. This is only an example of course. Things needed to be done can be more complex.</p>
<p>Basically I want to add a method to a table object to perform modifications to a specific row in that table and then do inserts and updates on other objects. I know that you can use partial classes and I do that extensively already.</p>
<p>Example:</p>
<pre><code>db.Customers.Where(c => c.CustomerID == 5).AddOrder(orderDetails);
</code></pre>
<p>I feel that I can't really put my problem into words to make it understandable :)</p>
|
<p>Entity classes in Linq to SQL are partial. You could extend them with the rules you need. </p>
<p>Or you could build your own business entities from the Linq to SQL entities. Your business entities would then contain the rules on when to do what.</p>
|
<p>I hate to say it, but what about stored procedures? </p>
<p>On my project, whatever extra functionality we want to provide we stick in a partial class. The data context class is marked partial, so you can add methods to the context without worrying about re-generating the context nuking your work. </p>
| 23,366
|
<p>I have a table with N rows, and I wanna select N-1 rows. </p>
<p>Suggestions on how to do this in one query, if it's possible..?</p>
|
<p>Does the last row have the highest ID? If so, I think this would work:</p>
<pre><code>SELECT * FROM TABLE WHERE ID != (SELECT MAX(ID) FROM TABLE)
</code></pre>
<p>MySQL does allow subselects in the current version, right?</p>
<p>However, in most cases, it'd probably perform better if you selected all the rows and then filtered the unwanted data out in your application.</p>
|
<p>Another way to do this could be:</p>
<pre><code>SELECT * FROM table WHERE ID <> LAST_INSERT_ID()
</code></pre>
<p>Reference: <a href="http://dev.mysql.com/doc/refman/5.7/en/getting-unique-id.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.7/en/getting-unique-id.html</a></p>
| 40,747
|
<p>The following SQL:</p>
<pre><code>SELECT notes + 'SomeText'
FROM NotesTable a
</code></pre>
<p>Give the error:</p>
<blockquote>
<p>The data types nvarchar and text are incompatible in the add operator.</p>
</blockquote>
|
<p>The only way would be to convert your text field into an nvarchar field.</p>
<pre><code>Select Cast(notes as nvarchar(4000)) + 'SomeText'
From NotesTable a
</code></pre>
<p>Otherwise, I suggest doing the concatenation in your application.</p>
|
<p>If you are using SQL Server 2005 (or greater) you might want to consider switching to NVARCHAR(MAX) in your table definition; TEXT, NTEXT, and IMAGE data types of SQL Server 2000 will be deprecated in future versions of SQL Server. SQL Server 2005 provides backward compatibility to data types, but you should probably be using VARCHAR(MAX), NVARCHAR(MAX), and VARBINARY(MAX) instead.</p>
| 7,795
|
<p>What tool or method do you recommend to find and replace values in your code? If code is on Linux/Unix, are find and grep the best method?</p>
|
<p>Take a look at <a href="http://petdance.com/ack/" rel="nofollow noreferrer">ack</a>, which is designed for searching big codebases.</p>
<p>For replacing, look at Perl's -i, -p and -e flags. You can do stuff like:</p>
<pre><code>$ perl -i -p -e's/\bthisword\b/thatword/g' $(find . -name *.html)
</code></pre>
<p>to replace all instances of thisword with thatword in all .html files in the tree.</p>
|
<p>find and grep don't build indecies, so they're always going to be slower than alternatives that do. That said, they work fine if your codebase is only a few dozen files.in Fi</p>
<p>Eclipse has a nice file search feature (Ctrl+H). It can also take language semantics into consideration if you have the right plugins (Java works out of the box, of course). The only caveat is that it can be a bit slow the first time you search in a certain file set.</p>
| 28,615
|
<p><strong>How can you make the experience with Eclipse faster?</strong> </p>
<p>For instance: <em>I disable all the plugins I don't need (Mylyn, Subclipse, …).</em></p>
<p>Instead of using a plugin for <a href="http://en.wikipedia.org/wiki/Mercurial" rel="noreferrer">Mercurial</a>, I configure <a href="https://en.wikipedia.org/wiki/TortoiseHg" rel="noreferrer">TortoiseHG</a> as an external tool.</p>
|
<p>The three most influential factors for Eclipse speed are:</p>
<ul>
<li>Using the <strong>latest version of Eclipse</strong> (2020-06 as on 26 June 2020)<br />
Note that <a href="https://stackoverflow.com/users/822870/david-bala%C5%BEic">David Balažic</a>'s <a href="https://stackoverflow.com/questions/316265/how-can-you-speed-up-eclipse/316535#comment38657862_316535">comment</a> (July 2014) contradicts that criteria which was working six years ago:</li>
</ul>
<blockquote>
<p>The "same" workspace in Indigo (3.7.2) SR2 loads in 4 seconds, in Kepler SR2 (4.3.2) in 7 seconds and in Luna (4.4.0) in 10 seconds. All are Java EE bundles. Newer versions have more bundled plugins, but still the trend is obvious. (by "same" workspace I mean: same (additionally installed) plugins used, same projects checked out from version control).</p>
</blockquote>
<ul>
<li><p>Launching it with the <strong>latest JDK</strong> (Java 14 at the time of writing, which does not prevent you to compile in your Eclipse project with any other JDK you want: 1.4.2, 1.5, 1.6 older...)</p>
<pre><code> -vm jdk1.6.0_10\jre\bin\client\jvm.dll
</code></pre>
</li>
<li><p>Configuring the <strong>eclipse.ini</strong> (see <a href="https://stackoverflow.com/questions/142357/what-are-the-best-eclipse-34-jvm-settings#144349">this question for a complete eclipse.ini</a>)</p>
<pre><code> -Xms512m
-Xmx4096m
[...]
</code></pre>
</li>
</ul>
<p>The <code>Xmx</code> argument is the amount of memory Eclipse will get (in simple terms). With <code>-Xmx4g</code>, it gets 4 GB of RAM, etc.</p>
<hr />
<p>Note:</p>
<ol>
<li>Referring to the jvm.dll has advantages:</li>
</ol>
<ul>
<li>Splash screen coming up sooner.</li>
<li>Eclipse.exe in the process list instead of java.exe.</li>
<li>Firewalls: Eclipse wants access to the Internet instead of Java.</li>
<li>Window management branding issues, especially on Windows and Mac.</li>
</ul>
<hr />
<p>Dec. 2020, <a href="https://stackoverflow.com/users/679858/udo">Udo</a> conforms <a href="https://stackoverflow.com/questions/316265/how-can-you-speed-up-eclipse/316535#comment115827363_316535">in the comments</a></p>
<blockquote>
<p>From version 4.8 (Photon) an up there was a steady speed gain after each version.<br />
The main platform was optimized every release to load faster, enable more features for the dark theme and to add more features for newer Java versions for the Java development tools.<br />
Especially with-in the last 3 versions the startup time was increased a lot. There should be a significant increase in start-up time with the newest version of Eclipse 2020-12.</p>
<p>In my experience it started a lot faster with each new version.<br />
But: There are still plug-ins which do not follow the new way of using the Eclipse API and are therefore still slow to start.<br />
Since the change to Java 11 as the minimum runtime version starting from Eclipse version 2020-09 at least the core system uses the newer features of the JVM. It is up to the providers of the other plug-ins to upgrade to newer APIs and to use the full power of modern CPUs (e.g. concurrent programming model).</p>
</blockquote>
|
<p>There could be several things that could delay the start and exit of eclipse. One of them is like familiar to what we have a lookalike in Windows. Disabling the windows animations and disabling startup activities speeds up windows to certain extent</p>
<p>Similar to what in eclipse we can have the same thing Windows-> General -> Preferences -> Appearance -> Turning OFF some decorative options. This would give a little boost but may not have much impact.</p>
<p>In my opinion, the projects in the work space you might have created should be limited to certain extent or rather creating a new work space if projects are more. For instance, when you try to run a single project on server it takes less time as compared to running several projects on the same server</p>
| 40,834
|
<p>What experience have you had with introducing a Ribbon style control to legacy MFC applications? </p>
<p>I know it exists in the new VC2008 Feature Pack, but changing compilers from VC2005 is a big deal for our source base and integration to our environment, Intel FORTRAN, ClearCase, many 3rd libraries.</p>
<p>There are quiet a few different commerical implementations, most focusing on C#/VB .NET, and only a few for native C++ MFC.</p>
<p>I have read all the usual reviews found by Google most are quiet old now, so I am interested to here from people who have actually done it, been through the pain barrier, released a legacy application with VC2005 and a Ribbon UI.</p>
<p>We currently use a very old version of Stingray Objective Toolkit to provide our MFC extensions like customizable toolbars and docking windows etc. </p>
<hr>
<p>Any one used <a href="http://www.prof-uis.com/" rel="nofollow noreferrer">Prof-UIS</a>, compared to the other commercial ones its relatively cheap, unlimited developer licensing is a 10th the cost of the others.</p>
<p>Are there any free, open source or L-GPL'd ones available?</p>
|
<p>In my projects I'm using the MFC Feature Pack in Visual Studio 2008, which is based on code from <a href="http://www.bcgsoft.com" rel="nofollow noreferrer">BCGSoft</a>. Their BCGControlBar Library Professional Edition includes a ribbon control and is compatible with Visual Studio 2005.</p>
<p>I'm not aware of any open source ribbon control libraries for C++, though.</p>
|
<p>We implemented a ribbon in our app due to pressure to have the latest/flashiest looking UI. It looks good, but the usability isn't good compared to using a plain toolbar!</p>
<p>To adhere to Microsoft's License to use the ribbon, you have to stick to their guidlines on how it should be used. Eg.. only the user can change ribbon tabs, you can't do it programatically except when switching to a context tab. All these limitations mean that the ribbon only applies to applications that are definitely document-centric. If you're app isn't document-centric, don't think you can just drop a ribbon in to replace a menu/toolbar driven system without giving it a lot of thought about how everything is going to fit together.</p>
| 13,344
|
<p>I would like to be able to add a "message" to a unit test, such that it actually appears within the TestResult.xml file generated by NUnit. For example, this is currently generated:</p>
<pre><code><results>
<test-case name="MyNamespace.Tests.MyTest" executed="True" success="True" time="0.203" asserts="4" />
</results>
</code></pre>
<p>I would like to be able to have an additional attribute (or node as the case may be), such as:</p>
<pre><code><results>
<test-case name="MyNamespace.Tests.MyTest" executed="True" success="True" time="0.203" asserts="4" message="Tested that some condition was met." />
</results>
</code></pre>
<p>The idea is that "message" above would somehow be defined within the test method itself (in my case, generated at run-time). Is there a property somewhere that I'm missing to be able to do something like this?</p>
|
<p>This may be missing the point, but how about naming the tests so they indicate what they test - then you may not even need the message. </p>
<p>If it proves to be absolutely necessary, I think you'll need to produce your own testrunner that would (off the top of my head) read an additional attribute off the TestCase and attach it to the output.</p>
|
<p>I can't see anything available at run time, but there are a couple of features that you might want to investigate: the <a href="http://www.nunit.org/index.php?p=description&r=2.4.8" rel="nofollow noreferrer">Description</a> attribute and the <a href="http://www.nunit.org/index.php?p=property&r=2.4.8" rel="nofollow noreferrer">Property</a> attribute both add text to the XML output file. Unfortunately, they're both defined at compile time.</p>
| 6,638
|
<p>I'm trying some of the ASP.NET MVC tutorials and one of them has the following steps:</p>
<ul>
<li>Right-click on the "App_Data" folder, and choose "Add New item"</li>
<li>Choose "SQL Server Database" under the "Data" category.</li>
</ul>
<p>However, once I do that, I get the following message from Visual Studio:</p>
<blockquote>
<p>Connections to SQL Server files (*.mdf) require SQL Server Express 2005 to function proprely. Please verify the installation of the component or download from the URL...</p>
</blockquote>
<p>The thing is that I have SQL Server 2008 Developer Edition installed, and I would really rather not install any Express versions (2005 or 2008) if I don't have to. Is there a work-around for this issue?</p>
|
<p>Actually SQL express is a whole different database engine then SQL Server 2005. So yes if you want to use mdf files you'd need SQL Express. </p>
|
<p>I have the same problem but I've sql 2008 express installed.
any way to make it work with sql 2008 express so I don't have to install the 4th sql instance on my machine??
I already have sql 2005, sql 2008, sql 2008 express</p>
<p>what the F... :)</p>
| 37,430
|
<p>I need to convert a value which is in a <code>DateTime</code> variable into a <code>varchar</code> variable formatted as <code>yyyy-mm-dd</code> format (without time part).</p>
<p>How do I do that?</p>
|
<p>With Microsoft Sql Server:</p>
<pre><code>--
-- Create test case
--
DECLARE @myDateTime DATETIME
SET @myDateTime = '2008-05-03'
--
-- Convert string
--
SELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10)
</code></pre>
|
<p>You don't say what language but I am assuming <code>C#/.NET</code> because it has a native <code>DateTime</code> data type. In that case just convert it using the <code>ToString</code> method and use a format specifier such as:</p>
<pre><code>DateTime d = DateTime.Today;
string result = d.ToString("yyyy-MM-dd");
</code></pre>
<p>However, I would caution against using this in a database query or concatenated into a SQL statement. Databases require a specific formatting string to be used. You are better off zeroing out the time part and using the DateTime as a SQL parameter if that is what you are trying to accomplish.</p>
| 10,001
|
<p>Sorry for the bad title, but I couldn't think of a better one.</p>
<p>I'm having a class A and a class B which is kind of a sub class of A, like so:</p>
<p>(Is there actually a correct name for it? Isn't "sub class" reserved for inheritance?)</p>
<pre><code>class A {
int i = 0;
class B {
int j = 1;
}
}
class Test {
public static void main() {
A a = new A();
B b = a.new B();
A c = ??? b ??? // get "a" back
}
}
</code></pre>
<p>From B every property of A can be accessed, therefore both, a.i and b.i, return 0. Now, I'm wondering whether it's somehow possible to retrieve the original object of type A out of b, as b contains everything that a contains? Simple casting apparently doesn't do the trick.</p>
<p>Second one:</p>
<pre><code>class A {
void print() {
System.out.println("This is class A.");
}
class B {
void print() {
// <--- How to access print() of class A (like this.A.print() or smth)?
System.out.println("This is class B.");
}
}
}
</code></pre>
<p>You could alternatively also provide me with some good resources on this topic, as I've been too stupid to find a good one so far.</p>
<p>Thanks in advance. :)</p>
|
<p>There doesn't seem to be a way to access the outer class from outside. But you can do it like this:</p>
<pre><code>class A {
int i = 0;
class B {
final A outer = A.this;
int j = 1;
}
}
class Test {
public static void main() {
A a = new A();
A.B b = a.new B();
A c = b.outer // get "a" back
}
}
</code></pre>
<p><code>ClassName.this</code> will be the instance of the outerclass associated with the instance of an inner class.</p>
|
<p>this seemed to work for me</p>
<pre><code>class A {
int i = 0;
class B {
int j = 1;
}
}
class Test {
public static void main() {
A a = new A();
A.B b = a.new B();
A c = (A)b.getClass().getDeclaredField("this$0").get(b);
}
}
</code></pre>
| 44,056
|
<p><a href="http://blogs.msdn.com/drnick/archive/2007/03/23/preventing-anonymous-access.aspx" rel="noreferrer">http://blogs.msdn.com/drnick/archive/2007/03/23/preventing-anonymous-access.aspx</a> </p>
<p>Can someone clarify whether it is possible to use wsHttpBinding in WCF and disable anonymous access in IIS without transport (ssl) or message security being required?</p>
|
<p>you are right, afaik in the scenario you describe wsHttpBinding requires us to use the internal WCF security stack. So what you would typically do is</p>
<ul>
<li>leave anonymous access enabled</li>
<li>create a serviceBehavior with <serviceAuthorization principalPermissionMode="UseWindowsGroups" /></li>
<li>annotate every concrete implementation of a service method using the PrincipalPermissionAttribute, which is a quite powerful tool with many different options to control access</li>
</ul>
<p>Would that be an acceptable solution for you or are there any other things to consider?</p>
<p>Basic Example:</p>
<pre><code>public class TestService : ITestService
{
[PrincipalPermission(SecurityAction.Demand, Name = "testdomain\\administrator")]
public string DoWork()
{
return "Hello World " + Thread.CurrentPrincipal.Identity.Name;
}
}
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="WcfSecurity.Www.TestServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
<serviceAuthorization principalPermissionMode="UseWindowsGroups" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="WcfSecurity.Www.TestServiceBehavior" name="WcfSecurity.Www.TestService">
<endpoint address="" binding="wsHttpBinding" contract="WcfSecurity.Www.ITestService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
</code></pre>
|
<p>we want to use windows integrated security. If you disable anonymous access in IIS and allow just windows, you cannot seem to use wsHttpBinding with WCF without using some security mode (e.g. transprot security which requires ssl). </p>
<p>We only want to use windows authentication we don't necessarily want to use ssl for transport security. </p>
<p>I was a little amazed this wasn't possible out of the box (as seemed to be confirmed by my link) as it would seem quite a common scenario for intern applications. </p>
<p>We don't want to downgrade to basicHttpBinding which would support windows authentication only.</p>
| 28,250
|
<p>I'm asking all of you who aren't using a library for this, but are constructing your own objects for managing data flowing to and from your database tables. Do I have a recordset object? one object per row of data? Both? Neither? Any suggestions or experiences welcome. Please don't tell me to use an ORM or other such toolkit. It's overkill for my project and besides, that's not the question now, is it?</p>
|
<p>i'd strongly suggest picking up <a href="http://martinfowler.com/" rel="nofollow noreferrer">martin fowler</a>'s <a href="https://rads.stackoverflow.com/amzn/click/com/0321127420" rel="nofollow noreferrer" rel="nofollow noreferrer">patterns of enterprise application architecture</a>, it describes a number of database patterns that would be helpful to know, and give you an idea of the evolution of patterns to full on ORM libraries.</p>
<p>specific patterns you may be interested in:</p>
<ul>
<li><a href="http://martinfowler.com/eaaCatalog/recordSet.html" rel="nofollow noreferrer">RecordSet</a></li>
<li><a href="http://martinfowler.com/eaaCatalog/rowDataGateway.html" rel="nofollow noreferrer">Row Data Gateway</a></li>
<li><a href="http://martinfowler.com/eaaCatalog/tableDataGateway.html" rel="nofollow noreferrer">Table Data Gateway</a></li>
</ul>
<p>these basic patterns will give you an idea of how to structure your objects, and the more advanced patterns (like active record/data mapper) you'll see how those relate to problem domains beyond where your needs are at the moment.</p>
|
<p>To manage the actual data flowing in and out of the database (without an ORM), you should look at Jakarta Commons DbUtils.</p>
<p>It provides very light-weight helpers to run queries and updates, such as automatically turning ResultSets into Lists of beans and such.</p>
| 21,263
|
<p>In Moss 2007 you have the ability to set the target audience for each individual web part within a page. Is there a way to preview how the page will look to another user without logging in as that user? What I am looking for is a way for someone with full control/design permissions on a site to be able to preview how the site will be displayed to another user. Any suggestions?</p>
<p>I have a few test accounts that our IS department uses to preview pages, however we do not allow non-IS departamental staff to use those accounts. Those staff members only have access to their one account. So, if a user makes changes the target audience on a web part on one of their pages, right now they have no way to preview how the page will look to someone else other than asking someone else to login & watching over their shoulder. I can't give out the account information for the test accounts, nor can I create new test accounts.</p>
<p>Thanks!</p>
<p>Edit: I have the ability to preview. The problem is that other users with full control of a site can't preview the page. Here's a scenarios: In my school division each school has a site. The principal has full control of his school's site. On the landing page, he wants all the school announcements to be visible. However, some should only be visible to teaching staff, while others need to be visible to the students. He uses audience targetting but cannot preview to see at a glance that the targetting is correct. A lot of the users are not computer savy so things need to be as simple as possible. Also, that was just one scenario, there are other scenarios that are not divided by school. There are many users with full control of a site with different requirements - so it's not feasible to create test accounts for all scenarios.</p>
|
<p>Edit: After re-reading the question I released that you want the users to be able to preview a page. I think you will need to look into writing a preview control that uses Impersonation to load the page. Not sure how feasible this is, but surely someone has created a preview feature. Sounds like a pretty common scenario to me.</p>
<p>Old Answer:
Could you not fire up a non MS browser such as Firefox, which will prompt for the username and password. </p>
<p>You can then just clear the session cookies to be prompted to log in as someone else.</p>
<p>This is the technique I used for an ASP.Net site that used authentication against the domain in a similar manner to SharePoint.</p>
|
<p>First I don't think it is possible to have a preview feature if you are using NT security. Maybe it is something you can do with forms authentication but I never used it.</p>
<p>On that subject. I think when you are developing new features or integrating stuff on a MOSS/WSS server you need a little flexibility.</p>
<p>With what I see you have to following things you can do. It is surely more cost effective than developing a custom solution. I assume you are using NT Security.</p>
<ul>
<li><strong>User accounts</strong> : Ask your domain administrator to have dedicated user accounts to play with.</li>
<li><strong>Virtual Machines</strong> : Ask to have some virual machines to be able to play with that server combined with tests accounts</li>
<li><strong>Sandboxed environment</strong> : Ask your IT dept to create a sandboxed MOSS environment to have to possibility to replicate your actual MOSS environment and create custom user scenarios.</li>
</ul>
| 18,600
|
<p>Is there any reason to avoid using <code>text-align: justify;</code>? </p>
<p>Does it reduce readability or cause problems?</p>
|
<p>Firstly, this is purely a design-related problem and solution. The design of your grid specifies if justifying text is needed. I think justify align alone has no major effect on usability. Bad typography that makes text illegible is what decreases usability. That said, make sure you have solid contrasts and a good balance of spacing in your type. Font-size matters too.</p>
<p><a href="http://rebecamendez.com/" rel="noreferrer">This site</a> is a successful attempt at justifying text online. Since you can't control the spaces between letters and words nearly as much with CSS as you can with InDesign, it's a lot harder to justify text and not have 'rivers' of whitespace run down your rows, which happens when the spaces between words exceeds the spaces between lines. Things that make justifying text difficult: long words, row widths that don't hold enough words, and too much contrast between the text and the background colors; they make the rivers appear wider and more apparent.</p>
<p>The typographic ideal is to have an even text-block, where if you squint the text block becomes a uniform solid shade. So if you keep text at about 10px and 60% gray on white background, and have rows that fit about 20 words, justify align shouldn't look ugly. But keep in mind this does nothing to improve usability. Small, relatively light text annoys a lot of people, especially the older readers. </p>
<p>I should note that with <code>&shy;</code> (soft hyphenation) correctly separating long troublesome words like super­awesome you can mimic proper typesetting (e.g. InDesign). There's a lot of stuff out there to help you do this. I would recommend the logic for hiding, manipulating, and displaying the text to be done on the client side, perhaps with <a href="http://code.google.com/p/hyphenator/" rel="noreferrer">this</a>.</p>
<p><strong>Edit</strong>: As others mention below, <a href="http://caniuse.com/#feat=css-hyphens" rel="noreferrer">css hyphens</a> are possible now, except not feasible (not in Chrome). Plus, <a href="http://generatedcontent.org/post/44751461516" rel="noreferrer">css4 offers even more control</a>.</p>
|
<p>I think it is perfectly OK on print, but it is clunky on most Web browsers, by lack of fine control of spacing and hyphenation. Typographers can even play slightly on letter spacing or font contraction in some cases, as pages/columns (at least in magazines) can be finely tuned.</p>
| 40,782
|
<p>Is Occam-pi a good language to learn to program LEGO MINDSTORMS & Surveyor Corporation SRV-1 robots for an programming newbie. Are there any opensource projects making use of the same -- to read source code. url for occam-pi :- <a href="http://www.transterpreter.org/" rel="nofollow noreferrer">http://www.transterpreter.org/</a></p>
|
<p>I have used the <a href="http://www.occam-pi.org" rel="nofollow noreferrer">occam-pi</a> on the <a href="http://www.transterpreter.org" rel="nofollow noreferrer">transterpreter</a> and it seems to do a good job. You may want to check this <a href="http://www.sububi.org/" rel="nofollow noreferrer">blog</a> out. It is written by one of the developers. If you give Matt an email he may be able to point you in the right direction for material. </p>
|
<p>Probably not. It's a research language, so there won't be the support for what you want. sorry.</p>
<p>The LEGO MINDSTORMS Education NXT Software is probably a better bet for a programming newbie. The SRV-1 is cool - but doesn't really have the supporting resources for beginners. </p>
<p>Good luck!</p>
| 18,301
|
<p>In my page, I am displaying a report after the user selects some information. On a button <code>onclick</code> event, I am displaying an image which rotates itself to indicate to the user that the request is being processed. The image rotates in the Firefox but not in IE(it just displays the image). Please give me your suggestions. </p>
<p>with regards</p>
<p>R.Prakash</p>
|
<p>I'm guessing this is because your page has submitted a standard, synchronous request to the server and is waiting for the response. I've noticed that in certain versions of IE even an animated GIF will freeze up.</p>
<p>You may want to change your server request to be asynchronous (a la AJAX). And one of the benefits will be no freezing of animated images.</p>
|
<p>Try opening that page on other machine.</p>
| 36,979
|
<p>Being new to test based development, this question has been bugging me. How much is too much? What should be tested, how should it be tested, and why should it be tested? The examples given are in C# with NUnit, but I assume the question itself is language agnostic.</p>
<p>Here are two current examples of my own, tests on a generic list object (being tested with strings, the initialisation function adds three items <code>{"Foo", "Bar", "Baz"}</code>):</p>
<pre><code>[Test]
public void CountChanging()
{
Assert.That(_list.Count, Is.EqualTo(3));
_list.Add("Qux");
Assert.That(_list.Count, Is.EqualTo(4));
_list[7] = "Quuuux";
Assert.That(_list.Count, Is.EqualTo(8));
_list.Remove("Quuuux");
Assert.That(_list.Count, Is.EqualTo(7));
}
[Test]
public void ContainsItem()
{
Assert.That(_list.Contains("Qux"), Is.EqualTo(false));
_list.Add("Qux");
Assert.That(_list.Contains("Qux"), Is.EqualTo(true));
_list.Remove("Qux");
Assert.That(_list.Contains("Qux"), Is.EqualTo(false));
}
</code></pre>
<p>The code is fairly self-commenting, so I won't go into what's happening, but is this sort of thing taking it too far? <code>Add()</code> and <code>Remove()</code> are tested seperately of course, so what level should I go to with these sorts of tests? Should I even have these sorts of tests?</p>
|
<p>I would say that what you're actually testing are equivalence classes. In my view, there is no difference between a adding to a list that has 3 items or 7 items. However, there is a difference between 0 items, 1 item and >1 items. I would probably have 3 tests each for Add/Remove methods for these cases initially.</p>
<p>Once bugs start coming in from QA/users, I would add each such bug report as a test case; see the bug reproduce by getting a red bar; fix the bug by getting a green bar. Each such 'bug-detecting' test is there to stay - it is my safety net (read: regression test) that even if I make this mistake again, I will have instant feedback.</p>
|
<p>Is <code>_list</code> an instance of a class you wrote? If so, I'd say testing it is reasonable. Though in that case, why are you building a custom List class?</p>
<p>If it's not code you wrote, don't test it unless you suspect it's in some way buggy.</p>
<hr>
<p>I try to test code that's independent and modular. If there's some sort of God-function in code I have to maintain, I strip out as much of it as possible into sub-functions and test them independantly. Then the God function can be written to be "obviously correct" -- no branches, no logic, just passing results from one well-tested subfunction to another.</p>
| 20,502
|
<p>I'm using <a href="http://urlrewriter.net/" rel="nofollow noreferrer">http://urlrewriter.net/</a> to rewrite urls at my website. For example, I'm rewriting:</p>
<blockquote>
<p><a href="http://www.example.com/schedule.aspx?state=ca" rel="nofollow noreferrer">http://www.example.com/schedule.aspx?state=ca</a></p>
</blockquote>
<p>to</p>
<blockquote>
<p><a href="http://www.example.com/california.aspx" rel="nofollow noreferrer">http://www.example.com/california.aspx</a></p>
</blockquote>
<p>What I'm trying to do (for SEO purposes) to to dynamically add the meta tag:</p>
<pre><code><meta name="robots" content="noindex,follow" />
</code></pre>
<p><em>only</em> to the page that hasn't been rewritten. This is because I want both URLs to work, but only the rewritten one to be indexed by search engines. </p>
<p>How do I determine which version of the page has been requested?</p>
<p><strong>EDIT</strong></p>
<p>Answers below suggest a 301 redirect instead of using a meta tag. Maybe I'll do this, but I still want to know the answer to the underlying question... how do I know if the page has been rewritten?</p>
|
<p>personally, I would 301 redirect from the un-rewritten one to the re-written one, and only use the single copy of the page. It is easier for users, and from an SEO perspective, you have 1 copy of the content.</p>
|
<p>I think that's the job of <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcontext.items.aspx" rel="nofollow noreferrer">HttpContext.Current.Items</a>.</p>
<p>You can save the "Redirection" in HttpContext.Current.Items and then in your pages, you can check it for a certain added value.</p>
<p>I believe you can add hooks to urlrewriter.net that could do it, something alongs:</p>
<pre><code>HttpContext.Current.Items["Redirected_From"] = currentUrlHere;
</code></pre>
<p>And then in your webpages, you could check it by:</p>
<pre><code>if (!string.IsNullOrEmpty(HttpContext.Current.Items["Redirected_From"]))
// the page's been redirected, do something!
else
// no it's visited normally.
</code></pre>
<p>I have long since left it for the ASP.NET Routing framework in .NET 3.5 SP1, it is better than urlrewriter.net IMO.</p>
| 32,370
|
<p>I'm trying to change assembly binding (from one version to another) dynamically.</p>
<p>I've tried this code but it doesn't work:</p>
<pre><code> Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection assemblyBindingSection = config.Sections["assemblyBinding"];
assemblyBindingSection.SectionInformation.ConfigSource = "bindingConf.xml";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("assemblyBinding");
</code></pre>
<p>with <code>bindingConf.xml</code> containing the assemblyBinding section configuration.</p>
<p>So can a change this section at runtime? how to do it? What alternatives do I have?</p>
|
<p>The best way I've found to dynamically bind to a different version of an assembly is to hook the <code>AppDomain.AssemblyResolve</code> event. This event is fired whenever the runtime is unable to locate the exact assembly that the application was linked against, and it allows you to provide another assembly, that you load yourself, in its place (as long as it is compatible).</p>
<p>For example, you can put in a static constructor on your application's main class that hooks the event like this:</p>
<pre><code>using System.Reflection;
static Program()
{
AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs e)
{
AssemblyName requestedName = new AssemblyName(e.Name);
if (requestedName.Name == "AssemblyNameToRedirect")
{
// Put code here to load whatever version of the assembly you actually have
return Assembly.LoadFrom("RedirectedAssembly.DLL");
}
else
{
return null;
}
};
}
</code></pre>
<p>This method avoids the need to deal with the assembly bindings in configuration files and is a bit more flexible in terms of what you can do with it.</p>
|
<p>RuntimeSection of the config file update at runtime using this code: </p>
<pre><code>private void ModifyRuntimeAppConfig()
{
XmlDocument modifiedRuntimeSection = GetResource("Framework35Rebinding");
if(modifiedRuntimeSection != null)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection assemblyBindingSection = config.Sections["runtime"];
assemblyBindingSection.SectionInformation.SetRawXml(modifiedRuntimeSection.InnerXml);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("runtime");
}
}
</code></pre>
<p>with Framework35Rebinding containing:</p>
<pre class="lang-xml prettyprint-override"><code><runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Build.Framework" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="3.5.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.CompactFramework.Build.Tasks" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="9.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</code></pre>
<p>and an app.config containing (before the execution of the program):</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v2.0.50727"/>
</startup>
<runtime>
</runtime>
</configuration>
</code></pre>
<p>Nevertheless it doesn't work for that I wanna do because assemblyBinding is only read at startup of the application whereas the <code>RefreshSection("runtime")</code></p>
| 42,200
|
<p>Visual studio 2005 comes with a project that lets you use the asp.net membership provider to look up, add, edit, and delete users and roles. It unfortunaltly can't be used online, and in order to have an adminiistration area in your site, it appears that you have to code your own admin interface. </p>
<p>Is there an opensource, or free project that has the functionality of netwebadmin, but can be used online? </p>
|
<p>You might want to have a look at this project on codeplex <a href="http://www.codeplex.com/AspNetWSAT" rel="nofollow noreferrer">http://www.codeplex.com/AspNetWSAT</a>, which has an admin interface that you can use. I think there are a few other similar ones around too.</p>
|
<p>I am not aware of anything that is readily available, although I have a general solution that I have been considering packaging up and making available as a general freebie, but I've found that there isn't much demand as most of the time it is all specific implementations anyway.</p>
| 44,548
|
<p>I am a COM object written in ATL that is used from a C++ application, and I want to pass an array of BYTEs between the two. My experience of COM/IDL so far is limited to passing simple types (BSTRs, LONGs, etc.).</p>
<p>Is there a relatively easy way to have the COM object pass an array to the caller? For example, I want to pass a raw image (TIFF) instead of messing with temporary files.</p>
|
<p>Try passing a safearray variant to the COM Object. Something like this to put a BYTE array inside a safearray variant....</p>
<pre><code>bool ArrayToVariant(CArray<BYTE, BYTE>& array, VARIANT& vtResult)
{
SAFEARRAY FAR* psarray;
SAFEARRAYBOUND sabounds[1];
sabounds[0].lLbound=0;
sabounds[0].cElements = (ULONG)array.GetSize();
long nLbound;
psarray = SafeArrayCreate(VT_UI1, 1, sabounds);
if(psarray == NULL)
return false;
for(nLbound = 0; nLbound < (long)sabounds[0].cElements ; nLbound++){
if(FAILED(SafeArrayPutElement(psarray, &nLbound, &array[nLbound]))){
SafeArrayDestroy(psarray);
return false;
}
}
VariantFree(vtResult);
vtResult.vt = VT_ARRAY|VT_UI1;
vtResult.parray = psarray;
return true;
}
</code></pre>
|
<p>You can use BSTR to pass an array of bytes.</p>
<pre><code>BYTE array[buffer_size];
...
BSTR toBePassed = SysAllocStringByteLen((OLECHAR*)array,length);
YourCOMMethod(toBePassed);
SysFreeString(toBePassed);
</code></pre>
<p>In your method:</p>
<pre><code>BYTE* pData = (BYTE*)bstrPassed;
DWORD dataLength = SysStringByteLen(bstrPassed);
</code></pre>
| 37,687
|
<p>I have two lists that are of the same length, is it possible to loop through these two lists at once?</p>
<p>I am looking for the correct syntax to do the below</p>
<pre><code>foreach itemA, itemB in ListA, ListB
{
Console.WriteLine(itemA.ToString()+","+itemB.ToString());
}
</code></pre>
<p>do you think this is possible in C#? And if it is, what is the lambda expression equivalent of this?</p>
|
<p>[edit]: to clarify; this is useful in the generic LINQ / <code>IEnumerable<T></code> context, where you <strong>can't use</strong> an indexer, because a: it doesn't exist on an enumerable, and b: you can't guarantee that you can read the data more than once. Since the OP mentions lambdas, it occurs that LINQ might not be too far away (and yes, I do realise that LINQ and lambdas are not quite the same thing).</p>
<p>It sounds like you need the missing <code>Zip</code> operator; you can spoof it:</p>
<pre><code>static void Main()
{
int[] left = { 1, 2, 3, 4, 5 };
string[] right = { "abc", "def", "ghi", "jkl", "mno" };
// using KeyValuePair<,> approach
foreach (var item in left.Zip(right))
{
Console.WriteLine("{0}/{1}", item.Key, item.Value);
}
// using projection approach
foreach (string item in left.Zip(right,
(x,y) => string.Format("{0}/{1}", x, y)))
{
Console.WriteLine(item);
}
}
// library code; written once and stuffed away in a util assembly...
// returns each pais as a KeyValuePair<,>
static IEnumerable<KeyValuePair<TLeft,TRight>> Zip<TLeft, TRight>(
this IEnumerable<TLeft> left, IEnumerable<TRight> right)
{
return Zip(left, right, (x, y) => new KeyValuePair<TLeft, TRight>(x, y));
}
// accepts a projection from the caller for each pair
static IEnumerable<TResult> Zip<TLeft, TRight, TResult>(
this IEnumerable<TLeft> left, IEnumerable<TRight> right,
Func<TLeft, TRight, TResult> selector)
{
using(IEnumerator<TLeft> leftE = left.GetEnumerator())
using (IEnumerator<TRight> rightE = right.GetEnumerator())
{
while (leftE.MoveNext() && rightE.MoveNext())
{
yield return selector(leftE.Current, rightE.Current);
}
}
}
</code></pre>
|
<p><a href="http://msmvps.com/blogs/senthil/default.aspx" rel="nofollow noreferrer">Senthil Kumar's tech blog</a>, has a series covering implementations of <strong>(Python) Itertools for C#</strong>, including <a href="http://docs.python.org/library/itertools.html#itertools.izip" rel="nofollow noreferrer"><code>itertools.izip</code></a>.</p>
<p>From <a href="http://msmvps.com/blogs/senthil/archive/2008/04/26/itertools-for-c-cycle-and-zip.aspx" rel="nofollow noreferrer">Itertools for C# - Cycle and Zip</a>, you have a solution for any number of <em>iterables</em> (not only <em>List<T></em>). Note that <code>Zip</code> yields an <code>Array</code> on each iteration:</p>
<pre><code>public static IEnumerable<T[]> Zip<T>(params IEnumerable<T>[] iterables)
{
IEnumerator<T>[] enumerators = Array.ConvertAll(iterables, (iterable) => iterable.GetEnumerator());
while (true)
{
int index = 0;
T[] values = new T[enumerators.Length];
foreach (IEnumerator<T> enumerator in enumerators)
{
if (!enumerator.MoveNext())
yield break;
values[index++] = enumerator.Current;
}
yield return values;
}
</code></pre>
<p>}</p>
<blockquote>
<p>The code gets enumerators for all the iterables, moves all enumerators forward, accumulates their current values into an array and yields the array. It does this until any one of the enumerators runs out of elements.</p>
</blockquote>
| 30,008
|
<p>I need a way to check for Wi-Fi routers/access points on my DS homebrew. I'm using PAlib.</p>
|
<p>i used the code from ds_wifi_test (which comes with the original dswifi library) when i tried to implement this. Basically, access points are scanned internally when you invoke <code>Wifi_ScanMode()</code>. You can then have the number of AP identified with <code>Wifi_GetNumAP()</code> and retrieve the information for the ith access point with <code>Wifi_GetAPData(i,&data);</code></p>
<pre><code>nbitems=Wifi_GetNumAP();
Wifi_AccessPoint ap;
for (int i=0;i<nbitems; i++) {
if(Wifi_GetAPData(i+scrolltop,&ap)==WIFI_RETURN_OK)
do_whatever_with(&ap);
}
</code></pre>
<p>I'm not aware of any "helper" functions through the PALib in this regards. All the PALib seems to have is a few "wrappers" to ease common tasks once a WFC setting has been defined (<a href="http://www.palib.info/wiki/doku.php?id=day20" rel="nofollow noreferrer">see day#20 tutorial</a>)</p>
|
<p>If I were you, I'd steer clear of PALib. It's built atop an outdated version of libnds, and isn't updated with the new version in the interests of backwards-compatibility. Instead, take the time to learn libnds, and reap the benefits of a well-maintained library that doesn't have dependencies of its own. The same code that sylvainulg wrote above will still work, as it is dependant on dswifi, not libnds or PALib.</p>
| 27,285
|
<p>Coming from a background, I'm familiar with GUI editors that do a poor job of producing code. However, I've never written a GUI using .NET. Does the GUI editor in Visual Studio have the same problem(s)? Are both the source files and output GUI good?</p>
|
<p>The GUI editor in Visual Studio is probably the best I've used. Also, because C# supports <a href="http://msdn.microsoft.com/en-us/library/wa80x488(VS.80).aspx" rel="nofollow noreferrer">partial classes</a>, there is a clean separation between the IDE-generated code and your own.</p>
|
<p>Yes, for the most, you should use the GUI editor. Not that you won't have to work around it every now and again.</p>
<p>Also it depends if you are talking WPF or Winforms.</p>
<p>Winforms I'd use it almost the majority of the time.
WPF, I'd hand roll a lot of it and occassionally use blend or something to do some of the more tricky layout things.</p>
| 23,006
|
<p>What does the following code do? A link to something in the PHP manual would also be nice.</p>
<pre><code>if ($_SERVER['SERVER_PORT'] <> 443) {
doSomething();
}
</code></pre>
|
<p>Same as !=, "Not equal"</p>
<pre><code>false <> true // operator will evaluate expression as true
false != true // operator will evaluate expression as true
</code></pre>
<p>Here is some reference: <a href="http://www.php.net/operators.comparison" rel="noreferrer">PHP Comparison Operators</a></p>
|
<p><code>$_SERVER['SERVER_PORT']</code> gets the port used by the web server to serve HTTP requests. <code>$_SERVER['SERVER_PORT'] <> 443</code> checks if the port is not equal to 443 (the default HTTPS port) and if not, invokes <code>doSomething()</code> </p>
| 30,990
|
<p>I just got a new Ender3 version two for Christmas and was very excited to use it so I put it together and used the sample filament that came with the printer and everything worked okay for a bit.</p>
<p>That was until I switched something in the settings, or in Cura, or something happened, because the nozzle is too far away from the bed when printing. I will use the auto home feature to level my bed with a piece of paper and once I get that pretty close I try and start my print, and it starts a few millimetres further away from the bed than when levelling it.</p>
<p>Any ideas to solve this?</p>
|
<p>This is probably caused by too few top layers in combination with a too low infill percentage. Increase skin layers and increase infill percentage.</p>
<p>If you have multiple layers already (at least about 4 for 0.2 mm layer height, for smaller layer heights even more), you might be printing at a too high temperature and or too few part cooling percentage and a too low infill percentage.</p>
|
<p>To combat the bad top layers, I usually use usually 5 top layers for any model of layer height 0.1 to 0.3 mm. I generally don't print with less than 9 % infill for PLA, which I have found sufficient to support even complex geometry on top.</p>
<p>Also, I generally use a mixed setup of layers: the outermost layers I demand as concentric because this is the most beautiful setup, while the lower levels are Zig-Zag patterned, as this gives the best layer-to-wall connection.</p>
| 1,814
|
<p>If we are writing about power-wise option - is using a console-based application in C#(.NET) better than having Windows GUI and what's the real difference expept few libraries loaded in operational memory?</p>
<p>The issue is about text comparisons and working with strings, connecting to Internet, gathering data, working with database. </p>
<p>I meant power-capability, but as I've read here, it's more about controls than any power-relation. Thx :)</p>
|
<p>From your description it seems that you want to write an HTML scraping software or some kind of web spider. I think your decision whether to write a GUI or a command line application should depend on who (users) or which other software components will use or integrate your program.</p>
<p>If there is no user interaction involved, I guess it would be just fine to write it as command line program. If you have some options to set you could pass them as arguments.</p>
<p>If it will be a recurring, isolated job, you could also consider writing the application as <strong>windows service</strong>, which could start with the machine.</p>
|
<p>There is no difference in what you can do with the things you mentioned (strings, internet, database). The difference between console and GUI apps is solely in how you interact with the user. Everything else is the same.</p>
<p>If you meant power consumption instead, then I'm afraid I misunderstood your question.</p>
| 26,404
|
<p>I have been reading through the <a href="http://yosefk.com/c++fqa/" rel="noreferrer">C++ FAQ</a> and was curious about the <a href="http://yosefk.com/c++fqa/friend.html" rel="noreferrer"><code>friend</code></a> declaration. I personally have never used it, however I am interested in exploring the language. </p>
<p>What is a good example of using <code>friend</code>?</p>
<hr>
<p>Reading the FAQ a bit longer I like the idea of the <code><<</code> <code>>></code> operator overloading and adding as a friend of those classes. However I am not sure how this doesn't break encapsulation. When can these exceptions stay within the strictness that is OOP?</p>
|
<p>Firstly (IMO) don't listen to people who say <code>friend</code> is not useful. It IS useful. In many situations you will have objects with data or functionality that are not intended to be publicly available. This is particularly true of large codebases with many authors who may only be superficially familiar with different areas. </p>
<p>There ARE alternatives to the friend specifier, but often they are cumbersome (cpp-level concrete classes/masked typedefs) or not foolproof (comments or function name conventions).</p>
<p>Onto the answer; </p>
<p>The <code>friend</code> specifier allows the designated class access to protected data or functionality within the class making the friend statement. For example in the below code anyone may ask a child for their name, but only the mother and the child may change the name. </p>
<p>You can take this simple example further by considering a more complex class such as a Window. Quite likely a Window will have many function/data elements that should not be publicly accessible, but ARE needed by a related class such as a WindowManager.</p>
<pre><code>class Child
{
//Mother class members can access the private parts of class Child.
friend class Mother;
public:
string name( void );
protected:
void setName( string newName );
};
</code></pre>
|
<p>Friends are also useful for callbacks. You could implement callbacks as static methods</p>
<pre><code>class MyFoo
{
private:
static void callback(void * data, void * clientData);
void localCallback();
...
};
</code></pre>
<p>where <code>callback</code> calls <code>localCallback</code> internally, and the <code>clientData</code> has your instance in it. In my opinion, </p>
<p>or...</p>
<pre><code>class MyFoo
{
friend void callback(void * data, void * callData);
void localCallback();
}
</code></pre>
<p>What this allows is for the friend to be a defined purely in the cpp as a c-style function, and not clutter up the class.</p>
<p>Similarly, a pattern I've seen very often is to put all the <em>really</em> private members of a class into another class, which is declared in the header, defined in the cpp, and friended. This allows the coder to hide a lot of the complexity and internal working of the class from the user of the header.</p>
<p>In the header:</p>
<pre><code>class MyFooPrivate;
class MyFoo
{
friend class MyFooPrivate;
public:
MyFoo();
// Public stuff
private:
MyFooPrivate _private;
// Other private members as needed
};
</code></pre>
<p>In the cpp,</p>
<pre><code>class MyFooPrivate
{
public:
MyFoo *owner;
// Your complexity here
};
MyFoo::MyFoo()
{
this->_private->owner = this;
}
</code></pre>
<p>It becomes easier to hide things that the downstream needn't see this way.</p>
| 3,809
|
<p>I have done this on Websphere (re: title of this topic) using wsdl2java for generating wsdl to java mapping xml file.
My endpoint is a generic stateless EJB. The code in EJB is generated by traversing the each wsdl and getting the wsdl operation and stuck it in the generated remote EJB interface.
Each EJB method impl is generic and handles all the services the same.
Used instructions on this doc to do this on WAS: <a href="http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.base.doc/info/aes/ae/twbs_devwbsjaxrpcwsdl.html" rel="nofollow noreferrer">http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.base.doc/info/aes/ae/twbs_devwbsjaxrpcwsdl.html</a></p>
<p>Now, I am asking you all for help if anyone has done something similar in Sun AS 9.1.</p>
<p>Starting from existing WSDL (and xsd) files. Knowing the sole EJB service endpoint implementation for each services are the same, and generating an EAR file (webservices.xml, ejb-jar.xml, etc).</p>
<p>Have struggled with wscompile and alike, but not getting anyware in the same fashion I did for WebSphere.</p>
<p>Thanks for help.</p>
|
<p>You want to create a WS client which runs under Sun AS? I don't know Sun AS in detail and I don't know the WS libraries it supplies. But you may want to use a public WS library:</p>
<ul>
<li><a href="http://ws.apache.org/axis2/" rel="nofollow noreferrer">Apache Axis 2</a></li>
<li><a href="http://cxf.apache.org/" rel="nofollow noreferrer">Apache CXF</a></li>
</ul>
<p>For every library there is documentation which describes how to create a project from WSDL.</p>
<p>You could even use Eclipse to create a project from WSDL for you: File -> New -> Other... -> Web Services -> WSDL. Make sure you have the "WST Web Services" Plugins installed.</p>
|
<p>I've never used it myself, but I just recently read about the <code>wsdlLocation()</code> attribute of the <code>WebService</code> annotation, which is supposed to map the service to a preexisting WSDL document (not sure if you're even using EJB3, though).</p>
| 38,422
|
<p>I have a few 'helper' style extension methods I use quite regularly now <em>(they are mostly quite simple, intuitive, and work for good not evil, so please don't have this descend into a discussion around whether or not I should use them).</em> They are largely extending core .NET CLR classes.</p>
<p>Currently, I have to copy the 'ExtensionMethods.cs' file that holds my extension methods to each new project within a solution to be able to use them in multiple projects.</p>
<p>Is it possible to define an extension to work over multiple projects within a solution, or wrap them in an 'extensions' dll, or are they confined to the scope of project?</p>
<p><strong>EDIT</strong> Whilst the 'dedicated project' answers are perfectly valid, I chose marxidad's as I prefer the approach he gives. Thanks for all the answers so far, and I have upmodded them all, as they were all good answers</p>
|
<p>If you don't want to create a whole project just for the extension methods, you can link the same file into separate projects without copying the file:</p>
<ol>
<li>In Solution Explorer, select the target project. </li>
<li>Select the Project menu. </li>
<li>Select Add Existing Item. </li>
<li>In the Add Existing Item dialog box, select the item you want to link.</li>
<li>From the Open button drop-down list, select Add As Link.</li>
</ol>
|
<p>Several answers suggests that someone would put the extension functions into a common assembly. Which is the right answer. But there's a weird thing for beginners: the IntelliSense couldn't help well enough.
Let's say I extended the <code>ObservableCollection</code> with a <code>ReplaceRange</code> function / method.
After a move the class of the extension functions, at first the compiler will say
<code>error CS1061: 'System.Collections.ObjectModel.ObservableCollection<WhateverDto>' does not contain a definition for 'ReplaceRange' and no extension method 'ReplaceRange' accepting a first argument of type 'System.Collections.ObjectModel.ObservableCollection<WhateverDto>' could be found (are you missing a using directive or an assembly reference?)</code>
If you then hover over the problematic <code>ReplaceRange</code> call, you won't get the offer to include the proper using statement automatically. Someone might think at that point that he/she did something wrong. Nothing is however, you just have to know where is your extension method, and you have to manually type the using statement for the namespace of the methods. After you got that right your source will compile.</p>
| 19,434
|
<p>Despite the documentation, NetworkStream.Write does not appear to wait until the data has been sent. Instead, it waits until the data has been copied to a buffer and then returns. That buffer is transmitted in the background.</p>
<p>This is the code I have at the moment. Whether I use ns.Write or ns.BeginWrite doesn't matter - both return immediately. The EndWrite also returns immediately (which makes sense since it is writing to the send buffer, not writing to the network).</p>
<pre><code> bool done;
void SendData(TcpClient tcp, byte[] data)
{
NetworkStream ns = tcp.GetStream();
done = false;
ns.BeginWrite(bytWriteBuffer, 0, data.Length, myWriteCallBack, ns);
while (done == false) Thread.Sleep(10);
}
public void myWriteCallBack(IAsyncResult ar)
{
NetworkStream ns = (NetworkStream)ar.AsyncState;
ns.EndWrite(ar);
done = true;
}
</code></pre>
<p>How can I tell when the data has actually been sent to the client?</p>
<p>I want to wait for 10 seconds(for example) for a response from the server after sending my data otherwise I'll assume something was wrong. If it takes 15 seconds to send my data, then it will always timeout since I can only start counting from when NetworkStream.Write returns - which is before the data has been sent. I want to start counting 10 seconds from when the data has left my network card.</p>
<p>The amount of data and the time to send it could vary - it could take 1 second to send it, it could take 10 seconds to send it, it could take a minute to send it. The server does send an response when it has received the data (it's a smtp server), but I don't want to wait forever if my data was malformed and the response will never come, which is why I need to know if I'm waiting for the data to be sent, or if I'm waiting for the server to respond.</p>
<p>I might want to show the status to the user - I'd like to show "sending data to server", and "waiting for response from server" - how could I do that?</p>
|
<p>I'm not a C# programmer, but the way you've asked this question is slightly misleading. The only way to know when your data has been "received", for any useful definition of "received", is to have a specific acknowledgment message in your protocol which indicates the data has been fully processed.</p>
<p>The data does not "leave" your network card, exactly. The best way to think of your program's relationship to the network is:</p>
<blockquote>
<p>your program -> lots of confusing stuff -> the peer program</p>
</blockquote>
<p>A list of things that might be in the "lots of confusing stuff":</p>
<ul>
<li>the CLR</li>
<li>the operating system kernel</li>
<li>a virtualized network interface</li>
<li>a switch</li>
<li>a software firewall</li>
<li>a hardware firewall</li>
<li>a router performing network address translation</li>
<li>a router on the peer's end performing network address translation</li>
</ul>
<p>So, if you are on a virtual machine, which is hosted under a different operating system, that has a software firewall which is controlling the virtual machine's network behavior - when has the data "really" left your network card? Even in the best case scenario, many of these components may drop a packet, which your network card will need to re-transmit. Has it "left" your network card when the first (unsuccessful) attempt has been made? Most networking APIs would say no, it hasn't been "sent" until the other end has sent a TCP acknowledgement.</p>
<p>That said, <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.write.aspx" rel="noreferrer">the documentation for NetworkStream.Write</a> seems to indicate that it will not return until it has at least initiated the 'send' operation:</p>
<blockquote>
<p>The Write method blocks until the requested number of bytes is sent or a SocketException is thrown.</p>
</blockquote>
<p>Of course, "is sent" is somewhat vague for the reasons I gave above. There's also the possibility that the data will be "really" sent by your program and received by the peer program, but the peer will crash or otherwise not actually process the data. So you should do a <code>Write</code> followed by a <code>Read</code> of a message that will only be emitted by your peer when it has actually processed the message.</p>
|
<p>Perhaps try setting
<code>tcp.NoDelay = true</code></p>
| 9,332
|
<p>.NET throws an exception trying to parse a datetime string in this format:</p>
<p><strong>Fri, 10 Oct 2008 00:05:51 CST</strong> </p>
<p>Convert.ToDateTime("Fri, 10 Oct 2008 00:05:51 CST") results in an exception:</p>
<blockquote>
<p>The string was not recognized as a
valid DateTime. There is a unknown
word starting at index 26</p>
</blockquote>
<p>Character 26 obviously being the start of "CST"</p>
<p>In a quick test, PHP and javascript can both parse this string into a date with no problem. Is .NET just full of fail or is there a reasonable explanation?</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/ey1cdcx8.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ey1cdcx8.aspx</a></p>
<p>You need to use the overloaded DateTime.Parse to accurately parse timezones.</p>
|
<p>If a specific date and time format will be parsed across different locales, use one of the overloads of the ParseExact method and provide a format specifier. </p>
| 23,469
|
<p>I have looked on FaceBook Developer page and found that it's possible to create a FaceBook application, however this application must be hosted by you!</p>
<p>I'm new, does any one have an experience on that?</p>
|
<p>I don't really see a question. Surely a lot developers created such an application (see all the available apps in facebook).</p>
<p>I personally tried it once. And yes, you need a place to publish your aplication (webserver)...</p>
<p>Some help to start: <a href="https://developers.facebook.com/docs/" rel="nofollow noreferrer">https://developers.facebook.com/docs/</a></p>
|
<p>You don't have to host your application. <a href="http://joyent.com/developers/facebook" rel="nofollow noreferrer">Here's a company that will host your Facebook application for free for one year.</a></p>
| 40,250
|
<p>I run a subprocess using:</p>
<pre><code> p = subprocess.Popen("subprocess",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
</code></pre>
<p>This subprocess could either exit immediately with an error on stderr, or keep running. I want to detect either of these conditions - the latter by waiting for several seconds.</p>
<p>I tried this:</p>
<pre><code> SECONDS_TO_WAIT = 10
select.select([],
[p.stdout, p.stderr],
[p.stdout, p.stderr],
SECONDS_TO_WAIT)
</code></pre>
<p>but it just returns:</p>
<pre><code> ([],[],[])
</code></pre>
<p>on either condition. What can I do?</p>
|
<p>Have you tried using the Popen.Poll() method. You could just do this:</p>
<pre><code>p = subprocess.Popen("subprocess",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
time.sleep(SECONDS_TO_WAIT)
retcode = p.poll()
if retcode is not None:
# process has terminated
</code></pre>
<p>This will cause you to always wait 10 seconds, but if the failure case is rare this would be amortized over all the success cases.</p>
<hr>
<p>Edit:</p>
<p>How about:</p>
<pre><code>t_nought = time.time()
seconds_passed = 0
while(p.poll() is not None and seconds_passed < 10):
seconds_passed = time.time() - t_nought
if seconds_passed >= 10:
#TIMED OUT
</code></pre>
<p>This has the ugliness of being a busy wait, but I think it accomplishes what you want.</p>
<p>Additionally looking at the select call documentation again I think you may want to change it as follows:</p>
<pre><code>SECONDS_TO_WAIT = 10
select.select([p.stderr],
[],
[p.stdout, p.stderr],
SECONDS_TO_WAIT)
</code></pre>
<p>Since you would typically want to read from stderr, you want to know when it has something available to read (ie the failure case).</p>
<p>I hope this helps.</p>
|
<p>This is a paraphrase on Evan's answer, but it takes into account the following :</p>
<ol>
<li>Explicitly canceling the Timer object : if the Timer interval would be long and the process will exit by its "own will" , this could hang your script :(</li>
<li><p>There is an intrinsic race in the Timer approach (the timer attempt killing the process <em>just after</em> the process has died and this on Windows will raise an exception). </p>
<pre><code> DEVNULL = open(os.devnull, "wb")
process = Popen("c:/myExe.exe", stdout=DEVNULL) # no need for stdout
def kill_process():
""" Kill process helper"""
try:
process.kill()
except OSError:
pass # Swallow the error
timer = Timer(timeout_in_sec, kill_process)
timer.start()
process.wait()
timer.cancel()
</code></pre></li>
</ol>
| 43,850
|
<p>Is there a regular expression which checks if a string contains only upper and lowercase letters, numbers, and underscores?</p>
|
<p>To match a string that contains <em>only</em> those characters (or an empty string), try</p>
<pre class="lang-none prettyprint-override"><code>"^[a-zA-Z0-9_]*$"
</code></pre>
<p>This works for .NET regular expressions, and probably a lot of other languages as well.</p>
<p>Breaking it down:</p>
<pre class="lang-none prettyprint-override"><code>^ : start of string
[ : beginning of character group
a-z : any lowercase letter
A-Z : any uppercase letter
0-9 : any digit
_ : underscore
] : end of character group
* : zero or more of the given characters
$ : end of string
</code></pre>
<p>If you don't want to allow empty strings, use <code>+</code> instead of <code>*</code>.</p>
<hr />
<p>As others have pointed out, some regex languages have a shorthand form for <code>[a-zA-Z0-9_]</code>. In the .NET regex language, you can turn on ECMAScript behavior and use <code>\w</code> as a shorthand (yielding <code>^\w*$</code> or <code>^\w+$</code>). Note that in other languages, and by default in .NET, <code>\w</code> is somewhat broader, and will match other sorts of Unicode characters as well (thanks to Jan for pointing this out). So if you're really intending to match <strong>only</strong> those characters, using the explicit (longer) form is probably best.</p>
|
<h3>Required Format</h3>
<p>Allow these three:</p>
<ol>
<li>0142171547295</li>
<li>014-2171547295</li>
<li>123abc</li>
</ol>
<p>Don't allow other formats:</p>
<pre class="lang-js prettyprint-override"><code>validatePnrAndTicketNumber(){
let alphaNumericRegex=/^[a-zA-Z0-9]*$/;
let numericRegex=/^[0-9]*$/;
let numericdashRegex=/^(([1-9]{3})\-?([0-9]{10}))$/;
this.currBookingRefValue = this.requestForm.controls["bookingReference"].value;
if(this.currBookingRefValue.length == 14 && this.currBookingRefValue.match(numericdashRegex)){
this.requestForm.controls["bookingReference"].setErrors({'pattern': false});
}else if(this.currBookingRefValue.length ==6 && this.currBookingRefValue.match(alphaNumericRegex)){
this.requestForm.controls["bookingReference"].setErrors({'pattern': false});
}else if(this.currBookingRefValue.length ==13 && this.currBookingRefValue.match(numericRegex) ){
this.requestForm.controls["bookingReference"].setErrors({'pattern': false});
}else{
this.requestForm.controls["bookingReference"].setErrors({'pattern': true});
}
}
</code></pre>
<pre class="lang-html prettyprint-override"><code><input name="booking_reference" type="text" [class.input-not-empty]="bookingRef.value"
class="glyph-input form-control floating-label-input" id="bookings_bookingReference"
value="" maxlength="14" aria-required="true" role="textbox" #bookingRef
formControlName="bookingReference" (focus)="resetMessageField()" (blur)="validatePnrAndTicketNumber()"/>
</code></pre>
| 43,614
|
<p>I am wanting to store the "state" of some actions the user is performing in a series of different ASP.Net webforms. What are my choices for persisting state, and what are the pros/cons of each solution?</p>
<p>I have been using Session objects, and using some helper methods to strongly type the objects:</p>
<pre><code> public static Account GetCurrentAccount(HttpSessionState session)
{
return (Account)session[ACCOUNT];
}
public static void SetCurrentAccount(Account obj, HttpSessionState session)
{
session[ACCOUNT] = obj;
}
</code></pre>
<p>I have been told by numerous sources that "Session is evil", so that is really the root cause of this question. I want to know what you think "best practice", and why.</p>
|
<p>There is nothing inherently evil with session state.</p>
<p>There are a couple of things to keep in mind that might bite you though:</p>
<ol>
<li>If the user presses the browser back button you go back to the previous page but your session state is not reverted. So your CurrentAccount might not be what it originally was on the page.</li>
<li>ASP.NET processes can get recycled by IIS. When that happens you next request will start a new process. If you are using in process session state, the default, it will be gone :-(</li>
<li>Session can also timeout with the same result if the user isn't active for some time. This defaults to 20 minutes so a nice lunch will do it.</li>
<li>Using out of process session state requires all objects stored in session state to be serializable.</li>
<li>If the user opens a second browser window he will expect to have a second and distinct application but the session state is most likely going to be shared between to two. So changing the CurrentAccount in one browser window will do the same in the other.</li>
</ol>
|
<p>Short term information, that only needs to live until the next request, can also be stored in the <code>ViewState</code>. This means that objects are serialized and stored in the page sent to the browser, which is then posted back to the server on a click event or similar. Then the <code>ViewState</code> is decoded and turned into objects again, ready to be retrieved.</p>
| 16,130
|
<p>Is it possible to use <a href="http://www.python.org/" rel="nofollow noreferrer">CPython</a> to develop Adobe Flash based applications?</p>
|
<p>You can try <a href="http://www.libming.org/" rel="nofollow noreferrer">ming</a>, a library for generating Macromedia Flash files (.swf).</p>
<p>It's written in C but it has wrappers that allow it to be used in C++, PHP, Python, Ruby, and Perl. </p>
|
<p>I guess it would be possible to compile the python interpreter to flash bytecode using this <a href="http://labs.adobe.com/downloads/alchemy.html" rel="nofollow noreferrer">http://labs.adobe.com/downloads/alchemy.html</a> and then use it to run python programs. But apart from that the answer is no.</p>
| 39,177
|
<p>I have the following snippet of code, changeTextArea is a TextArea object.</p>
<pre><code>changeTextArea.addKeyboardListener(new KeyboardListenerAdapter()
public void onKeyPress( Widget sender, char keyCode, int modifier){
//do something
//I WISH TO STOP THE EVENT THAT MAPS TO THIS KEYPRESS FROM BUBBLING ANY FURTHER
}
}
</code></pre>
<p>How would I stop the Event that is causing this method to be called from bubbling up from changeTextArea into the Panels/Widgets/Composites/Whatever that contain changeTextArea. Put succinctly, how do I stop it from bubbling any further. Any help would be appreciated (especially code samples).</p>
|
<p>As far as I know you can't do it via a keyboard listener, but it is possible by adding an event preview using the DOM class:</p>
<pre><code>DOM.addEventPreview(EventPreview preview)
</code></pre>
<p>Then when you get the event:</p>
<pre><code>onEventPreview(Event event)
</code></pre>
<p>You should return false, to say you want to cancel the event. The Event object also supports this method:</p>
<pre><code>public final void cancelBubble(boolean cancel)
</code></pre>
<p>Cancels bubbling for the given event. This will stop the event from being propagated to parent elements. </p>
<p>You can find more details here:
<a href="http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html?overview-summary.html" rel="noreferrer">http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html?overview-summary.html</a></p>
|
<p>you could reach it when possible by doing
<code>event.doit = false</code></p>
| 26,340
|
<p>I am wanting to buy a 3D printer to add to my shop.</p>
<p>I am an engineer and enjoy making/building things so the kit idea sounds fun and economical.</p>
<p>I see Tronxy has two different styles for their larger printers:</p>
<ul>
<li>P802 (reprap frame) style</li>
<li>X3 (metal frame) style.</li>
</ul>
<p>As far as I can see, both printers have the same basic resolution, accuracy, and material specs.</p>
<ol>
<li>What are the advantages/disadvantages/differences between the
P802 and X3? </li>
<li>How important is auto-leveling?</li>
</ol>
|
<p>You can not tell this by looking at the STL file alone, because how much material will be used depends on the print settings (obviously, printing at 100% infill will consume much more material than 10%).</p>
<p>The best way to check the material usage is to load the model into a slicer and slice it using your preferred settings. Most slicers will report the projected material usage, often in grams but sometimes in meters of filament (but the two figures are easily converted between each other if you know the density and diameter of your material).</p>
<p>Here is an example in the Cura slicer:</p>
<p><a href="https://i.stack.imgur.com/e23iM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/e23iM.png" alt="Cura print statistics"></a></p>
<p>Simplify3D (after you click "prepare to print!") also shows you the projected print time and material usage and even the cost of the material (if you have previously entered the material cost per kilogram):</p>
<p><a href="https://i.stack.imgur.com/pjcxO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pjcxO.png" alt="Simplify3D print statistics"></a></p>
|
<p>This is a link I found that analyzes your G-code ( filament usage, time, etc.): <a href="http://gcode.ws/" rel="nofollow noreferrer">gCodeViewer</a></p>
<p>From the description (emphasis is mine):</p>
<blockquote>
<ul>
<li>Analyze GCode
<ul>
<li>Print time, <strong><em>amount of plastic used</em></strong>, layer height, etc. for whole file and for single layer</li>
</ul></li>
</ul>
</blockquote>
<p>Here is a screenshot:</p>
<blockquote>
<p><a href="https://i.stack.imgur.com/pDsuL.png" rel="nofollow noreferrer" title="Screenshot"><img src="https://i.stack.imgur.com/pDsuL.png" alt="Screenshot" title="Screenshot"></a></p>
</blockquote>
| 549
|
<p>I'm using <a href="http://www.codeplex.com/bizunit" rel="noreferrer" title="BizUnit">BizUnit</a> to unit-tests my Biztalk orchestrations, but some orchestrations consume a WebService,and testing these seems more like integration testing than unit testing.</p>
<p>I'm familiar with using a mocking framework to mock the generated proxy objects, in order to test a web service from a Windows Forms application, but I would like to be able to do it in a more integrated way in a request-response port?</p>
<p>How would you approach this problem?</p>
|
<p>This goes to the heart of one of my main irritations as a BizTalk developer - BizTalk does not lend it self to unit testing. From the fact the 99% of your interfaces into BizTalk applications are message based and have a huge number of possible inputs, through to the opaque nature of orchestrations, BizTalk offers no real way of testing units of functionality as... well... units.</p>
<p>For BizTalk, integration tests are sadly often the only game in town.</p>
<p>That results in, due to no fault on the part of Kevin Smith, BizUnit being (IMO) a misnomer. A better name would perhaps be BizIntegrationIt. BizUnit offers a range of tools that assist in integration testing, the majority of its tests, like checking if a file has been written to a given directory or sending an HTTPRequest to a BizTalk HTTPReceive location are all strictly speaking, testing integration.</p>
<p>Now that I've gotten that rant out, what you are asking for is something I've been thinking about for a long time, the ability to create automated unit tests that give some real confidence that my making a small change to a map won't suddenly break something else downstream, as well as a way to remove dependance on external services.</p>
<p>I've never thought of any nice way of doing this but below is a solution that <strong>should</strong> work, I've done variations of each part of this in isolation but never tried to but them all together in this specific form.</p>
<p>So given the desire to mock a call to some external service (that may not even exist yet) without needing to actually make any external call <strong>and</strong> wanting to have the ability to set expectations for that service call and to specify the nature of the response, the only method I can think of is to develop a custom adapter.</p>
<h2>Mock webservice using custom adapter</h2>
<p>If you build a custom request-response adapter you can plug it into your send port in place of the SOAP adapter. You can then specify properties for the adapter that allow it to behave as a mock of your webservice. The adapter would be similar in concept to a loopback adapter but would allow internal mocking logic.</p>
<p>Things that you might want to include as adapter properties:</p>
<ul>
<li>Expected document (perhaps a disk location that specifies an example of what you expect your BizTalk applicaiton to send to the webservice).</li>
<li>Response document - the document that the adapter will send back to the messaging engine.</li>
<li>Specific expectations for the test such as lookup values in document elements.</li>
</ul>
<p>You could also have the custom adapter write to disk and setup a BizUnit step to validate the file that was written out.</p>
<p>Building a custom adapter is non-trivial, but possible, you can get a good start from the <a href="https://web.archive.org/web/20220825235952/https://www.microsoft.com/nl-nl" rel="nofollow noreferrer">BizTalk Adapter Wizard</a> and there is an article on deploying custom adapters <a href="https://learn.microsoft.com/en-us/biztalk/core/how-to-deploy-a-custom-adapter" rel="nofollow noreferrer">here</a>.</p>
<p>There is a bug in the code generated by the wizard, you will need to change <code>new Guid(""),</code> to <code>new Guid()</code>.</p>
<p>There are also some examples of building custom adapters in the BizTalk SDK.</p>
<p>Another option is to use a plain http page and the HTTP solicit response as discussed <a href="https://web.archive.org/web/20210117134552/http://geekswithblogs.net/gwiele/archive/2004/11/10/14737.aspx" rel="nofollow noreferrer">here</a>, all your logic goes in the http page. This is probably simpler if you are happy having an http call, and setting up an IIS port to listen for your test.</p>
<h2>Initialising unit tests</h2>
<p>You can import binding files into a BizTalk application using a .bat file.</p>
<p>If you make a new binding file for each test you run, as well as for your standard applicaiton set up, you can then run the appropriate batch file to apply the right binding.</p>
<p>Each binding file would change your webservice sendport to use the mock custom adapter and set the specific properties for that test.</p>
<p>You could then even make a custom BizUnit step that (perhaps) generated binding settings based on settings in the test step and then ran the shell commands to update the bindings.</p>
<h2>Testing Message Contents</h2>
<p>A final thing that you might want to consider, to really tie all this together, is some way of testing the contents of messages. You could do this in your mock adapter, but that would get tedious very quickly for large messages, or for a large range of possible input messages.</p>
<p>One option is to make a custom pipeline that calls <a href="https://www.schematron.com/" rel="nofollow noreferrer">Schematron</a> to validate files that it receives. Schematron is a schema language that allows a much richer level of file inspection that xsd, so you can check things like "If element x contains this content, I expect element y to be present".</p>
<p>If you built a custom pipeline that took a schematron schema as a parameter, you could then swap in a testing file for a specific unit test, validating that for this test, when you call the webservice you get a file that actually matches what you want (and doesn't just match the xsd)</p>
|
<p>I haven't had to do this in a while, but when I would test my Biztalk Apps I always used either soap ui or web service studio. I was able to test different input values without effort. </p>
| 32,051
|
<p>Delphi has a $WARN compiler directive that allows one to selectively enable or disable specific warnings. The Delphi 2009 help file describes the syntax:</p>
<pre><code>{$WARN identifier ON|OFF}
</code></pre>
<p>But it only lists the identifiers for 6 warnings.</p>
<p>I'd like to have a complete list of all the warning identifiers. In particular, I want to know the identifiers for the implicit string cast warnings W1057 and W1058 in Delphi 2009.</p>
<p>I managed to guess the one for implicit Ansi->Unicode casts (W1057):</p>
<pre><code>{$WARN IMPLICIT_STRING_CAST OFF}
</code></pre>
<p>Googling for that found me the other one:</p>
<pre><code>{$WARN IMPLICIT_STRING_CAST_LOSS OFF}
</code></pre>
<p>Though that solves my immediate need, I'd still like to know the complete list of warning identifiers. Stuff like this should be documented.</p>
|
<p>I looked through the help and didn't see a full list...so poking around the code it appears the compiler warning constants are all listed in:
CodeGear\RAD Studio\6.0\sources\toolsapi\DCCStrs.pas</p>
<p>Search for "Implicit_String_Cast_Loss" and you'll see the constant
sIMPLICIT_STRING_CAST_LOSS = 'DCC_IMPLICIT_STRING_CAST_LOSS';</p>
<p>I would assume the rest of the DCC_xxx strings with corresponding X_true/_false/_error defines are what you are after.</p>
<p>Online help hasn't been very good since Delphi 7.</p>
|
<p>If you press <em>Ctrl+O</em> twice it will add all the compiler directives to the top of the unit including all the warnings. Find the one you want and delete the rest.</p>
| 49,329
|
<p>I have several strings in the rough form:</p>
<pre><code>[some text] [some number] [some more text]
</code></pre>
<p>I want to extract the text in [some number] using the Java Regex classes.</p>
<p>I know roughly what regular expression I want to use (though all suggestions are welcome). What I'm really interested in are the Java calls to take the regex string and use it on the source data to produce the value of [some number].</p>
<p>EDIT: I should add that I'm only interested in a single [some number] (basically, the first instance). The source strings are short and I'm not going to be looking for multiple occurrences of [some number].</p>
|
<p>Full example:</p>
<pre><code>private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)");
public static void main(String[] args) {
// create matcher for pattern p and given string
Matcher m = p.matcher("Testing123Testing");
// if an occurrence if a pattern was found in a given string...
if (m.find()) {
// ...then you can use group() methods.
System.out.println(m.group(0)); // whole matched expression
System.out.println(m.group(1)); // first expression from round brackets (Testing)
System.out.println(m.group(2)); // second one (123)
System.out.println(m.group(3)); // third one (Testing)
}
}
</code></pre>
<p>Since you're looking for the first number, you can use such regexp:</p>
<pre><code>^\D+(\d+).*
</code></pre>
<p>and <code>m.group(1)</code> will return you the first number. Note that signed numbers can contain a minus sign:</p>
<pre><code>^\D+(-?\d+).*
</code></pre>
|
<p>if you are reading from file then this can help you</p>
<pre><code> try{
InputStream inputStream = (InputStream) mnpMainBean.getUploadedBulk().getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line;
//Ref:03
while ((line = br.readLine()) != null) {
if (line.matches("[A-Z],\\d,(\\d*,){2}(\\s*\\d*\\|\\d*:)+")) {
String[] splitRecord = line.split(",");
//do something
}
else{
br.close();
//error
return;
}
}
br.close();
}
}
catch (IOException ioExpception){
logger.logDebug("Exception " + ioExpception.getStackTrace());
}
</code></pre>
| 29,328
|
<p>I've been wanting to become proficient in a new language for a while. There are a few languages I want to learn but it's pretty important for me to be able to create a (Application) GUI. I work in C# so I have become very accustom to the GUI designer. </p>
<p>I would love to get better with C++ or Java (both of which I have a small amount of experience with). Other languages could be interesting too. I just really need to be able to make a GUI reasonably easily.</p>
<p>So what (non .net) language has a really good method of designing GUIs? </p>
<p>An extension to this question might be what are the most common GUI APIs/designers?</p>
|
<p>I would recommend you to look at Delphi. It's object pascal with a nice IDE and a nice community!</p>
<p>Take a look at <a href="http://www.codegear.com" rel="nofollow noreferrer">www.codegear.com</a></p>
<p>CodeGear have also a C++ IDE, so you can have the bundle and put your hand dirty at Delphi and C++!</p>
<p>Hope his helps</p>
<p>vIceBerg</p>
|
<p>Netbeans IDE for Java as a sweet GUI designer.</p>
| 19,291
|
<p>I have fname and lname in my database, and a name could be stored as JOHN DOE or john DOE or JoHN dOE, but ultimately I want to display it as John Doe</p>
<p>fname being John and lname being Doe</p>
|
<p>seeing it is tagged PHP:<br>
either </p>
<blockquote>
<p><code>string ucfirst ( string $str );</code> </p>
</blockquote>
<p>to uppercase first letter of the first word </p>
<p>or </p>
<blockquote>
<p><code>string ucwords ( string $str );</code> </p>
</blockquote>
<p>to uppercase the first letter of every word</p>
<p>you might want to use those in combination with</p>
<blockquote>
<p><code>string strtolower ( string $str );</code> </p>
</blockquote>
<p>to normalize all names to lower case first.</p>
|
<p>Change the names to lower and then add ('A' - 'a') to the first letter of fname & lname.</p>
| 22,077
|
<p>I'm trying to read a single XML document from stream at a time using dom4j, process it, then proceed to the next document on the stream. Unfortunately, dom4j's SAXReader (using JAXP under the covers) keeps reading and chokes on the following document element.</p>
<p>Is there a way to get the SAXReader to stop reading the stream once it finds the end of the document element? Is there a better way to accomplish this?</p>
|
<p>I was able to get this to work with some gymnastics using some internal JAXP classes:</p>
<ul>
<li>Create a custom scanner, a subclass of XMLNSDocumentScannerImpl
<ul>
<li>Create a custom driver, an implementation of XMLNSDocumentScannerImpl.Driver, inside the custom scanner that returns END_DOCUMENT when it sees an declaration or an element. Get the ScannedEntity from fElementScanner.getCurrentEntity(). If the entity has a PushbackReader, push back the remaining unread characters in the entity buffer onto the reader.</li>
<li>In the constructor, replaces the fTrailingMiscDriver with an instance of this custom driver.</li>
</ul></li>
<li>Create a custom configuration class, a subclass of XIncludeAwareParserConfiguration, that replaces the stock DOCUMENT_SCANNER with an instance of this custom scanner in its constructor.</li>
<li>Install an instance of this custom configuration class as the "com.sun.org.apache.xerces.internal.xni.parser.XMLParserConfiguration" property so it will be instantiated when dom4j's SAXReader class tries to create a JAXP XMLReader.</li>
<li>When passing a Reader to dom4j's SAXReader.read() method, supply a PushbackReader with a buffer size considerably larger than the one-character default. At least 8192 should be enough to support the default buffer size of the XMLEntityManager inside JAXP's copy of Apache2.</li>
</ul>
<p>This isn't the cleanest solution, as it involves subclassing internal JAXP classes, but it does work.</p>
|
<p>Most likely, you don't want to have more than one document in the same stream at the same time. I don't think that the SAXReader is smart enough to stop when it gets to the end of the first document. Why is it necessary to have multiple documents in the same stream like this?</p>
| 27,953
|
<p>There is a conversion process that is needed when migrating Visual Studio 2005 web site to Visual Studio 2008 web application projects.</p>
<p>It looks like VS2008 is creating a .designer. file for every aspx when you right click on a file or the project itself in Solution Explorer and select 'Convert to Web Application.'</p>
<p>What is the purpose of these designer files? And these won't exist on a release build of the web application, they are just intermediate files used during development, hopefully?</p>
|
<p>They hold all the form designer stuff that used to go in the #Region " Web Form Designer Generated Code " section of the code. instead of putting it in the .aspx.vb file where people might edit it (mistakenly or not), it's been moved to a separate file, so that you don't have ever look at it.</p>
|
<p>What kibbee said. </p>
<p>For the part of your question about existing on a release build, it depends on what kind of web site you have. If you have a pre-compiled web site, then <em>none</em> of code files (.vb, .cs, etc) need to be deployed the server. They are compiled into .dlls (assemblies) and deployed that way along with the .as*x files.</p>
| 4,811
|
<p>Just wondering where is best to put functionality in an MFC application that is triggered when the whole window is resized. I was thinking mainfrm but I couldn't seem to capture any OnSize messages... </p>
<p>Can someone tell me what I am doing wrong?</p>
|
<blockquote>
<p>Can someone tell me what I am doing wrong?</p>
</blockquote>
<p>You didn't include any interesting details, so here are a few guesses (because <em>of course</em> the mainframe normally gets sent <code>WM_SIZE</code> messages...):</p>
<ul>
<li>You didn't set up your message handler properly. Perhaps you forgot the message map entry?</li>
<li>You have an existing handler in place for <code>WM_WINDOWPOSCHANGED</code> that fails to call the default window procedure, thereby preventing <code>WM_SIZE</code> messages from being sent.</li>
</ul>
|
<p>I am guessing that you are using the Multiple Document Interface ( MDI ) application type. In this case, you should capture the WM_SIZE message in each of your views - the classes you have derived from CView.</p>
| 32,780
|
<p>I have never quite understood how/why I would use Maven modules (reactor builds).</p>
<p>We have tens of libraries that we share (as dependencies) among our products, and between libraries as well. If we were to switch to making them Maven modules, how would we set it up, both in SVN and in our working copies?</p>
<p>Do Maven modules really need to be subfolders? Do they need to be subfolders in the SVN repo too?</p>
<p>Assuming you just need subfolders in the working copy, I suppose <code>svn:externals</code> would work to make, say, a "util" library be a module of multiple projects at the same time. But I've read many bad things about using <code>svn:externals</code> because there is nothing to stop you from modifying the code in the external, but its not tracked. </p>
<p>Any suggestions? Am I missing the boat on modules?</p>
|
<p>No ... a modular project should only be used when the child project is integrated into the parent to create a larger artifact, so an example might be an Enterprise project, where your modules contain the EJB (server and client), the WAR, and then those are combined into an EAR file. This modularity is only for convenience and can be skipped if preferred.</p>
<p>In the case of reusable libraries, make them independent projects and deploy them to a shared repository. Then they must be referenced as dependencies in the project using them.</p>
|
<p>No ... a modular project should only be used when the child project is integrated into the parent to create a larger artifact, so an example might be an Enterprise project, where your modules contain the EJB (server and client), the WAR, and then those are combined into an EAR file. This modularity is only for convenience and can be skipped if preferred.</p>
<p>In the case of reusable libraries, make them independent projects and deploy them to a shared repository. Then they must be referenced as dependencies in the project using them.</p>
| 20,106
|
<p>I have a system (Ubuntu) with many processes and one (or more) have a memory leak. Is there a good way to find the process that has the leak? Some of the process are JVMs, some are not. Some are home grown some are open source.</p>
|
<p>You can run the <code>top</code> command (to run non-interactively, type <code>top -b -n 1</code>). To see applications which are leaking memory, look at the following columns:</p>
<ul>
<li>RPRVT - resident private address space size</li>
<li>RSHRD - resident shared address space size</li>
<li>RSIZE - resident memory size</li>
<li>VPRVT - private address space size</li>
<li>VSIZE - total memory size</li>
</ul>
|
<p>Difficult task. I would normally suggest to grab a debugger/memory profiler like <a href="http://valgrind.org/" rel="nofollow noreferrer">Valgrind</a> and run the programs one after one in it. Soon or later you will find the program that leaks and can tell it the devloper or fix it yourself.</p>
| 17,350
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.