instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>How do I generate an ETag HTTP header for a resource file?</p>
|
<p>An etag is an arbitrary string that the server sends to the client that the client will send back to the server the next time the file is requested.</p>
<p>The etag should be computable on the server based on the file. Sort of like a checksum, but you might not want to checksum every file sending it out.</p>
<pre><code> server client
<------------- request file foo
file foo etag: "xyz" -------->
<------------- request file foo
etag: "xyz" (what the server just sent)
(the etag is the same, so the server can send a 304)
</code></pre>
<p>I built up a string in the format "datestamp-file size-file inode number". So, if a file is changed on the server after it has been served out to the client, the newly regenerated etag won't match if the client re-requests it.</p>
<pre class="lang-c prettyprint-override"><code>char *mketag(char *s, struct stat *sb)
{
sprintf(s, "%d-%d-%d", sb->st_mtime, sb->st_size, sb->st_ino);
return s;
}
</code></pre>
|
<p>I would recommend not using them and going for last-modified headers instead.</p>
<p>Askapache has a useful article on this. (as they do pretty much everything it seems!)</p>
<p><a href="http://www.askapache.com/htaccess/apache-speed-etags.html" rel="nofollow noreferrer">http://www.askapache.com/htaccess/apache-speed-etags.html</a></p>
| 2,652
|
<p>What is the average time that it would take a complete novice, whose background is mostly Windows XP, to go through the FreeBSD handbook and get sufficient mastery to setup a server from the ground up?</p>
|
<p>It's impossible to say. Not only is it highly dependent upon what sort of person you are, but it also depends on what exactly you are doing and how you define "sufficient mastery". Being able to get Apache operational is a simple matter of following step-by-step tutorials, you could do that in a matter of hours. Being able to run a multi-user server <em>competently</em> takes a hell of a lot longer, and the handbook isn't nearly enough.</p>
|
<p>Depends on your reading speed :-)
Depends on your needs (I mean: what kind of server).
Once upon a time I did this - installing a FreeBSD on x86- (although I had some Linux knowledge already at that time), and it took me 3 hours, mainly that much time, because I was working on another machine in parallel. </p>
| 14,691
|
<p>I'm currently working on a Google Maps project and am implementing a search function. In my search function I'm trying to have content on the side listing which search makers that were just added to the map correspond to each hall. However in assembling this string I run into a problem where my <code>side_bar_html</code> variable will not output if I do not alert the data first.</p>
<p>Here is my searchMap function. The variable is declared as such: <code>var side_bar_html = "";</code></p>
<pre><code>function searchMap(term, map) {
closeSearch();
searchCount = 0;
searchMarkers = [];
var request = GXmlHttp.create();
request.open("GET", "admin/search.php?s=" + term, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var xmlDoc = GXml.parse(request.responseText);
var points = xmlDoc.documentElement.getElementsByTagName("point");
var polygonsToShow = [];
for (var i = 0; i < points.length; i++) {
var lat = parseFloat(points[i].getAttribute("lat"));
var lng = parseFloat(points[i].getAttribute("lng"));
var pid = points[i].getAttribute("id");
for(var j = 0; j < polygons.length; j++) {
if(polygons[j].vt_bid == pid) {
polygonsToShow.push(j);
}
}
var point = new GLatLng(lat,lng);
var pname = points[i].getAttribute("name");
var curMarker = createSearchMarker(point, pid, pname,getLetter(i));
map.addOverlay(curMarker);
}
//olays.buildings.checked = false; : Figure out some way to uncheck the buildings overlay checkbox?
for(var k = 0; k < polygons.length; k++) {
polygons[k].hide();
}
for(var l = 0; l < polygonsToShow.length; l++){
polygons[polygonsToShow[l]].show();
}
}
}
request.send(null);
alert(side_bar_html); //side_bar_html will be empty unless I alert the variable
searchResults = new HtmlControl('<div style="background-color:white; border:solid 1px grey; padding:2ex; overflow:auto; width:125px; margin:1px; font-size:14px;"><img align="right" style="cursor: pointer;" src="http://www.thebort.com/maps/images/close.gif" onclick="closeSearch()"><strong>Search</strong><br/>' + side_bar_html + '</div>', {selectable:true});
map.addControl(searchResults, new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(20, 70)));
}
</code></pre>
<p>And the function to create a search marker:</p>
<pre><code>function createSearchMarker(point, id, pname, letIcon) {
var marker = new GMarker(point,letIcon);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml('<a href="#" onclick=\'tb_show("' + pname + '","admin/get_info.php?b=' + id + '&KeepThis=true&TB_iframe=true&height=400&width=600",false); return false;\'>' + pname + '</a>');
});
side_bar_html = side_bar_html + '<a href="javascript:clickSearch(' + searchCount + ')">' + String.fromCharCode("A".charCodeAt(0) + searchCount) + ': ' + pname + '</a><br>';
marker.vt_id = id;
searchMarkers.push(marker);
searchCount++;
return marker;
}
</code></pre>
<p>I would like to keep code exposure for this project at a minimum right now so if anything needs expounding please let me know. Thanks!</p>
|
<p>So my understanding of your problem is that <code>side_bar_html</code> is set during the <code>onreadystatechange</code> function call, but you're not seeing it being set unless you alert it.</p>
<p>Here's what's probably happening: the Ajax request takes some time to happen. When you call <code>req.send(null)</code> then that kicks off the request, but your <code>onreadystatechange</code> function won't get called until sometime later, after your web browser has made the request and gotten back a response.</p>
<p>So when you immediately try to use the <code>side_bar_html</code> value, it doesn't work because the response hasn't come back yet. However, when you alert the value, the time it takes to perform the alert gives the browser time to get a response and set the <code>side_bar_html</code> value appropriately.</p>
<p>Your underlying problem is that Ajax is asynchronous (which is there the A comes from) and you're trying to use it synchronously (meaning that you assume that things will always happen in a particular order). Your best bet is to put the code that uses <code>side_bar_html</code> in your <code>onreadystatechange</code> function, so that it doesn't get used before it's set.</p>
|
<p>add the code below to the end of your onreadystatechange function (within the if statement checking for a value of 4). e.g:</p>
<pre><code>request.onreadystatechange = function() {
if (request.readyState == 4) {
var xmlDoc = GXml.parse(request.responseText);
var points = xmlDoc.documentElement.getElementsByTagName("point");
var polygonsToShow = [];
for (var i = 0; i < points.length; i++) {
var lat = parseFloat(points[i].getAttribute("lat"));
var lng = parseFloat(points[i].getAttribute("lng"));
var pid = points[i].getAttribute("id");
for(var j = 0; j < polygons.length; j++) {
if(polygons[j].vt_bid == pid) {
polygonsToShow.push(j);
}
}
var point = new GLatLng(lat,lng);
var pname = points[i].getAttribute("name");
var curMarker = createSearchMarker(point, pid, pname,getLetter(i));
map.addOverlay(curMarker);
}
//olays.buildings.checked = false; : Figure out some way to uncheck the buildings overlay checkbox?
for(var k = 0; k < polygons.length; k++) {
polygons[k].hide();
}
for(var l = 0; l < polygonsToShow.length; l++){
polygons[polygonsToShow[l]].show();
}
searchResults = new HtmlControl('<div style="background-color:white; border:solid 1px grey; padding:2ex; overflow:auto; width:125px; margin:1px; font-size:14px;"><img align="right" style="cursor: pointer;" src="http://www.thebort.com/maps/images/close.gif" onclick="closeSearch()"><strong>Search</strong><br/>' + side_bar_html + '</div>', {selectable:true});
map.addControl(searchResults, new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(20, 70)));
}
</code></pre>
| 36,058
|
<p>I’m writing a test that expects to receive an event from an object that it is calling. Specifically, I am calling out to an object that connects to an AIX machine via SSH (using the open source Granados project), then disconnecting, and I want to make sure I receive the OnConnectionClosed event that is being raised during the disconnect. It sounds simple enough, and I’ve written many tests like this in the past, but this time some strange behavior is occurring that I believe is related to threading.</p>
<p>Basically, the object I call is raising the ‘OnConnectionClosed’ event on a different thread than what I call it from. What I’m seeing is that when I run the test by selecting ‘Debug Test’ from the UI, it passes, but if I choose ‘Run Test’, it fails (even if there are no breakpoints set during the debug run). I’ve done some Googling and found <a href="http://plainoldstan.blogspot.com/2008/09/run-unit-test-on-mta-thread-vsts-test.html" rel="nofollow noreferrer">this post</a> that seems to indicate that by default the MSTest host runs in Single Thread mode but that a config change can make it run in Multi Thread mode. This sounded like it would logically fix my problem, but of course, it did not.</p>
<p>Some other posts I’ve come across also make me think that MSTest is simply not monitoring the background threads (so the events raised by them are not being ‘heard’). This would also make sense, and since it seems to work in debug mode, and it seems like the fix above should logically solve that problem, then I’m confused as to why it’s not working. It is possible that I’m simply not correctly dealing with the threads, although I would expect that to still be a problem in debug mode if it were the case.</p>
<p>Has anyone else tried to test something in a similar way? If so, did you encounter similar problems? And if so, how did you resolve them?</p>
<p>I’ve pasted the relevant unit test code below (I’ve removed the connection info for security reasons). </p>
<pre><code>[TestClass]
public class SSHReaderTests
{
private bool received = false;
private delegate bool SimpleFunc();
[TestInitialize]
public void MyTestInitialize()
{
received = false;
}
[TestMethod]
public void Should_raise_OnReaderConnectionClosed_event_after_successful_connection_is_disconnected()
{
IReader reader = new SSHReader();
reader.OnReaderConnectionClosed += delegate
{
received = true;
};
reader.Connect("*****", "*****", "*****");
//Assert.IsTrue(reader.IsConnected);
reader.Disconnect();
//Assert.IsFalse(reader.IsConnected);
Assert.IsTrue(WaitUntilTrue(delegate {
return received; }, 30000, 1000));
}
private static bool WaitUntilTrue(SimpleFunc func, int timeoutInMillis, int timeBetweenChecksInMillis)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while(stopwatch.ElapsedMilliseconds < timeoutInMillis)
{
if (func())
return true;
Thread.Sleep(timeBetweenChecksInMillis);
}
return false;
}
}
</code></pre>
|
<p>Use the WaitHandle classes in the System.Threading namespace. Either, AutoResetEvent or ManualResetEvent. The difference between the two is that AutoResetEvent lets one thread proceed each time it is set, while ManualResetEvent releases all waiting threads on set.</p>
<p>The reason your example doesn't work has to do with compiler optimizations. The code does not actually get compiled to what you would think at first glance. Most likely, the compiler will do something like place the local variable in a register and never actually fetch it during your loop that checks. You can avoid this type of thing with the volatile keyword, but I would highly recommend reading up on threading and concurrency for more details. Joe Duffy's blog at <a href="http://www.bluebytesoftware.com" rel="nofollow noreferrer">http://www.bluebytesoftware.com</a> is a great resource to get started, and I highly recommend his Concurrency Programming on Windows book that is coming out soon.</p>
|
<p>Not exactly what you arr asking about, but you may find some workable solutions or at least ideas by checking out the MS Research project called <a href="http://research.microsoft.com/projects/CHESS" rel="nofollow noreferrer">CHESS</a>. It's for multithreaded concurrency testing in .net.</p>
| 27,037
|
<p>How do I setup TeamCity 4.0 so that I can access it over port 443 on the internet? e.g. <a href="https://teamcity.mydomain.com" rel="nofollow noreferrer">https://teamcity.mydomain.com</a></p>
<p>I am running IIS 7 on the same server that TeamCity is installed. I see two options:</p>
<ol>
<li><p>Setup TeamCity to use port 8443 and
create a reverse proxy in IIS that
routes requests to the TeamCity
public IP address to the Tomcat port
on the internal IP address.</p></li>
<li><p>Setup Tomcat to run on a different
IP address than IIS 7, and configure
TeamCity to run on port 443.</p></li>
</ol>
<p>I'm not sure on the details of either of these steps.</p>
|
<p>It requires configuring the bundled Tomcat server for https. See here:</p>
<p><a href="http://confluence.jetbrains.net/display/TCD65/Using+HTTPS+to+access+TeamCity+server" rel="noreferrer">http://confluence.jetbrains.net/display/TCD65/Using+HTTPS+to+access+TeamCity+server</a></p>
<p>and here:</p>
<p><a href="http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html" rel="noreferrer">http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html</a></p>
<p>I also setup Tomcat to listen on just one IP Address. All of this turned out to be a real pain, and I still am not able to run TeamCity as a service. I can only run it at the command line. If I were going to do this over, I would install TeamCity to run on the default port, and reverse proxy to it using <a href="http://learn.iis.net/page.aspx/489/using-the-application-request-routing-module/" rel="noreferrer">IIS7 Application Request Routing</a> or Apache Virtual Directories.</p>
<p>[Edit]
I have done this over, and I used IIS Application Request Routing to set up a reverse proxy. It works perfectly, and Team City upgrades are painless as well.</p>
|
<p>Make sure you also use load these 2 modules</p>
<pre><code>LoadModule proxy_module bin/mod_proxy.so
LoadModule proxy_http_module bin/mod_proxy_http.so
ProxyPass /TeamCity http://localhost/TeamCity
ProxyPassReverse /TeamCity http://localhost/TeamCity
</code></pre>
| 42,983
|
<p>I have HTML code like this :</p>
<pre><code><div>
<a>Link A1</a>
<a>Link A2</a>
<a>Link A3</a>
</div>
<div>
<a>Link B1</a>
<a>Link B2</a>
<a>Link B3</a>
</div>
</code></pre>
<p>When user clicks a link from above HTML, I want to get the jQuery object of the corresponding <code><a></code> element, and then manipulate its sibling. I can't think of any way other than creating an ID for each <code><a></code> element, and passing that ID to an onclick event handler. I really don't want to use IDs. </p>
<p>Any suggestions?</p>
|
<p>Fortunately, jQuery selectors allow you much more freedom:</p>
<pre><code>$("div a").click( function(event)
{
var clicked = $(this); // jQuery wrapper for clicked element
// ... click-specific code goes here ...
});
</code></pre>
<p>...will attach the specified callback to each <code><a></code> contained in a <code><div></code>.</p>
|
<p>To select the sibling, you'd need something like:</p>
<pre><code>$(this).next();
</code></pre>
<p>So, Shog9's comment is not correct. First of all, you'd need to name the variable "clicked" outside of the div click function, otherwise, it is lost after the click occurs.</p>
<pre><code>var clicked;
$("div a").click(function(){
clicked = $(this).next();
// Do what you need to do to the newly defined click here
});
// But you can also access the "clicked" element here
</code></pre>
| 47,209
|
<p>I am working through some of the exercises in The C++ Programming Language by Bjarne Stroustrup. I am confused by problem 11 at the end of Chapter 12:</p>
<blockquote>(*5) Design and implement a library for writing event-driven simulations. Hint: <task.h>. ... An object of class task should be able to save its state and to have that state restored so that it can operate as a coroutine. Specific tasks can be defined as objects of classes derived from task. The program to be executed by a task might be defined as a virtual function. ... There should be a scheduler implementing a concept of virtual time. ... The tasks will need to communicate. Design a class queue for that. ...</blockquote>
<p>I am not sure exactly what this is asking for. Is a task a separate thread? (As far as I know it is not possible to create a new thread without system calls, and since this is a book about C++ I do not believe that is the intent.) Without interrupts, how is it possible to start and stop a running function? I assume this would involve busy waiting (which is to say, continually loop and check a condition) although I cannot see how that could be applied to a function that might not terminate for some time (if it contains an infinite loop, for example).</p>
<p><strong>EDIT:</strong> Please see my post below with more information.</p>
|
<blockquote>
<p>Hint: <task.h>.</p>
</blockquote>
<p>is a reference to an old cooperative multi-tasking library that shipped with <a href="http://www.softwarepreservation.org/projects/c_plus_plus#release_e" rel="nofollow noreferrer">early versions of CFront</a> (you can also download at that page).</p>
<p>If you read the paper "<a href="http://www.softwarepreservation.org/projects/c_plus_plus/cfront/release_e/doc/ClassesForCouroutines.pdf" rel="nofollow noreferrer">A Set of C++ Classes for Co-routine Style Programming</a>" things will make a lot more sense.</p>
<hr>
<p>Adding a bit:</p>
<p>I'm not an old enough programmer to have used the task library. However, I know that C++ was designed after Stroustrup wrote a simulation in Simula that had many of the same properties as the task library, so I've always been curious about it.</p>
<p>If I were to implement the exercise from the book, I would probably do it like this (please note, I haven't tested this code or even tried to compile it):</p>
<pre><code>class Scheduler {
std::list<*ITask> tasks;
public:
void run()
{
while (1) // or at least until some message is sent to stop running
for (std::list<*ITask>::iterator itor = tasks.begin()
, std::list<*ITask>::iterator end = tasks.end()
; itor != end
; ++itor)
(*itor)->run(); // yes, two dereferences
}
void add_task(ITask* task)
{
tasks.push_back(task);
}
};
struct ITask {
virtual ~ITask() { }
virtual void run() = 0;
};
</code></pre>
<p>I know people will disagree with some of my choices. For instance, using a struct for the interface; but structs have the behavior that inheriting from them is public by default (where inheriting from classes is private by default), and I don't see any value in inheriting privately from an interface, so why not make public inheritance the default?</p>
<p>The idea is that calls to ITask::run() will block the scheduler until the task arrives at a point where it can be interrupted, at which point the task will return from the run method, and wait until the scheduler calls run again to continue. The "cooperative" in "cooperative multitasking" means "tasks say when they can be interrupted" ("coroutine" usually means "cooperative multitasking"). A simple task may only do one thing in its run() method, a more complex task may implement a state machine, and may use its run() method to figure out what state the object is currently in and make calls to other methods based on that state. The tasks <strong>must</strong> relinquish control once in a while for this to work, because that is the definition of "cooperative multitasking." It's also the reason why all modern operating systems don't use cooperative multitasking.</p>
<p>This implementation does not (1) follow fair scheduling (maybe keeping a running total of clock ticks spent in in task's run() method, and skipping tasks that have used too much time relative to the others until the other tasks "catch up"), (2) allow for tasks to be removed, or even (3) allow for the scheduler to be stopped.</p>
<p>As for communicating between tasks, you may consider looking at <a href="http://swtch.com/libtask/" rel="nofollow noreferrer">Plan 9's libtask</a> or <a href="http://herpolhode.com/rob/" rel="nofollow noreferrer">Rob Pike's newsqueak</a> for inspiration (the "UNIX implementation of Newsqueak" download includes a paper, "The Implementation of Newsqueak" that discusses message passing in an interesting virtual machine).</p>
<p>But I believe this is the basic skeleton Stroustrup had in mind.</p>
|
<p>In the paper linked to by "me.yahoo.com/..." which describes the task.h class:</p>
<ol>
<li>Tasks execute in parallel</li>
<li>A task may be suspended and resumed later</li>
</ol>
<p>The library is described as a method of multiprogramming.</p>
<p><strong>Is it possible to do this without using threads or separate processes?</strong></p>
| 48,319
|
<p>We have a number of web-apps running on IIS 6 in a cluster of machines. One of those machines is also a state server for the cluster. We do not use sticky IP's.</p>
<p>When we need to take down the state server machine this requires the entire cluster to be offline for a few minutes while it's switched from one machine to another.</p>
<p>Is there a way to switch a state server from one machine to another with zero downtime?</p>
|
<p>You could use <a href="http://msdn.microsoft.com/en-us/library/dd187409.aspx" rel="nofollow noreferrer">Velocity</a>, which is a distributed caching technology from Microsoft. You would install the cache on two or more servers. Then you would <a href="http://blogs.msdn.com/velocity/archive/2008/10/29/changes-to-session-state-provider-configuration-web-config-for-ctp2.aspx" rel="nofollow noreferrer">configure your web app</a> to store session data in the Velocity cache. If you needed to reboot one of your servers, the entire state for your cluster would still be available. </p>
|
<p>You could use the SQL server option to store state. I've used this in the past and it works well as long as the ASPState table it creates is in memory. I don't know how well it would scale as an on-disk table.</p>
<p>If SQL server is not an option for whatever reason, you could use your load balancer to create a virtual IP for your state server and point it at the new state server when you need to change. There'd be no downtime, but people who are on your site at the time would lose their session state. I don't know what you're using for load balancing, so I don't know how difficult this would be in your environment.</p>
| 9,105
|
<p>What are the alternative "design methods" to the Model View Controller? MVC seems to be popular (SO was built with it, I know that much) but is it the only method used?</p>
|
<p>There are many others:</p>
<ul>
<li><p><a href="http://en.wikipedia.org/wiki/Model_View_Presenter" rel="noreferrer">Model View Presenter (MVP)</a></p>
<ul>
<li><a href="http://www.martinfowler.com/eaaDev/SupervisingPresenter.html" rel="noreferrer">Supervising Controller</a></li>
<li><a href="http://www.martinfowler.com/eaaDev/PassiveScreen.html" rel="noreferrer">Passive View</a></li>
</ul></li>
<li><p><a href="http://www.orbifold.net/default/?p=550" rel="noreferrer">Model View ViewModel (MVVM)</a></p>
<ul>
<li>This is common in WPF applications (though <a href="http://www.codeplex.com/CompositeWPF" rel="noreferrer">Prism</a> uses the MVP pattern (usually))</li>
</ul></li>
</ul>
|
<p>We use not so much an alternative but a hybrid called <a href="https://stackoverflow.com/questions/140098/is-mvc-ars-preferable-to-classic-mvc-to-prevent-overloading">MVC-ARS</a>.</p>
| 17,156
|
<p>I know that I need to tell my UITextField to resign first responder when I want to dismis the keyboard, but I'm not sure how to know when the user has pressed the "Done" key on the keyboard. Is there a notification I can watch for?</p>
|
<p>I set the delegate of the <code>UITextField</code> to my <code>ViewController</code> class. </p>
<p>In that class I implemented this method as following:</p>
<pre><code>- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
</code></pre>
|
<pre><code>textField.returnKeyType = UIReturnKeyDone;
</code></pre>
| 34,557
|
<p>I'm new to Flex, although not new to programming. I want to write a generic event handler that will be called by all my textinput boxes when they receive focus. When they have focus, I want to change the colour of the textinput box. When they lose focus, I want to restore the "inactive" color profile. I could write an ActionScript event handler for each textinput box, but we all know that's lame. :o) What I need, then, is a way to access the object which is calling the event handler.</p>
<p>In Delphi, I'd have written a function which passes in the Sender object, allowing me to access the calling object's properties. I'm guessing ActionScript/Flex has a completely different architecture, which is why I'm having difficulty doing this.</p>
<p>Thanks in anticipation!</p>
|
<p>You should subclass TextInput and handle the focus events in there. I think this would be the simplest way to achieve what you are looking for without having any complex code.</p>
|
<p>If you want to change the look of the focused input box, you can do this by setting the <code>focusSkin</code> property. If you want this to happen globally, you can put a style declaration in your CSS file. </p>
<p>In this CSS example I'm replacing the default focusSkin (<code>mx.skins.halo.HaloFocusRect</code>) with an embedded PNG file.</p>
<pre><code>TextInput {
focusSkin: Embed(source="focus.png");
}
</code></pre>
<p>TextInput has a few properties for altering the look of the focus, like changing the opacity of the focus skin (<code>focusAlpha</code> property). Check the <a href="http://livedocs.adobe.com/flex/3/langref/mx/controls/TextInput.html" rel="nofollow noreferrer">TextInput documentation</a> for more info.</p>
| 27,248
|
<p>Is it possible to change a sql server instance name? Or is it something that can only be set during installation?</p>
|
<p>To the best of my knowledge, they can only be changed at install time. You might be able to change the name with the installer package while keeping the current info. I would make backups of all of your databases and then try this.</p>
<p>On another note, changing instance names will just cause you so many headaches. Even if you can do it, I would strongly reccomend leaving well enough alone.</p>
|
<p>You can't rename the <b>instance</b> but you can rename a server (sql2000 only) - does that help at all?</p>
<p>Have a look at:</p>
<pre><code>sp_dropserver 'oldname', 'droplogins'
</code></pre>
<p>and then;</p>
<pre><code>sp_addserver 'newname', local
</code></pre>
<p>Be aware that if there are any jobs running on that server they'll need to be renamed too;</p>
<pre><code>use msdb
go
update sysjobs set originating_server = 'newname'
</code></pre>
<p>You'll need to restart your SQL Server</p>
| 43,030
|
<p>It will be important for developers wanting to develop for the chrome browser to be able to review existing bugs (to avoid too much pulling-out of hair), and to add new ones (to improve the thing). Yet I can't seem to find the bug tracking for this project. It <em>is</em> open source, right?</p>
|
<p>Google is calling it <a href="http://code.google.com/chromium/" rel="noreferrer">Chromium</a> on Google Code</p>
<p>The <a href="http://dev.chromium.org/for-testers/bug-reporting-guidelines" rel="noreferrer">Chromium Bug Reporting Page</a> is there and has the link to submit bugs listed. (Google Account Required)</p>
<p><a href="https://accounts.google.com/ServiceLogin?service=ah&passive=true&continue=https://appengine.google.com/_ah/conflogin%3Fcontinue%3Dhttps://bugs.chromium.org/p/chromium/issues/entryafterlogin" rel="noreferrer">Here's a direct link</a> to the bug report form.</p>
|
<p>From the <a href="http://www.google.com/support/chrome/bin/answer.py?answer=95760&query=bug&topic=&type=" rel="nofollow noreferrer">Google Site</a></p>
<ol>
<li>Click the Page menu page menu.</li>
<li>Select Report a bug or broken website.</li>
<li>Choose an issue type from the drop-down menu. The web address of the webpage you're on is recorded automatically.</li>
<li>If possible, add key details in the 'Description' field, including steps to reproduce the issue you're experiencing.</li>
<li>Keep 'Send source of current page' and 'Send screenshot of current page' checkboxes selected.</li>
<li>Click the Send report button to report a Google Chrome bug.</li>
</ol>
<p>I don't see any reference to public bug tracking... </p>
| 6,194
|
<p>I'm trying to do 'Attach to Process' for debugging in Visual Studio 2008 and I can't figure out what process to attach to. Help.</p>
|
<p>Indeed it is still w3wp.exe - You'll need to check the '<strong>Show processes in all sessions</strong>' option to get it to show up though.</p>
<p>(It caught me out for a while too.)</p>
|
<p>Isn't it w3wp.exe?</p>
| 8,599
|
<p>I'm using the jQuery Form plugin to upload an image. I've assigned a fade animation to happen the <code>beforeSubmit</code> callback, but as I'm running locally, it doesn't have time to finish before the <code>success</code> function is called. </p>
<p>I am using a callback function in my <code>fade();</code> call to make sure that one fade completes, before the next one begins, but that does not seem to guarantee that the function that's calling it is finished.</p>
<p>Am I doing something wrong? Shouldn't <code>beforeSubmit</code> complete before the ajax call is submitted?</p>
<p>Here's are the two callbacks:</p>
<p>beforeSubmit:</p>
<pre><code>function prepImageArea() {
if (userImage) {
userImage.fadeOut(1500, function() {
ajaxSpinner.fadeIn(1500);
});
}
}
</code></pre>
<p>success:</p>
<pre><code>function imageUploaded(data) {
var data = evalJson(data);
userImage.attr('src', data.large_thumb);
ajaxSpinner.fadeOut(1500, function() {
userImage.fadeIn(1500);
});
}
</code></pre>
|
<p>I think you may be getting too fancy with those fade animations :)... In the beforeSubmit the fadeOut is setup but the function returns immediately causing the submit to happen. I guess the upload is happening under 3 seconds causing the new image to appear before your animations are complete.</p>
<p>So if you really really want this effect, then you will need to do the image fadeout, spinner fadein, and once that is complete triggering the upload. Something like this:</p>
<pre><code>if (userImage) {
userImage.fadeOut(1500, function() {
ajaxSpinner.fadeIn(1500, function(){
//now trigger the upload and you don't need the before submit anymore
});
});
}
else {
// trigger the upload right away
}
</code></pre>
|
<p>Even though the beforeSubmit callback is called before submitting the form, the userImage.fadeOut function is synchronous (i.e. it spawns a separate thread of execution to execute the fade animation then it continues execution) and it returns immediately. The fade animation takes 1.5 seconds to complete and as you are running on localhost the ajax response is returned faster than 1.5 seconds and thus you won't see the animation, in real world applications it mostly unlikely that ajax requests would take less than 1.5 seconds, so you are good :)</p>
| 16,570
|
<p>I need to create an object which exposes an <code>IDictionary<K,V></code> interface, but I don't want to fill in the entire interface implemntation.</p>
<p>It would be nice to have the equivalent of Java's AbstractDictionary, which leaves you very little to impelment a complete dictionary (HashMap, in Java):</p>
<ul>
<li>If you don't need to iterate the collection, you have a single method to implement (TryGetValue)</li>
<li>If you want it to be writeable, you implement another entry (Add).</li>
</ul>
|
<p><code>System.Collections.Generic</code> namespace contains three implementations of <code>IDictionary<K,V></code>: <code>Dictionary<TKey, TValue></code>, <code>SortedDictionary<TKey, TValue></code> and <code>SortedList<TKey, TValue></code>.</p>
|
<p>If I'm building my own dictionary class, I inherit from System.Collections.ObjectModel.KeyedCollection. </p>
<p>EDIT for all those who don't understand API design.</p>
<p>You should never, ever return a generic List or Dictionary from a public property or function. Insead you should return a class specially built for that purpose. This way you can add additional functionality to it later.</p>
<pre><code>Dictionay<integer, Order> Orders() {get;}
CustomerOrders Orders() {get;}
</code></pre>
<p>With the second version you can do things like add a Total property and have the user actually find it.</p>
<p>In theory you could return a subclass of Dictionary that adds the Total property, but then the user would have to A. know you are doing it, and B. include a cast to get to the property.</p>
| 44,119
|
<p>How do you define your UserControls as being in a namespace below the project namespace, ie. [RootNameSpace].[SubSectionOfProgram].Controls?</p>
<p><strong>Edit due to camainc's answer:</strong> I also have a constraint that I have to have all the code in a single project.</p>
<p><strong>Edit to finalise question:</strong> As I suspected it isn't possible to do what I required so camainc's answer is the nearest solution.</p>
|
<p>I'm not sure if this is what you are asking, but this is how we do it.</p>
<p>We namespace all of our projects in a consistent manner, user controls are no different. We also namespace using the project settings window, although you could do it through a combination of the project window and in code.</p>
<p>Each solution gets a namespace like this:</p>
<pre><code>[CompanyName].[SolutionName].[ProjectName]
</code></pre>
<p>So, our user controls are normally in a project called "Controls," which would have a namespace of:</p>
<pre><code>OurCompany.ThisSolution.Controls
</code></pre>
<p>If we have controls that might span several different solutions, we just namespace it like so:</p>
<pre><code>OurCompany.Common.Controls
</code></pre>
<p>Then, in our code we will import the library, or add the project to the solution.</p>
<pre><code>Imports OurCompany
Imports OurCompany.Common
Imports OurCompany.Common.Controls
</code></pre>
<p>We also name the folders where the projects live the same as the namespace, down to but not including the company name (all solutions are assumed to be in the company namespace):</p>
<p>\Projects<br>
\Projects\MySolution<br>
\Projects\MySolution\Controls</p>
<p>-- or --</p>
<p>\Projects\<br>
\Projects\Common<br>
\Projects\Common\Assemblies<br>
\Projects\Common\Controls</p>
<p>etc.</p>
<p>Hope that helps...</p>
|
<p>Do you mean you want to be able to access user controls at runtime (in code) via </p>
<blockquote>
<p><code>[ProjectNamespace].[YourSpecialNamespace].Controls</code></p>
</blockquote>
<p>rather than the default of </p>
<blockquote>
<p><code>[ProjectNamespace].Controls</code></p>
</blockquote>
<p>? Because I don't believe that is possible. If I'm not mistaken, the <code>Controls</code> collection of your project/app is built-in by the framework - you can't change it. You can, as camainc noted, use the project settings window (or code) to place the controls themselves in a specific namespace thusly:</p>
<blockquote>
<p><code>Namespace [YourSpecialNamespace]</code></p>
<p><code>Public Class Form1</code></p>
<p><code>[...]</code></p>
<p><code>End Class</code></p>
<p><code>End Namespace</code></p>
</blockquote>
<p>Of course, thinking about it some more, I suppose you could design and build your own <code>Controls</code> collection in your namespace - perhaps as a wrapper for the built-in one... </p>
| 8,808
|
<p>I have an AdvancedDataGrid that uses customer grouping of data. Not all of the groups will be at the same level in the hierarchy, and groups can contain both groups and members. We have a sort callback, but it's not being called except for groups at the leaf-most levels. See code below for an example -- expand all of the groups, then click the sort column on "date of birth" to get a reverse sort by date of birth. (Oddly, for some unfathomable reason, the first ascending sort works.)</p>
<p>We're not getting called for any of the data that's grouped at the same level as a group member.</p>
<p>How do I fix this?</p>
<p>Thanks.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white" >
<mx:Script>
<![CDATA[
import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;
import mx.collections.HierarchicalData;
import mx.utils.ObjectUtil;
private var arrData : Array = [
{ name: "User A", dob: "04/14/1980" },
{ name: "User B", dob: "01/02/1975" },
{ name: "Group A", children: [
{ name: "User E", dob: "09/13/1972" },
{ name: "User F", dob: "11/22/1993" }
]
},
{ name: "Group B", children: [
{ name: "Group B1", children: [
{ name: "User I", dob: "01/23/1984" },
{ name: "User J", dob: "11/10/1948" }
]
},
{ name: "User G", dob: "04/09/1989" },
{ name: "User H", dob: "06/20/1963" }
]
},
{ name: "User C", dob: "12/30/1977" },
{ name: "User D", dob: "10/27/1968" }
];
private function date_sortCompareFunc(itemA:Object, itemB:Object):int
{
if ( itemA.hasOwnProperty("dob") && itemB.hasOwnProperty("dob"))
{
var dateA:Date = new Date(Date.parse(itemA.dob));
var dateB:Date = new Date(Date.parse(itemB.dob));
return ObjectUtil.dateCompare(dateA, dateB);
}
else if ( itemA.hasOwnProperty("dob"))
{
return 1;
}
else if (itemB.hasOwnProperty("dob"))
{
return -1;
}
return ObjectUtil.stringCompare(itemA.name, itemB.name);
}
private function date_dataTipFunc(item:Object):String
{
if (item.hasOwnProperty("dob"))
{
return dateFormatter.format(item.dob);
}
return "";
}
private function label_dob(item:Object, col:AdvancedDataGridColumn):String
{
var dob:String="";
if(item.hasOwnProperty("dob"))
{
dob=item.dob;
}
return dob;
}
]]>
</mx:Script>
<mx:DateFormatter id="dateFormatter" formatString="MMMM D, YYYY" />
<mx:AdvancedDataGrid id="adgTest" dataProvider="{new HierarchicalData(this.arrData)}" designViewDataType="tree" width="746" height="400">
<mx:columns>
<mx:AdvancedDataGridColumn headerText="Name" dataField="name"/>
<mx:AdvancedDataGridColumn dataField="dob" headerText="Date of birth"
labelFunction="label_dob"
sortCompareFunction="date_sortCompareFunc"
showDataTips="true"
dataTipFunction="date_dataTipFunc" />
</mx:columns>
</mx:AdvancedDataGrid>
</mx:Application>
</code></pre>
|
<p>It seems as if the first row contains null data or an empty string, and the advanceddatagrid is set to use grouped data, then the sort function doesn't get called.</p>
<p>it's a bit of a hack, yes, but if you can put in an unrealistic (say 1/1/1770), constant piece of data that you could insert at the database/file read/data input level then use the column labelFunction to render as null if the data matches that column, it should work, or at least the sort function will get called.</p>
<pre><code> public function dateCellLabel(item:Object, column:AdvancedDataGridColumn):String
{
var date:String = item[column.dataField];
if (date=="1/1/1770")
return null;
else
return date;
}
</code></pre>
<p>Sorry about answering this so late, but at least if somebody else tries to find the answer, they might see this.</p>
|
<p>This has something to do with the logic of the SortCompareFunction.</p>
<p>Put <code>dob:"01/01/1970"</code> for all the group nodes and the sort works as expected, is that correct?</p>
| 18,776
|
<p>I am looking for a good, free (preferred) screen sharing program that works well for pair programming and code review sessions for Windows (Vista x64, Server 2008). It should allow either person take control of the screen and be fairly responsive for text editing over decent broadband connections. Additional features like the ability to draw/mark/annotate the other persons screen would be nice.</p>
<p>Edit: This will be used by developers in remote locations.</p>
|
<p><a href="http://connect.microsoft.com/site/sitehome.aspx?SiteID=94" rel="nofollow noreferrer">Windows Shared View</a> works for me. It allows you to only share certain windows and even shows where your "attendees" mouse is. It would be best to use that in connection with some sort of voip connection so that you don't have to type questions/responses back and forth.</p>
|
<p>Would a VNC client not do the trick, combined with a one of those screen overlay apps people use for presentations (screenpen rings a bell)?</p>
| 37,009
|
<p>I'm looking for a table or list of standard time estimations for developments in ABAP, something customizable in some variables according to the development team, complexity of project, etc...</p>
<p>Something similar to:</p>
<pre><code>Simple Module Pool -> 10 hours
Complex Module Pool -> 30 hours
Definition of Dictionary -> (0,4 * number_of_tables * average_fields ) hours
ALV Report -> (2 * number_of_parameters) hours
</code></pre>
<p>I've searched but haven't found anything yet. I found AboveSoft Adaptive Estimator, what looks like a software tool to do what I need, but I prefer something... manual, an official or standard table.</p>
<p>Do you know anything like that?</p>
<p>Thank you in advance.</p>
<p>Updated, as requested in comments by Rob S., to provide more information for future similar questions:</p>
<p>What I'm looking for is a bunch of formulas, any metric system that can be applicable to (or even created for) time estimations on SAP development.</p>
<p>I'm looking for a technic/tool/method to estimate SAP work, duration, cost, something similar to COCOMO II, FP, ESTIMACS or SLIM for SAP development.</p>
|
<p>If I am reading this right, you are looking for a something to estimate how long it would take someone to program an application. I would doubt an official table actually exists. </p>
<p>Development time is highly variable. Programmer experience, complexity of requirements, clarity of requirements, and dozens of other factors affect how much time development takes. So even if an official table exists, it may not be accurate. </p>
|
<p>Let me guess... you're a project manager?</p>
<p>There is no "one way" in programming, especially not in the highly specialized world of ABAP.</p>
| 36,022
|
<p>I need to run a Java application, which we are trying to port to Java 6, on an NT box.</p>
<p>I manage to run java 5 on it (although not officially supported), but when I try to run java 6 I get the following error:</p>
<pre><code>Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\Program Files\Java\jre1.6.0_05\bin\awt.dll: The specified procedure could not be found
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(Unknown Source)
at java.lang.ClassLoader.loadLibrary(Unknown Source)
at java.lang.Runtime.loadLibrary0(Unknown Source)
at java.lang.System.loadLibrary(Unknown Source)
at sun.security.action.LoadLibraryAction.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.awt.NativeLibLoader.loadLibraries(Unknown Source)
at sun.awt.DebugHelper.<clinit>(Unknown Source)
at java.awt.EventQueue.<clinit>(Unknown Source)
at javax.swing.SwingUtilities.invokeLater(Unknown Source)
at ui.sequencer.test.WindowTest.main(WindowTest.java:136)
</code></pre>
<p>Anybody has any idea how to solve this?</p>
<p>This persists even when I move the java executables to another directory with no spaces in its name.</p>
<p>p.s.
I know, I should upgrade, but it's not up to me or my company - this is a very very bug huge gigantic company we work with, and they intend to keep NT for another 5 years.</p>
|
<p>OK, Thanks for all the viewers and to @Roel Spiker and @Partyzant for their answers.</p>
<p><strong>It can't be done.</strong> Not unless you install windows2000 on the NT box. This is because awt.dll fr J6SE uses new methods in User32.dll, which is part of the windows OS (linked to kernel.dll et al). Use the dll dependency walker and see for yourself.
Another possible solution is to alter OpenJDK slightly to use other methods available in windows NT.</p>
|
<p>Java SE 6 <a href="http://java.sun.com/javase/6/webnotes/install/system-configurations.html" rel="nofollow noreferrer">requires</a> at least Windows 2000.</p>
| 18,397
|
<p>Is there any way that my script can retrieve metadata values that are declared in its own header? I don't see anything promising in the API, except perhaps <code>GM_getValue()</code>. That would of course involve a special name syntax. I have tried, for example: <code>GM_getValue("@name")</code>.</p>
<p>The motivation here is to avoid redundant specification.</p>
<p>If GM metadata is not directly accessible, perhaps there's a way to read the body of the script itself. It's certainly in memory somewhere, and it wouldn't be too awfully hard to parse for <code>"// @"</code>. (That may be necessary in my case any way, since the value I'm really interested in is <code>@version</code>, which is an extended value read by <a href="http://userscripts.org/" rel="noreferrer">userscripts.org</a>.)</p>
|
<p><strong>This answer is out of date :</strong> As of Greasemonkey 0.9.16 (Feb 2012) please see <a href="https://stackoverflow.com/a/10475344/1820">Brock's answer</a> regarding <code>GM_info</code></p>
<hr>
<p>Yes. A very simple example is:</p>
<pre><code>var metadata=<>
// ==UserScript==
// @name Reading metadata
// @namespace http://www.afunamatata.com/greasemonkey/
// @description Read in metadata from the header
// @version 0.9
// @include https://stackoverflow.com/questions/104568/accessing-greasemonkey-metadata-from-within-your-script
// ==/UserScript==
</>.toString();
GM_log(metadata);
</code></pre>
<p>See <a href="http://groups.google.com/group/greasemonkey-users/browse_thread/thread/2003daba08cc14b6/62a635f278d8f9fc" rel="nofollow noreferrer">this thread on the greasemonkey-users group</a> for more information. A more robust implementation can be found near the end.</p>
|
<p>Building on Athena's answer, here is my generalized solution that yields an object of name/value pairs, each representing a metadata property. Note that certain properties can have multiple values, (@include, @exclude, @require, @resource), therefore my parser captures those as Arrays - or in the case of @resource, as a subordinate Object of name/value pairs.</p>
<pre>
var scriptMetadata = parseMetadata(.toString());
function parseMetadata(headerBlock)
{
// split up the lines, omitting those not containing "// @"
function isAGmParm(element) { return /\/\/ @/.test(element); }
var lines = headerBlock.split(/[\r\n]+/).filter(isAGmParm);
// initialize the result object with empty arrays for the enumerated properties
var metadata = { include: [], exclude: [], require: [], resource: {} };
for each (var line in lines)
{
[line, name, value] = line.match(/\/\/ @(\S+)\s*(.*)/);
if (metadata[name] instanceof Array)
metadata[name].push(value);
else if (metadata[name] instanceof Object) {
[rName, rValue] = value.split(/\s+/); // each resource is named
metadata[name][rName] = rValue;
}
else
metadata[name] = value;
}
return metadata;
}
// example usage
GM_log("version: " + scriptMetadata["version"]);
GM_log("res1: " + scriptMetadata["resource"]["res1"]);
</pre>
<p>This is working nicely in my scripts.</p>
<p>EDIT: Added @resource and @require, which were introduced in Greasemonkey 0.8.0.</p>
<p>EDIT: FF5+ compatibility, Array.filter() no longer accepts a regular expression</p>
| 13,016
|
<p>Most of my experience is on the MSFT stack, but I am now working on a side project, helping someone with a personal site with cheap hosting that is built on the LAMP stack. My options for installing extras are limited, so I'm wondering about how to write my data access code without embedding raw queries in the .php files.</p>
<p>I like to keep things simple, even with .NET. I generally write stored procedures for everything, and I have a helper class that wraps all calls to execute procedures and return data sets. I'm not looking for a full-blown ORM, but it might be the way to go and others who view this question might be looking for that. </p>
<p>Remember that I'm on a $7/month GoDaddy account, so I'm limited to what's already installed in their basic package.</p>
<p><strong>Edit:</strong> Thanks rix0rr, Alan, Anders, dragon, I will check all of those out. I edited the question to be more open to ORM solutions, since they are so popular.</p>
|
<p>Take a look at the <a href="http://framework.zend.com" rel="nofollow noreferrer">Zend Framework</a>, specifically Zend_Db. It has a Database Abstraction layer that doesn't require anything other than the MySQLi extension to be installed and isn't a full-blown ORM model.</p>
|
<p>I would try a framework. <em>Zend Framework</em> has been cited. <a href="http://www.symfony-project.org/" rel="nofollow noreferrer">Symfony</a> seems interesting. It's based on ideas from <em>Ruby on Rails</em>.</p>
| 4,226
|
<p>I have a problem applying the <code>DebuggerDisplay</code> attribute on a generic class:</p>
<pre><code>[DebuggerDisplay("--foo--")]
class Foo
{
}
[DebuggerDisplay("Bar: {t}")]
class Bar<T>
{
public T t;
}
</code></pre>
<p>When inspecting an object of type <code>Bar<Foo></code> I would expect it to show as <code>Bar: --foo--</code>, but I get <code>Bar: {Foo}</code></p>
<p>What am I doing wrong?</p>
|
<p>The DebuggerDisplay attribute is not recursive. The {} inside the string essentially say evaluate this expression and display the result inline. The string for the inner result is calculated as if there was no DebuggerDisplay attribute in play for type or member. That is why you see {Foo} instead of --foo--. </p>
<p>The reason for this is reliability. It is far too easy to have mutually recursive DebuggerDisplay attribute tags. This would cause a stack overflow or infinite loop to occur when evaluating an inner expression. Not recursively evaluating the DebuggerDisplay attribute prevents this infinite recursion (although it's still quite possible for the user to create it themselves inside a particular expression). </p>
<p>One way you can control the way the inner expression is displayed is by overriding the .ToString() method. This will be evaluated when computing the display string for an inner expression.</p>
|
<p><em>[Disclaimer: I'm affiliated with OzCode]</em></p>
<p>You can use OzCode's Reveal feature which supports nested/recursive debug information.
<a href="https://i.stack.imgur.com/hWlRv.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hWlRv.gif" alt="enter image description here"></a><br>
Once you define it for an instance it would be used automatically for all instances of that type.</p>
| 32,332
|
<p>I need to use C++ to read in text with spaces, followed by a numeric value.</p>
<p>For example, data that looks like:</p>
<pre><code>text1
1.0
text two
2.1
text2 again
3.1
</code></pre>
<p>can't be read in with 2 <code>"infile >>"</code> statements. I'm not having any luck with <code>getline</code>
either. I ultimately want to populate a <code>struct</code> with these 2 data elements. Any ideas?</p>
|
<p>The standard IO library isn't going to do this for you alone, you need some sort of simple parsing of the data to determine where the text ends and the numeric value begins. If you can make some simplifying assumptions (like saying there is exactly one text/number pair per line, and minimal error recovery) it wouldn't be too bad to getline() the whole thing into a string and then scan it by hand. Otherwise, you're probably better off using a regular expression or parsing library to handle this, rather than reinventing the wheel.</p>
|
<p>If you can be sure that your input is well-formed, you can try something like this sample:</p>
<pre><code>#include <iostream>
#include <sstream>
int main()
{
std::istringstream iss("text1 1.0 text two 2.1 text2 again 3.1");
for ( ;; )
{
double x;
if ( iss >> x )
{
std::cout << x << std::endl;
}
else
{
iss.clear();
std::string junk;
if ( !(iss >> junk) )
break;
}
}
}
</code></pre>
<p>If you do have to validate input (instead of just trying to parse anything looking like a double from it), you'll have to write some kind of parser, which is not hard but boring.</p>
| 38,888
|
<p>Basically I'm trying to accomplish the same thing that "mailto:bgates@microsoft.com" does in Internet Explorer Mobile.</p>
<p>But I want to be able to do it from a managed Windows Mobile application. I don't want to send an email pro grammatically in the background.</p>
<p>I want to be able to create the email in Pocket Outlook and then let the user do the rest.</p>
<p>Hopefully that helps you hopefully help me!</p>
|
<p>I assume you use C#. You add a reference to System.Diagnostics and then write the following code:</p>
<pre><code>ProcessStartInfo psi =
new ProcessStartInfo("mailto:bla@bla.com?subject=MySubject", "");
Process.Start(psi);
</code></pre>
<p>This will start the default email client on your mobile device.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/aa767737(VS.85).aspx" rel="nofollow noreferrer">mailto protocol definition</a> might come handy too.</p>
|
<p>You can also use Microsoft.WindowsMobile.PocketOutlook.MessagingApplication.DisplayComposeForm like so:</p>
<pre><code>OutlookSession sess = new OutlookSession();
EmailAccountCollection accounts = sess.EmailAccounts;
//Contains all accounts on the device
//I'll just choose the first one -- you might want to ask them
MessagingApplication.DisplayComposeForm(accounts[0],
"someone@somewhere.com", "The Subject", "The Body");
</code></pre>
<p>The DisplayComposeForm method has a lot of overloads with options for attachments and more.</p>
| 20,992
|
<p>I recently inherited a database on which one of the tables has the primary key composed of encoded values (Part1*1000 + Part2).<br>
I normalized that column, but I cannot change the old values.
So now I have</p>
<pre><code>select ID from table order by ID
ID
100001
100002
101001
...
</code></pre>
<p>I want to find the "holes" in the table (more precisely, the first "hole" after 100000) for new rows.<br>
I'm using the following select, but is there a better way to do that?</p>
<pre><code>select /* top 1 */ ID+1 as newID from table
where ID > 100000 and
ID + 1 not in (select ID from table)
order by ID
newID
100003
101029
...
</code></pre>
<p>The database is Microsoft SQL Server 2000. I'm ok with using SQL extensions.</p>
|
<pre><code>select ID +1 From Table t1
where not exists (select * from Table t2 where t1.id +1 = t2.id);
</code></pre>
<p>not sure if this version would be faster than the one you mentioned originally.</p>
|
<p>This will give you the complete picture, where <strong>'Bottom'</strong> stands for <strong>gap start</strong> and <strong>'Top'</strong> stands for <strong>gap end</strong>:</p>
<pre><code> select *
from
(
(select <COL>+1 as id, 'Bottom' AS 'Pos' from <TABLENAME> /*where <CONDITION*/>
except
select <COL>, 'Bottom' AS 'Pos' from <TABLENAME> /*where <CONDITION>*/)
union
(select <COL>-1 as id, 'Top' AS 'Pos' from <TABLENAME> /*where <CONDITION>*/
except
select <COL>, 'Top' AS 'Pos' from <TABLENAME> /*where <CONDITION>*/)
) t
order by t.id, t.Pos
</code></pre>
<p><strong>Note: First</strong> and <strong>Last</strong> results are <strong><em>WRONG</em></strong> and should not be regarded, but taking them out would make this query a lot more complicated, so this will do for now.</p>
| 21,037
|
<p>I have a real question.</p>
<p>I have a database with the schema as follows:</p>
<p><strong>item</strong></p>
<ul>
<li>id </li>
<li>description</li>
<li>other junk</li>
</ul>
<p><strong>tag</strong></p>
<ul>
<li>id</li>
<li>name</li>
</ul>
<p><strong>item2tag</strong></p>
<ul>
<li>item_id</li>
<li>tag_id</li>
<li>count</li>
</ul>
<p>Basically, each item is tagged as up to 10 things, with varying counts. There are 50,000 items and 50,000 tags, and about 500,000 entries in items2tag. I'd like to find, given one item, the "most similar" item.</p>
<p>By "most similar" I mean the item that has the most similar combination of tags... if something is "cool" twice as much as it is "funny," I want to find all other things that are almost "cool" twice as much as they are "funny." Of course, this should apply to 10 tags, not just 2.</p>
<p>Any ideas?</p>
|
<p>Well, you can look at linear algebra to give a n dimensional vector to each item, and then compute the distance between items to find the closest items, but that's pretty complex with even small data sets.</p>
<p>Which is why Google came up with Map Reduce. This will probably be your best bet, but even then it's non-trivial.</p>
<p>-Adam</p>
|
<p>Given your representation of item-tag relationship as vectors,
What you have is an instance of <a href="http://en.wikipedia.org/wiki/Nearest_neighbor_search" rel="nofollow noreferrer">nearest-neighbor search</a>.
You may find pointers in the field of <a href="http://en.wikipedia.org/wiki/Collaborative_filtering" rel="nofollow noreferrer">Collaborative Filtering</a>.</p>
| 40,881
|
<p>I have this CTC i3 printer; when I print square test prints, as it moves along the Y-axis back to zero (front). It extrudes lines but very thin or none at all.</p>
<p>But opposite direction along the Y axis is 100 % </p>
<p><img src="https://i.stack.imgur.com/BChHj.jpg" alt="enter image description here"></p>
<p><img src="https://i.stack.imgur.com/PvPDT.jpg" alt="enter image description here"></p>
|
<p>Without images of the problem it is difficult to diagnose, but, the described symptoms sounds as if the nozzle is too close to the bed. If the nozzle is too close to the bed, and the extruder not strong enough, the filament flow is very limited due to pressure caused by a very small opening between the nozzle and the bed. Skipping of the extruder may wear out (grind) the filament and stop extrusion altogether.</p>
<p>Re-level the bed with a (thicker) piece of paper or with a feeler gauge. Alternatively, increase the height of the nozzle by re-defining the height or add an extra Z raise in the slicer (see question: "<a href="https://3dprinting.stackexchange.com/questions/13330/how-can-i-add-an-offset-to-the-first-layer-to-increase-clearance/13334">How can I add an offset to the first layer to increase clearance?</a>").</p>
|
<p>Clearly you're having an extrusion problem. Extrusion problems usually come either from a clogged nozzle (as @Adam S. said) or from the extruder it self. To determine where the problem is located I would first do a flow rate test using <a href="https://www.youtube.com/watch?v=lWBkPIXTOlo&feature=emb_logo" rel="nofollow noreferrer">this</a>. When doing this test you can determine if the extruder is grinding the filament or if it's not grabbing it too much. After the calibration of the flowrate you can be certain that the printer is (by .gcode) pushing the correct amount of filament. If the problem persist I would first do an unclogging (since it's cheaper than the following option) using something like <a href="https://www.youtube.com/watch?v=XR7tUVLku14" rel="nofollow noreferrer">this</a>. </p>
<p>If both previous options do not solve the problem, I would highly recommend you to by a mk-8 like metal extruder. After a while, the plastic one that comes with the printer loses force and you'll lose steps. Personally, I had a similar problem where the first layer was printed in a droplet pattern and was solved by changing the extruder to a metal one.</p>
<p>Try these options and if the problem persist you could upload some pictures of the first layer or a video. Other possibilities I think of are that the filament is having trouble passing through the Bowden tube or maybe you'll have to reasemble the hotend.</p>
| 1,661
|
<p>As as part of my daily routine, I have the misfortune of administering an ancient, once "just internal" JSP web application that relies on the following authentication schema:</p>
<pre><code>...
// Validate the user name and password.
if ((user != null) && (password != null) && (
(user.equals("brianmay") && password.equals("queen")) ||
(user.equals("rogertaylor") && password.equals("queen")) ||
(user.equals("freddiemercury") && password.equals("queen")) ||
(user.equals("johndeacon") && password.equals("queen"))
)) {
// Store the user name as a session variable.
session.putValue("user", user);
...
</code></pre>
<p>As much as I would like to, the Queen members have never been users of the system but anyway it does make a great example, does it not?</p>
<p>Despite that by policy this client enforces security by domain authentication among other things, therefore this issue isn't seen as a security risk, still, my idea is to at least obfuscate that plain text credentials using perhaps a simple MD5 or SHA1 method, so such sensitive data is not visible to the naked eye.</p>
<p>I'm a total newbie when it comes to JSP so I would really appreciate any piece of advice you'd be willing to share with me.</p>
<p>Thanks much in advance!</p>
|
<p>It is hard to understand the exact scheme you are thinking about but I assume the password is coming in from a request and you want to calculate the MD5 hash in a JSP that the request is being sent to. After that you can compare it to the pre-computed MD5 version. You could even be more secure if it isn't being done with https and use a <a href="http://pajhome.org.uk/crypt/md5/" rel="nofollow noreferrer">javascript MD5 library</a> to hash the password before submitting it.</p>
<p>You can MD5 a string in java like this:</p>
<pre><code>try
{
String digestInput = "queen";
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(digestInput.getBytes());
BASE64Encoder base64Encoder = new BASE64Encoder();
String digestString = base64Encoder.encode(messageDigest.digest());
// digestString now contains the md5 hashed password
}
catch (Exception e)
{
// do some type of logging here
}
</code></pre>
|
<p>First of all you should move that logic from jsp to a separate class.</p>
<p>Second, you shouldn't keep plain text password anywhere in the code. Use some kind of one way hash function (md5, sha1, ...) and keep only password hashes.</p>
<p>When checking for user password, first hash it and then compare hashes.</p>
| 39,757
|
<p>Is there a better way to profile code then:</p>
<pre><code>$start1 = microtime(TRUE);
for($i=0;$i<count($array);$i++)
{
//do something
}
$time1 = microtime(TRUE) - $start1;
</code></pre>
|
<p>Xdebug or Zend Debugger if you have some difficulty to install Xdebug.</p>
<p>Their profiler will time everything for you without any modification of your code.</p>
<p><a href="http://www.xdebug.org/" rel="nofollow noreferrer">http://www.xdebug.org/</a></p>
<p><a href="http://www.zend.com/en/community/pdt" rel="nofollow noreferrer">http://www.zend.com/en/community/pdt</a></p>
<p><a href="http://devzone.zend.com/article/2899-Profiling-PHP-Applications-With-xdebug" rel="nofollow noreferrer">http://devzone.zend.com/article/2899-Profiling-PHP-Applications-With-xdebug</a> - a serie of tutorials about xdebug.</p>
|
<p>Without using an external tool, I would say you've done the best you can.</p>
<p>If you want to use a tool built for the purpose, the other answers are dead-on.</p>
| 22,570
|
<p>In the Linux kernel, given the <code>task_struct</code>'s <code>mm</code> I can access the process's list of <code>vm_area_struct</code>s. Given these <code>vm_area_struct</code>s, how do I get the <code>struct page</code>s which actually correspond to this vma? </p>
<p>I tried looking for functions in mm/memory.c and the like, but I was at a loss.</p>
<p>Edit: the idea is to find which pages in the vma are currently in memory and which are not. But I <strong>don't</strong> want someone telling me how to do this bit, as that's a small part of a homework assignment that I need to figure out on my own. But I can't seem to figure out how to find the pages that correspond to this vma. If I can find the pages, I figure I can check to see if they have a valid pfn or not.</p>
|
<p>From your comment to another answer (edit: the other answer seems to have been deleted), it seems you want to read from user space. The function to get the user space pages would be <a href="http://lwn.net/Articles/28548/" rel="nofollow noreferrer"><code>get_user_pages()</code></a>, but that is most probably not what you want; you probably want <code>copy_from_user</code>/<code>copy_to_user</code>.</p>
|
<p>I don't have the direct answer off-hand, but it won't take you long to navigate the structures by using lxr.linux.no</p>
<p>Given you already have the struct you want to start from, take a look from <a href="http://lxr.linux.no/linux+v2.6.29/+code=vm_area_struct" rel="nofollow noreferrer">http://lxr.linux.no/linux+v2.6.29/+code=vm_area_struct</a>. You can look for definitions, see where a single struct is used, etc... If you already know the final struct name you are looking for, you can go in reverse and navigate up until you reach the mm. </p>
<p>Note that if your net connection is not so good, you may want to install a local copy of the indexed source by getting the lxr packages of your distro and generating the index locally. It used to take 2 hours on a 400mhz / 128mb machine, nowadays it should go much much much faster.</p>
| 38,409
|
<p>I am building a project using Visual Studio. The project has a dependency on a lib file generated by another project. This project is there is the parent directory of the actual project I am building. </p>
<p>To be more clear,
I have a "ParentDir" which has two subDirectories Project1 and Project2 under it.
Now Project1 depends on lib generated by Project2.</p>
<p>In the properties of Project1, I am trying to give a relative path using
$(SolutionDir)/../ParentDir/Project2/Debug
But this does not seem to work.</p>
<p>Can you tell me where i am going wrong, or suggest the correct way of achieving this.</p>
|
<p>Add the dependant project to your solution and set it as a dependency of the other project using project properties. Then it just magically works ;).</p>
<p>A solution is just a file that describes a set of related (interconnected) projects and the relation between them, so this is the correct way of doing it.</p>
|
<p>I think Visual Studio does not expand the relative path properly when the ".." is placed somewhere in the middle of the path string. It only knows how to expand ..{sub-path}.</p>
| 16,086
|
<p>I created a NamedTemporaryFile, added some content in it and now I want to save it into a model FileField. </p>
<p>The problem is that I get a SuspiciousOperation because the tmp directory is not within the FileSystemStorage directory.</p>
<p>What's the proper way to do this?</p>
|
<p>You want django to check it for you because it ensures file is put inside MEDIA_ROOT dir so it's accessible for download.</p>
<p>In any case you want to put files outside MEDIA_ROOT (in this case '/tmp') you should do something like this:</p>
<pre><code>from django.core.files.storage import FileSystemStorage
fs = FileSystemStorage(location='/tmp')
class YourModel(models.Model):
...
file_field = models.FileField(..., storage=fs)
</code></pre>
<p>see <a href="http://docs.djangoproject.com/en/dev/topics/files/#the-built-in-filesystem-storage-class" rel="nofollow noreferrer">Django documentation</a></p>
|
<p>I ended up doing the oposite way romke explains: I'm creating the temporary file in the MEDIA_ROOT.</p>
<p>Another solution could be working with the file in /tmp and then moving it to MEDIA_ROOT.</p>
<p>My initial confusion comes from the way forms are working with uploaded files: they are located in the /tmp directory (or in memory) and then moved automatically to the upload_to directory. I was looking for a generic way of doing it in Django.</p>
| 49,638
|
<p>We all know that premature optimization is the root of all evil because it leads to unreadable/unmaintainable code. Even worse is pessimization, when someone implements an "optimization" because they <em>think</em> it will be faster, but it ends up being slower, as well as being buggy, unmaintainable, etc. What is the most ridiculous example of this that you've seen?</p>
|
<p>I think the phrase "premature optimization is the root of all evil" is way, way over used. For many projects, it has become an excuse not to take performance into account until late in a project. </p>
<p>This phrase is often a crutch for people to avoid work. I see this phrase used when people should really say "Gee, we really didn't think of that up front and don't have time to deal with it now". </p>
<p>I've seen many more "ridiculous" examples of dumb performance problems than examples of problems introduced due to "pessimization"</p>
<ul>
<li>Reading the same registry key thousands (or 10's of thousands) of times during program launch.</li>
<li>Loading the same DLL hundreds or thousands of times</li>
<li>Wasting mega bytes of memory by keeping full paths to files needlessly</li>
<li>Not organizing data structures so they take up way more memory than they need</li>
<li>Sizing all strings that store file names or paths to MAX_PATH</li>
<li>Gratuitous polling for thing that have events, callbacks or other notification mechanisms</li>
</ul>
<p>What I think is a better statement is this: "optimization without measuring and understanding isn't optimization at all - its just random change". </p>
<p>Good Performance work is time consuming - often more so that the development of the feature or component itself. </p>
|
<p>Any significant optimization effort that isn't based on triaged reports from a profiler tool earns a big WTF from me.</p>
| 40,206
|
<p>I see many different Java terms floating around. I need to install the JDK 1.6. It was my understanding that Java 6 == Java 1.6. However, when I install Java SE 6, I get a JVM that reports as version 11.0! Who can solve the madness?</p>
|
<ul>
<li>JDK - Java Development Kit</li>
<li>JRE - Java Runtime Environment</li>
<li>Java SE - Java Standard Edition</li>
</ul>
<p>SE defines a set of capabilities and functionalities; there are more complex editions (Enterprise Edition – EE) and simpler ones (Micro Edition – ME – for mobile environments).</p>
<p>The JDK includes the compiler and other tools needed to develop Java applications; JRE does not. So, to run a Java application someone else provides, you need JRE; to develop a Java application, you need JDK.</p>
<p><em>Edited</em>:
As Chris Marasti-Georg pointed out in a comment, you can find out lots of information at Sun's <a href="http://java.sun.com/" rel="noreferrer">Java</a> web site, and in particular from the <a href="http://java.sun.com/javase/downloads/index.jsp" rel="noreferrer">Java SE</a> section, (2nd option, Java SE Development Kit (JDK) 6 Update 10).</p>
<hr>
<p><em>Edited 2011-04-06:</em>
The world turns, and Java is now managed by Oracle, which bought Sun. Later this year, the <code>sun.com</code> domain is supposed to go dark. The new page (based on a redirect) is this <a href="http://www.oracle.com/technetwork/java/index.html" rel="noreferrer">Java</a> page at the Oracle Tech Network. (See also <a href="http://java.com/" rel="noreferrer">java.com</a>.)</p>
<hr>
<p><em>Edited 2013-01-11:</em> And the world keeps on turning (2012-12-21 notwithstanding), and lo and behold, JRE 6 is about to reach its end of support. <a href="http://www.oracle.com/technetwork/java/eol-135779.html" rel="noreferrer">Oracle</a> says no more public updates to Java 6 after February 2013.</p>
<p>Within a given version of Java, this answer remains valid. JDK is the Java Development Kit, JRE is the Java Runtime Environment, Java SE is the standard edition, and so on. But the version 6 (1.6) is becoming antiquated.</p>
<p><em>Edited 2015-04-29:</em> And with another couple of revolutions around the sun, the time has come for the end of support for Java SE 7, too. In April 2015, Oracle <a href="http://www.oracle.com/technetwork/java/eol-135779.html" rel="noreferrer">affirmed</a> that it was no longer providing public updates to Java SE 7. The tentative end of public updates for Java SE 8 is March 2017, but that end date is subject to change (later, not earlier).</p>
|
<p>With the release of Java 5, the product version was made distinct from the developer version as described <a href="http://java.sun.com/j2se/1.5.0/docs/relnotes/version-5.0.html" rel="nofollow noreferrer">here</a></p>
<h2>Version 1.5.0 or 5.0?</h2>
<p>Both version numbers "1.5.0" and "5.0" are used to identify this release of the Java 2 Platform Standard Edition. Version "5.0" is the product version, while "1.5.0" is the developer version. The number "5.0" is used to better reflect the level of maturity, stability, scalability and security of the J2SE.</p>
<h3>"Version 5.0" Used in Platform and Product Names</h3>
<p>Version 5.0 is used in the platform and product names as given in this table:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>Full Name</th>
<th>Abbreviation</th>
</tr>
</thead>
<tbody>
<tr>
<td>Platform name</td>
<td>Java™ 2 Platform Standard Edition 5.0</td>
<td>J2SE™ 5.0</td>
</tr>
<tr>
<td>Products delivered under the platform</td>
<td>J2SE™ Development Kit 5.0</td>
<td>JDK™ 5.0</td>
</tr>
<tr>
<td></td>
<td>J2SE™ Runtime Environment 5.0</td>
<td>JRE 5.0</td>
</tr>
</tbody>
</table>
</div><h3>"Version 1.5.0" Used by Developers</h3>
<p>J2SE also keeps the version number 1.5.0 (or 1.5) in some places that are visible only to developers, or where the version number is parsed by programs. As mentioned, 1.5.0 refers to exactly the same platform and products numbered 5.0. Version numbers 1.5.0 and 1.5 are used at:</p>
<ul>
<li>java -version (among other info, returns java version "1.5.0")</li>
<li>java -fullversion (returns java full version "1.5.0-b64")</li>
<li>javac -source 1.5 (javac -source 5 also works)</li>
<li>java.version system property</li>
<li>java.vm.version system property</li>
<li>@since 1.5 tag values</li>
<li>jdk1.5.0 installation directory</li>
<li>jre1.5.0 installation directory</li>
<li><a href="http://java.sun.com/j2se/1.5.0" rel="nofollow noreferrer">http://java.sun.com/j2se/1.5.0</a> website (<a href="http://java.sun.com/j2se/5.0" rel="nofollow noreferrer">http://java.sun.com/j2se/5.0</a>
also works)</li>
</ul>
| 31,174
|
<p>I use an sql server regularly and have recently been getting frustrated by the performance. It would be difficult for me to get direct access to find out the hardware so:</p>
<p>Is there a direct way in management studio to assess performance or find out the exact hardware.</p>
<p>Alternatively does someone have a set of test sql procedures I could try and ideally compare to other results to get an idea of it's performance.</p>
<p>So far I have setup a few quick queries on my local machines sql express server just as test these seem to run quicker than the sql server on the network which is meant to be high performance although no one knows when it was last upgraded I have a feeling it hasn't been for 6 or 7 years. Obviously these test don't account for the possibility of others querying at the same time or network transfers of results... Hopefully someone has a better solution.</p>
|
<p>IF you are on 2005:</p>
<p>SELECT * FROM sys.dm_os_performance_counters</p>
<p>That will give you some sql only stats. You will not find much info about the machine without at least terminal access. In the sql startup log you can see some info on processors as well.</p>
|
<p>You also might try updating your references in your server. I had an issue a while back that 1 query returned in 100ms and an identical query in 5+ minutes and the only difference between the 2 was a Capital letter in the table name in my query (whih obviously shouldn't matter).</p>
<p>After some searching and <a href="https://stackoverflow.com/questions/150017/case-sensitivity-when-querying-sql-server-2005-from-net-using-oledb">SO-Questioning</a>, I found that I needed to update my statistics. Could it be something like this is needed for your database / SQL Server too?</p>
| 36,596
|
<p>I have a sorted collection of objects (it can be either SortedList or SortedDictionary, I will use it mainly for reading so add performance is not that important). How can I get the i-th value?</p>
<p>So e.g. when I have numbers 1, 2, 3, 4, 5 in the collection and I want the median (so 3 in this example), how can I do it?</p>
|
<p>You can use code like </p>
<pre><code>list.Values[index]
</code></pre>
<p>for a sorted list. </p>
<p>The easiest way with a SortedDictonary would be to use the ElementAt() method:</p>
<pre><code>dict.ElementAt(index).Value
</code></pre>
<p>However, this is slower than in the list case.</p>
<p>In either case, you need to check your count. If it is odd, take index = (list.length-1) / 2 ). If it is even, take index1 = list.length/2 AND index2 = list.length/2 - 1 and average the values.</p>
|
<p>If you need to get an element by index in a SortedDictionary many times, the performance is miserable. Make a new SortedList with the SortedDictionary as input and access the SortedList. Runs many, many times faster.</p>
| 28,985
|
<p>My question is simple; is it possible to over object-orient your code? </p>
<p>How much is too much? At what point are you giving up readability and maintainability for the sake of OO? </p>
<p>I am a huge OO person but sometimes I wonder if I am over-complicating my code.... </p>
<p>Thoughts?</p>
|
<blockquote>
<p>is it possible to over object-orient your code</p>
</blockquote>
<p>Yes</p>
|
<p>I guess it is possible, but its hard to answer your in abstract terms (no pun intended). Give an example of over OO.</p>
| 7,793
|
<p>The code is rather long yet simple:</p>
<ul>
<li>100 leaky JavaScript objects are created.</li>
<li>10 leaky elements are created from the JS objects.</li>
<li>1 element is removed and 1 is added 10000 times.</li>
</ul>
<p>I assume that the <code>detachEvent</code> call is not functioning properly.
Also, if you change <code>this.eventParams</code> from an array to a simple variable, the leak goes away. Why?</p>
<pre><code> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Memory Leak With Fix</title>
<style type="text/css">
.leakyEle
{
border: solid 1px red;
background-color: Gray;
}
</style>
<script type="text/javascript">
/******************************* MAIN ********************************/
var leakObjArray = new Array();
AddEvent(window, 'load', Startup, false);
function Startup() {
for(var i=0; i<100; i++) {
leakObjArray.push(new LeakyObj(i));
}
for(var j=0; j<10; j++) {
leakObjArray[j].CreateLeakyEle();
}
var container = document.getElementById('Container');
AddEvent(container, 'click', Run, false);
alert('Close this dialog and click the document to continue.');
}
function Run() {
var k = 0;
var l = 10;
for(var m = 0; m<10000; m++) {
leakObjArray[k].DestroyLeakyEle();
leakObjArray[l].CreateLeakyEle();
if(k<leakObjArray.length - 1) {
k++;
} else {
k = 0;
}
if(l<leakObjArray.length - 1) {
l++;
} else {
l = 0;
}
}
for(var i=0; i<leakObjArray.length; i++) {
leakObjArray[i].DestroyLeakyEle();
}
alert('Test Complete.');
}
/******************************* END MAIN ********************************/
/******************************* LEAKY OBJECT ********************************/
function LeakyObj(id) {
this.id = id;
this.leakyEle = null;
this.containerEle = document.getElementById('Container');
this.clicked = false;
this.eventParams = new Array();
}
LeakyObj.prototype.CreateLeakyEle = function() {
var leakyEle = document.createElement('div');
leakyEle.id = 'leakyEle' + this.id;
leakyEle.className = 'leakyEle';
leakyEle.innerHTML = this.id + ' --- XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' +
'<br/>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' +
'<br/>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' +
'<br/>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' +
'<br/>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
this.leakyEle = leakyEle;
var _self = this;
this.eventParams.push(AddEventWithReturnParams(this.leakyEle, 'click', function() { _self.EventHandler(); }, false));
this.containerEle.appendChild(leakyEle);
}
LeakyObj.prototype.DestroyLeakyEle = function() {
if(this.leakyEle != null) {
this.containerEle.removeChild(this.leakyEle);
for(var i=0; i<this.eventParams.length; i++) {
RemoveEventOverload(this.eventParams[i]);
}
this.leakyEle = null;
}
}
LeakyObj.prototype.EventHandler = function() {
this.leakyEle.style.display = 'none';
this.clicked = true;
}
/******************************* END LEAKY OBJECT ********************************/
/******************************* GENERAL FUNCS ********************************/
function AddEvent(elm, evType, fn, useCapture){
var success = false;
if(elm.addEventListener) {
if(evType == 'mousewheel') evType = 'DOMMouseScroll';
elm.addEventListener(evType, fn, useCapture);
success = true;
} else if(elm.attachEvent) {
if(evType == 'mousewheel') {
window.onmousewheel = document.onmousewheel = fn;
success = true;
} else {
var r = elm.attachEvent('on' + evType, fn);
success = r;
}
} else {
success = false;
}
elm = null;
return success;
}
function AddEventWithReturnParams(elm, evType, fn, useCapture) {
var eventParams = new EventParams(elm, evType, fn, useCapture);
AddEvent(elm, evType, fn, useCapture);
return eventParams;
}
function RemoveEvent(elm, evType, fn, useCapture) {
if(elm) {
if(elm.removeEventListener) {
elm.removeEventListener(evType, fn, useCapture);
return true;
} else if(elm.detachEvent) {
var r = elm.detachEvent('on' + evType, fn);
return r;
} else {
debugger;
}
}
}
function RemoveEventOverload(eventParams) {
if(eventParams) {
return RemoveEvent(eventParams.element, eventParams.eventType, eventParams.handler, eventParams.capture);
}
}
function EventParams(elm, evType, fn, useCapture) {
return {
element: elm,
eventType: evType,
handler: fn,
capture: useCapture
}
}
/******************************* END GENERAL FUNCS ********************************/
</script>
</head>
<body>
<div id="Container"></div>
</body>
</html>
</code></pre>
|
<p>looks like you're pushing stuff onto the eventParams array inside CreateLeakyEle, but never removing it? Is that right?</p>
|
<p>If you take a look at your code, you should notice that in each eventParams object stored in your eventParams array, you have references to the objects, but you never empty out your array. Try clearing out your array...</p>
| 33,934
|
<p>I have to present some 'process' or 'flow' of the application at work on friday. I was hoping to prepare a flow chart before I begin the hands on demo. </p>
<p>Any suggestions for freeware sw to make simple flowcharts on Windows?</p>
|
<p><a href="http://live.gnome.org/Dia" rel="noreferrer">Dia</a> might be worth looking at.</p>
<blockquote>
<p>It can be used to draw many different kinds of diagrams. It currently
has special objects to help draw entity relationship diagrams, UML
diagrams, flowcharts, network diagrams, and many other diagrams. It is
also possible to add support for new shapes by writing simple XML
files, using a subset of SVG to draw the shape.</p>
</blockquote>
<p>Here is a <a href="http://dia-installer.de/" rel="noreferrer">download page</a>.</p>
|
<p>If you have Microsoft Word or Excel you can select Insert|Shapes|Flowchart to create a Flowchart. I know it is not free but if you have Microsoft Office already, it may be an option.</p>
| 46,723
|
<p>How do you tell if a function in JavaScript is defined?</p>
<p>I want to do something like this</p>
<pre><code>function something_cool(text, callback) {
alert(text);
if( callback != null ) callback();
}
</code></pre>
<p>But it gets me a</p>
<blockquote>
<p>callback is not a function</p>
</blockquote>
<p>error when callback is not defined.</p>
|
<pre><code>typeof callback === "function"
</code></pre>
|
<p>One-line solution:</p>
<pre><code>function something_cool(text, callback){
callback && callback();
}
</code></pre>
| 11,132
|
<p>I have the following program:</p>
<pre><code>~/test> cat test.cc
int main()
{
int i = 3;
int j = __sync_add_and_fetch(&i, 1);
return 0;
}
</code></pre>
<p>I'm compiling this program using GCC 4.2.2 on Linux running on a multi-cpu 64-bit Intel machine:</p>
<pre><code>~/test> uname --all
Linux doom 2.6.9-67.ELsmp #1 SMP Wed Nov 7 13:56:44 EST 2007 x86_64 x86_64 x86_64 GNU/Linux
</code></pre>
<p>When I compile the program in 64-bit mode, it compiles and links fine:</p>
<pre><code>~/test> /share/tools/gcc-4.2.2/bin/g++ test.cc
~/test>
</code></pre>
<p>When I compile it in 32-bit mode, I get the following error:</p>
<pre><code>~/test> /share/tools/gcc-4.2.2/bin/g++ -m32 test.cc
/tmp/ccEVHGkB.o(.text+0x27): In function `main':
: undefined reference to `__sync_add_and_fetch_4'
collect2: ld returned 1 exit status
~/test>
</code></pre>
<p>Although I will never actually run on a 32-bit processor, I do need a 32-bit executable so I can link with some 32-bit libraries.</p>
<p>My 2 questions are:</p>
<ol>
<li><p>Why do I get a link error when I compile in 32-bit mode?</p></li>
<li><p>Is there some way to get the program to compile and link, while still being able to link with a 32-bit library?</p></li>
</ol>
|
<p>From the <a href="http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/Atomic-Builtins.html#Atomic-Builtins" rel="noreferrer">GCC page on Atomic Builtins</a>:</p>
<blockquote>
<p>Not all operations are supported by
all target processors. If a particular
operation cannot be implemented on the
target processor, a warning will be
generated and a call an external
function will be generated. The
external function will carry the same
name as the builtin, with an
additional suffix `_n' where n is the
size of the data type.</p>
</blockquote>
<p>Judging from your compiler output, which refers to <code>__sync_add_and_fetch_4</code>, this is what's happening. For some reason, GCC is not generating the external function properly.</p>
<p>This is likely why you're only getting an error in 32-bit mode - when compiling for 64-bit mode, it compiles for your processor more closely. When compiling for 32-bit, it may well be using a generic arch (i386, for example) which does not natively support those features. Try specifying a specific architecture for your chip family (Xeon, Core 2, etc.) via -mcpu and see if that works.</p>
<p>If not, you'll have to figure out why GCC isn't including the appropriate function that it should be generating.</p>
|
<p>From the <a href="http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/Atomic-Builtins.html#Atomic-Builtins" rel="noreferrer">GCC page on Atomic Builtins</a>:</p>
<blockquote>
<p>Not all operations are supported by
all target processors. If a particular
operation cannot be implemented on the
target processor, a warning will be
generated and a call an external
function will be generated. The
external function will carry the same
name as the builtin, with an
additional suffix `_n' where n is the
size of the data type.</p>
</blockquote>
<p>Judging from your compiler output, which refers to <code>__sync_add_and_fetch_4</code>, this is what's happening. For some reason, GCC is not generating the external function properly.</p>
<p>This is likely why you're only getting an error in 32-bit mode - when compiling for 64-bit mode, it compiles for your processor more closely. When compiling for 32-bit, it may well be using a generic arch (i386, for example) which does not natively support those features. Try specifying a specific architecture for your chip family (Xeon, Core 2, etc.) via -mcpu and see if that works.</p>
<p>If not, you'll have to figure out why GCC isn't including the appropriate function that it should be generating.</p>
| 15,879
|
<p>What are the pros and cons of using table aliases in SQL? I personally try to avoid them, as I think they make the code less readable (especially when reading through large where/and statements), but I'd be interested in hearing any counter-points to this. When is it generally a good idea to use table aliases, and do you have any preferred formats?</p>
|
<p>Table aliases are a necessary evil when dealing with highly normalized schemas. For example, and I'm not the architect on this DB so bear with me, it can take 7 joins in order to get a clean and complete record back which includes a person's name, address, phone number and company affiliation. </p>
<p>Rather than the somewhat standard single character aliases, I tend to favor short word aliases so the above example's SQL ends up looking like: </p>
<pre><code>select person.FirstName
,person.LastName
,addr.StreetAddress
,addr.City
,addr.State
,addr.Zip
,phone.PhoneNumber
,company.CompanyName
from tblPeople person
left outer join tblAffiliations affl on affl.personID = person.personID
left outer join tblCompany company on company.companyID = affl.companyID
</code></pre>
<p>... etc</p>
|
<p>Aliases are required when joining tables with columns that have identical names.</p>
| 3,222
|
<p>(I asked <a href="https://stackoverflow.com/questions/282830/looking-for-small-open-source-vbnet-project-with-extensive-unit-testing">this</a> question but did not receive much response. It was recommended that I ask the same question with regards to C#. )</p>
<p>I am a VB.NET developer with little C# experience (yes, I know I need to write more in C#), looking for small open source projects that demonstrate high unit testing coverage from which to learn.</p>
<p>I'm looking for <strong><em>small</em></strong> projects because I don't want to have to wade through a ton of code to get a better understanding of how to apply unit testing in my own situation, in which I write mostly IT business apps used internally by my company.</p>
<p>UPDATE: Original question that got me asking about this is <a href="https://stackoverflow.com/questions/236156/could-you-recommend-any-open-source-projects-where-the-source-is-extensively-te">here</a></p>
|
<p>My <a href="http://pobox.com/~skeet/csharp/miscutil" rel="nofollow noreferrer">MiscUtil</a> library has variable test coverage - some parts are very thoroughly tested, and others were written before I knew about unit testing.</p>
<p>If you wanted to learn by writing some tests for the uncovered stuff, you'd be very welcome :)</p>
<p>It's a big of a grab-bag of useful bits and pieces - which is handy in some ways, as you can take almost any bit and study it on its own. There's no "overall architecture" to learn.</p>
|
<p>this link is related to Silverlight but the concepts are probably very similar (from a TDD'ish point of view): <a href="http://www.jeff.wilcox.name/2008/11/04/test-framework-source/" rel="nofollow noreferrer">http://www.jeff.wilcox.name/2008/11/04/test-framework-source/</a></p>
| 36,601
|
<p>I have several xml files, the names of which are stored in another xml file. </p>
<p>I want to use xsl to produce a summary of the combination of the xml files. I remember there was a way to do this with the msxml extensions (I'm using msxml).</p>
<p>I know I can get the content of each file using <code>select="document(filename)"</code> but I'm not sure how to combine all these documents into one.</p>
<p>21-Oct-08 I should have mentioned that I want to do further processing on the combined xml, so it is not sufficient to just output it from the transform, I need to store it as a node set in a variable.</p>
|
<p>Here is just a small example of what you <strong>could</strong> do:</p>
<p><em>file1.xml:</em></p>
<pre><code><foo>
<bar>Text from file1</bar>
</foo>
</code></pre>
<p><em>file2.xml:</em></p>
<pre><code><foo>
<bar>Text from file2</bar>
</foo>
</code></pre>
<p><em>index.xml:</em></p>
<pre><code><index>
<filename>file1.xml</filename>
<filename>file2.xml</filename>
</code></pre>
<p></p>
<p><em>summarize.xsl:</em></p>
<pre><code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl">
<xsl:variable name="big-doc-rtf">
<xsl:for-each select="/index/filename">
<xsl:copy-of select="document(.)"/>
</xsl:for-each>
</xsl:variable>
<xsl:variable name="big-doc" select="exsl:node-set($big-doc-rtf)"/>
<xsl:template match="/">
<xsl:element name="summary">
<xsl:apply-templates select="$big-doc/foo"/>
</xsl:element>
</xsl:template>
<xsl:template match="foo">
<xsl:element name="text">
<xsl:value-of select="bar"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>Applying the stylesheet to <em>index.xml</em> gives you:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?><summary><text>Text from file1</text><text>Text from file2</text></summary>
</code></pre>
<p>The trick is to load the different documents with the document function (extension function supported by almost all XSLT 1.0 processors), to output the contents as part of a variable body and then to convert the variable to a node-set for further processing.</p>
|
<p>Have a look at the <a href="http://msdn.microsoft.com/en-us/library/ms256465(VS.85).aspx" rel="nofollow noreferrer"><code>document()</code> function documentation</a>.</p>
<p>You can use <code>document()</code> to load further XML documents during the transformation process. They are loaded as node sets. That means you would initially feed the XML that contains the file names to load to the XSLT, and take it from there:</p>
<pre><code><xsl:copy-of select="document(@href)/"/>
</code></pre>
| 26,740
|
<p>How can I read an Open Office 3.0 spreadsheet (.ods) from Groovy? I'd like to select specific columns from a named worksheet. Ideally, it would be useful to add a 'where' clause, or other criteria clause.</p>
|
<p>I've never used it, but <a href="http://api.openoffice.org/" rel="nofollow noreferrer">Open Office has a Java API</a>, which of course you could use from Groovy as well. It looks like the best places to start reading are the <a href="http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/OpenOffice.org_Developers_Guide" rel="nofollow noreferrer">Developer's Guide</a>, the <a href="http://api.openoffice.org/docs/java/ref/overview-summary.html" rel="nofollow noreferrer">Java UNO Reference</a>, and the samples in <a href="http://wiki.services.openoffice.org/wiki/API/Samples/Java" rel="nofollow noreferrer">Java</a> and (hey!) <a href="http://wiki.services.openoffice.org/wiki/API/Samples/Groovy" rel="nofollow noreferrer">Groovy</a>. Hope that helps!</p>
|
<p><em>Since the title does not mention Groovy (only question specifics does), I didn't want to make this a new question.</em></p>
<p>How to generally read an Open Office spreadsheet document? There are tools for creating one (ooo-python) but not for reading one. They are XML but just bluntly diving into that and trying to get the right logic of extracting the data I want seems so sub-optimal.</p>
<p>What I'd like is features similar to Excel COM support, but from a command line tool (or scripting language).</p>
| 28,155
|
<p>What's the cleanest, most effective way to validate decimal numbers in JavaScript?</p>
<p>Bonus points for:</p>
<ol>
<li>Clarity. Solution should be clean and simple.</li>
<li>Cross-platform.</li>
</ol>
<p>Test cases:</p>
<pre><code>01. IsNumeric('-1') => true
02. IsNumeric('-1.5') => true
03. IsNumeric('0') => true
04. IsNumeric('0.42') => true
05. IsNumeric('.42') => true
06. IsNumeric('99,999') => false
07. IsNumeric('0x89f') => false
08. IsNumeric('#abcdef') => false
09. IsNumeric('1.2.3') => false
10. IsNumeric('') => false
11. IsNumeric('blah') => false
</code></pre>
|
<p><a href="https://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric/174921#174921">@Joel's answer</a> is pretty close, but it will fail in the following cases:</p>
<pre><code>// Whitespace strings:
IsNumeric(' ') == true;
IsNumeric('\t\t') == true;
IsNumeric('\n\r') == true;
// Number literals:
IsNumeric(-1) == false;
IsNumeric(0) == false;
IsNumeric(1.1) == false;
IsNumeric(8e5) == false;
</code></pre>
<p>Some time ago I had to implement an <code>IsNumeric</code> function, to find out if a variable contained a numeric value, <strong>regardless of its type</strong>, it could be a <code>String</code> containing a numeric value (I had to consider also exponential notation, etc.), a <code>Number</code> object, virtually anything could be passed to that function, I couldn't make any type assumptions, taking care of type coercion (eg. <code>+true == 1;</code> but <code>true</code> shouldn't be considered as <code>"numeric"</code>).</p>
<p>I think is worth sharing this set of <a href="http://run.plnkr.co/plunks/93FPpacuIcXqqKMecLdk/" rel="noreferrer"><strong>+30 unit tests</strong></a> made to numerous function implementations, and also share the one that passes all my tests:</p>
<pre><code>function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
</code></pre>
<p><strong>P.S.</strong> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN" rel="noreferrer">isNaN</a> & <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite" rel="noreferrer">isFinite</a> have a confusing behavior due to forced conversion to number. In ES6, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN" rel="noreferrer">Number.isNaN</a> & <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite" rel="noreferrer">Number.isFinite</a> would fix these issues. Keep that in mind when using them. </p>
<hr>
<p><strong>Update</strong> :
<a href="https://github.com/jquery/jquery/blob/2.2-stable/src/core.js#L215" rel="noreferrer">Here's how jQuery does it now (2.2-stable)</a>: </p>
<pre><code>isNumeric: function(obj) {
var realStringObj = obj && obj.toString();
return !jQuery.isArray(obj) && (realStringObj - parseFloat(realStringObj) + 1) >= 0;
}
</code></pre>
<p><strong>Update</strong> :
<a href="https://github.com/angular/angular/blob/4.3.x/packages/common/src/pipes/number_pipe.ts#L172" rel="noreferrer">Angular 4.3</a>:</p>
<pre><code>export function isNumeric(value: any): boolean {
return !isNaN(value - parseFloat(value));
}
</code></pre>
|
<p>The following may work as well.</p>
<pre><code>function isNumeric(v) {
return v.length > 0 && !isNaN(v) && v.search(/[A-Z]|[#]/ig) == -1;
};
</code></pre>
| 3,870
|
<p>In the <code>IDisposable.Dispose</code> method is there a way to figure out if an exception is being thrown?</p>
<pre><code>using (MyWrapper wrapper = new MyWrapper())
{
throw new Exception("Bad error.");
}
</code></pre>
<p>If an exception is thrown in the <code>using</code> statement I want to know about it when the <code>IDisposable</code> object is disposed.</p>
|
<p><strong>No</strong>, there is no way to do this in the .Net framework, you cannot figure out the current-exception-which-is-being-thrown in a finally clause. </p>
<p>See this <a href="http://samsaffron.com/blog/archive/2007/08/06/16.aspx" rel="noreferrer">post on my blog</a>, for a comparison with a similar pattern in Ruby, it highlights the gaps I think exist with the IDisposable pattern. </p>
<p>Ayende has a trick that will allow you to <a href="http://ayende.com/Blog/archive/2007/06/20/Did-you-know-Find-out-if-an-exception-was-thrown.aspx" rel="noreferrer">detect an exception happened</a>, however, it will not tell you which exception it was.</p>
|
<p>This will catch exceptions thrown either directly or inside the dispose method:</p>
<pre><code>try
{
using (MyWrapper wrapper = new MyWrapper())
{
throw new MyException("Bad error.");
}
}
catch ( MyException myex ) {
//deal with your exception
}
catch ( Exception ex ) {
//any other exception thrown by either
//MyWrapper..ctor() or MyWrapper.Dispose()
}
</code></pre>
<p>But this is relying on them using this this code - it sounds like you want MyWrapper to do that instead.</p>
<p>The using statement is just to make sure that Dispose always gets called. It's really doing this:</p>
<pre><code>MyWrapper wrapper;
try
{
wrapper = new MyWrapper();
}
finally {
if( wrapper != null )
wrapper.Dispose();
}
</code></pre>
<p>It sounds like what you want is:</p>
<pre><code>MyWrapper wrapper;
try
{
wrapper = new MyWrapper();
}
finally {
try{
if( wrapper != null )
wrapper.Dispose();
}
catch {
//only errors thrown by disposal
}
}
</code></pre>
<p>I would suggest dealing with this in your implementation of Dispose - you should handle any issues during Disposal anyway.</p>
<p>If you're tying up some resource where you need users of your API to free it in some way consider having a <code>Close()</code> method. Your dispose should call it too (if it hasn't been already) but users of your API could also call it themselves if they needed finer control.</p>
| 27,117
|
<p>In MS SQL Server, I create my scripts to use customizable variables:</p>
<pre><code>DECLARE @somevariable int
SELECT @somevariable = -1
INSERT INTO foo VALUES ( @somevariable )
</code></pre>
<p>I'll then change the value of <code>@somevariable</code> at runtime, depending on the value that I want in the particular situation. Since it's at the top of the script it's easy to see and remember.</p>
<p>How do I do the same with the PostgreSQL client <code>psql</code>?</p>
|
<p>Postgres variables are created through the \set command, for example ...</p>
<pre><code>\set myvariable value
</code></pre>
<p>... and can then be substituted, for example, as ...</p>
<pre><code>SELECT * FROM :myvariable.table1;
</code></pre>
<p>... or ...</p>
<pre><code>SELECT * FROM table1 WHERE :myvariable IS NULL;
</code></pre>
<p><em>edit: As of psql 9.1, variables can be expanded in quotes as in:</em> </p>
<pre><code>\set myvariable value
SELECT * FROM table1 WHERE column1 = :'myvariable';
</code></pre>
<p><em>In older versions of the psql client:</em> </p>
<p>... If you want to use the variable as the value in a conditional string query, such as ...</p>
<pre><code>SELECT * FROM table1 WHERE column1 = ':myvariable';
</code></pre>
<p>... then you need to include the quotes in the variable itself as the above will not work. Instead define your variable as such ...</p>
<pre><code>\set myvariable 'value'
</code></pre>
<p>However, if, like me, you ran into a situation in which you wanted to make a string from an existing variable, I found the trick to be this ...</p>
<pre><code>\set quoted_myvariable '\'' :myvariable '\''
</code></pre>
<p>Now you have both a quoted and unquoted variable of the same string! And you can do something like this ....</p>
<pre><code>INSERT INTO :myvariable.table1 SELECT * FROM table2 WHERE column1 = :quoted_myvariable;
</code></pre>
|
<p>I've posted a new solution for this <a href="https://stackoverflow.com/questions/13316773/is-there-a-way-to-define-a-named-constant-in-a-postgresql-query/54322738#54322738">on another thread</a>.</p>
<p>It uses a table to store variables, and can be updated at any time. A static immutable getter function is dynamically created (by another function), triggered by update to your table. You get nice table storage, plus the blazing fast speeds of an immutable getter.</p>
| 5,758
|
<p>I want to bring up a file dialog in Java that defaults to the application installation directory.</p>
<p>What's the best way to get that information programmatically?</p>
|
<pre><code>System.getProperty("user.dir")
</code></pre>
<p>gets the directory the Java VM was started from.</p>
|
<pre><code>System.getProperty("user.dir");
</code></pre>
<p>The above method gets the user's working directory when the application was launched. This is fine if the application is launched by a script or shortcut that ensures that this is the case.</p>
<p>However, if the app is launched from somewhere else (entirely possible if the command line is used), then the return value will be wherever the user was when they launched the app.</p>
<p>A more reliable method is to <a href="http://illegalargumentexception.blogspot.com/2008/04/java-finding-application-directory.html" rel="nofollow noreferrer">work out the application install directory using ClassLoaders</a>.</p>
| 4,807
|
<p>Code below is not working as expected to detect if it is in design mode (VS.Net 2003 - Control Library):</p>
<p>if (this.Site != null && this.Site.DesignMode == true) <br>
{<br>
// Design Mode<br>
}<br>
else<br>
{<br>
// Run-time<br>
}<br></p>
<p>It is used in a complex user control, deriving from another user control and including other user controls on it.<br>
Is there another way to detect design time in a VS.NET 2003 or what is the problem with the code above? </p>
|
<p><code>DesignMode</code> won't work from inside a constructor. Some alternatives (not sure if they work in 1.1) are</p>
<p><code>if (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime)</code></p>
<p>or</p>
<p>call <code>GetService(typeof(IDesignerHost))</code> and see if it returns something.</p>
<p>I've had better luck with the first option.</p>
|
<p>I guess you could use HttpContext.Current == null as described at <a href="http://west-wind.com/weblog/posts/189.aspx" rel="nofollow noreferrer">http://west-wind.com/weblog/posts/189.aspx</a></p>
<p>In .Net 2.0 there's Control.DesignMode (<a href="http://msdn.microsoft.com/en-us/library/system.web.ui.control.designmode.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.web.ui.control.designmode.aspx</a>). I guess you have a good reasons to stay on VS 2003 though, so upgrading might not be an option for you.</p>
<p><strong>Update</strong> If you are doing Winforms, Component.DesignMode (<a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.component.designmode.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.componentmodel.component.designmode.aspx</a>) is the right way to check. Though, if this.Site.DesignMode doesn't work properly, Component.DesignMode might not work as well, as it does exactly the check you are doing (Site != null && Site.DesignMode).</p>
<p>This might be a long shot, but are you sure that your base control does not override the Site property?</p>
| 17,474
|
<p>I have a Tevo Tarantula 3D printer.</p>
<p>I'm trying to print a calibration cube. </p>
<p>The slicer is Cura and is set for a 1.75 mm filament extruded by a nozzle of 0.4 mm, with a heat bed temperature of 60°C and extruder 200°C. </p>
<p>As seen in the image I stopped the printer after a minute, when I noticed that the filament wasn't sticking to the hotbed. </p>
<p><a href="https://i.stack.imgur.com/zdPaw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zdPaw.jpg" alt="Photo of filament not adhering the printbed"></a></p>
<p>I've also made other tests, but the result is the same - the upper right part of the print lifts and touches the moving nozzle. </p>
<p>How could I resolve this? Any advice? </p>
|
<p>I don't have this specific printer but this used to happen to me as well on my D-Bot. The reason being bed not being leveled properly. Ensure that your bed is leveled such that the distance between the nozzle and bed is about 0.2mm after homing. Also coat your bed with something sticky like glue or hairspray. You won't need this if you are using a PEI sheet. </p>
|
<p>I've cleaned the heated bed as suggested using ethanol,
then I've tested the Z distance of the nozzle from the bed with a paper sheet and it was ok. Lastly, I tried to raise the temperature of the extruder for the first layer to 215°C. I think that this did the trick.</p>
| 591
|
<p>I'm using StructureMap in my project and when the application finishes running I need to call the Dispose() method on all of the Singleton instances inside the ObjectFactory that implement IDisposable.</p>
<p>I cannot find anyway to do it via the StructureMap API.</p>
<p>Another thought I had was to get a reference to every instance and call it myself, but I cannot figure out how to loop through all of the instances.</p>
|
<p>I don't know how to directly change the offset, but I managed to fix this by:</p>
<ol>
<li>Changing the increment amount by X (1 million in my case).</li>
<li>Inserting a dummy record.</li>
<li>Reducing the increment amount back down to 1.</li>
<li>Deleting the dummy record.</li>
</ol>
<p>I used this SQL statement to change the increment amount:</p>
<pre><code>ALTER TABLE tbl ALTER COLUMN col SET INCREMENT BY x
</code></pre>
|
<p>I don't know how to directly change the offset, but I managed to fix this by:</p>
<ol>
<li>Changing the increment amount by X (1 million in my case).</li>
<li>Inserting a dummy record.</li>
<li>Reducing the increment amount back down to 1.</li>
<li>Deleting the dummy record.</li>
</ol>
<p>I used this SQL statement to change the increment amount:</p>
<pre><code>ALTER TABLE tbl ALTER COLUMN col SET INCREMENT BY x
</code></pre>
| 46,162
|
<p>I'm trying to embed an xsl into a XML file. The reason for doing this is to create a single file that could be moved to different computers, this would prevent the need to move the xsl file. </p>
<p>The xsl file is creating a table and grabbing a test step from the xml and whether it passed or failed, pretty simple.<br>
The issue I'm having, I think, is that the xsl has javascript and its being displayed when the xml is loaded in IE. </p>
<p>When I load the xml file with IE, the javascript is displayed above the table and below the table the xml is displayed.</p>
<p>Here is how my document is laid-out :</p>
<pre><code><!DOCTYPE doc [
<!ATTLIST xsl:stylesheet
id ID #REQUIRED>
]>
<doc>
<xsl:stylesheet id="4.1.0"
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:user="http://www.ni.com/TestStand"
xmlns:vb_user="http://www.ni.com/TestStand/" >
<xsl:template match="xsl:stylesheet" />
<xsl:text disable-output-escaping="yes">
<msxsl:script language="vbscript" implements-prefix="vb_user">
option explicit
'This function will return the localized decimal point for a decimal number
Function GetLocalizedDecimalPoint ()
dim lDecPoint
lDecPoint = Mid(CStr(1.1),2,1)
GetLocalizedDecimalPoint = lDecPoint
End Function
</msxsl:script>
<msxsl:script language="javascript" implements-prefix="user"><![CDATA[
// This style sheet will not show tables instead of graphs for arrays of values if
// 1. TSGraph control is not installed on the machine
// 2. Using the stylesheet in windows XP SP2. Security settings prevent stylesheets from creatign the GraphControl using scripting.
// Refer to the TestStand Readme for more information.
//more javascript functions
//code to build table and insert data from the xml
</xsl:stylesheet>
<Reports>
<Report Type='UUT' Title='UUT Report' Link='-1-2008-12-3-10-46-52-713' UUTResult='Failed' StepCount='51'>
// rest of xml
</Report>
</Reports>
</doc>
</code></pre>
|
<p><a href="http://www.w3.org/TR/xslt#section-Embedding-Stylesheets" rel="nofollow noreferrer"><strong>Although the W3C XSLT Spec supports embedding an XSLT stylesheet</strong></a> into an XML document, it seems that IE and Firefox do not support this.</p>
<p><strong>UPDATE</strong>: As per the comment by Robert Niestroj, years later, in Oct. 2014, this works in FireFox 33.</p>
<p><strong>However, there is a good alternative: embed the XML document into the XSLT stylesheet</strong>.</p>
<p>Below is an example.</p>
<p><strong>An XSLT stylesheet containing an embedded XML document</strong>:</p>
<pre>
<?xml-stylesheet type="text/xsl" href="myEmbedded.xml"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:variable name="vEmbDoc">
<doc>
<head></head>
<body>
<para id="foo">Hello I am foo</para>
</body>
</doc>
</xsl:variable>
<xsl:template match="para">
<h1><xsl:value-of select="."/></h1>
</xsl:template>
<xsl:template match="xsl:template"/>
</xsl:stylesheet>
</pre>
<p>When tis file is opened in IE, the wanted result is displayed by the browser:</p>
<h1>Hello I am foo</h1>
<p><strong>Do note</strong>, that it is necessary to include templates that ignore most of the XSLT instructions (in this case we are ignoring any <code><xsl:template></code> by simply having no template body.</p>
|
<p>Stylesheet embedding is possible for most browsers but IE.
Find the reference to a description and example in the posting below.</p>
<p>IE6/7/8 do not support embedded stylesheets by default.</p>
<p>You may want to use the workaround enabling IE to process embedded stylesheets from here:</p>
<p><a href="http://www.biglist.com/lists/lists.mulberrytech.com/xsl-list/archives/201001/msg00390.html" rel="nofollow noreferrer">http://www.biglist.com/lists/lists.mulberrytech.com/xsl-list/archives/201001/msg00390.html</a></p>
| 47,065
|
<p>I have an EXE loaded into a byte array, and I am trying to load it into an assembly object using Assembly.Load. I am getting errors trying to load.</p>
<p>Here is the code that is causing the exception:</p>
<pre><code>Assembly a = Assembly.Load(bin);
</code></pre>
<p>bin is my byte array, loaded from the EXE.</p>
<p><strong>Here is the exception I am getting:</strong></p>
<blockquote>
<p>Could not load file or assembly '109590 bytes loaded from calc_tester, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.</p>
</blockquote>
<p>Any help is appreciated.</p>
|
<p>Make sure the file you're trying to load is a .NET Managed exe/dll.</p>
|
<p>I am not sure, but because it is an EXE, it might be failing because of the unmanaged headers in the EXE?</p>
<p>Why not just do a LoadFrom( filename )?</p>
| 43,887
|
<p>I am looking for template/generator libraries for C++ that are similar to eg. Ruby's Erb, Haml, PHP's Smarty, etc.</p>
<p>It would be great if I it would sport some basic features like loops, if/else, int conversion to strings, etc.</p>
<p>Parameter passing to template rendering engine is also important if I could pass all of them in a hash map instead of calling some function for each of parameters.</p>
<p>Do you have any recommendations?</p>
<p>I can see also the possibility of embedding languages like Lua, however I haven't found a templatizing library for that either.</p>
|
<p>A quick review of the mentioned project.</p>
<p><a href="http://rgrz.tumblr.com/post/13808947359/review-of-html-template-engines-in-c-language" rel="nofollow noreferrer">http://rgrz.tumblr.com/post/13808947359/review-of-html-template-engines-in-c-language</a></p>
<h2>ClearSilver</h2>
<ul>
<li>Site: <a href="http://www.clearsilver.net" rel="nofollow noreferrer">http://www.clearsilver.net</a></li>
<li>Project: <a href="https://code.google.com/p/clearsilver/" rel="nofollow noreferrer">https://code.google.com/p/clearsilver/</a></li>
<li>Group: <a href="http://tech.groups.yahoo.com/group/ClearSilver" rel="nofollow noreferrer">http://tech.groups.yahoo.com/group/ClearSilver</a></li>
<li>License: New BSD License</li>
<li>Language: C</li>
<li>Last Update: Nov 28, 2011</li>
<li>Last Release: 0.10.5 on July 12, 2007</li>
<li>Document: Rich</li>
<li>Community: Medium (<10 discussion per month)</li>
</ul>
<h2>Teng</h2>
<ul>
<li>Site: <a href="http://teng.sourceforge.net" rel="nofollow noreferrer">http://teng.sourceforge.net</a></li>
<li>Code: <a href="http://teng.svn.sourceforge.net/teng/" rel="nofollow noreferrer">http://teng.svn.sourceforge.net/teng/</a></li>
<li>Group: <a href="http://sourceforge.net/projects/teng/" rel="nofollow noreferrer">http://sourceforge.net/projects/teng/</a></li>
<li>License: New BSD License</li>
<li>Language: C++</li>
<li>Binding: php, python</li>
<li>Last Update: Mar 8, 2011</li>
<li>Last Release: 2.1.1 on Mar 8, 2011</li>
<li>Document: Rich</li>
<li>Community: Low (rare discussion since 2010)</li>
</ul>
<h2>Templatizer</h2>
<ul>
<li>Site: <a href="http://www.lazarusid.com/libtemplate.shtml" rel="nofollow noreferrer">http://www.lazarusid.com/libtemplate.shtml</a></li>
<li>Project: download only</li>
<li>Group: none</li>
<li>License: free to use</li>
<li>Language: C (low level)/C++ (interface) mixed</li>
<li>Last Update: unknown</li>
<li>Last Release: unknown</li>
<li>Document: none</li>
<li>Community: none</li>
</ul>
<h2>HTML Template C++</h2>
<ul>
<li>Site: <a href="http://nulidex.com/code/docs/html_template/" rel="nofollow noreferrer">http://nulidex.com/code/docs/html_template/</a></li>
<li>Project: <a href="http://sourceforge.net/projects/htmltemplatec" rel="nofollow noreferrer">http://sourceforge.net/projects/htmltemplatec</a> </li>
<li>Group: <a href="http://sourceforge.net/projects/htmltemplatec" rel="nofollow noreferrer">http://sourceforge.net/projects/htmltemplatec</a></li>
<li>License: GPL</li>
<li>Language: C++</li>
<li>Last Update: Mar 27, 2011</li>
<li>Last Release: Beta 0.7.4, Mar 27, 2011</li>
<li>Document: Medium</li>
<li>Community: none</li>
</ul>
<h2>ctpp</h2>
<ul>
<li>Site: <a href="http://ctpp.havoc.ru/en/" rel="nofollow noreferrer">http://ctpp.havoc.ru/en/</a></li>
<li>Project: download only</li>
<li>Group: none</li>
<li>License: BSD License</li>
<li>Language: C++ with C API</li>
<li>Last Update: Oct 5, 2011</li>
<li>Last Release: Version 2.7.2 on Oct 5, 2011</li>
<li>Document: Rich</li>
<li>Community: none</li>
</ul>
<h2>Wt</h2>
<ul>
<li>Site: <a href="http://www.webtoolkit.eu/wt/" rel="nofollow noreferrer">http://www.webtoolkit.eu/wt/</a></li>
<li>Project: <a href="http://www.webtoolkit.eu/wt/" rel="nofollow noreferrer">http://www.webtoolkit.eu/wt/</a></li>
<li>Group: <a href="http://www.webtoolkit.eu/wt/community" rel="nofollow noreferrer">http://www.webtoolkit.eu/wt/community</a></li>
<li>License: GPL and Commercial</li>
<li>Language: C++</li>
<li>Last Update: Nov 29, 2011</li>
<li>Last Release: 3.2.0 on Nov 29, 2011</li>
<li>Document: Rich</li>
<li>Community: Low (rare activity)</li>
</ul>
<h2>Flate</h2>
<ul>
<li>Site: <a href="http://flate.dead-inside.org/" rel="nofollow noreferrer">http://flate.dead-inside.org/</a></li>
<li>Project: none</li>
<li>Group: none</li>
<li>License: LGPL v2.1</li>
<li>Language: C</li>
<li>Last Update: Sep 4, 2010</li>
<li>Last Release: 2.0 on Sep 4, 2010</li>
<li>Document: Poor</li>
<li>Community: none</li>
</ul>
<h2>Jinja2C++</h2>
<ul>
<li>Site: <a href="https://jinja2cpp.dev" rel="nofollow noreferrer">https://jinja2cpp.dev</a></li>
<li>Project: <a href="https://github.com/jinja2cpp" rel="nofollow noreferrer">https://github.com/jinja2cpp</a></li>
<li>Group: <a href="https://gitter.im/Jinja2Cpp/Lobby" rel="nofollow noreferrer">https://gitter.im/Jinja2Cpp/Lobby</a></li>
<li>Conan packages: <a href="https://bintray.com/beta/#/flexferrum/conan-packages/jinja2cpp:flexferrum?tab=overview" rel="nofollow noreferrer">https://bintray.com/beta/#/flexferrum/conan-packages/jinja2cpp:flexferrum?tab=overview</a></li>
<li>License: MPL-2.0</li>
<li>Language: C++14/17</li>
<li>Last Update: Oct 01, 2019</li>
<li>Last Release: 1.0.0 on Oct 01, 2019</li>
<li>Document: Moderate</li>
<li>Community: none</li>
</ul>
|
<p>I have tried using template engine and Dynamic C++ Pages provided by the ffead-cpp framework, an example implementation is shown on the <a href="http://code.google.com/p/ffead-cpp/wiki/ExampledcpFile" rel="nofollow">wiki</a> </p>
| 46,358
|
<p>I would like to know if there is software that, given a regex and of course some other constraints like length, produces random text that always matches the given regex.
Thanks</p>
|
<p><a href="http://code.google.com/p/xeger" rel="noreferrer">Xeger</a> is capable of doing it: </p>
<pre><code>String regex = "[ab]{4,6}c";
Xeger generator = new Xeger(regex);
String result = generator.generate();
assert result.matches(regex);
</code></pre>
|
<p>Instead of starting from a regexp, you should be looking into writing a small context free grammer, this will allow you to easily generate such random text. Unfortunately, I know of no tool which will do it directly for you, so you would need to do a bit of code yourself to actually generate the text. If you have not worked with grammers before, I suggest you read a bit about bnf format and "compiler compilers" before proceeding...</p>
| 34,524
|
<p>I've tested in Chrome, do I need to test in Safari?</p>
|
<p>I've noticed Safari handles Asian characters better than Chrome.
Also Chrome and Safari rely on the same Webkit for rendering pages, but their Javascript engines are totally different, so if you use Javascript in your pages you need to check both.</p>
|
<p>In a word, No. You can't assume that because it works in one it will definitely work in all cases in the other. Sure, 99% of the time, it might be the same - but 99% isn't 100% - at least, it wasn't last time I checked. Call me a pedantic git if you like.</p>
| 48,866
|
<p>I have a table in a ORACLE 10g database with a column "<code>kzCode NUMBER(1)</code>".</p>
<p>If I try to map this with Hibernate annotations in JBOSS Server WebApp like this:</p>
<pre><code>@Column(nullable=false)
private Integer kzCode;
</code></pre>
<p>I got an error: </p>
<pre><code>org.hibernate.HibernateException: Wrong column type: kzCode, expected: integer
</code></pre>
<p>I also tried </p>
<pre><code>@Column(nullable=false) private BigInteger kzCode;
</code></pre>
<p>error: </p>
<pre><code>org.hibernate.HibernateException: Wrong column type: kzCode, expected:numeric(19,2)
</code></pre>
<p>I don't really know, what Java type to take.</p>
|
<p>ok, got it!</p>
<p>I had a wrong dialect property in persistence.xml file.
Now all works fine..</p>
|
<pre><code>@Column(nullable=false)
private Boolean kzCode;
</code></pre>
<p>or if you really want it to be a number, change the Oracle type to NUMBER(36, 0) and use long or Long in your Java.</p>
| 44,726
|
<p>How can I create an Excel spreadsheet with C# without requiring Excel to be installed on the machine that's running the code?</p>
|
<p>You can use a library called ExcelLibrary. It's a free, open source library posted on Google Code:</p>
<p><a href="https://code.google.com/archive/p/excellibrary/" rel="noreferrer">ExcelLibrary</a></p>
<p>This looks to be a port of the PHP ExcelWriter that you mentioned above. It will not write to the new .xlsx format yet, but they are working on adding that functionality in.</p>
<p>It's very simple, small and easy to use. Plus it has a DataSetHelper that lets you use DataSets and DataTables to easily work with Excel data.</p>
<p>ExcelLibrary seems to still only work for the older Excel format (.xls files), but may be adding support in the future for newer 2007/2010 formats. </p>
<p>You can also use <a href="https://github.com/JanKallman/EPPlus" rel="noreferrer">EPPlus</a>, which works only for Excel 2007/2010 format files (.xlsx files). There's also <a href="https://github.com/tonyqus/npoi" rel="noreferrer">NPOI</a> which works with both.</p>
<p>There are a few known bugs with each library as noted in the comments. In all, EPPlus seems to be the best choice as time goes on. It seems to be more actively updated and documented as well.</p>
<p>Also, as noted by @АртёмЦарионов below, EPPlus has support for Pivot Tables and ExcelLibrary may have some support (<a href="https://code.google.com/archive/p/excellibrary/issues/98" rel="noreferrer">Pivot table issue in ExcelLibrary</a>)</p>
<p>Here are a couple links for quick reference:<br/>
<a href="https://code.google.com/archive/p/excellibrary/" rel="noreferrer">ExcelLibrary</a> - <a href="https://www.gnu.org/licenses/lgpl.html" rel="noreferrer">GNU Lesser GPL</a><br/>
<a href="https://github.com/JanKallman/EPPlus" rel="noreferrer">EPPlus</a> - <a href="https://github.com/JanKallman/EPPlus#license" rel="noreferrer">GNU (LGPL) - No longer maintained</a><br/>
<a href="https://www.epplussoftware.com/" rel="noreferrer">EPPlus 5</a> - <a href="https://www.epplussoftware.com/en/LicenseOverview" rel="noreferrer">Polyform Noncommercial - Starting May 2020</a><br/>
<a href="https://github.com/tonyqus/npoi" rel="noreferrer">NPOI</a> - <a href="https://github.com/tonyqus/npoi/blob/master/LICENSE" rel="noreferrer">Apache License</a></p>
<p><b>Here some example code for ExcelLibrary:</b></p>
<p>Here is an example taking data from a database and creating a workbook from it. Note that the ExcelLibrary code is the single line at the bottom:</p>
<pre><code>//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
//Open a DB connection (in this example with OleDB)
OleDbConnection con = new OleDbConnection(dbConnectionString);
con.Open();
//Create a query and fill the data table with the data from the DB
string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();
adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();
//Add the table to the data set
ds.Tables.Add(dt);
//Here's the easy part. Create the Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);
</code></pre>
<p>Creating the Excel file is as easy as that. You can also manually create Excel files, but the above functionality is what really impressed me.</p>
|
<p>I am using following code for create excel 2007 file which create the file and write in that file but when i open the file but it give me error that
exel cannot open the file bcz file might be coruupted or extension of the file is not compatible.
but if i used .xls for file it work fines</p>
<pre><code>for (int i = 0; i < TotalFile; i++)
{
Contact.Clear();
if (innerloop == SplitSize)
{
for (int j = 0; j < SplitSize; j++)
{
string strContact = DSt.Tables[0].Rows[i * SplitSize + j][0].ToString();
Contact.Add(strContact);
}
string strExcel = strFileName + "_" + i.ToString() + ".xlsx";
File.WriteAllLines(strExcel, Contact.ToArray());
}
}
</code></pre>
<p>also refer link</p>
<p><a href="http://dotnet-magic.blogspot.in/2011/10/createformat-excel-file-from-cnet.html" rel="nofollow">http://dotnet-magic.blogspot.in/2011/10/createformat-excel-file-from-cnet.html</a></p>
| 18,205
|
<p>So you know a lot of Mac apps use "bundles": It looks like a single file to your application, but it's actually a folder with many files inside.</p>
<p>For a version control system to handle this, it needs to:</p>
<ul>
<li>check out all the files in a directory, so the app can modify them as necessary</li>
<li>at checkin,
<ul>
<li>commit files which have been modified</li>
<li>add new files which the application has created</li>
<li>mark as deleted files which are no longer there (since the app deleted them)</li>
<li>manage this as one atomic change</li>
</ul></li>
</ul>
<p>Any ideas on the best way to handle this with existing version control systems? Are any of the versioning systems more adept in this area? </p>
|
<p>Mercurial in particular versions based on file, not directory structure. Therefore, your working tree, which is a fully-fledged repository, doesn't spit out .svn folders at each level.</p>
<p>It also means that a directory that is replaced, like an Application or other Bundle, will still find it's contents with particular file names under revision control. File names are monitored, not inodes or anything fancy like that!</p>
<p>Obviously, if a new file is added to the Bundle, you'll need to explicitly add this to your repository. Similarly, removing a file from a Bundle should be done with an 'hg rm'.</p>
<p>There aren't any decent Mercurial GUIs for OS X yet, but if all you do is add/commit/merge, it isn't that hard to use a command line.</p>
|
<p>An update from the future:</p>
<p>If I recall, the problem with managing bundles in SVN was all the .svn folders getting cleared each time you made a bundle. This shouldn't be a problem any more, now that SVN stores everything in a single .svn folder at the root.</p>
| 4,666
|
<p>Whilst investigating a memory leak I discovered that it was caused by calling NewRow() on a Table inside a loop many times. However the DataRow created was never added to the Table Rows collection and the Table Rows Count never got above zero.</p>
<p>My question is why does this use up more memory every time NewRow is called even though the newly created DataRow never gets added to the Rows collection and the DataRow returned from NewRow is always assigned to the same local variable (thereby apparently discarding the last new row).</p>
<p>Please ignore the issue of why the code is creating DataRows that don't get added to the table!</p>
|
<p>DataRow inherits schema from the DataTable, so there are references from DataRow to the table schema that generated the row. The new row is in Detached state in the table.<br>
this is why GC left the new unused rows alone. </p>
|
<p>If you create newRow = table.NewRow() and then in the code below decide than this newRow you more not need.
1) Add if row in the table.
2) Remove, it will prevent memory leak.</p>
<pre><code> var table = new DataTable();
while (true)
{
var newRow = table.NewRow();
table.Rows.Add(newRow); //Without this 2 rows you will have memory leak.
table.Rows.Remove(newRow);//
}
</code></pre>
| 30,042
|
<p>I'm looking for something containing similar functions to Matlab’s financial and financial derivatives toolbox but don’t have the cash to spend on matlab. I would appreciate any info on free or open source libraries or programs that will let me easily calculate interest rates, risk etc.</p>
|
<p>How about <a href="http://www.jquantlib.org/index.php/Main_Page" rel="noreferrer">JQuantLib</a> or <a href="http://quantlib.org/index.shtml" rel="noreferrer">QuantLib</a>?</p>
|
<p>How about the <a href="http://www.gnu.org/software/octave/" rel="nofollow noreferrer">Octave</a> financial functions?</p>
<p><a href="http://www.gnu.org/software/octave/doc/interpreter/Financial-Functions.html#Financial-Functions" rel="nofollow noreferrer">http://www.gnu.org/software/octave/doc/interpreter/Financial-Functions.html#Financial-Functions</a></p>
<p>I'm not familiar with the Matlab toolbox, so you'll have to judge for yourself.</p>
<blockquote>
<p>GNU Octave is a high-level language,
primarily intended for numerical
computations. It provides a convenient
command line interface for solving
linear and nonlinear problems
numerically, and for performing other
numerical experiments using a language
that is mostly compatible with Matlab.
It may also be used as a
batch-oriented language.</p>
</blockquote>
| 43,164
|
<p>How can I validate date strings in Perl? I'd like to account for leap years and also time zones. Someone may enter dates in the following formats:</p>
<pre>
11/17/2008
11/17/2008 3pm
11/17/2008 12:01am
11/17/2008 12:01am EST
11/17/2008 12:01am CST
</pre>
|
<p>I use <a href="http://search.cpan.org/dist/DateTime-Format-DateManip/lib/DateTime/Format/DateManip.pm" rel="nofollow noreferrer">DateTime::Format::DateManip</a> for things like this. Using your dates....</p>
<pre><code>use DateTime::Format::DateManip;
my @dates = (
'11/17/2008',
'11/17/2008 3pm',
'11/17/2008 12:01am',
'11/17/2008 12:01am EST',
'11/17/2008 12:01am CST',
);
for my $date ( @dates ) {
my $dt = DateTime::Format::DateManip->parse_datetime( $date );
die "Cannot parse date $date" unless defined $dt;
say $dt;
}
# no dies.. produced the following....
# => 2008-11-17T00:00:00
# => 2008-11-17T15:00:00
# => 2008-11-17T00:01:00
# => 2008-11-17T05:01:00
# => 2008-11-17T06:01:00
</code></pre>
<p>NB. I'm on GMT here!</p>
|
<p>I'll post my answers here as I come across them.</p>
<p>use Time::Local<br>
<a href="http://www.perlmonks.org/?node_id=642627" rel="nofollow noreferrer">http://www.perlmonks.org/?node_id=642627</a></p>
| 38,050
|
<p>Should I be able to hand turn the stepper motor for the extruder of an Ender 3?</p>
<p>Trying to figure out why the motor isn’t turning on a new to me, never used, but out-of-warranty Ender 3.</p>
<p>Swapping controller cables I discovered the extruder port on the motherboard is dead, but even if I put it on the X axis and manually move the axis it makes the sound like it should move, but doesn’t actually move at all.</p>
<p>Trying to figure out if it’s seized or something. Doing a resistance test with a multimeter shows a resistance of 4 for either of the two pairs of wires. I am not sure what else to test.</p>
<p>I have a hard time believing I need a new control board and a new stepper motor, but maybe two things are broke.</p>
<p>Thanks for the help!</p>
<hr />
<h2>EDIT - Got the Extruder Working</h2>
<p>After the comments here mentioned that "Yes, it should be able to be moved by hand", curiosity got the better of me and I said, "Well, if its broken, let's see why".</p>
<p>I did the following:</p>
<ol>
<li>I tried to turn the stepper motor by hand again, just to confirm I wasn't crazy from the day before when I tried it. It wouldn't budge.</li>
<li>I removed all four screws on the bottom of the stepper motor and attempted to pry things apart. While fiddling with it, I thought I saw the stepper motor turn.</li>
<li>Sure enough, I now tried to spin the stepper motor and it moved relatively easily.</li>
<li>I put the 4 screws back in place and validated I could still hand turn the motor. I could in fact do so.</li>
<li>I hooked the stepper motor back up to the X axis controller and told it to move, and sure enough now it moves and works!</li>
<li>Just as a sanity check, I then hooked it up to the extruder controller and it again wouldn't turn.</li>
</ol>
<p>I'm going to try what @towe recommended to make sure the controller board is in fact fried, but I <em>think</em> I might JUST have a fried board and not a fried motor.</p>
|
<p>Yes - you should be able to turn the extruder by hand when it is unplugged and therefore not powered.</p>
<p>The V2 comes with a blue plastic knob for this purpose, it may be too small to turn the shaft by hand.</p>
<p>When powered and "steppers enabled" the motors need a lot more force to overcome, but even that can be done by hand or a machine crash.</p>
<p>If you can't turn the extruder at all, its probably toast. That you've tested other ports on the board is excellent problem solving.</p>
<p>Whatever damaged the motor has likely damaged the board too, or vise versa.</p>
<p>You likely need both parts replaced to get this printer working again. Could be expensive - you might want to compare cost of parts with cost of a new printer, remembering there may be other non-functional components still undiscovered.</p>
<p>Plausibly, with a dead extruder, you could slap a laser on this unit and make it a dedicated burner. The creality laser module is around $50 USD.</p>
|
<p>Criggie's answer is basically correct, but I disagree with the conclusion that it:</p>
<blockquote>
<p>Could be expensive - you might want to compare cost of parts with cost of a new printer, remembering there may be other non-functional components still undiscovered.</p>
</blockquote>
<p>If you want to turn the Ender 3 into a decent printer, the controller board is one of the components you want to replace anyway, since it comes with either (old models) extremely loud and poorly performing A4988 stepper drivers or (newer models) TMC2208 stepper drivers hard-wired in a mode where they don't work well and malfunction if you enable Linear Advance (which is critical to getting decent prints on a bowden extruder system). Good boardsthat are exact fits for the housing and cable connectors, with TMC2209 steppers that lack the above problems, can be had for $35 or so.</p>
<p>If the motor is dead, that's a pain but not expensive to replace. Equivalent motors are available for $15 or so all over the place, or you could make the upgrade to a light-weight geared direct drive extruder with pancake stepper instead of the large NEMA 17 (which negates pretty much all of the disadvantages of direct drive and gives you a much better printer than you started with).</p>
| 2,145
|
<p>I just don't get it.
I use cocos2d for development of a small game on the iPhone/Pod. The framework is just great, but I fail at touch detection. I read that you just need to overwrite the proper functions (e.g. "touchesBegan" ) in the implementation of a class which subclasses CocosNode. But it doesn't work. What could I do wrong?</p>
<p>the function:</p>
<pre><code>-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{NSLog(@"tickle, hihi!");}
</code></pre>
<p>did I get it totally wrong?</p>
|
<p>Layer is the only cocos2d class which gets touches.</p>
<p>The trick is that ALL instances of Layer get passed the touch events, one after the other, so your code has to handle this.</p>
<p>I did it like this:</p>
<pre><code>-(BOOL)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView: [touch view]];
CGPoint cLoc = [[Director sharedDirector] convertCoordinate: location];
float labelX = self.position.x - HALF_WIDTH;
float labelY = self.position.y - HALF_WIDTH;
float labelXWidth = labelX + WIDTH;
float labelYHeight = labelY + WIDTH;
if( labelX < cLoc.x &&
labelY < cLoc.y &&
labelXWidth > cLoc.x &&
labelYHeight > cLoc.y){
NSLog(@"WE ARE TOUCHED AND I AM A %@", self.labelString);
return kEventHandled;
} else {
return kEventIgnored;
}
</code></pre>
<p>}</p>
<p>Note that the cocos2d library has a "ccTouchesEnded" implementation, rather than the Apple standard. It allows you to return a BOOL indicating whether or not you handled the event.</p>
<p>Good luck!</p>
|
<p>-Make your scene conforms to protocol <code>CCTargetedTouchDelegate</code>
-Add This line to <code>init</code> of your scene:</p>
<pre><code>[[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];
</code></pre>
<p>-Implement these functions:</p>
<pre><code>- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
return YES;
}
-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
//here touch is ended
}
</code></pre>
| 49,476
|
<p>When I try to add a HTTP header key/value pair on a <code>WebRequest</code> object, I get the following exception:</p>
<blockquote>
<p>This header must be modified using the appropriate property</p>
</blockquote>
<p>I've tried adding new values to the <code>Headers</code> collection by using the Add() method but I still get the same exception.</p>
<pre><code>webRequest.Headers.Add(HttpRequestHeader.Referer, "http://stackoverflow.com");
</code></pre>
<p>I can get around this by casting the WebRequest object to a HttpWebRequest and setting the properties such as <code>httpWebReq.Referer ="http://stackoverflow.com"</code>, but this only works for a handful of headers that are exposed via properties.</p>
<p>I'd like to know if there's a way to get a finer grained control over modifying headers with a request for a remote resource.</p>
|
<p>If you need the short and technical answer go right to the last section of the answer.</p>
<p>If you want to know better, read it all, and i hope you'll enjoy...</p>
<hr>
<p>I countered this problem too today, and what i discovered today is that:</p>
<ol>
<li><p>the above answers are true, as:</p>
<p>1.1 it's telling you that the header you are trying to add already exist and you should then modify its value using the appropriate property (the indexer, for instance), instead of trying to add it again.</p>
<p>1.2 Anytime you're changing the headers of an <code>HttpWebRequest</code>, you need to use the appropriate properties on the object itself, if they exist.</p></li>
</ol>
<p>Thanks FOR and Jvenema for the leading guidelines...</p>
<ol start="2">
<li><p>But, What i found out, and <strong>that was the missing piece in the puzzle</strong> is that:</p>
<p>2.1 The <code>WebHeaderCollection</code> class is generally accessed through <code>WebRequest</code>.Headers or <code>WebResponse</code>.Headers. <strong>Some common headers are considered restricted and are either exposed directly by the API (such as Content-Type) or protected by the system and cannot be changed.</strong></p></li>
</ol>
<p>The restricted headers are:</p>
<ul>
<li><code>Accept</code></li>
<li><code>Connection</code></li>
<li><code>Content-Length</code></li>
<li><code>Content-Type</code></li>
<li><code>Date</code></li>
<li><code>Expect</code></li>
<li><code>Host</code></li>
<li><code>If-Modified-Since</code></li>
<li><code>Range</code></li>
<li><code>Referer</code></li>
<li><code>Transfer-Encoding</code></li>
<li><code>User-Agent</code></li>
<li><code>Proxy-Connection</code></li>
</ul>
<hr>
<p>So, next time you are facing this exception and don't know how to solve this, remember that there are some restricted headers, and the solution is to modify their values using the appropriate property explicitly from the <code>WebRequest</code>/<code>HttpWebRequest</code> class.</p>
<hr>
<p>Edit: (useful, from comments, comment by user <a href="https://stackoverflow.com/questions/239725/cannot-set-some-http-headers-when-using-system-net-webrequest#comment15470171_4752359">Kaido</a>)</p>
<blockquote>
<p>Solution is to check if the header exists already or is restricted (<code>WebHeaderCollection.IsRestricted(key)</code>) before calling add</p>
</blockquote>
|
<p>I'm using just: </p>
<pre><code>request.ContentType = "application/json; charset=utf-8"
</code></pre>
| 29,668
|
<p>Sometimes I break long conditions in <code>if</code>s onto several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way?</p>
|
<p>You don't need to use 4 spaces on your second conditional line. Maybe use:</p>
<pre><code>if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Also, don't forget the whitespace is more flexible than you might think:</p>
<pre><code>if (
cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'
):
do_something
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Both of those are fairly ugly though.</p>
<p>Maybe lose the brackets (the <a href="https://www.python.org/dev/peps/pep-0008/#multiline-if-statements" rel="noreferrer">Style Guide</a> discourages this though)?</p>
<pre><code>if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and cond4 == 'val4':
do_something
</code></pre>
<p>This at least gives you some differentiation.</p>
<p>Or even:</p>
<pre><code>if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something
</code></pre>
<p>I think I prefer:</p>
<pre><code>if cond1 == 'val1' and \
cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something
</code></pre>
<p>Here's the <a href="https://www.python.org/dev/peps/pep-0008/#multiline-if-statements" rel="noreferrer">Style Guide</a>, which (since 2010) recommends using brackets.</p>
|
<p>Pack your conditions into a list, then do smth. like:</p>
<pre><code>if False not in Conditions:
do_something
</code></pre>
| 21,908
|
<p>Question number three in my quest to properly understand MVC <em>before</em> I implement it:</p>
<p>I have two cases in mind:</p>
<ol>
<li>The primary application
window needs to launch the
preferences window. (One View
invoking another View.)</li>
<li>The primary Model for an application
needs to access a property
in the preferences Model. (One Model
accessing another Model.)</li>
</ol>
<p>These questions are related in that they both involve communication across Model-View-Controller triplets, a topic that I haven't found much discussion of in my Googling. </p>
<p>The obvious way to fix this is to wrap everything in a top-level "application" object that handles transactions between Models and allows Controllers to invoke one another's methods. I have seen this implemented, but I'm not convinced its a good idea. I can also see possibilities involving Controllers observing more than one Model and responding to more than one View, but this seems like its going to become very cluttered and difficult to follow.</p>
<p>Suggestions on how best to implement this sort of cross-talk? I feel like its a very obvious question, but I've been unable to find a well-documented solution.</p>
<p>On a broader note, if anyone has a link that shows typical approaches to these sorts of MVC issues, I would love to see it. I haven't had much luck finding solid, non-trivial references. Examples in Python would be lovely, but I'll gladly read anything.</p>
<p><strong>Edit 1</strong>:</p>
<p>I see some pretty interesting things being said below and in general no-one seems to have a problem with the approach I've described. It is already almost a lazy form of the FrontController design that Vincent is describing. I certainly don't foresee any problems in implementing that pattern, however, it doesn't seem that anyone has really addressed the question in regards to communication amongst Models. All the answers seem to be addressing communication among objects in a single Model. I'm more interested in maintaining separate Models for separate components of the application, so that I'm not stuffing fifty state properties into a single Model class. Should I be maintaining them as sub-Models instead?</p>
|
<p>You may want to consider looking up the Front Controller design pattern.</p>
<blockquote>
<p>The Front Controller pattern defines a single component that is responsible for processing application requests. A front controller centralizes functions such as view selection, security, and templating, and applies them consistently across all pages or views. Consequently, when the behavior of these functions need to change, only a small part of the application needs to be changed: the controller and its helper classes. </p>
</blockquote>
<p>This way all requests from the view goes to the FrontController who then decides which specific action (controller) to invoke. Sometimes, it could forward straight to another view as in your first case.</p>
<p>There is no problem with multiple objects in the model talking to each other. In fact that will be very common. The way I see it, all the objects in the Model act like one component to represent the data and operations on the data.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms978723.aspx" rel="nofollow noreferrer">This</a> article might help. And <a href="http://java.sun.com/blueprints/patterns/FrontController.html" rel="nofollow noreferrer">this</a> one.</p>
|
<p>Model does not mean a single model object. The model is the subset of the entirety of your domain model which is directly related to the controller actions and the views in question.</p>
| 28,205
|
<p>Is there any lib that convert very long numbers to string just copying the data?</p>
<p>These one-liners are too slow:</p>
<pre><code>def xlong(s):
return sum([ord(c) << e*8 for e,c in enumerate(s)])
def xstr(x):
return chr(x&255) + xstr(x >> 8) if x else ''
print xlong('abcd'*1024) % 666
print xstr(13**666)
</code></pre>
|
<p>You want the struct module.</p>
<pre><code>packed = struct.pack('l', 123456)
assert struct.unpack('l', packed)[0] == 123456
</code></pre>
|
<p>Performance of <code>cPickle</code> vs. <code>marshal</code> (Python 2.5.2, Windows):</p>
<pre><code>python -mtimeit -s"from cPickle import loads,dumps;d=13**666" "loads(dumps(d))"
1000 loops, best of 3: 600 usec per loop
python -mtimeit -s"from marshal import loads,dumps;d=13**666" "loads(dumps(d))"
100000 loops, best of 3: 7.79 usec per loop
python -mtimeit -s"from pickle import loads,dumps;d= 13**666" "loads(dumps(d))"
1000 loops, best of 3: 644 usec per loop
</code></pre>
<p><code>marshal</code> is much faster.</p>
| 42,627
|
<p>I'm using the <code>cacheCounter</code> in <code>CakePHP</code>, which increments a counter for related fields.</p>
<p>Example, I have a Person table a Source table. Person.source_id maps to a row in the Source table. Each person has one Source, and each Source has none or many Person rows.</p>
<p><code>cacheCounter</code> is working great when I change the value of a source on a person. It increments <code>Source.Person_Count</code>. Cool.</p>
<p>But when it increments, it adds it to the destination source for a person, but doesn't remove it from the old value. I tried <code>updateCacheControl()</code> in <code>afterSave</code>, but that didn't do anything.</p>
<p>So then I wrote some code in my model for <code>afterSave</code> that would subtract the source source_id, but it always did this even when I wasn't even changing the <code>source_id</code>. (So the count went negative).</p>
<p>My question: Is there a way to tell if a field was changed in the model in <code>CakePHP</code>?</p>
|
<p>To monitor changes in a field, you can use this logic in your model with no changes elsewhere required:</p>
<pre><code>function beforeSave() {
$this->recursive = -1;
$this->old = $this->find(array($this->primaryKey => $this->id));
if ($this->old){
$changed_fields = array();
foreach ($this->data[$this->alias] as $key =>$value) {
if ($this->old[$this->alias][$key] != $value) {
$changed_fields[] = $key;
}
}
}
// $changed_fields is an array of fields that changed
return true;
}
</code></pre>
|
<p>See if the "save" uses some sort of DBAL call that returns "affected rows", usually this is how you can judge if the last query changed data, or if it didn't. Because if it didn't, the affected rows after an UPDATE-statement are 0.</p>
| 14,098
|
<p>I have an application that uses <code>window.open()</code> to generate dynamic popups. Unfortunately, I've had trouble creating the content of the new windows using the standard DOM functions (<code>createElement</code>, <code>appendChild</code>), and I've gone to using <code>document.write()</code> to generate the page.</p>
<p>Concretely, how can I go from this:</p>
<pre><code>function writePopup()
{
var popup = window.open("", "popup", "height=400px, width=400px");
var doc = popup.document;
doc.write("<html>");
doc.write("<head>");
doc.write("<title>Written Popup</title>");
doc.write("</head>");
doc.write("<body>");
doc.write("<p>Testing Write</p>");
doc.write("</body>");
doc.write("</html>");
doc.close();
}
</code></pre>
<p>To a function that creates the same popup using the DOM? </p>
<p>Edit: I did consider using an absolutely positioned element to simulate a popup, and though it looks better, the users need to be able to print the information being shown.</p>
|
<p>Why not use a library function such as <a href="http://plugins.jquery.com/project/modaldialog" rel="nofollow noreferrer">http://plugins.jquery.com/project/modaldialog</a> instead of reinventing the wheel?</p>
<p>[EDIT] OR</p>
<pre><code>function writePopup(){
var popup = window.open("", "_blank", "height=400px, width=400px");
var doc = popup.document;
doc.title = 'Written Popup';
var p = doc.createElement('p');
p.innerHTML = 'Testing Write';
doc.body.appendChild(p);
}
</code></pre>
|
<p>Would it be possible to have another page that generates the dynamic content, and pop it open, passing arguments that identify the content you want generated, instead of trying to write to a new window?</p>
| 33,266
|
<p>Does anyone know how I can check to see if a directory is writeable in PHP? </p>
<p>The function <a href="http://php.net/manual/en/function.is-writable.php" rel="nofollow noreferrer"><code>is_writable</code></a> doesn't work for folders.</p>
<blockquote>
<p>Edit: It does work. See the accepted answer.</p>
</blockquote>
|
<p>Yes, it does work for folders....</p>
<blockquote>
<p>Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable. </p>
</blockquote>
|
<p>this is how I do it:</p>
<p>create a file with <code>file_put_contents()</code> and check the return value, if it is positive (number of written in Bytes) then you can go ahead and do what you have to do, if it is FALSE then it is not writable </p>
<pre><code>$is_writable = file_put_contents('directory/dummy.txt', "hello");
if ($is_writable > 0) echo "yes directory it is writable";
else echo "NO directory it is not writable";
</code></pre>
<p>then you can delete the dummy file by using unlink()</p>
<pre><code>unlink('directory/dummy.txt');
</code></pre>
| 13,446
|
<p>I need to find out the file/directory name that a .lnk is pointing to using c#.</p>
<p>What is the simplest way to do this?</p>
<p>Thanks.</p>
|
<p>I wrote this for video browser, it works really well </p>
<pre><code>#region Signitures imported from http://pinvoke.net
[DllImport("shfolder.dll", CharSet = CharSet.Auto)]
internal static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, StringBuilder lpszPath);
[Flags()]
enum SLGP_FLAGS
{
/// <summary>Retrieves the standard short (8.3 format) file name</summary>
SLGP_SHORTPATH = 0x1,
/// <summary>Retrieves the Universal Naming Convention (UNC) path name of the file</summary>
SLGP_UNCPRIORITY = 0x2,
/// <summary>Retrieves the raw path name. A raw path is something that might not exist and may include environment variables that need to be expanded</summary>
SLGP_RAWPATH = 0x4
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
struct WIN32_FIND_DATAW
{
public uint dwFileAttributes;
public long ftCreationTime;
public long ftLastAccessTime;
public long ftLastWriteTime;
public uint nFileSizeHigh;
public uint nFileSizeLow;
public uint dwReserved0;
public uint dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;
}
[Flags()]
enum SLR_FLAGS
{
/// <summary>
/// Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set,
/// the high-order word of fFlags can be set to a time-out value that specifies the
/// maximum amount of time to be spent resolving the link. The function returns if the
/// link cannot be resolved within the time-out duration. If the high-order word is set
/// to zero, the time-out duration will be set to the default value of 3,000 milliseconds
/// (3 seconds). To specify a value, set the high word of fFlags to the desired time-out
/// duration, in milliseconds.
/// </summary>
SLR_NO_UI = 0x1,
/// <summary>Obsolete and no longer used</summary>
SLR_ANY_MATCH = 0x2,
/// <summary>If the link object has changed, update its path and list of identifiers.
/// If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine
/// whether or not the link object has changed.</summary>
SLR_UPDATE = 0x4,
/// <summary>Do not update the link information</summary>
SLR_NOUPDATE = 0x8,
/// <summary>Do not execute the search heuristics</summary>
SLR_NOSEARCH = 0x10,
/// <summary>Do not use distributed link tracking</summary>
SLR_NOTRACK = 0x20,
/// <summary>Disable distributed link tracking. By default, distributed link tracking tracks
/// removable media across multiple devices based on the volume name. It also uses the
/// Universal Naming Convention (UNC) path to track remote file systems whose drive letter
/// has changed. Setting SLR_NOLINKINFO disables both types of tracking.</summary>
SLR_NOLINKINFO = 0x40,
/// <summary>Call the Microsoft Windows Installer</summary>
SLR_INVOKE_MSI = 0x80
}
/// <summary>The IShellLink interface allows Shell links to be created, modified, and resolved</summary>
[ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")]
interface IShellLinkW
{
/// <summary>Retrieves the path and file name of a Shell link object</summary>
void GetPath([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out WIN32_FIND_DATAW pfd, SLGP_FLAGS fFlags);
/// <summary>Retrieves the list of item identifiers for a Shell link object</summary>
void GetIDList(out IntPtr ppidl);
/// <summary>Sets the pointer to an item identifier list (PIDL) for a Shell link object.</summary>
void SetIDList(IntPtr pidl);
/// <summary>Retrieves the description string for a Shell link object</summary>
void GetDescription([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName);
/// <summary>Sets the description for a Shell link object. The description can be any application-defined string</summary>
void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
/// <summary>Retrieves the name of the working directory for a Shell link object</summary>
void GetWorkingDirectory([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath);
/// <summary>Sets the name of the working directory for a Shell link object</summary>
void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);
/// <summary>Retrieves the command-line arguments associated with a Shell link object</summary>
void GetArguments([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath);
/// <summary>Sets the command-line arguments for a Shell link object</summary>
void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
/// <summary>Retrieves the hot key for a Shell link object</summary>
void GetHotkey(out short pwHotkey);
/// <summary>Sets a hot key for a Shell link object</summary>
void SetHotkey(short wHotkey);
/// <summary>Retrieves the show command for a Shell link object</summary>
void GetShowCmd(out int piShowCmd);
/// <summary>Sets the show command for a Shell link object. The show command sets the initial show state of the window.</summary>
void SetShowCmd(int iShowCmd);
/// <summary>Retrieves the location (path and index) of the icon for a Shell link object</summary>
void GetIconLocation([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath,
int cchIconPath, out int piIcon);
/// <summary>Sets the location (path and index) of the icon for a Shell link object</summary>
void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
/// <summary>Sets the relative path to the Shell link object</summary>
void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved);
/// <summary>Attempts to find the target of a Shell link, even if it has been moved or renamed</summary>
void Resolve(IntPtr hwnd, SLR_FLAGS fFlags);
/// <summary>Sets the path and file name of a Shell link object</summary>
void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);
}
[ComImport, Guid("0000010c-0000-0000-c000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IPersist
{
[PreserveSig]
void GetClassID(out Guid pClassID);
}
[ComImport, Guid("0000010b-0000-0000-C000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IPersistFile : IPersist
{
new void GetClassID(out Guid pClassID);
[PreserveSig]
int IsDirty();
[PreserveSig]
void Load([In, MarshalAs(UnmanagedType.LPWStr)]
string pszFileName, uint dwMode);
[PreserveSig]
void Save([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName,
[In, MarshalAs(UnmanagedType.Bool)] bool fRemember);
[PreserveSig]
void SaveCompleted([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName);
[PreserveSig]
void GetCurFile([In, MarshalAs(UnmanagedType.LPWStr)] string ppszFileName);
}
const uint STGM_READ = 0;
const int MAX_PATH = 260;
// CLSID_ShellLink from ShlGuid.h
[
ComImport(),
Guid("00021401-0000-0000-C000-000000000046")
]
public class ShellLink
{
}
#endregion
public static string ResolveShortcut(string filename)
{
ShellLink link = new ShellLink();
((IPersistFile)link).Load(filename, STGM_READ);
// TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files.
// ((IShellLinkW)link).Resolve(hwnd, 0)
StringBuilder sb = new StringBuilder(MAX_PATH);
WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();
((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);
return sb.ToString();
}
</code></pre>
|
<p>Or simply test <code>mydir</code> and if it does not exists, <code>mydir.lnk</code> with <code>File.Exixts()</code>.</p>
<p>Works for a file.</p>
| 16,825
|
<p>In an UML component diagram, how does one tag or identify a component as a database, so that it's easily recognizable? In the old days there was the cylinder symbol for showing database but that's not part of the UML. Same goes for an application server for instance, how would that be shown?</p>
<p>Are stereotypes applicable here? Can the component symbol be enhanced with graphical elements?</p>
|
<p>Just use the <code><<database>></code> for the component diagram.</p>
<p>For a more detailed information check out this article: <a href="http://www.sparxsystems.com.au/resources/uml_datamodel.html" rel="noreferrer">http://www.sparxsystems.com.au/resources/uml_datamodel.html</a></p>
|
<p>You tag databases <code><<database>></code> and servers as (it appears) <code><<infrastructure>></code> <a href="http://www.agilemodeling.com/artifacts/componentDiagram.htm" rel="nofollow noreferrer">according to Scott Ambler</a>. I pulled this information from Figure 1, but I would recommend reading this article (and his other articles - they are good reads).</p>
<p>Something else I want to point out - UML is just one method of modeling. In formal documentation, I try to adhere to the standard. However, when planning and documenting for the team, I use whatever makes sense and is understood by the team. For you, that might mean putting a cylinder labeled "DB" or the name of the DB in the component box.</p>
| 30,631
|
<p>Is it good practice to have more than one <code>try{} catch{}</code> statement per method?</p>
|
<p>In my point of view it is good practice to have each method handle only a single task. As such you'll rarely need to have multiple try/catch blocks within a single method. However, I don't see any problems with it. </p>
<p>As Lisa pointed out you should catch specific exceptions and <em>only</em> catch the exceptions the method can actually handle. </p>
|
<p>I would say that depends. To me, it looks a little sloppy having all these try-catches everywhere. I try to consolidate to a try block with many catches. Sometimes this doesn't work, you may need to have them separate, but to keep things readable, that's how I prefer it at least.</p>
<p>Also if your method is too long of course, you can extract methods to distribute your try catching.</p>
| 48,662
|
<p>Is it possible to write connect and open a SQL Compact 3.5 database from within MS Access 2003? I want to be able to use MS Access 2003 to manipulate data in a SQL Compact 3.5 database. If it is possible, then what statements would be used to open the database?</p>
|
<p>This is just an idea and I can't confirm that it will work, but given that SQL Compact lacks an ODBC driver and you can't have linked tables, perhaps you can use an OLEDB connect string for SQL Compact as the Source Connect String of a saved QueryDef in Access. If you can get that to work you may be able to create a saved QueryDef for each table, and then utilize them as though the queries were linked tables.</p>
<p>I can't test it on my machine because the only OLEDB provider I have installed is Jet, and Access doesn't seem to like that.</p>
<p>But it might be worth a try. Possibly it's not going to work, as I can't find anywhere that anyone has done this in Access. But I don't really see why it shouldn't work.</p>
<p>Again, I could simply be wrong, though.</p>
|
<p>Though I did not try it specifically with SQL Compact, connecting to the server should be standard:</p>
<ol>
<li>Check that the ADODB file (msado21.tlb) is correctly refernced in your available tools</li>
<li><p>Write down your connection string somewhere like this one: </p>
<p>MyConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=YourDatabaseName;Data Source=YourSQLServerInstanceName"</p>
<p>This string is written for an 'integrated security' context. In cas you want to change it for an SQL security context, please check <a href="http://www.connectionstrings.com/" rel="nofollow noreferrer">here</a> to update the string. Ideally, this string should be declared as a public variable in your code.</p></li>
</ol>
<p>Once this is done, you can open an ADODB recordset and begin to manipulate it:</p>
<pre><code>public sub connectionTest
Dim activeConnection as ADODB.connection, _
activeRecordset as ADODB.recordset
Set activeConnection = New ADODB.connection
activeConnection.connectionString = myCOnnectionString
activeConnection.open
set activeRecordset = New ADODB.recordset
'this will open a read-only recordset'
activeRecordset.open _
"SELECT * FROM myTableName", _
activeConnection, _
adOpenStatic, _
adLockReadOnly
if activeRecordset.EOF and activeRecordset.BOF then
debug.print "No records in this table"
else
activeRecordset.moveFirst
do while not activeRecordset.EOF
debug.print activerecordset.fields("myFieldName").value
activeRecordset.moveNext
loop
endif
activeRecordset.close
set activeRecordset = nothing
activeConnection.close
set activeConnection = nothing
end sub
</code></pre>
| 42,517
|
<p>Going back to my previous question on OCSP, does anybody know of "reliable" OCSP libraries for Python, Java and C?</p>
<p>I need "client" OCSP functionality, as I'll be checking the status of Certs against an OCSP responder, so responder functionality is not that important.</p>
<p>Thanks</p>
|
<p>Have you check pyOpenSSL.. am sure openssl supports ocsp and python binding may support it</p>
|
<p><a href="http://www.openssl.org/" rel="nofollow noreferrer">OpenSSL</a> is the most widely used product for OCSP in C. It's quite reliable, although incredibly obtuse. I'd recommend looking at apps/ocsp.c for a pretty good example of how to make OCSP requests and validate responses.</p>
<p>Vista and Server 2008 have built-in OCSP support in CAPI; check out <a href="http://msdn.microsoft.com/en-us/library/aa377167.aspx" rel="nofollow noreferrer">CertVerifyRevocation</a>.</p>
| 17,325
|
<p>I'm building a static ASP.NET site (using Masterpages and a few forms) and I'm about to release it onto my production server.</p>
<p>I know about changing <code><compilation debug="true"></code> to false, but I'm wondering what other things I can do to obtain the highest speed possible. There is no data access in the site, it's all static content.</p>
<p>Does anyone have a checklist they run through or know of a good resource for setting up sites in a production environment, with a focus on performance?</p>
<p><strong>Checklist so far</strong> (Feel free to edit this yourself with any worth additions)</p>
<ol>
<li>Make sure <code><compilation debug="false" /></code> is actually set to <strong>false</strong> in Web.Config</li>
<li>Make sure <code><trace enabled="false" /></code> is actually set to <strong>false</strong> in Web.Config</li>
<li>Set necessary read/write/modify folder permissions for site</li>
<li>Enable GZIP in IIS (reduces size of pages/css/javascript dramatically)</li>
<li>Have you considered OutputCaching for any pages / controls?</li>
<li>Consider setting up Web Tests (Eg WatiN for .NET) to make sure functionality on your site is still working ok</li>
<li>Make sure it isn't Friday afternoon!</li>
</ol>
|
<p>If you're writing any log or output files, make sure the proper folder permissions are setup in the production environment. Typically debug/test environments are much more lax on file read/write permissions than production.</p>
|
<p>You should read this:<br>
<a href="https://stackoverflow.com/questions/72394/what-should-a-developer-know-before-building-a-public-web-site">https://stackoverflow.com/questions/72394/what-should-a-developer-know-before-building-a-public-web-site</a></p>
<p>It's currently the 9th highest voted question on SO and in the top 3 most favorited. The caveat is that it's platform agnostic, so it's missing some ASP.Net-specific items.</p>
| 41,245
|
<p>I have an ASP.NET web page with a Login control on it. When I hit Enter, the Login button doesn't fire; instead the page submits, doing nothing.</p>
<p>The standard solution to this that I've found online is to enclose the Login control in a Panel, then set the Panel default button. But apparently that doesn't work so well if the page has a master page. I've tried setting the default button in code with <em>control</em>.ID, <em>control</em>.ClientID, and <em>control</em>.UniqueID, and in each case I get:</p>
<blockquote>
<p>The DefaultButton of panelName must be the ID of a control of type IButtonControl.</p>
</blockquote>
<p>I'm sure there's a way to do this with JavaScript, but I'd really like to do it with plain old C# code if possible. Is it possible?</p>
|
<p>This should be helpful: <a href="http://weblogs.asp.net/jgalloway/archive/2007/10/03/asp-net-setting-the-defaultbutton-for-a-login-control.aspx" rel="noreferrer">http://weblogs.asp.net/jgalloway/archive/2007/10/03/asp-net-setting-the-defaultbutton-for-a-login-control.aspx</a></p>
<p>You can use the following to reference the button within the Login control template:</p>
<pre><code>DefaultButton="Login$LoginButton"
</code></pre>
<p>Basically, you can define a DefaultButton not just on the Form level, but also on individual Panel level, as long as the focus is within the panel, the default button for the panel will be used if you hit "Enter"</p>
|
<p>Based on your good answers, made a custom control that<br/>
enables a Page to have several default buttons based on which panel which is in focus.<br/>
It overrides Panel's OnLoad method and DefaultButton property.</p>
<pre><code>public class DefaultButtonPanel:Panel
{
protected override void OnLoad(EventArgs e)
{
if(!string.IsNullOrEmpty(DefaultButton))
{
LinkButton btn = FindControl(DefaultButton) as LinkButton;
if(btn != null)
{
Button defaultButton = new Button {ID = DefaultButton.Replace(Page.IdSeparator.ToString(), "_") + "_Default", Text = " "};
defaultButton.Style.Add("display", "none");
PostBackOptions p = new PostBackOptions(btn, "", null, false, true, true, true, true, btn.ValidationGroup);
defaultButton.OnClientClick = Page.ClientScript.GetPostBackEventReference(p) + "; return false;";
Controls.Add(defaultButton);
DefaultButton = defaultButton.ID;
}
}
base.OnLoad(e);
}
/// <summary>
/// Set the default button in a Panel.
/// The UniqueID of the button, must be relative to the Panel's naming container UniqueID.
///
/// For example:
/// Panel UniqueID is "Body$Content$pnlLogin"
/// Button's UniqueID is "Body$Content$ucLogin$btnLogin"
/// (because it's inside a control called "ucLogin")
/// Set Panel.DefaultButton to "ucLogin$btnLogin".
/// </summary>
/// <param name="panel"></param>
/// <param name="button"></param>
public override string DefaultButton
{
get
{
return base.DefaultButton;
}
set
{
string uniqueId = value;
string panelIdPrefix = this.NamingContainer.UniqueID + Page.IdSeparator;
if (uniqueId.StartsWith(panelIdPrefix))
{
uniqueId = uniqueId.Substring(panelIdPrefix.Length);
}
base.DefaultButton = uniqueId;
}
}
}
</code></pre>
| 24,645
|
<p>I need to write a browser interface for an application running embedded on a single board computer (<a href="http://www.gumstix.com/store/catalog/product_info.php?products_id=178" rel="nofollow noreferrer">Gumstix Verdex</a> for anyone who's interested), so I won't be able to use any web frameworks due to space and processor constraints (and availability for the environment I'm running in). I'm limited to the core Python and cgi modules to create pages that will communicate with a C++ application.</p>
<p>Can anyone recommend a good resource (web or book form, but books are preferred) for learning CGI programming in Python?</p>
<p>What I need the application to do is fairly simple. I have a C++ program running on the same device and I need to create a browser based user interface so the configuration settings of that application can be changed. The UI needs to communicate with the C++ application, where the final data validation will be done. Preliminary validation can be done on the UI using Javascript, then again on the server using Python, but the final validation has to be done in the application itself, since it's getting its initial config from a file anyway. The configuration data takes all forms (booleans, ints, floats, and strings).</p>
|
<p>One of the biggest resources for CGI programming is the <a href="https://web.archive.org/web/20090413024447/http://hoohoo.ncsa.uiuc.edu/cgi/" rel="nofollow noreferrer">CGI homepage</a>. Once you're done with that, familiarizing yourself with the <a href="https://docs.python.org/library/cgi.html" rel="nofollow noreferrer">cgi</a> and <a href="https://docs.python.org/library/cgitb.html" rel="nofollow noreferrer">cgitb</a> modules should be your next task.</p>
<p>But don't discount learning <a href="http://wsgi.org/" rel="nofollow noreferrer">WSGI</a> <a href="https://docs.python.org/library/wsgiref.html" rel="nofollow noreferrer">(libref)</a> and using a CGI-to-WSGI adaptor such as <a href="http://www.saddi.com/software/flup/" rel="nofollow noreferrer">flup</a>.</p>
|
<ul>
<li><a href="http://www.cs.virginia.edu/~lab2q/" rel="nofollow noreferrer">http://www.cs.virginia.edu/~lab2q/</a></li>
<li><a href="http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python/" rel="nofollow noreferrer">http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python/</a></li>
<li><a href="http://gnosis.cx/publish/programming/feature_5min_python.html" rel="nofollow noreferrer">http://gnosis.cx/publish/programming/feature_5min_python.html</a></li>
</ul>
<p>All found via google...</p>
<p>And take a look at pyblosxom as well: <a href="http://pyblosxom.svn.sourceforge.net/viewvc/pyblosxom/" rel="nofollow noreferrer">http://pyblosxom.svn.sourceforge.net/viewvc/pyblosxom/</a> it's a weblog system written in python, uses CGI.</p>
| 28,128
|
<p>I have a bunch of legacy documents that are HTML-like. As in, they look like HTML, but have additional made up tags that aren't a part of HTML</p>
<pre><code><strong>This is an example of a <pseud-template>fake tag</pseud-template></strong>
</code></pre>
<p>I need to parse these files. PHP is the only only tool available. The documents don't come close to being well formed XML. </p>
<p>My original thought was to use the loadHTML methods on PHPs DOMDocument. However, these methods choke on the make up HTML tags, and will refuse to parse the string/file.</p>
<pre><code>$oDom = new DomDocument();
$oDom->loadHTML("<strong>This is an example of a <pseud-template>fake tag</pseud-template></strong>");
//gives us
DOMDocument::loadHTML() [function.loadHTML]: Tag pseud-template invalid in Entity, line: 1 occured in ....
</code></pre>
<p>The only solution I've been able to come up with is to pre-process the files with string replacement functions that will remove the invalid tags and replace them with a valid HTML tag (maybe a span with an id of the tag name).</p>
<p>Is there a more elegant solution? A way to let DOMDocument know about additional tags to consider as valid? Is there a different, robust HTML parsing class/object out there for PHP?</p>
<p>(if it's not obvious, I don't consider regular expressions a valid solution here)</p>
<p><strong>Update</strong>: The information in the fake tags is part of the goal here, so something like Tidy isn't an option. Also, I'm after something that does the some level, if not all, of well-formedness cleanup for me, which is why I was looking the DomDocument's loadHTML method in the first place.</p>
|
<p>You can suppress warnings with <a href="http://www.php.net/manual/en/function.libxml-use-internal-errors.php" rel="noreferrer"><code>libxml_use_internal_errors</code></a>, while loading the document. Eg.:</p>
<pre><code>libxml_use_internal_errors(true);
$doc = new DomDocument();
$doc->loadHTML("<strong>This is an example of a <pseud-template>fake tag</pseud-template></strong>");
libxml_use_internal_errors(false);
</code></pre>
<p>If, for some reason, you need access to the warnings, use <a href="http://www.php.net/manual/en/function.libxml-get-errors.php" rel="noreferrer"><code>libxml_get_errors</code></a></p>
|
<p>My quick and dirty solution to this problem was to run a loop that matches my list of custom tags with a regular expression. The regexp doesn't catch tags that have another inner custom tag inside them. </p>
<p>When there is a match, a function to process that tag is called and returns the "processed HTML". If that custom tag was inside another custom tag than the parent becomes childless by the fact that actual HTML was inserted in place of the child, and it will be matched by the regexp and processed at the next iteration of the loop. </p>
<p>The loop ends when there are no childless custom tags to be matched. Overall it's iterative (a while loop) and not recursive.</p>
| 9,223
|
<p>What'd also interest me is which have more or less dependencies.</p>
|
<p>I'm using <a href="http://coderay.rubychan.de/" rel="nofollow noreferrer">Coderay</a> (<a href="http://blog.logeek.fr/2008/3/31/data-visualization-with-ruby-and-rmagick-where-are-those-bikes" rel="nofollow noreferrer">see it in action at the bottom of this article</a>)</p>
<p>Not sure how many (if any) dependencies it has.</p>
|
<p><a href="http://www.google.hu/search?q=ruby+syntax+highlighting+library&btnG=Keres%C3%A9s&hl=hu&sa=2" rel="nofollow noreferrer">Google is our friend</a>...</p>
<p>First hit: <a href="http://syntax.rubyforge.org/chapter-1.html#s1" rel="nofollow noreferrer">http://syntax.rubyforge.org/chapter-1.html#s1</a></p>
| 27,268
|
<p>I am writing a C# program which captures signals from a external device, and sends keystrokes to another application. I am using SendKeys and it works fine.</p>
<p>SendKeys does "press" a key by holding and releasing it immediately. I would like to make it push key and release it at will.</p>
<p>My question is : "is there a way to send a "push" signal to a key, then a "release" signal after a certain amount of time ?"</p>
<p>I am not sure SendKeys is able to do this. Any clue ?</p>
|
<p>I don't think it's possible from .NET directly
You could try using keybd_event native call by p/invoking the function as described here: <a href="http://pinvoke.net/default.aspx/user32.keybd_event" rel="nofollow noreferrer">http://pinvoke.net/default.aspx/user32.keybd_event</a></p>
<p>The MSDN for keybd_event is here: <a href="http://msdn.microsoft.com/en-us/library/ms646304(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms646304(VS.85).aspx</a></p>
<p>Hope that helps!</p>
|
<p>I once was looking to do the same thing on powerpoint, to hide the cursor, and later to stop the slideshow. But it's hard and tricky as there's many top level windows appeared in powerpoint, also it's hard to figure out which part of the emulation failed if it doesn't work. After looking into the message queue using Spy++, I notice that the accelerator command was sent after the keypress, so instead, I emulated the accelerator command, and it works like charm. So you might want to look into alternative like this.</p>
| 20,771
|
<p>I am overriding a lot of SAP's Portal functionality in my current project. I have to create a custom fixed width framework, custom iView trays, custom KM API functionality, and more.</p>
<p>With all of these custom parts, I will not be using a lot of the style functionality implemented by SAP's Theme editor. What I would like to do is create an external CSS, store it outside of the Portal and reference it. Storing externally will allow for easier updates rather than storing the CSS within a portal application. It would also allow for all custom pieces to have their styles in once place.</p>
<p>Unfortunately, I've not found a way to gain access to the HEAD portion of the page that allows me to insert an external stylesheet. Portal Applications can do so using the IResource object to gain access to internal references, but not items on another server.</p>
<p>I'm looking for any ideas that would allow me to gain this functionality. I have <a href="https://www.sdn.sap.com/irj/sdn/thread?threadID=1046064&tstart=0" rel="nofollow noreferrer">x-posted on SAP's SDN</a>, but I suspect I'll get a better answer here.</p>
|
<p>I'd consider it dirty hack, but as a non-Portal developer I'd consider using JavaScript to insert a new link element in the head pointing to your new CSS file. Of course you'd have a flash of un-styled content because the script probably won't run until after part of the page has been downloaded and rendered, but it may be an adequate solution.</p>
|
<p>I hate that I'm answering my own question, but I did find a potential solution that's not documented well and in typical SAP fashion uses deprecated methods. So it might be a slightly less dirty hack than what Eric suggested. I found it through an unrelated SDN forum post.</p>
<p>Basically, you dive into the request object and gather the PortalNode. Once you have that, you ask it for a value of a IPortalResponse. This object can be cast to a PortalHtmlResponse. That object has a deprecated method called getHtmlDocument. Using that method, you can use some Html mirror objects to get the head and insert new links.</p>
<p>Sample:</p>
<pre><code>IPortalNode node = request.getNode().getPortalNode();
IPortalResponse resp = (IPortalResponse) node.getValue(IPortalResponse.class.getName());
if (resp instanceof PortalHtmlResponse) {
PortalHtmlResponse htmlResp = (PortalHtmlResponse) resp;
HtmlDocument doc = htmlResp.getHtmlDocument();
HtmlHead myHead = doc.getHead();
HtmlLink cssLink = new HtmlLink("http://myserver.com/css/mycss.css");
cssLink.setType("text/css");
cssLink.setRel("stylesheet");
myHead.addElement(cssLink);
}
</code></pre>
| 8,781
|
<p>I am currently using Telerik's carousel control, but it is lacking many features and is buggy. Is there a good control out there that looks the the coverflow control in itunes?</p>
|
<p>ElementFlow control is inside the codeplex project called <a href="http://www.codeplex.com/fluidkit" rel="nofollow noreferrer">FluidKit</a> - can be downloaded from <a href="http://www.codeplex.com/fluidkit" rel="nofollow noreferrer">here</a> </p>
|
<p><a href="http://www.telerik.com/products/wpf/carousel.aspx" rel="nofollow noreferrer">http://www.telerik.com/products/wpf/carousel.aspx</a>
<a href="http://www.devexpress.com/Products/NET/Controls/WPF/Carousel/dependency_properties.xml" rel="nofollow noreferrer">http://www.devexpress.com/Products/NET/Controls/WPF/Carousel/dependency_properties.xml</a></p>
<p>Both of these are FAR more versatile than your average cover flow clone (though they can easily just do that too if you want). I'd recommend Telerik well above DevExpress as WPF is still a relatively immature technology and DevExpress are very poor at keeping up with the tech game (they only JUST released a VS2010-supporting version of their DXperience suite despite promising it "just around the corner" since the start of January, while Telerik, ComponentOne etc all keep up with current tech. Not good enough for enterprise).</p>
| 19,800
|
<p>I generally try and keep all related entities in the same repository. The following are entities that have a relationship between the two (marked with indentation):</p>
<ul>
<li>User
<ul>
<li>UserPreference</li>
</ul></li>
</ul>
<p>So they make sense to go into a user repository. However users are often linked to many different entities, what would you do in the following example?</p>
<ul>
<li><p>User</p>
<ul>
<li>UserPrefence</li>
<li>Order</li>
</ul></li>
<li><p>Order</p>
<ul>
<li>Product</li>
</ul></li>
</ul>
<p>Order has a relationship with both product and user but you wouldn't put functionality for all 4 entities in the same repository. What do you do when you are dealing with the user entities and gathering order information? You may need extra information about the product and often ORMs will offer the ability of lazy loading. However if your product entity is in a separate repository to the user entity then surely this would cause a conflict between repositories?</p>
|
<p>In the Eric Evan's Domain Driven Design ( <a href="http://domaindrivendesign.org/index.htm" rel="nofollow noreferrer">http://domaindrivendesign.org/index.htm</a> ) sense of things you should first think about what about your Aggregates. You then build you repositories around those.</p>
<p>There are many techniques for handling Aggregates that relate to each other. The one that I use most often is to only allow Aggregates to relate to each other through a read only interface. One of the key thoughts behind Aggregates is that you can't change state of underlying objects without going through the root. So if Product and User are root Aggregates in your model than I can't update a Product if I got to it by going through User->Order->Product. I have to get the Product from the Product repository to edit it. (From a UI point of view you can make it look like you go User->Order->Product, but when you hit the Product edit screen you grab the entity from the Product Repository).</p>
<p>When you are looking at a Product (in code) by going from User->Order->Product you should be looking at a Product interface that does not have any way to change the underlying state of the Product (only gets no sets etc.)</p>
<p>Organize your Aggregates and therefor Repositories by how you use them. I can see User and Prodcut being their own Aggregates and having their own Repositories. I'm not sure from your description if Order should belong to User or also be stand alone.</p>
<p>Either way use a readonly interface when Aggregates relate. When you have to cross over from one Aggregate to the other go fetch it from its own Repository.</p>
<p>If your Repositories are caching then when you load an Order (through a User) only load the Product Id's from the database. Then load the details from the Product Repository using the Product Id. You can optimize a bit by loading any other invariants on the Product as you load the Order.</p>
|
<p>If SQL Server is your database, and by repository you mean a database, then I would just stick the information in whatever database makes sense and have a view in dependent databases that selects out of the other database via three-dot notation.</p>
| 48,171
|
<p>I get the concept of creating a business object or entity to represent something like a Person. I can then serialize the Person using a DTO and send it down to the client. If the client changes the object, it can have an IsDirty flag on there so when it gets sent back to the server I know to update it.</p>
<p>But what if I have an Order object? This has the main header informaton, customer, supplier, required date, etc. Then it has OrderItems which is a List< OrderItem>, being the items to be ordered. I want to be able to use this business object on my UI. So I have some textboxes hooked up to the location, supplier, required date, etc and a grid hooked up to OrderItems. Since OrderItems is a List I can easily add and delete records to it. But how do I track this, especially the deleted items. I don't want the deleted items to be visible in my grid and I shouldn't be able to iterate over them if I used foreach, because they have been deleted. But I still need to track the fact there was a deletion. How do I track the changes. I think I need to use a unit of work? But then the code seems to become quite complex. So then I wonder why not simply use DataTables and get the change tracking for free? But then I read how business objects are the way to go.</p>
<p>I’ve found various examples on simple Person examples, bnut not header-detail examples like Orders.</p>
<p>BTW using C# 3.5 for this.</p>
|
<p>Firstly, you can use an existing framework that addresses these issues, like CSLA.NET. The author of this framework has tackled these very issues. Go to <a href="http://www.rockfordlhotka.net/cslanet/" rel="nofollow noreferrer">http://www.rockfordlhotka.net/cslanet/</a> for this. Even if you don't use the full framework, the concepts are still applicable.</p>
<p>If you wanted to roll your own, what I've done in the past was to instead of using List for my collections, I've used a custom type derived from BindingList. Inhereting from BindingList allows you to override the behaviour of add/remove item. So you can for example have another internal collection of "delteted" items. Every time the overriden Remove method is called on your collection, put the item into the "deleted" collection, and then call the base implementation of the Remove method. You can do the same for added items or changed items.</p>
|
<p>The data objects don't track changes. The change tracking occurs on the DataContext and objects that you've retrieved through the DataContext. So in order to track changes you need to do the following:</p>
<pre><code>public class FooDataContext : DataContext
{
public Table<Order> Orders;
}
public class Order
{
[DbColumn(Identity = true)]
[Column(DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]
public int Id { get; set; }
[DbColumn(Default = "(getutcdate())")]
[Column(DbType = "DateTime", CanBeNull = false, IsDbGenerated = true)]
public DateTime DateCreated { get; set; }
[Column(DbType = "varchar(50)", CanBeNull = false, IsDbGenerated = false)]
public string Name { get; set; }
}
</code></pre>
<p>Now in your codebehind you can do something like:</p>
<pre><code>public void UpdateOrder(int id, string name)
{
FooDataContext db = new FooDataContext();
Order order = db.Orders.Where(o=>o.Id == id).FirstOrDefault();
if (order == null) return;
order.Name = name;
db.SubmitChanges();
}
</code></pre>
<p>I wouldn't recommend directly using the data context in the code behind, but this is a good way to get started with Linq To SQL. I would recommend putting all your database interactions in an external project and call from the GUI to the classes that encapsulate this behavior.</p>
<p>I would recommend creating a Linq To Sql (dbml) file if you're new to Linq To Sql.</p>
<p>Right click on your project in solution explorer, and select Add New Item. Select Linq To SQL file, and it will then let you connect to your database and select the tables.</p>
<p>You can then look at the generated code, and get some great ideas on how Linq To Sql works and what you can do with it.</p>
<p>Use that as a guideline on working with Linq to SQL and that will take you far...</p>
| 10,560
|
<p>We have an application where people can type in multiple langugaes. Though we only have one database to store all the data. We have text columns as nvarchar ( assuming we only want text data to be in multiple languages and not all dates etc.)</p>
<p>Do you think this is a feasbile solution and are there any other points to consider besides sorting and searching ?</p>
<p>Thanks.</p>
|
<p>I think it depends on the type of data. For names + addresses it's probably ok... a name is a name no matter what language it's in.</p>
<p>For descriptive text (eg a notes field) it might be confusing... at the very least you might want to record the language that the text is in so that you can filter against it later?</p>
|
<p>--some thoughts</p>
<pre><code> USE [db]
GO
/****** Object: Table [dbo].[CultureInfo] Script Date: 06/23/2009 21:07:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CultureInfo](
[CultureInfoId] [int] IDENTITY(1,1) NOT NULL,
[CultureName] [varchar](10) NOT NULL,
[DisplayName] [varchar](50) NULL,
[ISO_639x_Value] [nchar](6) NULL,
[CultureCode] [nvarchar](10) NULL,
[CollationName] [varchar](50) NULL,
CONSTRAINT [PK_CultureInfo] PRIMARY KEY CLUSTERED
(
[CultureInfoId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('af-ZA' , 'Afrikaans - South Africa' , '0x0436' , 'AFK' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('sq-AL' , 'Albanian - Albania' , '0x041C' , 'SQI' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ar-DZ' , 'Arabic - Algeria' , '0x1401' , 'ARG' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ar-BH' , 'Arabic - Bahrain' , '0x3C01' , 'ARH' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ar-EG' , 'Arabic - Egypt' , '0x0C01' , 'ARE' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ar-IQ' , 'Arabic - Iraq' , '0x0801' , 'ARI' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ar-JO' , 'Arabic - Jordan' , '0x2C01' , 'ARJ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ar-KW' , 'Arabic - Kuwait' , '0x3401' , 'ARK' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ar-LB' , 'Arabic - Lebanon' , '0x3001' , 'ARB' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ar-LY' , 'Arabic - Libya' , '0x1001' , 'ARL' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ar-MA' , 'Arabic - Morocco' , '0x1801' , 'ARM' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ar-OM' , 'Arabic - Oman' , '0x2001' , 'ARO' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ar-QA' , 'Arabic - Qatar' , '0x4001' , 'ARQ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ar-SA' , 'Arabic - Saudi Arabia' , '0x0401' , 'ARA' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ar-SY' , 'Arabic - Syria' , '0x2801' , 'ARS' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ar-TN' , 'Arabic - Tunisia' , '0x1C01' , 'ART' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ar-AE' , 'Arabic - United Arab Emirates' , '0x3801' , 'ARU' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ar-YE' , 'Arabic - Yemen' , '0x2401' , 'ARY' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('hy-AM' , 'Armenian - Armenia' , '0x042B' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('Cy-az-AZ' , 'Azeri (Cyrillic) - Azerbaijan' , '0x082C' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('Lt-az-AZ' , 'Azeri (Latin) - Azerbaijan' , '0x042C' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('eu-ES' , 'Basque - Basque' , '0x042D' , 'EUQ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('be-BY' , 'Belarusian - Belarus' , '0x0423' , 'BEL' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('bg-BG' , 'Bulgarian - Bulgaria' , '0x0402' , 'BGR' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ca-ES' , 'Catalan - Catalan' , '0x0403' , 'CAT' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('zh-CN' , 'Chinese - China' , '0x0804' , 'CHS' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('zh-HK' , 'Chinese - Hong Kong SAR' , '0x0C04' , 'ZHH' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('zh-MO' , 'Chinese - Macau SAR' , '0x1404' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('zh-SG' , 'Chinese - Singapore' , '0x1004' , 'ZHI' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('zh-TW' , 'Chinese - Taiwan' , '0x0404' , 'CHT' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('zh-CHS' , 'Chinese (Simplified)' , '0x0004' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('zh-CHT' , 'Chinese (Traditional)' , '0x7C04' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('hr-HR' , 'Croatian - Croatia' , '0x041A' , 'HRV' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('cs-CZ' , 'Czech - Czech Republic' , '0x0405' , 'CSY' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('da-DK' , 'Danish - Denmark' , '0x0406' , 'DAN' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('div-MV' , 'Dhivehi - Maldives' , '0x0465' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('nl-BE' , 'Dutch - Belgium' , '0x0813' , 'NLB' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('nl-NL' , 'Dutch - The Netherlands' , '0x0413' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('en-AU' , 'English - Australia' , '0x0C09' , 'ENA' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('en-BZ' , 'English - Belize' , '0x2809' , 'ENL' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('en-CA' , 'English - Canada' , '0x1009' , 'ENC' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('en-CB' , 'English - Caribbean' , '0x2409' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('en-IE' , 'English - Ireland' , '0x1809' , 'ENI' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('en-JM' , 'English - Jamaica' , '0x2009' , 'ENJ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('en-NZ' , 'English - New Zealand' , '0x1409' , 'ENZ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('en-PH' , 'English - Philippines' , '0x3409' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('en-ZA' , 'English - South Africa' , '0x1C09' , 'ENS' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('en-TT' , 'English - Trinidad and Tobago' , '0x2C09' , 'ENT' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('en-GB' , 'English - United Kingdom' , '0x0809' , 'ENG' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('en-US' , 'English - United States' , '0x0409' , 'ENU' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('en-ZW' , 'English - Zimbabwe' , '0x3009' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('et-EE' , 'Estonian - Estonia' , '0x0425' , 'ETI' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('fo-FO' , 'Faroese - Faroe Islands' , '0x0438' , 'FOS' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('fa-IR' , 'Farsi - Iran' , '0x0429' , 'FAR' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('fi-FI' , 'Finnish - Finland' , '0x040B' , 'FIN' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('fr-BE' , 'French - Belgium' , '0x080C' , 'FRB' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('fr-CA' , 'French - Canada' , '0x0C0C' , 'FRC' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('fr-FR' , 'French - France' , '0x040C' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('fr-LU' , 'French - Luxembourg' , '0x140C' , 'FRL' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('fr-MC' , 'French - Monaco' , '0x180C' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('fr-CH' , 'French - Switzerland' , '0x100C' , 'FRS' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('gl-ES' , 'Galician - Galician' , '0x0456' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ka-GE' , 'Georgian - Georgia' , '0x0437' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('de-AT' , 'German - Austria' , '0x0C07' , 'DEA' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('de-DE' , 'German - Germany' , '0x0407' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('de-LI' , 'German - Liechtenstein' , '0x1407' , 'DEC' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('de-LU' , 'German - Luxembourg' , '0x1007' , 'DEL' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('de-CH' , 'German - Switzerland' , '0x0807' , 'DES' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('el-GR' , 'Greek - Greece' , '0x0408' , 'ELL' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('gu-IN' , 'Gujarati - India' , '0x0447' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('he-IL' , 'Hebrew - Israel' , '0x040D' , 'HEB' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('hi-IN' , 'Hindi - India' , '0x0439' , 'HIN' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('hu-HU' , 'Hungarian - Hungary' , '0x040E' , 'HUN' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('is-IS' , 'Icelandic - Iceland' , '0x040F' , 'ISL' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('id-ID' , 'Indonesian - Indonesia' , '0x0421' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('it-IT' , 'Italian - Italy' , '0x0410' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('it-CH' , 'Italian - Switzerland' , '0x0810' , 'ITS' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ja-JP' , 'Japanese - Japan' , '0x0411' , 'JPN' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('kn-IN' , 'Kannada - India' , '0x044B' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('kk-KZ' , 'Kazakh - Kazakhstan' , '0x043F' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('kok-IN' , 'Konkani - India' , '0x0457' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ko-KR' , 'Korean - Korea' , '0x0412' , 'KOR' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ky-KZ' , 'Kyrgyz - Kazakhstan' , '0x0440' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('lv-LV' , 'Latvian - Latvia' , '0x0426' , 'LVI' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('lt-LT' , 'Lithuanian - Lithuania' , '0x0427' , 'LTH' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('mk-MK' , 'Macedonian (FYROM)' , '0x042F' , 'MKD' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ms-BN' , 'Malay - Brunei' , '0x083E' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ms-MY' , 'Malay - Malaysia' , '0x043E' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('mr-IN' , 'Marathi - India' , '0x044E' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('mn-MN' , 'Mongolian - Mongolia' , '0x0450' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('nb-NO' , 'Norwegian (Bokmål) - Norway' , '0x0414' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('nn-NO' , 'Norwegian (Nynorsk) - Norway' , '0x0814' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('pl-PL' , 'Polish - Poland' , '0x0415' , 'PLK' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('pt-BR' , 'Portuguese - Brazil' , '0x0416' , 'PTB' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('pt-PT' , 'Portuguese - Portugal' , '0x0816' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('pa-IN' , 'Punjabi - India' , '0x0446' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ro-RO' , 'Romanian - Romania' , '0x0418' , 'ROM' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ru-RU' , 'Russian - Russia' , '0x0419' , 'RUS' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('sa-IN' , 'Sanskrit - India' , '0x044F' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('Cy-sr-SP' , 'Serbian (Cyrillic) - Serbia' , '0x0C1A' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('Lt-sr-SP' , 'Serbian (Latin) - Serbia' , '0x081A' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('sk-SK' , 'Slovak - Slovakia' , '0x041B' , 'SKY' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('sl-SI' , 'Slovenian - Slovenia' , '0x0424' , 'SLV' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-AR' , 'Spanish - Argentina' , '0x2C0A' , 'ESS' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-BO' , 'Spanish - Bolivia' , '0x400A' , 'ESB' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-CL' , 'Spanish - Chile' , '0x340A' , 'ESL' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-CO' , 'Spanish - Colombia' , '0x240A' , 'ESO' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-CR' , 'Spanish - Costa Rica' , '0x140A' , 'ESC' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-DO' , 'Spanish - Dominican Republic' , '0x1C0A' , 'ESD' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-EC' , 'Spanish - Ecuador' , '0x300A' , 'ESF' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-SV' , 'Spanish - El Salvador' , '0x440A' , 'ESE' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-GT' , 'Spanish - Guatemala' , '0x100A' , 'ESG' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-HN' , 'Spanish - Honduras' , '0x480A' , 'ESH' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-MX' , 'Spanish - Mexico' , '0x080A' , 'ESM' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-NI' , 'Spanish - Nicaragua' , '0x4C0A' , 'ESI' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-PA' , 'Spanish - Panama' , '0x180A' , 'ESA' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-PY' , 'Spanish - Paraguay' , '0x3C0A' , 'ESZ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-PE' , 'Spanish - Peru' , '0x280A' , 'ESR' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-PR' , 'Spanish - Puerto Rico' , '0x500A' , 'ES' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-ES' , 'Spanish - Spain' , '0x0C0A' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-UY' , 'Spanish - Uruguay' , '0x380A' , 'ESY' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('es-VE' , 'Spanish - Venezuela' , '0x200A' , 'ESV' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('sw-KE' , 'Swahili - Kenya' , '0x0441' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('sv-FI' , 'Swedish - Finland' , '0x081D' , 'SVF' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('sv-SE' , 'Swedish - Sweden' , '0x041D' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('syr-SY' , 'Syriac - Syria' , '0x045A' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ta-IN' , 'Tamil - India' , '0x0449' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('tt-RU' , 'Tatar - Russia' , '0x0444' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('te-IN' , 'Telugu - India' , '0x044A' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('th-TH' , 'Thai - Thailand' , '0x041E' , 'THA' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('tr-TR' , 'Turkish - Turkey' , '0x041F' , 'TRK' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('uk-UA' , 'Ukrainian - Ukraine' , '0x0422' , 'UKR' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('ur-PK' , 'Urdu - Pakistan' , '0x0420' , 'URD' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('Cy-uz-UZ' , 'Uzbek (Cyrillic) - Uzbekistan' , '0x0843' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('Lt-uz-UZ' , 'Uzbek (Latin) - Uzbekistan' , '0x0443' , ' ' )
insert into CultureInfo (CultureName , DisplayName , ISO_639x_Value , CultureCode ) values ('vi-VN' , 'Vietnamese - Vietnam' , '0x042A' , 'VIT' )
</code></pre>
| 21,937
|
<p>A number of business areas I work with use a folder structure to organise their Sharepoint housed documents (not ideal I know, but we're stuck with it). </p>
<p>I would like to use a web part page to present a number of views of their document libraries based on the subfolders that the documents appear in, but this is proving more difficult than I had thought. Has anyone overcome this problem in the past?</p>
|
<p>With Sharepoint Designer you can edit the CAML of your XSLT List View. </p>
<p>If you set the Scope attribute of the View element to <em>Recursive</em> or <em>RecursiveAll</em>, which returns all Files and Folders, you can filter the documents by <em>FileDirRef</em>:</p>
<pre><code><Where>
<Contains>
<FieldRef Name='FileDirRef' />
<Value Type='Lookup'>MyFolder</Value>
</Contains>
</Where>
</code></pre>
<p>This returns all documents which contain the string 'MyFolder' in their path. </p>
<p>I found infos about this on <a href="http://platinumdogs.wordpress.com/2009/07/21/querying-document-libraries-or-pulling-teeth-with-caml/" rel="noreferrer">http://platinumdogs.wordpress.com/2009/07/21/querying-document-libraries-or-pulling-teeth-with-caml/</a> and useful information abouts fields at <a href="http://blog.thekid.me.uk/archive/2007/03/21/wss-field-display-amp-internal-names-for-lists-amp-document-libraries.aspx" rel="noreferrer">http://blog.thekid.me.uk/archive/2007/03/21/wss-field-display-amp-internal-names-for-lists-amp-document-libraries.aspx</a> </p>
|
<p>What kind of document library information do you want in the view?
How do you want the user to filter the view?</p>
<p>In general the most powerful way of creating views in sharepoint is with the data view web part.
<a href="http://office.microsoft.com/en-us/sharepointdesigner/HA100948041033.aspx" rel="nofollow noreferrer">http://office.microsoft.com/en-us/sharepointdesigner/HA100948041033.aspx</a></p>
<p>You will need Microsoft Office SharePoint Designer. </p>
<p>You can present different views of you folders using the data view filter and sorting controls.</p>
<p>You can use web part connections to filter a dataview.
You can use any datasource linked to say a drop down to filter a dataview.
<a href="https://stackoverflow.com/questions/177076/how-to-tie-a-dropdown-list-to-a-gridview-in-sharepoint-2007">How to tie a dropdown list to a gridview in Sharepoint 2007?</a></p>
| 37,759
|
<p>Has anyone managed to do this? I tried making a managed wrapper class for IPropertyStore but am getting AccessViolationExceptions on the methods (i.e. IPropertyStore::GetValue) that take a pointer to PROPVARIANT (rendered as a MarshalAs(UnmanagedType.Struct) out parameter in my managed version) Probably my understanding of COM and interop is inadequate --- I'm not sure if the problems are in my PROPVARIANT struct declaration (which currently just uses StructLayout.Sequential, declares a sequence of bytes, and manually manipulates the bytes to get values of the various types in the union etc.), COM issues with what process owns what, or something else. I've tried various other versions of the PROPVARIANT such as using StructLayout.Explicit for the unions, nothing's worked. Retrieving PROPERTYKEYs with IPropertyStore::GetAt --- which is declared natively as taking a pointer to PROPERTYKEY and as having an out parameter of my own StructLayout.Sequential PROPERTYKEY in my wrapper --- works just fine, by the way.</p>
|
<p>Speaking of nullable types - I think they can be used to solve the problem of forcing/not forcing the initialization of an enum. Say we have</p>
<pre><code>enum Color { Red, Blue }
</code></pre>
<p>And let's say you have a function:</p>
<pre><code>void Draw(Color c);
</code></pre>
<p>That function says that it <strong>requires</strong> a valid <code>Color</code>. However, we could also have this function:</p>
<pre><code>void Draw(Color? c);
</code></pre>
<p>That says that the function can handle not being passed a color (<code>null</code> would be passed to indicate "don't care").</p>
<p>Well, it's one alternative to <code>None</code> members.</p>
|
<p>Depends how the type is used. It's often easier for users of the type not to have an "undefined" value, because you don't have to special-case one value. But if you need one (because values sometimes need to be in a state which is otherwise not any of the enumerated values) then you need one. You usually don't save any special-case code by using two enums instead of one.</p>
<p>It's a bit like asking whether you should use nullable types.</p>
| 44,988
|
<p>I am wondering what is your experience with AxoSoft OnTime issues tracking and project management solution in case you have ever used it (pros and cons)...</p>
<p>Cheers,
B.</p>
|
<p>The. Client. Is. Bloody. Slow!</p>
<p>But yes, we use it. And it is powerful. And configurable.</p>
<p>But hell is the client slow!</p>
<p>Use the http(s) if at all possible.</p>
|
<p>We use it and its got a lot of nice features - def some quirks, but since we have implemented it - it has kept us all on the same page. It has some nice integration plugins to visual studio as well.</p>
<p>I would say its worth a go.</p>
<p>Sorry, just wanted to add: we use it for issue tracking only</p>
| 26,203
|
<p>I am attempting to construct model tank tracks with accompanying wheels and sprockets. All parts will be printed in PLA. The tracks will be driven by electric motors.</p>
<p>What would be a suitable grease for this project to minimize friction without damaging the plastics.</p>
|
<p>I use cosmetic vaseline - <a href="https://en.wikipedia.org/wiki/Petroleum_jelly" rel="noreferrer">petroleum jelly</a>. Usually it is white to transparent and odorless. It's cheap and available in all drugstores and cosmetics stores.</p>
<p>As suggested by Tom van der Zanden I'm adding additional info about interactions of vaseline and plastics.
I've found many web sites which claim that vaseline can damage plastics but none of them really proved that statement. There is nothing about it neither on producers sites nor wikipedia or any other believable sources I've found. So according to it and my practice I'm pretty sure that vaseline won't damage popular plastics (including common filaments).</p>
<p>The only information I've found is that vaseline can damage natural rubber but I cannot confirm that on my own.</p>
<p>Of course it might not be true for some materials so be careful and check the interactions first on invisible side or on refuses.</p>
|
<p>I have been using <em>sewing machine oil</em> for my 3D printed extruder gear for a couple of years, without any noticeable wear so far.</p>
<p>In general, I believe any kind of low viscosity oil would do, but then again, it also depends on the environment in which you plan to use the model. If you plan on using it outside, for instance, you probably should get some grease that does not attract dirt, as the dirt itself will grind down the gears quickly.</p>
| 298
|
<p>Let's say I have a class that has a member called data which is a list. </p>
<p>I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.</p>
<p>What's your technique for doing this?</p>
<p>Do you just check the type by looking at <code>__class__</code>?</p>
<p>Is there some trick I might be missing?</p>
<p>I'm used to C++ where overloading by argument type is easy. </p>
|
<p>A much neater way to get 'alternate constructors' is to use classmethods. For instance:</p>
<pre><code>>>> class MyData:
... def __init__(self, data):
... "Initialize MyData from a sequence"
... self.data = data
...
... @classmethod
... def fromfilename(cls, filename):
... "Initialize MyData from a file"
... data = open(filename).readlines()
... return cls(data)
...
... @classmethod
... def fromdict(cls, datadict):
... "Initialize MyData from a dict's items"
... return cls(datadict.items())
...
>>> MyData([1, 2, 3]).data
[1, 2, 3]
>>> MyData.fromfilename("/tmp/foobar").data
['foo\n', 'bar\n', 'baz\n']
>>> MyData.fromdict({"spam": "ham"}).data
[('spam', 'ham')]
</code></pre>
<p>The reason it's neater is that there is no doubt about what type is expected, and you aren't forced to guess at what the caller intended for you to do with the datatype it gave you. The problem with <code>isinstance(x, basestring)</code> is that there is no way for the caller to tell you, for instance, that even though the type is not a basestring, you should treat it as a string (and not another sequence.) And perhaps the caller would like to use the same type for different purposes, sometimes as a single item, and sometimes as a sequence of items. Being explicit takes all doubt away and leads to more robust and clearer code.</p>
|
<p>OK, great. I just tossed together this example with a tuple, not a filename, but that's easy. Thanks all.</p>
<pre><code>class MyData:
def __init__(self, data):
self.myList = []
if isinstance(data, tuple):
for i in data:
self.myList.append(i)
else:
self.myList = data
def GetData(self):
print self.myList
</code></pre>
<p>a = [1,2]</p>
<p>b = (2,3)</p>
<p>c = MyData(a)</p>
<p>d = MyData(b)</p>
<p>c.GetData()</p>
<p>d.GetData()</p>
<p>[1, 2]</p>
<p>[2, 3]</p>
| 17,106
|
<p>I have a 4 side convex Polygon defined by 4 points in 2D, and I want to be able to generate random points inside it.</p>
<p>If it really simplifies the problem, I can limit the polygon to a parallelogram, but a more general answer is preferred.</p>
<p>Generating random points until one is inside the polygon wouldn't work because it's really unpredictable the time it takes.</p>
|
<p>A. If you can restrict your input to parallelogram, this is really simple:</p>
<ol>
<li>Take two random numbers between 0 and 1. We'll call then <code>u</code> and <code>v</code>.</li>
<li><p>If your parallelogram is defined by the points ABCD such that AB, BC, CD and DA are the sides, then take your point as being:</p>
<pre><code> p = A + (u * AB) + (v * AD)
</code></pre></li>
</ol>
<p>Where <code>AB</code> is the vector from A to B and <code>AD</code> the vector from A to D.</p>
<p>B. Now, if you cannot, you can still use the barycentric coordinates. The barycentric coordinates correspond, for a quad, to 4 coordinates <code>(a,b,c,d)</code> such that <code>a+b+c+d=1</code>. Then, any point <code>P</code> within the quad can be described by a 4-uple such that:</p>
<pre><code>P = a A + b B + c C + d D
</code></pre>
<p>In your case, you can draw 4 random numbers and normalize them so that they add up to 1. That will give you a point. Note that the distribution of points will NOT be uniform in that case.</p>
<p>C. You can also, as proposed elsewhere, decompose the quad into two triangles and use the half-parallelogram method (i.e., as the parallelogram but you add the condition <code>u+v=1</code>) or the barycentric coordinates for triangles. However, if you want uniform distribution, the probability of having a point in one of the triangle must be equal to the area of the triangle divided by the area of the quad.</p>
|
<p>For PostGIS, this is what I am using (you might want a ward for possible infinite loops). You might export the algorithm to your programming language:</p>
<pre><code>CREATE or replace FUNCTION random_point(geometry)
RETURNS geometry
AS $$
DECLARE
env geometry;
corner1 geometry;
corner2 geometry;
minx real;
miny real;
maxx real;
maxy real;
x real;
y real;
ret geometry;
begin
select ST_Envelope($1) into env;
select ST_PointN(ST_ExteriorRing(env),1) into corner1;
select ST_PointN(ST_ExteriorRing(env),3) into corner2;
select st_x(corner1) into minx;
select st_x(corner2) into maxx;
select st_y(corner1) into miny;
select st_y(corner2) into maxy;
loop
select minx+random()*(maxx-minx) into x;
select miny+random()*(maxy-miny) into y;
select ST_SetSRID(st_point(x,y), st_srid($1)) into ret;
if ST_Contains($1,ret) then
return ret ;
end if;
end loop;
end;
$$
LANGUAGE plpgsql
volatile
RETURNS NULL ON NULL INPUT;
</code></pre>
| 29,803
|
<p>Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:</p>
<pre><code>class MyStruct():
def __init__(self, field1, field2, field3):
self.field1 = field1
self.field2 = field2
self.field3 = field3
</code></pre>
|
<p>Use a <a href="https://docs.python.org/2/library/collections.html#collections.namedtuple" rel="noreferrer">named tuple</a>, which was added to the <a href="http://docs.python.org/library/collections.html" rel="noreferrer">collections module</a> in the standard library in Python 2.6. It's also possible to use Raymond Hettinger's <a href="http://code.activestate.com/recipes/500261/" rel="noreferrer">named tuple</a> recipe if you need to support Python 2.4.</p>
<p>It's nice for your basic example, but also covers a bunch of edge cases you might run into later as well. Your fragment above would be written as:</p>
<pre><code>from collections import namedtuple
MyStruct = namedtuple("MyStruct", "field1 field2 field3")
</code></pre>
<p>The newly created type can be used like this:</p>
<pre><code>m = MyStruct("foo", "bar", "baz")
</code></pre>
<p>You can also use named arguments:</p>
<pre><code>m = MyStruct(field1="foo", field2="bar", field3="baz")
</code></pre>
|
<p>I think Python structure dictionary is suitable for this requirement.</p>
<pre class="lang-py prettyprint-override"><code>d = dict{}
d[field1] = field1
d[field2] = field2
d[field2] = field3
</code></pre>
| 5,660
|
<p>I'm looking for someone reasonably cheap but better than the majority of budget hosts out there. I'm currently with brinkster.net and I've become increasingly annoyed at the their immense unreliability and low available resources.</p>
<p>Fasthosts business plan is close, but has no mysql, only has ASP.NET 2.0 and is maybe slightly more expensive than I was hoping for.</p>
|
<p>I have had several sites hosted on <a href="http://discountasp.net" rel="nofollow noreferrer">http://discountasp.net</a> and have had very good results. They are on year 4 of being voted best ASP.NET host in the asp.netPRO reader's choice survey.</p>
|
<p>I've been with these guys for quite a bit,
<a href="http://www.webhost4life.com/" rel="nofollow noreferrer">http://www.webhost4life.com/</a>
<br>
Cheap and cheerful.</p>
| 11,624
|
<p>I have a string containing a date, and another string containing the date format of the first string. Is there a function that I can call to convert that date into something like a SYSTEMTIME structure? Basically, I'd like the opposite of <a href="http://msdn.microsoft.com/en-us/library/ms776293(VS.85).aspx" rel="nofollow noreferrer">GetDateFormat()</a>.</p>
|
<p>No, but you can write a function that will convert the date format string into a <code>sscanf</code> format string and series of variables. Then copy the data from the variables to the <code>SYSTEMTIME</code> structure and you're all set.</p>
<p>It's not trivial, but it is probably the most flexible arrangement if you must support many different date formats.</p>
|
<p>In the source file <a href="http://code.google.com/p/kgui/source/browse/trunk/kgui.cpp" rel="nofollow noreferrer">Here</a>.</p>
<p>I have a function that reads dates in a bunch of different formats, the function is called </p>
<pre><code>bool kGUIDate::Setz(const char *datestring)
</code></pre>
<p>It's a class that reads in the day / month / year and also handles hours / minutes / seconds.</p>
<p>The code is LGPL so feel free to copy it.</p>
<pre><code>/* formats excepted are: */
/* yyyy-mm-dd */
/* Wdy, DD-Mon-YY HH:MM:SS GMT */
/* Wdy, D Mon YY HH:MM:SS GMT */
</code></pre>
| 28,981
|
<p>We're setting up an OpenSolaris server on Amazon's EC2 service. However, vi/vim doesn't work properly, and pkg doesn't have nano/pico.</p>
<p>Is there any other text-editor maybe?</p>
|
<p>Sounds like you may just need to set an appropriate termtype to get vi working. Look into the "TERM" environment variable options, perhaps one of those will help you.</p>
|
<p>SUN is working on the SUNWgnu-nano package to include this in the next release. In the meantime, you can compile the nano sources yourself. It worked for me. To compile, follow these steps:</p>
<ol>
<li>Make sure you install SUNWgcc package so that gcc is installed.</li>
<li><p>Download the source package from the debian distribution.
<a href="http://packages.debian.org/source/stable/nano" rel="nofollow noreferrer">http://packages.debian.org/source/stable/nano</a></p></li>
<li><p>Unzip the package with 'gunzip xxxx.tar.gz' where xxxx.tar.gz is the source package you downloaded.</p></li>
<li><p>Untar the package with 'tar -xf xxxx' where xxxx is the unzipped source package.</p></li>
<li><p>Go to the source folder. Do a './configure' to create the make file for your system.</p></li>
<li>Type 'make' to create the binary</li>
<li>The 'nano' binary should be located in the src subfolder. Copy this to '/usr/bin'. And create a soft link for 'pico' to it i.e. 'ln -s /usr/bin/nano pico'</li>
</ol>
<p>Test it out!</p>
| 42,879
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.