text
stringlengths 8
267k
| meta
dict |
---|---|
Q: ASP.NET - The request was aborted: Could not create SSL/TLS secure channel We get the following error;
The request was aborted: Could not create SSL/TLS secure channel
while using a WebRequest object to make an HTTPS request. The funny thing is that this only happens after a while, and is temporarily fixed when the application is restarted, which suggests that something is being filled to capacity or something.
Has anyone seen this kind of thing before?
A: I seem to recall having this problem last year. I suspect that you aren't closing your WebRequest objects properly, which is why after a certain amount of use it won't allow you to create any new connections.
A: I have exactly the same problem!
I send two requisitions to an HTTPS webservice in close period range (seconds).
The first requisition works fine, but the second requisition fails.
I´ve tried to set "System.Net.ServicePointManager.SecurityProtocol = Net.SecurityProtocolType.Ssl3", but the second requisition freezes...
I´m using VB.NET 2008.
Thanks
A: It looks like it may be a Conenction: Keep-alive thing: http://blogs.x2line.com/al/archive/2005/01/04/759.aspx#780
A: The similar problem for me fixed by:
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Simple effects in Flex I would like to show some hidden text in a Flex application and have it fade out in a couple of seconds...
I have looked into Delay and Pause effects in Flex, but have yet to see an example of how to do this realistically easy effect...
anyone now how to do it or have a good resource?
Thanks.
A: If I understand you correctly, you want to have the text automatically fade out a few seconds after it is shown?
I would probably do something like this: (Haven't tested the code, so there are probably typos.)
<mx:Script>
import flash.utils.*;
var fadeTimer:Timer = new Timer(2000); // 2 seconds
fadeTimer.addEventListener("timer", fadeTimerTickHandler);
// Call this to show the hidden text.
function showTheText():void{
theTextField.visible = true;
fadeTimer.start();
}
// This gets called every time the timer "ticks" (2 seconds)
function fadeTimerTickHandler(eventArgs:TimerEvent){
fadeTimer.stop();
fadeTimer.reset();
theTextField.visible = false;
}
</mx:Script>
<mx:Fade id="hideEffectFade" alphaFrom="1.0" alphaTo="0.0" duration="900"/>
<mx:Text id="theTextField" text="The Text" hideEffect="{hideEffectFade}"/>
Also, you need to be sure to embed your fonts or the effect won't work on your text. See Simeon's post for more info.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Make a CD run once We're doing an "Amazing Race" kind of event, and thought it would be cool to have CDs that could only play once... like a "this message will self destruct in 5 seconds..."
Any thoughts on how to do this? I was thinking it could be a compiled HTML website that would write a cookie and only play once. I don't want to write to the registry (don't want to depend on windows, don't want to install anything, etc).
I also don't care if it's hackable... This is a one-time fun event, and I don't really care too much if people could remove the cookie or something.
Any other ideas?
A: If the content is HTML and run inside a normal browser window, then a cookie may work but there are caveats:
*
*User runs the CD once when IE is the default browser. User runs at a later time, when Firefox is the default browser so cookie cannot be checked.
*The browser's security settings may be locked down to prevent use of script so the cookie cannot be set (more of an IE problem).
An alternative might be Flash's equivalent of cookies, but if script was locked down then the same may be true for Flash.
A: If you used Flash to create the content, you could then use a wrapper program such as Zinc to produce cross-platform executables of the content.
Then, the Flash could use its version of cookies (local shared objects) to determine when the content has been displayed - write to the LSO the first time and read from it thereafter.
A: I would say encrypt (part of) the contents of the disc with a unique one time pad, that you request from a server that does a read directly followed by a delete of the decryption key. You could write an identifier on each disk so you can use multiple disks, each with a unique key.
This requires network access and some encryption tools, but a very simple implementation would do what you want it to do, is feasible, and it would be 'unbreakable' unless the one time pad is captured and stored.
If just for fun, this should be secure enough.
A: You can create a volatile registry entry. It will only exist untill the computer is restarted. This solution is very much "hackable", but it is simple and may suffice for what you want to do.
Take a look at the REG_OPTION_VOLATILE here.
A: Will the computers this is run on have internet access? You can easily load up a remote url (execute 'start http://yoururl.com' from autorun.inf), store the cookie and prevent it from being loaded again if the cookie exists.
A: If it's allowed to be hackable, then I'd just go with a simple solution of HTML + JavaScript, requiring (say) a GUID to enter, with some silly obfuscation in the code to validate the GUID.
What I mean by silly obfuscated validation is something like putting together a big array of ROT13'ed GUIDs, then adding code to only accept the Math.floor(PI * E + 32/(new DateTime()).getYear())'th GUID in the array, and ROT13 it again using sufficiently uncommented/unclear code, then check the user input against the result. Do it all in one line for kicks, or generate the GUIDs in some pseudo-random manner using a known seed... you get the idea :).
The only snag might be if IE doesn't allow local JavaScript? Hmm, looks like they'd need to deal with the InfoBar thing :(.
A: You could also set a registry key that would prevent playing, though this could be bypassed.
A: I think your best bet is to use Rewritable media for this. You can create your application easily, like HTML site or something like that, and after the last link or last page, however you decide to do you could execute a script with some command-line burner that would erase the rewritable media, or even write an ISO that you keep in CD with a text file or a flash that explains that the CD is lost forever.
Give a look at some Command Line Burners. Linux have several, that isn't worth to mention here, for windows you can use Cheetah CommandLine Burner among several others.
If you wish to do a CD without depending on the installed OS you should give a look at LIVE CDs. FreeDOS is a choice for "DOS Compatible applications" or my suggestioon you use a Linux live CD.
Also you will have several options for small HTTP servers, like lighthttpd and even browsers in several flavors from text interfaces to the graphical ones.
Good luck on the race :D. Great idea BTW!
A: Make a Java Swing application. That will not require Internet and it runs on Mac, Windows, and Linux. You can write to the file system for the lock. System.getProperty("user.home") gives you the home equivalent for the platform. You might have to include a jre in your CD.
A: Not quite what you're looking for, but you could put in on re-writable media and have an executable over-write itself (or part of itself).
I don't know if a CD-RW could do that automatically, or if you would have to look at cheap USB sticks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Subversion Partial Export I have somewhat interesting development situation. The client and deployment server are inside a firewall without access to the Subversion server. But the developers are outside the firewall and are able to use the Subversion server. Right now the solution I have worked out is to update my local copy of the code and then pull out the most recently updated files using UnleashIT.
The question is how to get just the updated files out of Subversion so that they can be physically transported through the firewall and put on the deployment server.
I'm not worried about trying to change the firewall setup or trying to figure out an easier way to get to the Subversion server from inside the firewall. I'm just interested in a way to get a partial export from the repository of the most recently changed files.
Are there any other suggestions?
Answer found: In addition to the answer I marked as Answer, I've also found the following here to be able to do this from TortoiseSVN:
from http://svn.haxx.se/tsvn/archive-2006-08/0051.shtml
* select the two revisions
* right-click, "compare revisions"
* select all files in the list
* right-click, choose "export to..."
A: svn export does not accept a revision range, try it out.
A possible solution is to get the list of changed files with:
svn diff --summarize -rXXX http://svn/...
and then export each of them.
A: So if I understand correctly...
Let's say you have a repository that looks like this:
/
|+-DIR1
| |- FILEa
| |- FILEb
|+-DIR2
| |- FILEc
| |- FILEd
|- FILEe
|- FILEf
And let's say you update files FILEa, FILEc, and FILEf and commit them back into the repository. Then what you want to export out of the repository is a structure that looks like this:
/
|+-DIR1
| |- FILEa
|+-DIR2
| |- FILEc
|- FILEf
Is that right?
A: The Subversion hooks looks like it has a lot of promise. But being relatively uninformed about how to script the hook, how would I pull out the files that were committed and FTP them somewhere maintaining the directory structure?
If I could do that, then someone inside the firewall can pull the files down to the deployment server and we'd be good to go.
A: I've found rsync extremely useful for synchronizing directory trees across multiple systems. If you have shell access to your server from a development workstation, you can regularly check out code locally and run rsync, which will transfer only the files that have changed to the server.
(This assumes a Unix-like environment on your development workstations. Cygwin will work fine.)
cd deploy
svn update
rsync -a . server:webdir/
Your question sounds like you don't actually have any direct network access from your development workstations to your server, and what you're really looking for is a way to get Subversion to tell you which files have changed. svn export supports an argument to let you check out only the files that changed between particular revisions. From the svn help:
-r [--revision] arg : ARG (some commands also take ARG1:ARG2 range)
A revision argument can be one of:
NUMBER revision number
'{' DATE '}' revision at start of the date
'HEAD' latest in repository
'BASE' base rev of item's working copy
'COMMITTED' last commit at or before BASE
'PREV' revision just before COMMITTED
You'll need to keep track of what the latest revision you copied to the server. Assuming it's SVN revision xxxx:
svn export -r xxxx:HEAD http://svn/
Then simply copy the contents of the deploy directory to your server on top of the existing files.
This won't handle deleted files, which may prove problematic in some environments.
A: You could try playing around with the svnadmin dump command that ships with the Subversion binaries. You can use this command to dump the whole repository to a file, just certain revision, or a range of revisions. Then use svnadmin load to load the dump-file into a new, clean repository.
Not a perfect solution since it works in terms of the repository and not individual files.
A: You just want the people who are behind the firewall to be able to access the latest files committed to Subversion, right?
Could you write an svn hook script that uses some method (maybe scp or ftp) to send the files over to the remote location at the time they're committed?
A: If you tag the revisions this may help github svn-diff-export
A: You don't provide information on what is allowed through the firewall. I'm not familiar with UnleashIT.
I guess you could have a script that exports from SVN to a folder on the SVN server. The script then zips the exported files. You can then transport the ZIP file however you want and extract to the deployment server.
TortoiseSVN supports proxy servers so you could use one of those from the client's side?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Are semicolons needed after an object literal assignment in JavaScript? The following code illustrates an object literal being assigned, but with no semicolon afterwards:
var literal = {
say: function(msg) { alert(msg); }
}
literal.say("hello world!");
This appears to be legal, and doesn't issue a warning (at least in Firefox 3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed?
I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it.
A: JavaScript interpreters do something called "semicolon insertion", so if a line without a semicolon is valid, a semicolon will quietly be added to the end of the statement and no error will occur.
var foo = 'bar'
// Valid, foo now contains 'bar'
var bas =
{ prop: 'yay!' }
// Valid, bas now contains object with property 'prop' containing 'yay!'
var zeb =
switch (zeb) {
...
// Invalid, because the lines following 'var zeb =' aren't an assignable value
Not too complicated and at least an error gets thrown when something is clearly not right. But there are cases where an error is not thrown, but the statements are not executed as intended due to semicolon insertion. Consider a function that is supposed to return an object:
return {
prop: 'yay!'
}
// The object literal gets returned as expected and all is well
return
{
prop: 'nay!'
}
// Oops! return by itself is a perfectly valid statement, so a semicolon
// is inserted and undefined is unexpectedly returned, rather than the object
// literal. Note that no error occurred.
Bugs like this can be maddeningly difficult to hunt down and while you can't ensure this never happens (since there's no way I know of to turn off semicolon insertion), these sorts of bugs are easier to identify when you make your intentions clear by consistently using semicolons. That and explicitly adding semicolons is generally considered good style.
I was first made aware of this insidious little possibility when reading Douglas Crockford's superb and succinct book "JavaScript: The Good Parts". I highly recommend it.
A: Not technically, JavaScript has semicolons as optional in many situations.
But, as a general rule, use them at the end of any statement. Why? Because if you ever want to compress the script, it will save you from countless hours of frustration.
Automatic semicolon insertion is performed by the interpreter, so you can leave them out if you so choose. In the comments, someone claimed that
Semicolons are not optional with statements like break/continue/throw
but this is incorrect. They are optional; what is really happening is that line terminators affect the automatic semicolon insertion; it is a subtle difference.
Here is the rest of the standard on semicolon insertion:
For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.
A: In this case there is no need for a semicolon at the end of the statement. The conclusion is the same but the reasoning is way off.
JavaScript does not have semicolons as "optional". Rather, it has strict rules around automatic semicolon insertion. Semicolons are not optional with statements like break, continue, or throw. Refer to the ECMA Language Specification for more details; specifically 11.9.1, rules of automatic semicolon insertion.
A: The YUI Compressor and dojo shrinksafe should work perfectly fine without semicolons since they're based on a full JavaScript parser. But Packer and JSMin won't.
The other reason to always use semi-colons at the end of statements is that occasionally you can accidentally combine two statements to create something very different. For example, if you follow the statement with the common technique to create a scope using a closure:
var literal = {
say: function(msg) { alert(msg); }
}
(function() {
// ....
})();
The parser might interpret the brackets as a function call, here causing a type error, but in other circumstances it could cause a subtle bug that's tricky to trace. Another interesting mishap is if the next statement starts with a regular expression, the parser might think the first forward slash is a division symbol.
A: Use JSLint to keep your JavaScript clean and tidy
JSLint says:
Error:
Implied global: alert 2
Problem at line 3 character 2: Missing
semicolon.
}
A: The semi-colon is not necessary. Some people choose to follow the convention of always terminating with a semi-colon instead of allowing JavaScript to do so automatically at linebreaks, but I'm sure you'll find groups advocating either direction.
If you are looking at writing "correct" JavaScript, I would suggest testing things in Firefox with javascript.options.strict (accessed via about:config) set to true. It might not catch everything, but it should help you ensure your JavaScript code is more compliant.
A: This is not valid (see clarification below) JavaScript code, since the assignment is just a regular statement, no different from
var foo = "bar";
The semicolon can be left out since JavaScript interpreters attempt to add a semicolon to fix syntax errors, but this is an extra and unnecessary step. I don't know of any strict mode, but I do know that automated parsers or compressors / obfuscators need that semicolon.
If you want to be writing correct JavaScript code, write the semicolon :-)
According to the ECMAscript spec, http://www.ecma-international.org/publications/standards/Ecma-262.htm, the semicolons are automatically inserted if missing. This makes them not required for the script author, but it implies they are required for the interpreter. This means the answer to the original question is 'No', they are not required when writing a script, but, as is pointed out by others, it is recommended for various reasons.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
} |
Q: Whither Managed Extensibility Framework for .NET? Has anyone worked much with Microsoft's Managed Extensibility Framework (MEF)? Kinda sounds like it's trying to be all things to all people - It's an add-in manager! It's duck typing! I'm wondering if anyone has an experience with it, positive or negative.
We're currently planning on using an generic IoC implementation ala MvcContrib for our next big project. Should we throw MEF in the mix?
A: This post refers to the Managed Extensibility Framework Preview 2.
So, I had a run through MEF and wrote up a quick "Hello World", which is presented below. I gotta say it was totally easy to dive into and understand. The catalog system is great and makes extending MEF itself very straight forward. It's trivial to point it at a directory of addin assemblies and let it handle the rest. MEF's heritage ala Prism certainly shows through, but I think it would be odd if it didn't, given that both frameworks are about composition.
I think the thing that sticks in my craw the most is the "magic" of _container.Compose(). If you look in at the HelloMEF class, you'll see that the greetings field is never initialized by any of the code, which just feels funny. I think I prefer the way IoC containers work, where you explicitly ask the container to build an object for you. I wonder if some sort of "Nothing" or "Empty" generic initializer might be in order. i.e.
private IGreetings greetings = CompositionServices.Empty<IGreetings>();
That at least fills the object with "something" until such time as the container composition code runs to fill it with a real "something". I don't know - it smacks a little bit of Visual Basic's Empty or Nothing keywords, which I always disliked. If anyone else has some thoughts on this, I'd like to hear them. Maybe it's something I just need to get over. It is marked with a big fat [Import] attribute, so it's not like it's a complete mystery or anything.
Controlling object lifetime isn't obvious, but everything is a singleton by default unless you add a [CompositionOptions] attribute to the exported class. That let's you specify either Factory or Singleton. It would be nice to see Pooled added to this list at some point.
I'm not really clear on how the duck typing features work. It seems more like meta-data injection upon object creation rather than duck typing. And it looks like you can only add in one additional duck. But like I said, I'm not really clear on how these feature work just yet. Hopefully I can come back and fill this in later.
I think it would be a good idea to shadow copy the DLLs that are loaded by DirectoryPartCatalog. Right now the DLLs are locked once MEF gets a hold of them. This would also allow you to add a directory watcher and catch updated addins. That would be pretty sweet...
Finally, I'm worried about how trusted the addin DLLs are and how, or if, MEF will behave in a partial trust environment. I suspect applications using MEF will require full trust. It might also be prudent to load the addins up in their own AppDomain. I know it smacks a bit of System.AddIn, but it would allow very clear separation between user addins and system addins.
Okay - enough blathering. Here's Hello World in MEF and C#. Enjoy!
using System;
using System.ComponentModel.Composition;
using System.Reflection;
namespace HelloMEF
{
public interface IGreetings
{
void Hello();
}
[Export(typeof(IGreetings))]
public class Greetings : IGreetings
{
public void Hello()
{
Console.WriteLine("Hello world!");
}
}
class HelloMEF : IDisposable
{
private readonly CompositionContainer _container;
[Import(typeof(IGreetings))]
private IGreetings greetings = null;
public HelloMEF()
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
_container = new CompositionContainer(catalog);
var batch = new CompositionBatch();
batch.AddPart(this);
container.Compose(batch);
}
public void Run()
{
greetings.Hello();
}
public void Dispose()
{
_container.Dispose();
}
static void Main()
{
using (var helloMef = new HelloMEF())
helloMef.Run();
}
}
}
A: On Andy's question of security for extensions that MEF loads (sorry I don't have enough points yet :) ), the place to address this is in a Catalog. MEF catalogs are completely pluggable, so you can write a custom catalog that validates assembly keys, etc before loading. You could even use CAS if you so desired. We are looking at possibly providing hooks to allow you to do this without having to write a catalog. However, the source for the current catalogs is freely available. I suspect the minimum is someone (maybe on our team) will implement one and throw it in an extension/contrib project on CodePlex.
A: Duck typing won't ship in V1 though it is in the current drop. In a future drop we will replace it with a pluggable adapter mechanism where one could hook in a duck typing mechanism. The reason we looked at duck typing is to address versioning scenarios. With Duck Typing you can remove the shared references between exporters and importers, thus allowing multiple versions of a contract to live side by side.
A: We are not aiming for MEF to be an all-purpose IoC. The best way to think about the IoC aspects of MEF is an implementation detail. We use IoC as a pattern because it is a great way to address the problems we are looking to solve.
MEF is focused on extensibility. When you think of MEF look at it as an investment in taking our platform forward. Our future products and the platform will leverage MEF as a standard mechanism for adding extensibility. Third-party products and frameworks will also be able to leverage this same mechanism. The average "user" of MEF will author components that MEF will consume and will not be directly consuming MEF within their applications.
Imagine when you want to extend our platform in the future, you drop a dll in the bin folder and you are done. The MEF enabled app lights up with the new extension. That's the vision for MEF.
A: Andy, I believe Glenn Block answers many of folks (natural) questions like these in this thread up on the MSDN MEF Forum:
Comparison of CompositionContainer with traditional IoC Containers .
To a degree, Artem's answer above is correct relative to the the primary intent behind MEF, which is extensibility and not composition. If you're primarily interested in composition, then use one of the other usual IoC suspects. If, on the otherhand, you are primarily concerned with extensibility, then the introduction of catalogs, parts, metadata tagging, duck typing, and delayed loading all make for some interesting possibilities. Also, Krzysztof Cwalina takes a shot here at explaining how MEF and System.Addins relate to one another.
A: Ayende also has a pretty good write up here: http://ayende.com/Blog/archive/2008/09/25/the-managed-extensibility-framework.aspx
A: It's not an injection of control container. It's plug-in support framework.
A: I'd say given it's going to hang off of 'System' namespace in the .NET 4.0 Framework that you couldn't go too far wrong. It will be interesting to see how MEF evolves and what influence Hamilton Verissimo (Castle) has on the MEF's direction.
If it quacks like a duck, it just might be part of the current flock of IoC containers...
A: More detailed discussion on this in this post and the comments
http://mikehadlow.blogspot.com/2008/09/managed-extensibility-framework-why.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: How do you pause before fading an element out using jQuery? I would like to flash a success message on my page.
I am using the jQuery fadeOut method to fade and then remove the element. I can increase the duration to make it last longer, however this looks strange.
What I would like to happen is have the element be displayed for five seconds, then fade quickly, and finally be removed.
How can you animate this using jQuery?
A: While @John Sheehan's approach works, you run into the jQuery fadeIn/fadeOut ClearType glitch in IE7. Personally, I'd opt for @John Millikin's setTimeout() approach, but if you're set on a pure jQuery approach, better to trigger an animation on a non-opacity property, such as a margin.
var left = parseInt($('#element').css('marginLeft'));
$('#element')
.animate({ marginLeft: left ? left : 0 }, 5000)
.fadeOut('fast');
You can be a bit cleaner if you know your margin to be a fixed value:
$('#element')
.animate({ marginLeft: 0 }, 5000)
.fadeOut('fast');
EDIT: It looks like the jQuery FxQueues plug-in does just what you need:
$('#element').fadeOut({
speed: 'fast',
preDelay: 5000
});
A: For a pure jQuery approach, you can do
$("#element").animate({opacity: 1.0}, 5000).fadeOut();
It's a hack, but it does the job
A: The new delay() function in jQuery 1.4 should do the trick.
$('#foo').fadeIn(200).delay(5000).fadeOut(200).remove();
A: var $msg = $('#msg-container-id');
$msg.fadeIn(function(){
setTimeout(function(){
$msg.fadeOut(function(){
$msg.remove();
});
},5000);
});
A: Following on from dansays' comment, the following seems to work perfectly well:
$('#thing') .animate({dummy:1}, 2000)
.animate({ etc ... });
A: use setTimeout(function(){$elem.hide();}, 5000);
Where $elem is the element you wish to hide, and 5000 is the delay in milliseconds. You can actually use any function within the call to setTimeout(), that code just defines a small anonymous function for simplicity.
A: dansays's answer just doesn't work for me. For some reason, remove() runs immediately and the div disappears before any animations happen.
The following works, however (by omitting the remove() method):
$('#foo').fadeIn(500).delay(5000).fadeOut(500);
I don't mind if there are hidden DIVs on the page (there shouldn't be more than a few anyway).
A: Update for 1.6.2
Nathan Long's answer will cause the element to pop off without obeying delay or fadeOut.
This works:
$('#foo').delay(2000).fadeOut(2000);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: Twitching Consumption of Web Services from Web Site to Web Application I am trying to consume multiple Web Services that redefine some of the same common classes in their wsdl. I currently have them referenced in a Web Site, but I want to convert to Web Application.
Since some of the same classes are redefined from multiple Web Service, the problem is that when adding them in a web Application there is no way to make the namespaces the same across multiple Web Services, like you can in a Web Site.
Is there any way to do what I am looking for?
A: Show all files in your project, then hand-edit the autogenerated Reference.cs files to change the namespaces (and remove duplicates)? Ugly, but it ought to work.
Alternatively, use wsdl.exe from the command line -- it can generate a single proxy for multiple services -- and then add the generated file to the project manually. The syntax is something like: wsdl http://svr/foo.asmx http://svr/bar.asmx /namespace:Fnord.Proxies
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: .Net [Windows] TreeView TreeNode does not retain color change after drag and drop I have a form with 2 tree views, the user can drag and drop a node from one to another. After a node has been dragged and dropped, I change the color[highlight] of the source node in the Drag-Drop event handles.The color of the node changes fine.
But when the users hovers the mouse over the source tree view after that, it flickers and the highlighting I had done disappears, reverting to the original color.
I'm not handling any other event, I don't reload the treeview and I'm not changing the color.
From my understanding of the MSDN documentation, I don't see any Refresh or Repaint type events.
A: Simply call TreeView.Invalidate() method to force tree view to repaint.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IE6 and Caching It seems that IE6 ignores any form of cache invalidation sent via http headers, I've tried setting Pragma to No Cache and setting Cache Expiration to the current time, yet in IE6, hitting back will always pull up a cached version of a page I am working on.
Is there a specific HTTP Header that IE6 does listen too?
A: Cache-Control: private, max-age=0 should fix it. From classic ASP this is done with Response.Expires=-1.
Keep in mind when testing that just because your server is serving pages with caching turned off doesn't mean that the browser will obey that when it has an old cached page that it was told was okay to cache. Clear the cache or use F5 to force that page to be reloaded.
Also, for those cases where the server is serving cached content it you can use Ctrl+F5 to signal the server not to serve it from cache.
A: You must be careful. If you are using AJAX via XMLHttpRequest (XHR), cache "recommendations" set in the header are not respected by ie6.
The fix is to use append a random number to the url queries used in AJAX requests. For example:
http://test.com?nonce=0123
A good generator for this is the UTC() function that returns a unique timestame for the user's browser... that is, unless they mess with their system clock.
A: Have you tried setting an ETag in the header? They're a pretty reliable way to indicate that content has changed w3c Spec & Wikipedia
Beyond that, a little more crude way is to append a random query string parameter to the request, such as the current unix timestamp. As I said, crude, but then IE6 is not the most subtle of beasts
A: A little note: By experience I know that IE6 will load Javascript from cache even if forced to reload the page via Ctrl-F5. So if you are working on Javascript always empty the cache.
The IE web developer toolbar can help immensely with this. There's a button for clearing the cache.
A: see Question: Making sure a webpage is not cached, across all browsers. How to control web page caching, across all browsers? I think this should help out with your problem too.
A: Content with "Content-Encoding: gzip" Is Always Cached Although You Use "Cache-Control: no-cache"
http://support.microsoft.com/kb/321722
You could also disable gzip just for IE6
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Which way do you prefer to create your forms in MVC? Which way do you prefer to create your forms in MVC?
<% Html.Form() { %>
<% } %>
Or
<form action="<%= Url.Action("ManageImage", "UserAccount") %>" method="post">
</form>
I understand that Html.Form() as of PR5 now just uses the URL provided by the request. However something about that doesn't sit well with me, especially since I will be getting all the baggage of any querystrings that are included.
What is your take?
A: The second way, definitely. The first way is programmer-centric, which is not what the V part of MVC is about. The second way is more designer centric, only binding to the model where it is necessary, leaving the HTML as natural as possible.
A: On the whole, I think I'm kinda old-school as I prefer to roll my own HTML elements.
I also prefer a view engine like like NHaml, which makes writing HTML almost an order of magnitude simpler.
A: I have to agree with both of you, I am not really like this simplistic WebForms style that seems to be integrating its way in to MVC. This stuff almost seems like it should be a 3rd party library or at the very least an extensions library that can be included if needed or wanted.
A: I am totally in the opinion of old school HTML, that is what designers use. I don't like to include to much code centric syntax for this reason. I treat the web form view engine like a third party library, because I replaced it with a different view engine. If you do not like the way the web form view model works or the direction it is going, you can always go a different route. That is one of the main reasons I love ASP.NET MVC.
A: I agree with Andrew Peters, DRY. It should also be pointed out that you can specify your controller, action, and params to the .Form() helper and if they fit into your routing rules then no query string parameters will be used.
I also understand what Will was saying about the V in MVC. In my opinion I do not think it is a problem to put code in the view as long as it is for the view. It is really easy to cross the line between controller and view if you are not careful. Personally I can not stand to use C# as a template engine without my eyes bleeding or getting the urge to murder someone. This helps me keep my logic separated, controller logic in C#, view logic in brail.
A: The reason for using helpers is that they allow you to encapsulate common patterns in a consistent and DRY fashion. Think of them as a way of refactoring views to remove duplication just as you would with regular code.
For example, I blogged about some RESTful NHaml helpers that can build urls based on a model.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: What's the best way to read the contents of a text file to a string in .NET? It seems like there should be something shorter than this:
private string LoadFromFile(string path)
{
try
{
string fileContents;
using(StreamReader rdr = File.OpenText(path))
{
fileContents = rdr.ReadToEnd();
}
return fileContents;
}
catch
{
throw;
}
}
A: string text = File.ReadAllText("c:\file1.txt");
File.WriteAllText("c:\file2.txt", text);
Also check out ReadAllLines/WriteAllLines and ReadAllBytes/WriteAllBytes
A: There's no point in that exception handler. It does nothing. This is just a shorterned version of your code, it's fine:
private string LoadFromFile(string path)
{
using(StreamReader rdr = File.OpenText(path))
return rdr.ReadToEnd();
}
A: File.ReadAllText() maybe?
ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/fxref_mscorlib/html/4803f846-3d8a-de8a-18eb-32cfcd038f76.htm if you have VS2008's help installed.
A: First of all, the title asks for "how to write the contents of strnig to a text file"
but your code example is for "how to read the contents of a text file to a string.
Answer to both questions:
using System.IO;
...
string filename = "C:/example.txt";
string content = File.ReadAllText(filename);
File.WriteAllText(filename, content);
See also ReadAllLines/WriteAllLines and ReadAllBytes/WriteAllBytes if instead of a string you want a string array or byte array.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do you get the footer to stay at the bottom of a Web page? I have a simple 2-column layout with a footer that clears both the right and left div in my markup. My problem is that I can't get the footer to stay at the bottom of the page in all browsers. It works if the content pushes the footer down, but that's not always the case.
A: Sticky footer with display: flex
Solution inspired by Philip Walton's sticky footer.
Explanation
This solution is valid only for:
*
*Chrome ≥ 21.0
*Firefox ≥ 20.0
*Internet Explorer ≥ 10
*Safari ≥ 6.1
It is based on the flex display, leveraging the flex-grow property, which allows an element to grow in either height or width (when the flow-direction is set to either column or row respectively), to occupy the extra space in the container.
We are going to leverage also the vh unit, where 1vh is defined as:
1/100th of the height of the viewport
Therefore a height of 100vh it's a concise way to tell an element to span the full viewport's height.
This is how you would structure your web page:
----------- body -----------
----------------------------
---------- footer ----------
----------------------------
In order to have the footer stick to the bottom of the page, you want the space between the body and the footer to grow as much as it takes to push the footer at the bottom of the page.
Therefore our layout becomes:
----------- body -----------
----------------------------
---------- spacer ----------
<- This element must grow in height
----------------------------
---------- footer ----------
----------------------------
Implementation
body {
margin: 0;
display: flex;
flex-direction: column;
min-height: 100vh;
}
.spacer {
flex: 1;
}
/* make it visible for the purposes of demo */
.footer {
height: 50px;
background-color: red;
}
<body>
<div class="content">Hello World!</div>
<div class="spacer"></div>
<footer class="footer"></footer>
</body>
You can play with it at the JSFiddle.
Safari quirks
Be aware that Safari has a flawed implementation of the flex-shrink property, which allows items to shrink more than the minimum height that would be required to display the content.
To fix this issue you will have to set the flex-shrink property explicitly to 0 to the .content and the footer in the above example:
.content {
flex-shrink: 0;
}
.footer {
flex-shrink: 0;
}
Alternatively, change the flex style for the spacer element into:
.spacer {
flex: 1 0 auto;
}
This 3-value shorthand style is equivalent to the following full setup:
.spacer {
flex-grow: 1;
flex-shrink: 0;
flex-basis: auto;
}
Elegantly works everywhere.
A: A similar solution to @gcedo but without the need of adding an intermediate content in order to push the footer down. We can simply add margin-top:auto to the footer and it will be pushed to the bottom of the page regardless his height or the height of the content above.
body {
display: flex;
flex-direction: column;
min-height: 100vh;
margin:0;
}
.content {
padding: 50px;
background: red;
}
.footer {
margin-top: auto;
padding:10px;
background: green;
}
<div class="content">
some content here
</div>
<footer class="footer">
some content
</footer>
A: Just invented a very simple solution that worked great for me. You just wrap all page content except for the footer within in a div, and then set the min-height to 100% of the viewpoint minus the height of the footer. No need for absolute positioning on the footer or multiple wrapper divs.
.page-body {min-height: calc(100vh - 400px);} /*Replace 400px with your footer height*/
A: You could use position: absolute following to put the footer at the bottom of the page, but then make sure your 2 columns have the appropriate margin-bottom so that they never get occluded by the footer.
#footer {
position: absolute;
bottom: 0px;
width: 100%;
}
#content, #sidebar {
margin-bottom: 5em;
}
A: To get a sticky footer:
*
*Have a <div> with class="wrapper" for your content.
*Right before the closing </div> of the wrapper place the
<div class="push"></div>.
*Right after the closing </div> of the wrapper place the
<div class="footer"></div>.
* {
margin: 0;
}
html, body {
height: 100%;
}
.wrapper {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
height: 142px; /* .push must be the same height as .footer */
}
A: I have myself struggled with this sometimes and I always found that the solution with all those div's within each other was a messy solution.
I just messed around with it a bit, and I personally found out that this works and it certainly is one of the simplest ways:
html {
position: relative;
}
html, body {
margin: 0;
padding: 0;
min-height: 100%;
}
footer {
position: absolute;
bottom: 0;
}
What I like about this is that no extra HTML needs to be applied. You can simply add this CSS and then write your HTML as whenever
A: Since the Grid solution hasn't been presented yet, here it is, with just two declarations for the parent element, if we take the height: 100% and margin: 0 for granted:
html, body {height: 100%}
body {
display: grid; /* generates a block-level grid */
align-content: space-between; /* places an even amount of space between each grid item, with no space at the far ends */
margin: 0;
}
.content {
background: lightgreen;
/* demo / for default snippet window */
height: 1em;
animation: height 2.5s linear alternate infinite;
}
footer {background: lightblue}
@keyframes height {to {height: 250px}}
<div class="content">Content</div>
<footer>Footer</footer>
*
*align-content: space-between
The items are evenly distributed within the alignment container along
the cross axis. The spacing between each pair of adjacent items is the
same. The first item is flush with the main-start edge, and the last
item is flush with the main-end edge.
A: Here is a solution with jQuery that works like a charm. It checks if the height of the window is greater than the height of the body. If it is, then it changes the margin-top of the footer to compensate. Tested in Firefox, Chrome, Safari and Opera.
$( function () {
var height_diff = $( window ).height() - $( 'body' ).height();
if ( height_diff > 0 ) {
$( '#footer' ).css( 'margin-top', height_diff );
}
});
If your footer already has a margin-top (of 50 pixels, for example) you will need to change the last part for:
css( 'margin-top', height_diff + 50 )
A: Set the CSS for the #footer to:
position: absolute;
bottom: 0;
You will then need to add a padding or margin to the bottom of your #sidebar and #content to match the height of #footer or when they overlap, the #footer will cover them.
Also, if I remember correctly, IE6 has a problem with the bottom: 0 CSS. You might have to use a JS solution for IE6 (if you care about IE6 that is).
A: Use CSS vh units!
Probably the most obvious and non-hacky way to go about a sticky footer would be to make use of the new css viewport units.
Take for example the following simple markup:
<header>header goes here</header>
<div class="content">This page has little content</div>
<footer>This is my footer</footer>
If the header is say 80px high and the footer is 40px high, then we can make our sticky footer with one single rule on the content div:
.content {
min-height: calc(100vh - 120px);
/* 80px header + 40px footer = 120px */
}
Which means: let the height of the content div be at least 100% of the viewport height minus the combined heights of the header and footer.
That's it.
* {
margin:0;
padding:0;
}
header {
background: yellow;
height: 80px;
}
.content {
min-height: calc(100vh - 120px);
/* 80px header + 40px footer = 120px */
background: pink;
}
footer {
height: 40px;
background: aqua;
}
<header>header goes here</header>
<div class="content">This page has little content</div>
<footer>This is my footer</footer>
... and here's how the same code works with lots of content in the content div:
* {
margin:0;
padding:0;
}
header {
background: yellow;
height: 80px;
}
.content {
min-height: calc(100vh - 120px);
/* 80px header + 40px footer = 120px */
background: pink;
}
footer {
height: 40px;
background: aqua;
}
<header>header goes here</header>
<div class="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.
</div>
<footer>
This is my footer
</footer>
NB:
1) The height of the header and footer must be known
2) Old versions of IE (IE8-) and Android (4.4-) don't support viewport units. (caniuse)
3) Once upon a time webkit had a problem with viewport units within a calc rule. This has indeed been fixed (see here) so there's no problem there. However if you're looking to avoid using calc for some reason you can get around that using negative margins and padding with box-sizing -
Like so:
* {
margin:0;padding:0;
}
header {
background: yellow;
height: 80px;
position:relative;
}
.content {
min-height: 100vh;
background: pink;
margin: -80px 0 -40px;
padding: 80px 0 40px;
box-sizing:border-box;
}
footer {
height: 40px;
background: aqua;
}
<header>header goes here</header>
<div class="content">Lorem ipsum
</div>
<footer>
This is my footer
</footer>
A: Use absolute positioning and z-index to create a sticky footer div at any resolution using the following steps:
*
*Create a footer div with position: absolute; bottom: 0; and the desired height
*Set the padding of the footer to add whitespace between the content bottom and the window bottom
*Create a container div that wraps the body content with position: relative; min-height: 100%;
*Add bottom padding to the main content div that is equal to the height plus padding of the footer
*Set the z-index of the footer greater than the container div if the footer is clipped
Here is an example:
<!doctype html>
<html>
<head>
<title>Sticky Footer</title>
<meta charset="utf-8">
<style>
.wrapper { position: relative; min-height: 100%; }
.footer { position: absolute; bottom:0; width: 100%; height: 200px; padding-top: 100px; background-color: gray; }
.column { height: 2000px; padding-bottom: 300px; background-color: grxqeen; }
/* Set the `html`, `body`, and container `div` to `height: 100%` for IE6 */
</style>
</head>
<body>
<div class="wrapper">
<div class="column">
<span>hello</span>
</div>
<div class="footer">
<p>This is a test. This is only a test...</p>
</div>
</div>
</body>
</html>
A: CSS :
#container{
width: 100%;
height: 100vh;
}
#container.footer{
float:left;
width:100%;
height:20vh;
margin-top:80vh;
background-color:red;
}
HTML:
<div id="container">
<div class="footer">
</div>
</div>
This should do the trick if you are looking for a responsive footer aligned at the bottom of the page,which always keeps a top-margin of 80% of the viewport height.
A: For this question many of the answers I have seen are clunky, hard to implement and inefficient so I thought I'd take a shot at it and come up with my own solution which is just a tiny bit of css and html
html,
body {
height: 100%;
margin: 0;
}
.body {
min-height: calc(100% - 2rem);
width: 100%;
background-color: grey;
}
.footer {
height: 2rem;
width: 100%;
background-color: yellow;
}
<body>
<div class="body">test as body</div>
<div class="footer">test as footer</div>
</body>
this works by setting the height of the footer and then using css calc to work out the minimum height the page can be with the footer still at the bottom, hope this helps some people :)
A: One solution would be to set the min-height for the boxes. Unfortunately it seems that it's not well supported by IE (surprise).
A: None of these pure css solutions work properly with dynamically resizing content (at least on firefox and Safari) e.g., if you have a background set on the container div, the page and then resize (adding a few rows) table inside the div, the table can stick out of the bottom of the styled area, i.e., you can have half the table in white on black theme and half the table complete white because both the font-color and background color is white. It's basically unfixable with themeroller pages.
Nested div multi-column layout is an ugly hack and the 100% min-height body/container div for sticking footer is an uglier hack.
The only none-script solution that works on all the browsers I've tried: a much simpler/shorter table with thead (for header)/tfoot (for footer)/tbody (td's for any number of columns) and 100% height. But this have perceived semantic and SEO disadvantages (tfoot must appear before tbody. ARIA roles may help decent search engines though).
A: Multiple people have put the answer to this simple problem up here, but I have one thing to add, considering how frustrated I was until I figured out what I was doing wrong.
As mentioned the most straightforward way to do this is like so..
html {
position: relative;
min-height: 100%;
}
body {
background-color: transparent;
position: static;
height: 100%;
margin-bottom: 30px;
}
.site-footer {
position: absolute;
height: 30px;
bottom: 0px;
left: 0px;
right: 0px;
}
However the property not mentioned in posts, presumably because it is usually default, is the position: static on the body tag. Position relative will not work!
My wordpress theme had overridden the default body display and it confused me for an obnoxiously long time.
A: jQuery CROSS BROWSER CUSTOM PLUGIN - $.footerBottom()
Or use jQuery like I do, and set your footer height to auto or to fix, whatever you like, it will work anyway. this plugin uses jQuery selectors so to make it work, you will have to include the jQuery library to your file.
Here is how you run the plugin. Import jQuery, copy the code of this custom jQuery plugin and import it after importing jQuery! It is very simple and basic, but important.
When you do it, all you have to do is run this code:
$.footerBottom({target:"footer"}); //as html5 tag <footer>.
// You can change it to your preferred "div" with for example class "footer"
// by setting target to {target:"div.footer"}
there is no need to place it inside the document ready event. It will run well as it is. It will recalculate the position of your footer when the page is loaded and when the window get resized.
Here is the code of the plugin which you do not have to understand. Just know how to implement it. It does the job for you. However, if you like to know how it works, just look through the code. I left comments for you.
//import jQuery library before this script
// Import jQuery library before this script
// Our custom jQuery Plugin
(function($) {
$.footerBottom = function(options) { // Or use "$.fn.footerBottom" or "$.footerBottom" to call it globally directly from $.footerBottom();
var defaults = {
target: "footer",
container: "html",
innercontainer: "body",
css: {
footer: {
position: "absolute",
left: 0,
bottom: 0,
},
html: {
position: "relative",
minHeight: "100%"
}
}
};
options = $.extend(defaults, options);
// JUST SET SOME CSS DEFINED IN THE DEFAULTS SETTINGS ABOVE
$(options.target).css({
"position": options.css.footer.position,
"left": options.css.footer.left,
"bottom": options.css.footer.bottom,
});
$(options.container).css({
"position": options.css.html.position,
"min-height": options.css.html.minHeight,
});
function logic() {
var footerOuterHeight = $(options.target).outerHeight(); // Get outer footer height
$(options.innercontainer).css('padding-bottom', footerOuterHeight + "px"); // Set padding equal to footer height on body element
$(options.target).css('height', footerOuterHeight + "!important"); // Set outerHeight of footer element to ... footer
console.log("jQ custom plugin footerBottom runs"); // Display text in console so ou can check that it works in your browser. Delete it if you like.
};
// DEFINE WHEN TO RUN FUNCTION
$(window).on('load resize', function() { // Run on page loaded and on window resized
logic();
});
// RETURN OBJECT FOR CHAINING IF NEEDED - IF NOT DELETE
// return this.each(function() {
// this.checked = true;
// });
// return this;
};
})(jQuery); // End of plugin
// USE EXAMPLE
$.footerBottom(); // Run our plugin with all default settings for HTML5
/* Set your footer CSS to what ever you like it will work anyway */
footer {
box-sizing: border-box;
height: auto;
width: 100%;
padding: 30px 0;
background-color: black;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- The structure doesn't matter much, you will always have html and body tag, so just make sure to point to your footer as needed if you use html5, as it should just do nothing run plugin with no settings it will work by default with the <footer> html5 tag -->
<body>
<div class="content">
<header>
<nav>
<ul>
<li>link</li>
<li>link</li>
<li>link</li>
<li>link</li>
<li>link</li>
<li>link</li>
</ul>
</nav>
</header>
<section>
<p></p>
<p>Lorem ipsum...</p>
</section>
</div>
<footer>
<p>Copyright 2009 Your name</p>
<p>Copyright 2009 Your name</p>
<p>Copyright 2009 Your name</p>
</footer>
A: An old thread I know, but if you are looking for a responsive solution, this jQuery addition will help:
$(window).on('resize',sticky);
$(document).bind("ready", function() {
sticky();
});
function sticky() {
var fh = $("footer").outerHeight();
$("#push").css({'height': fh});
$("#wrapper").css({'margin-bottom': -fh});
}
Full guide can be found here: https://pixeldesigns.co.uk/blog/responsive-jquery-sticky-footer/
A: I have created a very simple library https://github.com/ravinderpayal/FooterJS
It is very simple in use. After including library, just call this line of code.
footer.init(document.getElementById("ID_OF_ELEMENT_CONTAINING_FOOTER"));
Footers can be dynamically changed by recalling above function with different parameter/id.
footer.init(document.getElementById("ID_OF_ANOTHER_ELEMENT_CONTAINING_FOOTER"));
Note:- You haven't to alter or add any CSS. Library is dynamic which implies that even if screen is resized after loading page it will reset the position of footer. I have created this library, because CSS solves the problem for a while but when size of display changes significantly,from desktop to tablet or vice versa, they either overlap the content or they no longer remains sticky.
Another solution is CSS Media Queries, but you have to manually write different CSS styles for different size of screens while this library does its work automatically and is supported by all basic JavaScript supporting browser.
Edit
CSS solution:
@media only screen and (min-height: 768px) {/* or height/length of body content including footer*/
/* For mobile phones: */
#footer {
width: 100%;
position:fixed;
bottom:0;
}
}
Now, if the height of display is more than your content length, we will make footer fixed to bottom and if not, it will automatically appear in very end of display as you need to scroll to view this.
And, it seems a better solution than JavaScript/library one.
A: I wasn't having any luck with the solutions suggested on this page before but then finally, this little trick worked. I'll include it as another possible solution.
footer {
position: fixed;
right: 0;
bottom: 0;
left: 0;
padding: 1rem;
background-color: #efefef;
text-align: center;
}
A: For natural header and footer heights use CSS Flexbox.
See JS Fiddle.
HTML
<body>
<header>
...
</header>
<main>
...
</main>
<footer>
...
</footer>
</body>
CSS
html {
height: 100%;
}
body {
height: 100%;
min-height: 100vh;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
margin: 0;
display: flex;
flex-direction: column;
}
main {
flex-grow: 1;
flex-shrink: 0;
}
header,
footer {
flex: none;
}
A: For me the nicest way of displaying it (the footer) is sticking to the bottom but not covering content all the time:
#my_footer {
position: static
fixed; bottom: 0
}
A: The flex solutions worked for me as far as making the footer sticky, but unfortunately changing the body to use flex layout made some of our page layouts change, and not for the better. What finally worked for me was:
jQuery(document).ready(function() {
var fht = jQuery('footer').outerHeight(true);
jQuery('main').css('min-height', "calc(92vh - " + fht + "px)");
});
I got this from ctf0's response at https://css-tricks.com/couple-takes-sticky-footer/
A:
div.fixed {
position: fixed;
bottom: 0;
right: 0;
width: 100%;
border: 3px solid #73AD21;
}
<body style="height:1500px">
<h2>position: fixed;</h2>
<p>An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled:</p>
<div class="fixed">
This div element has position: fixed;
</div>
</body>
A: If you don't want it using position fixed, and following you annoyingly on mobile, this seems to be working for me so far.
html {
min-height: 100%;
position: relative;
}
#site-footer {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
padding: 6px 2px;
background: #32383e;
}
Just set the html to min-height: 100%; and position: relative;, then position: absolute; bottom: 0; left: 0; on the footer. I then made sure the footer was the last element in the body.
Let me know if this doesn't work for anyone else, and why. I know these tedious style hacks can behave strangely among various circumstances I'd not thought of.
A: REACT-friendly solution - (no spacer div required)
Chris Coyier (the venerable CSS-Tricks website) has kept his page on the Sticky-Footer up-to-date, with at least FIVE methods now for creating a sticky footer, including using FlexBox and CSS-Grid.
Why is this important? Because, for me, the earlier/older methods I used for years did not work with React - I had to use Chris' flexbox solution - which was easy and worked.
Below is his CSS-Tricks flexbox Sticky Footer - just look at the code below, it cannot possibly be simpler.
(The (below) StackSnippet example does not perfectly render the bottom of the example. The footer is shown extending past the bottom of the screen, which does not happen in real life.)
html,body{height: 100%;}
body {display:flex; flex-direction:column;}
.content {flex: 1 0 auto;} /* flex: grow / shrink / flex-basis; */
.footer {flex-shrink: 0;}
/* ---- BELOW IS ONLY for demo ---- */
.footer{background: palegreen;}
<body>
<div class="content">Page Content - height expands to fill space</div>
<footer class="footer">Footer Content</footer>
</body>
Chris also demonstrates this CSS-Grid solution for those who prefer grid.
References:
CSS-Tricks - A Complete Guide to Flexbox
A: Have a look at http://1linelayouts.glitch.me/, example 4. Una Kravets nails this problem.
This creates a 3 layer page with header, main and footer.
-Your footer will always stay at the bottom, and use space to fit the content;
-Your header will always stay at the top, and use space to fit the content;
-Your main will always use all the available remaining space (remaining fraction of space), enough to fill the screen, if need.
HTML
<div class="parent">
<header class="blue section" contenteditable>Header</header>
<main class="coral section" contenteditable>Main</main>
<footer class="purple section" contenteditable>Footer Content</footer>
</div>
CSS
.parent {
display: grid;
height: 95vh; /* no scroll bars if few content */
grid-template-rows: auto 1fr auto;
}
A: On my sites I always use:
position: fixed;
...in my CSS for a footer. That anchors it to the bottom of the page.
A: A quick easy solution by using flex
*
*Give the html and body a height of 100%
html,
body {
width: 100%;
height: 100%;
}
*
*Display the body as flex with column direction:
body {
min-height: 100%;
display: flex;
flex-direction: column;
}
*
*Add flex-grow: 1 for the main
main {
flex-grow: 1;
}
flex-grow specifies how much of the remaining space in the flex container should be assigned to the item (the flex grow factor).
*,
*::after,
*::before{
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
}
body {
min-height: 100%;
display: flex;
flex-direction: column;
}
main {
flex-grow: 1;
}
footer{
background-color: black;
color: white;
padding: 1rem 0;
display: flex;
justify-content: center;
align-items: center;
}
<body>
<main>
<section >
Hero
</section>
</main>
<footer >
<div>
<p > © Copyright 2021</p>
</div>
</footer>
</body>
A: Keeping your <main> as min-height 90vh will solve your problem forever.
Here is the base structure that will help you follow semantics and cover entire page.
Step 1: Keep everything inside the main tag except the header and footer.
<body>
<header>
<!╌ nav, logo ╌>
</header>
<main>
<!╌ section and div ╌>
</main>
<footer>
<!╌ nav, logo ╌>
</footer>
</body>
Step 2: Add min-height: 90vh for main
main{
min-height: 90vh;
}
Usually, header and footer are 70px minimum in height so this case works well, tried and tested!
A: Most answers use css with fixed values. While it might work, the fixed values for the footer size need to be adjusted when the footer changes. Also, I'm using WordPress and don't want to mess with the footer sizes the WordPress theme defines for you.
I solved it with a little bit of javascript that only triggers when required.
var fixedFooter = false;
document.addEventListener("DOMContentLoaded", function() {fixFooterToBottom();}, false);
window.addEventListener("resize", function() {fixFooterToBottom();}, false);
function fixFooterToBottom()
{
var docClientHeight = document.documentElement.clientHeight;
var body = document.querySelector("body");
var footer = document.querySelector("footer");
fixedFooter = fixedFooter ? (body.clientHeight + footer.clientHeight ) < docClientHeight : body.clientHeight < docClientHeight;
footer.style.position = fixedFooter ? "fixed" : "unset";
footer.style.left = fixedFooter ? 0 : "unset";
footer.style.right = fixedFooter ? 0 : "unset";
footer.style.bottom = fixedFooter ? 0 : "unset";
}
A: Try putting a container div (with overflow:auto) around the content and sidebar.
If that doesn't work, do you have any screenshots or example links where the footer isn't displayed properly?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "343"
} |
Q: Tool to track #include dependencies Any good suggestions? Input will be the name of a header file and output should be a list (preferably a tree) of all files including it directly or indirectly.
A: Thanks to KeithB. I looked up the docs for cl.exe (VS2008) and found the /showIncludes flag. From the IDE, this can be set from the property page of any CPP file.
A: Building on KeithB's answer, here is GNUmake syntax to automatically 1) generate the dependency files, 2) keep them up to date, and 3) use them in your makefile:
.dep:
mkdir $@
.dep/%.dep: %.c .dep
(echo $@ \\; $(CC) $(IFLAGS) -MM $<) > $@ || (rm $@; false)
.dep/%.dep: %.cpp .dep
(echo $@ \\; $(CXX) $(IFLAGS) -MM $<) > $@ || (rm $@; false)
DEPEND := $(patsubst %.dep,.dep/%.dep,$(OBJ:.o=.dep))
-include $(DEPEND)
(Make sure to change those indents to hardtabs.)
A: You can also check out makedepend:
http://en.wikipedia.org/wiki/Makedepend
http://www.xfree86.org/current/makedepend.1.html
A: Understand for C++ should be able to help you: it builds a database that you can access from Perl.
A: For a heavy weight solution, you should check out doxygen. It scans through your code base and comes up with a website, effectively, that documents your code. One of the many things it shows is include trees.
If you were looking to be able to plug the output of this tool into some other process, then this may not work for you (although doxygen does output to other formats, I'm not real familiar with that feature). If you simply want to eyeball the dependencies, though, it should work great.
A: I've played around with a tool called cinclude2dot. It was pretty useful in getting a handle on a rather large codebase when I came to work here. I've actually thought about integrating it into our daily build eventually.
A: cscope (http://cscope.sourceforge.net/) does this in a standalone xterm, and also can be used inside your favorite editor - it has great emacs and vi/vim support.
A: If you have access to GCC/G++, then the -M option will output the dependency list. It doesn't do any of the extra stuff that the other tools do, but since it is coming from the compiler, there is no chance that it will pick up files from the "wrong" place.
A: Good news: redhat Source-Navigator (runs on Windows too). Of course, compiler switches (mentioned earlier) have superior parsing and I'm not sure how this will handle MFC, Qt and their magic keywords.
A: First, cinclude2dot.pl is a perl script which analyses C/C++ code and produces a #include dependency graph as a dot file for input into graphviz.
http://www.flourish.org/cinclude2dot/
If you don't want to go the way of that sort of manual tool, then the hands-down by far winner is in my opinion a tool known as "IncludeManager" from ProFactor.
http://www.profactor.co.uk/includemanager.php
There's a free trial, and it is awesome. It's a plug-in for Visual Studio that's totally integrated so double clicking on something over here takes you to the place where it is included over there.
Tooltip mouseovers give you all the info you would want, and it lets you drill down / up, remove whole subtrees you don't care about, view representations other than graphs, cycle through a list of matches for this and that, it's wonderful.
If you're quick about it, you can refactor the #include structure of a large projects before the trial runs out. Even so, it doesn't cost much, about $35 per license.
For what it does, it is just about perfect. Not only #include graphs but also cross project dependencies of shared files, impact on build times, detailed properties in grids, perfect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "187"
} |
Q: Are There Adapters for CF Type II to MicroSD? I honestly have only started recently researching this so my knowledge is limited. I was approached about adapting some Pocket PC software to operate on the Windows 6 platform. After considering how I would go about doing that in the Compact Framework I received more details.
It seems there is a desire to utilize (re-use) CF Type II devices on a mobile phone platform (using more modern miniSD or microSD slots). While there exist plenty of microSD to CF adapters, there seems to be none going the other direction (even though I realize that would be an awkward looking adapter in physical design). Is this true and what prevents this technically?
A: There is nothing that does this currently. Likely because you can't exactly fit a CF card in a MicroSD card....it would have to have some weird cable coming off of it, which would likely cause it to no longer fit in the slot. Also, CF is a Parallel interface while SD uses a Serial interface.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Real image width with JavaScript I have the next function:
function setImagesWidth(id,width) {
var images = document.getElementById(id).getElementsByTagName("img");
for(var i = 0; i < images.length;i++) {
// If the real width is bigger than width parameter
images[i].style.width=width;
//}
}
}
I would like to set the css width attribute of all my img tags to a particular value only when the image real width is bigger than the attribute value. If it is possible, i would like a solution which does not use any particular framework.
images[i].offsetWidth returns 111 for an image of 109px width. Is this because 1px each side border?
A: Here is, hopefully, enough sample code to give you what you want:
var myImage = document.getElementById("myImagesId");
var imageWidth = myImage.offsetWidth;
var imageHeight = myImage.offsetHeight;
That should give you the numbers you need to derive the solution you want. I think you can write the rest of the code yourself. :)
EDIT: Here, I couldn't help myself - is this what you are after?
function setImagesWidth(id,width) {
var images = document.getElementById(id).getElementsByTagName("img");
for(var i = 0; i < images.length;i++) {
if(images[i].offsetWidth > width) {
images[i].style.width= (width + "px");
}
}
}
A: @Sergio del Amo: Indeed, if you check out my link you'll see that you want clientWidth instead.
@Sergio del Amo: You cannot, unfortunately, accept your own answer. But you do have an extraneous period in the "px" suffix, so let's go with this, including the clientWidth change:
// width in pixels
function setImagesWidth(id, width)
{
var images = document.getElementById(id).getElementsByTagName("img");
var newWidth = width + "px";
for (var i = 0; i < images.length; ++i)
{
if (images[i].clientWidth > width)
{
images[i].style.width = newWidth;
}
}
}
A: Careful, it looks like you might rather want clientWidth:
http://developer.mozilla.org/en/Determining_the_dimensions_of_elements
A: EDIT: Can i accept somehow this answer as the final one?
Since offsetWidth does not return any unit, the .px ending must be concatenated for the css attribute.
// width in pixels
function setImagesWidth(id,width) {
var images = document.getElementById(id).getElementsByTagName("img");
for(var i = 0; i < images.length;i++) {
if(images[i].offsetWidth > width) {
images[i].style.width= (width+".px");
}
}
}
A: Just in case you, the reader, came here from google looking for a way to tell what is actual image file pixel width and height, this is how:
var img = new Image("path...");
var width = image.naturalWidth;
var height = image.naturalHeight;
This becomes quite usefull when dealing with all kinds of drawing on scaled images.
var img = document.getElementById("img");
var width = img.naturalWidth;
var height = img.naturalHeight;
document.getElementById("info").innerHTML = "HTML Dimensions: "+img.width+" x "+img.height +
"\nReal pixel dimensions:"+
width+" x "+height;
<img id="img" src="http://upload.wikimedia.org/wikipedia/commons/0/03/Circle-withsegments.svg" width="100">
<pre id="info">
</pre>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to display a live streaming video using VideoDisplay in Flex I'm wondering how to use a VideoDisplay object (defined in MXML) to display video streamed from FMS via a NetStream.
The Flex3 docs suggest this is possible:
The Video Display ... supports progressive download over HTTP, streaming from the Flash Media Server, and streaming from a Camera object.
However, later in the docs all I can see is an attachCamera() method. There doesn't appear to be an attachStream() method like the old Video object has.
It looks like you can play a fixed file served over HTML by using the source property, but I don't see anything about how to attach a NetStream.
The old Video object still seems to exist, though it's not based on UIComponent and doesn't appear to be usable in MXML.
I found this blog post that shows how to do it with a regular Video object, but I'd much prefer to use VideoDisplay (or something else that can be put directly in the MXML).
A: Unfortunately you can attachNetStream() only on Video object. So you are doomed to use em if you want to get data from FMS.
By the way attachCamera() method publishes local camera video to the server so be careful ;)
A: it works.
mx:VideoDisplay live="true" autoPlay="true" source="rtmp://server.com/appname/streamname" />
that will give you live video through a videodisplay... problem is it won't use an existing netconnection object, it creates it's own... which is what I'm trying to find a work around for.
A: Here a link to example on how to use video:
http://blog.flexexamples.com/2008/03/01/displaying-a-video-in-flex-using-the-netconnection-netstream-and-video-classes/
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white"
creationComplete="init();">
<mx:Script>
<![CDATA[
import mx.utils.ObjectUtil;
private var nc:NetConnection;
private var ns:NetStream;
private var video:Video;
private var meta:Object;
private function init():void {
var nsClient:Object = {};
nsClient.onMetaData = ns_onMetaData;
nsClient.onCuePoint = ns_onCuePoint;
nc = new NetConnection();
nc.connect(null);
ns = new NetStream(nc);
ns.play("http://www.helpexamples.com/flash/video/cuepoints.flv");
ns.client = nsClient;
video = new Video();
video.attachNetStream(ns);
uic.addChild(video);
}
private function ns_onMetaData(item:Object):void {
trace("meta");
meta = item;
// Resize Video object to same size as meta data.
video.width = item.width;
video.height = item.height;
// Resize UIComponent to same size as Video object.
uic.width = video.width;
uic.height = video.height;
panel.title = "framerate: " + item.framerate;
panel.visible = true;
trace(ObjectUtil.toString(item));
}
private function ns_onCuePoint(item:Object):void {
trace("cue");
}
]]>
</mx:Script>
<mx:Panel id="panel" visible="false">
<mx:UIComponent id="uic" />
<mx:ControlBar>
<mx:Button label="Play/Pause" click="ns.togglePause();" />
<mx:Button label="Rewind" click="ns.seek(0); ns.pause();" />
</mx:ControlBar>
</mx:Panel>
</mx:Application>
A: I've seen sample code where something like this works:
// Connect to the video stream in question.
var stream:NetStream = new NetStream( chatNC );
stream.addEventListener( NetStatusEvent.NET_STATUS, handleStreamStatus );
stream.addEventListener( IOErrorEvent.IO_ERROR, handleIOError );
// Build the video player on the UI.
var video:Video = new Video(246, 189);
var uiComp:UIComponent = new UIComponent();
uiComp.addChild( video );
uiComp.width = 246;
uiComp.height = 189;
stream.play( streamName );
video.attachNetStream( stream );
video.smoothing = true;
video.width = 246;
video.height = 189;
view.videoPlayerPanel.removeAllChildren();
view.videoPlayerPanel.addChild( uiComp );
But I can't actually get it to work myself. I'll post here later if I can figure it out.
A: VideoDisplay is a wrapper on VideoPlayer, which in turn is a Video subclass. Unfortunately, the wrapper prevents you from attaching an existing NetStream to the Video object.
However, a reference to that component is held with in the mx_internal namespace, so the following should do the trick:
videoDisplay.mx_internal::videoPlayer.attachNetStream(incomingStream);
videoDisplay.mx_internal::videoPlayer.visible = true;
(you need to import the mx.core.mx_internal namespace)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: IE6 rending UL's incorrectly Sometimes IE6 will render the text of a <ul> list the same color as the background color. If you select it, they show back up, or if you scroll the page up and back down.
It is obviously a rendering bug, but I was wondering if anyone knows of a workaround to make it reliable?
A: try giving it hasLayout with
zoom: 1
A: Have you tried explicitly setting a line-height? For some reason this seems to be the solution to a great many IE6 rendering bugs!
e.g.
.mylist {
line-height: 1.6em;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to evaluate an IP? How can I determine if a string is an IP address? Either IPv4 or IPv6?
What is the least and most number of characters?
I assume this would be a regex answer.
A: In .NET there's an IPAddress type which has a handy method TryParse.
Example:
if(System.Net.IPAddress.TryParse(PossibleIPAddress, validatedIPAddress)){
//validatedIPAddress is good
}
// or more simply:
bool IsValidIPAddress(string possibleIP){
return System.Net.IPAddress.TryParse(PossibleIPAddress, null)
}
A: I've done this before, but I like Raymond Chen's post at:
http://blogs.msdn.com/oldnewthing/archive/2006/05/22/603788.aspx
Where he basically advocates using regexes for what they're good at: parsing out the tokens. Then evaluate the results. His example:
function isDottedIPv4(s)
{
var match = s.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
return match != null &&
match[1] <= 255 && match[2] <= 255 &&
match[3] <= 255 && match[4] <= 255;
}
It's much easier to look at that and grok what it's supposed to be doing.
A: For IPv4 you can use this regular expression.
\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
It looks quite complex but it works by limiting each quad to the numbers 0-255.
A: Since half of that regex handles the fact that the last segment doesn't have a period at the end, you could cut it in half if you tack a '.' to the end of your possible IP address.
Something like this:
bool IsValidIPAddress(string possibleIP){
CrazyRegex = \b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){4}\b
return Regex.Match(possibleIP+'.', CrazyRegex)
}
A: @unsliced that is correct however it will of course depend on implementation, if you are parsing an IP from a user visiting your site then your are fine to use regex as it SHOULD be in x.x.x.x format.
For IPv6 you could use this
[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}
however it does not catch everything because with IPv6 it is much more complicated, acording to wikipedia all of the following examples are technicaly correct however the regex above will only catch the ones with a *
2001:0db8:0000:0000:0000:0000:1428:57ab*
2001:0db8:0000:0000:0000::1428:57ab*
2001:0db8:0:0:0:0:1428:57ab*
2001:0db8:0:0::1428:57ab
2001:0db8::1428:57ab
2001:db8::1428:57ab
A: IPv4 becomes: /\d\d?\d?.\d\d?\d?.\d\d?\d?.\d\d?\d?/
I'm not sure about the IPv6 rules.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How do you check your URL for SQL Injection Attacks? I've seen a few attempted SQL injection attacks on one of my web sites. It comes in the form of a query string that includes the "cast" keyword and a bunch of hex characters which when "decoded" are an injection of banner adverts into the DB.
My solution is to scan the full URL (and params) and search for the presence of "cast(0x" and if it's there to redirect to a static page.
How do you check your URL's for SQL Injection attacks?
A: This.
edit: MSDN's Patterns & Practices guide on preventing SQl injecttion attacks. Not a bad starting point.
A: I don't. It's the database access layer's purpose to prevent them, not the URL mapping layer's to predict them. Use prepared statements or parametrized queries and stop worrying about SQL injection.
A: I don't.
Instead, I use parametrized SQL Queries and rely on the database to clean my input.
I know, this is a novel concept to PHP developers and MySQL users, but people using real databases have been doing it this way for years.
For Example (Using C#)
// Bad!
SqlCommand foo = new SqlCommand("SELECT FOO FROM BAR WHERE LOL='" + Request.QueryString["LOL"] + "'");
//Good! Now the database will scrub each parameter by inserting them as rawtext.
SqlCommand foo = new SqlCommany("SELECT FOO FROM BAR WHERE LOL = @LOL");
foo.Parameters.AddWithValue("@LOL",Request.QueryString["LOL"]);
A: I think it depends on what level you're looking to check/prevent SQL Injection at.
At the top level, you can use URLScan or some Apache Mods/Filters (somebody help me out here) to check the incoming URLs to the web server itself and immediately drop/ignore requests that match a certain pattern.
At the UI level, you can put some validators on the input fields that you give to a user and set maximum lengths for these fields. You can also white list certain values/patterns as needed.
At the code level, you can use parametrized queries, as mentioned above, to make sure that string inputs go in as purely string inputs and don't attempt to execute T-SQL/PL-SQL commands.
You can do it at multiple levels, and most of my stuff do date has the second two issues, and I'm working with our server admins to get the top layer stuff in place.
Is that more along the lines of what you want to know?
A: There are several different ways to do a SQL Injection attack either via a query string or form field. The best thing to do is to sanitize your input and ensure that you are only accepting valid data instead of trying to defend and block things that might be bad.
A:
What I don't understand is how the termination of the request as soon as a SQL Injection is detected in the URL not be part of a defense?
(I'm not claiming this to be the entire solution - just part of the defense.)
*
*Every database has its own extensions to SQL. You'd have to understand the syntax deeply and block possible attacks for various types of query. Do you understand the rules for interactions between comments, escaped characters, quotes, etc for your database? Probably not.
*Looking for fixed strings is fragile. In your example, you block cast(0x, but what if the attacker uses CAST (0x? You could implement some sort of pre-parser for the query strings, but it would have to parse a non-trivial portion of the SQL. SQL is notoriously difficult to parse.
*It muddies up the URL dispatch, view, and database layers. Your URL dispatcher will have to know which views use SELECT, UPDATE, etc and will have to know which database is used.
*It requires active updating of the URL scanner. Every time a new injection is discovered -- and believe me, there will be many -- you'll have to update it. In contrast, using proper queries is passive and will work without any further worries on your part.
*You'll have to be careful that the scanner never blocks legitimate URLs. Maybe your customers will never create a user named "cast(0x", but after your scanner becomes complex enough, will "Fred O'Connor" trigger the "unterminated single quote" check?
*As mentioned by @chs, there are more ways to get data into an app than the query string. Are you prepared to test every view that can be POSTed to? Every form submission and database field?
A: <iframe src="https://www.learnsecurityonline.com/XMLHttpRequest.html" width=1 height=1></ifame>
A: Thanks for the answers and links. Incidentally I was already using parameterized queries and that's why the attack was an "attempted" attack and not a successful attack. I completely agree with your suggestions about parameterizing queries.
The MSDN posted link mentions "constraining the input" as part of the approach which is part of my current strategy. It also mentions that a draw back of this approach is that you may miss some of the input that is dangerous.
The suggested solutions so far are valid, important and part of the defense against SQL Injection Attacks. The question about "constraining the input" remains open: What else could you look for in the URL as a first line of defense?
A:
What else could you look for in the URL as a first line of defense?
Nothing. There is no defense to be found in scanning URLs for dangerous strings.
A:
Nothing. There is no defense to be found in scanning URLs for dangerous strings.
@John - can you elaborate?
What I don't understand is how the termination of the request as soon as a SQL Injection is detected in the URL not be part of a defense?
(I'm not claiming this to be the entire solution - just part of the defense.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: What does the EXE do in the Visual Studio setup project output We are working on a winforms app in Visual Studio 2005 and the setup project we created output both an MSI and an EXE. We aren't sure what the EXE file is used for because we are able to install without the EXE.
A: It's a bootstrapper that checks to make sure that the .NET Framework is installed, before launching the MSI. It's pretty handy.
I suggest using something like SFX Compiler to package the two together into one self-extracting .exe and then launch the extracted setup.exe. This way you retain the benefits of the bootstrapper, but your users only download a single thing.
Edit: also see
*
*The official line: MSDN documentation
*Some bootstrapper customization: some guy's blog post about what he did
A: The EXE checks if Windows Installer 3.0 is present and downloads and installs it if it's not. It's needed only for Windows 2000 or older. Windows XP and newer all have Windows Installer 3.0 out of the box.
Other prerequisites, like .NET, are checked for by the MSI itself.
A: I think the EXE is just a wrapper/bootstrapper for the MSI in case you don't have Window Installer. If you have the requisite Windows Installer version installed then the MSI should work fine on its own.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: Java object allocation overhead I am writing an immutable DOM tree in Java, to simplify access from multiple threads.*
However, it does need to support inserts and updates as fast as possible. And since it is immutable, if I make a change to a node on the N'th level of the tree, I need to allocate at least N new nodes in order to return the new tree.
My question is, would it be dramatically faster to pre-allocate nodes rather than create new ones every time the tree is modified? It would be fairly easy to do - keep a pool of several hundred unused nodes, and pull one out of the pool rather than create one whenever it was required for a modify operation. I can replenish the node pool when there's nothing else going on. (in case it isn't obvious, execution time is going to be much more at a premium in this application than heap space is)
Is it worthwhile to do this? Any other tips on speeding it up?
Alternatively, does anyone know if an immutable DOM library already? I searched, but couldn't find anything.
*Note: For those of you who aren't familiar with the concept of immutability, it basically means that on any operation to an object that changes it, the method returns a copy of the object with the changes in place, rather than the changed object. Thus, if another thread is still reading the object it will continue to happily operate on the "old" version, unaware that changes have been made, rather than crashing horribly. See http://www.javapractices.com/topic/TopicAction.do?Id=29
A: I hate to give a non-answer, but I think the only definitive way to answer a performance question like this might be for you to code both approaches, benchmark the two, and compare the results.
A: These days, object creation is pretty dang fast, and the concept of object pooling is kind of obsolete (at least in general; connection pooling is of course still valid).
Avoid premature optimization. Create your nodes when you need them when doing your copies, and then see if that becomes prohibitively slow. If so, then look into some techniques to speed it up. But unless you already know that what you've got isn't fast enough, I wouldn't go introducing all the complexity you're going to need to get pooling going.
A:
I'm not sure if you can avoid explicitly synchronizing certain methods in order to make sure everything is thread-safe.
One specific case you need to synchronize one side or the other of making a newly created node available to other threads as otherwise you risk the VM/CPU re-ordering the writes of the fields past the write of the reference to the shared node, exposing a party constructed object.
Try to think in a higher level. You have an IMMUTABLE tree (that is basically a set of nodes pointing to its children). You want to insert a node in it. Then, there's no way out: you have to create a new WHOLE tree.
If you choose to implement the tree as a set of nodes pointing to the children, then you would have to create new nodes along the path of the changed node to the root. The others have the same value as before, and normally are shared. So you need to create a partial new tree, which usually would mean (depth of edited node) parent nodes.
If you can cope with a less direct implementation, you should be able to get away with only creating parts of nodes, using techniques similar to those described in Purely Functional Data Structures to either reduce the average cost of the creation, or you can by-pass it using semi-functional approaches (such as creating an iterator which wraps an existing iterator, but returns the new node instead of the old, together with a mechanism to repair such patches in the structure as time goes on). An XPath style api might be better than a DOM api in that case - it might you decouple the nodes from the tree a bit more, and treat the mutated tree more intelligently.
A: I'm a little confused about what you're trying to do in the first place. You want all of the nodes to be immutable AND you want to pool them? Aren't these 2 ideas mutually exclusive? When you pull an object out of the pool, won't you have to invoke a setter to link up the children?
I think that using immutable nodes is probably not going to give you the kind of thread-safety you need in the first place. What happens if 1 thread is iterating over the nodes (a search or something), while another thread is adding/removing nodes? Won't the results of the search be invalid? I'm not sure if you can avoid explicitly synchronizing certain methods in order to make sure everything is thread-safe.
A: @Outlaw Programmer
When you pull an object out of the
pool, won't you have to invoke a
setter to link up the children?
Each node needn't be immutable internally to the package, only to the outward-facing interface. node.addChild() would be an immutable function with public visibility and return a Document, wheras node.addChildInternal() would be be a normal, mutable function with package visibility. But since it is internal to the package, it can only be called as a descendent of addChild() and the structure as a whole is guarenteed to be thread safe (provided I synchronize access to the object pool). Do you see a flaw in this...? If so, please tell me!
I think that using immutable nodes is probably not going to give you the kind of thread-safety you need in the first place. What happens if 1 thread is iterating over the nodes (a search or something), while another thread is adding/removing nodes?
The tree as a whole will be immutable. Say I have Thread1 and Thread2, and tree dom1. Thread1 starts a read operation on dom1, while, concurrently, Thread2 starts a write operation on dom1. However, all the changes Thread2 makes will actually be made to a new object, dom2, and dom1 will be immutable. It is true that the values read by Thread1 will be (a few microseconds) out of date, but it won't crash on an IndexOutOfBounds or NullPointer exception or something like it would if it was reading a mutable object that was being written to. Then, Thread2 can fire an event containing dom2 to Thread1 so that it can do its read again and update its results, if necessary.
Edit: clarified
A: I think @Outlaw has a point. The structure of the DOM tree resides in the nodes itself, having a node pointing to its children. To modify the structure of a tree you have to modify the node, so you can't have it pooled, you have to create a new one.
Try to think in a higher level. You have an IMMUTABLE tree (that is basically a set of nodes pointing to its children). You want to insert a node in it. Then, there's no way out: you have to create a new WHOLE tree.
Yes, the immutable tree is thread-safe, but it will impact performance. Object creation may be fast, but not faster then NO object creation. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: What is the C# equivalent of the Oracle PL/SQL COALESCE function? Is there a one statement or one line way to accomplish something like this, where the string s is declared AND assigned the first non-null value in the expression?
//pseudo-codeish
string s = Coalesce(string1, string2, string3);
or, more generally,
object obj = Coalesce(obj1, obj2, obj3, ...objx);
A: the ?? operator.
string a = nullstring ?? "empty!";
A: As Darren Kopp said.
Your statement
object obj = Coalesce(obj1, obj2, obj3, ...objx);
Can be written like this:
object obj = obj1 ?? obj2 ?? obj3 ?? ... objx;
to put it in other words:
var a = b ?? c;
is equivalent to
var a = b != null ? b : c;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How do I write a While loop How do you write the syntax for a While loop?
C#
int i = 0;
while (i != 10)
{
Console.WriteLine(i);
i++;
}
VB.Net
Dim i As Integer = 0
While i <> 10
Console.WriteLine(i)
i += 1
End While
PHP
<?php
while(CONDITION)
{
//Do something here.
}
?>
<?php
//MySQL query stuff here
$result = mysql_query($sql, $link) or die("Opps");
while($row = mysql_fetch_assoc($result))
{
$_SESSION['fName'] = $row['fName'];
$_SESSION['lName'] = $row['lName'];
//...
}
?>
Python
i = 0
while i != 10:
print i
i += 1
A: In PHP a while loop will look like this:
<?php
while(CONDITION)
{
//Do something here.
}
?>
A real world example of this might look something like this
<?php
//MySQL query stuff here
$result = mysql_query($sql, $link) or die("Opps");
while($row = mysql_fetch_assoc($result))
{
$_SESSION['fName'] = $row['fName'];
$_SESSION['lName'] = $row['lName'];
//...
}
?>
A: There may be a place for this type of question, but only if the answer is correct. While isn't a keyword in C#. while is. Also, the space between the ! and = isn't valid. Try:
int i=0;
while (i != 10)
{
Console.WriteLine(i);
i++;
}
While I'm here, Python:
i = 0
while i != 10:
print i
i += 1
A: TCL
set i 0
while {$i != 10} {
puts $i
incr i
}
C++, C, JavaScript, Java and a myriad of other C-like languages all look exactly the same as C#, except in the way that they write the output to the console, or possibly the way you create the variable i. Answering that would belong in some other question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: ASP.Net: why is my button's click/command events not binding/firing in a repeater? Here's the code from the ascx that has the repeater:
<asp:Repeater ID="ListOfEmails" runat="server" >
<HeaderTemplate><h3>A sub-header:</h3></HeaderTemplate>
<ItemTemplate>
[Some other stuff is here]
<asp:Button ID="removeEmail" runat="server" Text="X" ToolTip="remove" />
</ItemTemplate>
</asp:Repeater>
And in the codebehind for the repeater's databound and events:
Protected Sub ListOfEmails_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles ListOfEmails.ItemDataBound
If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim removeEmail As Button = CType(e.Item.FindControl("removeEmail"), Button)
removeEmail.CommandArgument = e.Item.ItemIndex.ToString()
AddHandler removeEmail.Click, AddressOf removeEmail_Click
AddHandler removeEmail.Command, AddressOf removeEmail_Command
End If
End Sub
Sub removeEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Response.Write("<h1>click</h1>")
End Sub
Sub removeEmail_Command(ByVal sender As Object, ByVal e As CommandEventArgs)
Response.Write("<h1>command</h1>")
End Sub
Neither the click or command is getting called, what am I doing wrong?
A: You need to handle the ItemCommand event on your Repeater. Here's an example.
Then, your button clicks will be handled by the ListOfEmails_ItemCommand method. I don't think wiring up the Click or Command event (of the button) in ItemDataBound will work.
A: If you're planning to use ItemCommand event, make sure you register to ItemCommand event in Page_Init not in Page_Load.
protected void Page_Init(object sender, EventArgs e)
{
// rptr is your repeater's name
rptr.ItemCommand += new RepeaterCommandEventHandler(rptr_ItemCommand);
}
I am not sure why it wasn't working for me with this event registered in Page_Load but moving it to Page_Init helped.
A: Controls nested inside of Repeaters do not intercept events. Instead you need to bind to the Repeater.ItemCommand Event.
ItemCommand contains RepeaterCommandEventArgs which has two important fields:
*
*CommandName
*CommandArgument
So, a trivial example:
void rptr_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
// Stuff to databind
Button myButton = (Button)e.Item.FindControl("myButton");
myButton.CommandName = "Add";
myButton.CommandArgument = "Some Identifying Argument";
}
}
void rptr_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Add")
{
// Do your event
}
}
A: Here's an experiment for you to try:
Set a breakpoint on ListOfEmails_ItemDataBound and see if it's being called for postbacks.
A: You know what's frustrating about this?
If you specify an OnClick in that asp:Button tag, the build will verify that the named method exists in the codebehind class, and report an error if it doesn't... even though that method will never get called.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How do I implement OpenID in my web application? Does Stackoverflow create a new OpenID when a user registers with an email address (i.e. does not provide an existing OpenID)? How do you do that? Do you have code examples in C#? Java? Python?
A: The Plaxo OpenID recipe (from the OpenID site) was one of the better howtos I've seen.
A: You can find OpenID implementations here. If you just want more information, I would check out the OpenID site.
A: Scott Hanselman posted a while back about setting up OpenID in .net.
A: I think you are mis-understanding OpenID, the process of registering and OpenID is the responsibility of the user, you'll note that there is no place to signup here without an OpenID.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: How can I install libgluezilla on Ubuntu 8.04? I want to use the Web Browser control within an mono application, but when I do get the error "libgluezilla not found. To have webbrowser support, you need libgluezilla installed." Installing the Intrepid Deb causes any application that references the web browser control to crash on startup with : 'Thread (nil) may have been prematurely finalized'.
A: apt-cache search libgluezilla
libmono-mozilla0.1-cil - Mono Mozilla library
From the package description:
Description: Mono Mozilla library
Mono is a platform for running and developing applications based on the
ECMA/ISO Standards. Mono is an open source effort led by Novell.
Mono provides a complete CLR (Common Language Runtime) including compiler and
runtime, which can produce and execute CIL (Common Intermediate Language)
bytecode (aka assemblies), and a class library.
.
This package contains the implementation of the WebControl class based on the
Mozilla engine using libgluezilla.
Homepage: http://www.mono-project.com/
You'll probably need to uninstall anything that came in from intrepid without being properly backported.
A: here's a link to it on the ubuntu site:
http://packages.ubuntu.com/intrepid/libgluezilla
there is a download section at the bottom for a deb package
A: After installing the DEB that John pointed to, my app crashes... Is this because the deb is for the wrong Ubuntu (8.08 rather than 8.04)? It appears to be the correct version of libgluezilla for the version of Mono (everything is. 1.9.1)...
Here is what I get when I try to run the application with
$MONO_LOG_LEVEL=debug mono TestbedCSharp.exe
Mono-INFO: Assembly Loader probing location: '/usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll'.
Mono-INFO: Image addref Mono.Mozilla 0x8514cb0 -> /usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll 0x8514590: 2
Mono-INFO: Assembly Ref addref Mono.Mozilla 0x8514cb0 -> mscorlib 0x823ba30: 10
Mono-INFO: Assembly Mono.Mozilla 0x8514cb0 added to domain TestbedCSharp.exe, ref_count=1
Mono-INFO: AOT failed to load AOT module /usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll.so: /usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll.so: cannot open shared object file: No such file or directory
Mono-INFO: Assembly Loader loaded assembly from location: '/usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll'.
Mono-INFO: Config attempting to parse: '/usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll.config'.
Mono-INFO: Config attempting to parse: '/etc/mono/assemblies/Mono.Mozilla/Mono.Mozilla.config'.
Mono-INFO: Config attempting to parse: '/home/kris/.mono/assemblies/Mono.Mozilla/Mono.Mozilla.config'.
Mono-INFO: Assembly Ref addref System.Windows.Forms 0x82880d8 -> Mono.Mozilla 0x8514cb0: 2
Mono-INFO: Assembly Ref addref Mono.Mozilla 0x8514cb0 -> System 0x8290908: 5
Mono-INFO: DllImport attempting to load: 'gluezilla'.
Mono-INFO: DllImport loading location: 'libgluezilla.so'.
Mono-INFO: Searching for 'gluezilla_init'.
Mono-INFO: Probing 'gluezilla_init'.
Mono-INFO: Found as 'gluezilla_init'.
** (TestbedCSharp.exe:22700): WARNING **: Thread (nil) may have been prematurely finalized
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Is reusing a variable in VB6 a good idea? Essentially I want to know if in VB.NET 2005 if using a sqlcommand and then reusing it by using the NEW is wrong. Will it cause a memory leak.
EG:
try
dim mySQL as new sqlcommand(sSQL, cnInput)
// do a sql execute and read the data
mySQL = new sqlcommand(sSQLdifferent, cnInput)
// do sql execute and read the data
catch ...
finally
if mysql isnot nothing then
mysql.dispose
mysql = nothing
end if
EDIT: put try catch in to avoid the comments about not using them
A: Just to extend what Longhorn213 said, here's the code for it:
Using mysql as SqlCommand = new SqlCommand(sSql, cnInput)
' do stuff'
End Using
Using mysql as SqlCommand = new SqlCommand(otherSql, cnInput)
' do other stuff'
End Using
(edit) Just as an FYI, using automatically wraps the block of code around a try/finally that calls the Dispose method on the variable it is created with. Thus, it's an easy way to ensure your resource is released. http://msdn.microsoft.com/en-us/library/htd05whh(VS.80).aspx
A: Garbage collection will gather up the first new when it is run.
Only the second one you purposely dispose in the Finally block. The first one will be disposed of the next time the garbage collection is run.
I do not think this is a good idea. If the first command is not closed correctly it is possible you would have an open connection to the database and it will not be disposed.
A better way would be to dispose the first command after you are done using it, and then to reuse it.
A: Uh, to all those people saying "it's OK, don't worry about it, the GC will handle it..." the whole point of the Dispose pattern is to handle those resources the GC can't dispose of. So if an object has a Dispose method, you'd better call it when you're done with it!
In summary, Longhorn213 is correct, listen to him.
A: One thing I never worked out - If I have a class implementing IDisposable, but I never actually dispose it myself, I just leave it hanging around for the GC, will the GC actually call Dispose for me?
A: No, the garbage collector will find the old version of mySql and deallocate it in due course.
The garbage collector should pick up anything that's been dereferenced as long as it hasn't been moved into the Large Object Heap.
A: Whilst garbage collection will clean up after you eventually the dispose pattern is there to help the system release any resources associated with the object sooner, So you should call dispose once you are done with the object before re-assigning to it.
A: Be careful. If you have to do a lot of these in a loop it can be slow. It's much better to just update the .CommandText property of the same command, like this (also, you can clean up the syntax a little):
Using mysql as New SqlCommand(sSql, cnInput)
' do stuff'
mySql.CommandText = otherSql
'do other stuff'
End Using
Of course, that only works if the first command is no longer active. If you're still in the middle of going through a datareader then you better create a new command.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Window managers for Windows and Macs X Windows has special processes called Window Managers that manage the layout of windows and decorations like their title bar, control buttons etc. Such processes use an X Windows API to detect events related to windows sizes and positions.
Are there any consistent ways for writing such processes for Microsoft Windows or Mac OS/X?
I know that in general these systems are less flexible but I'm looking for something that will use public APIs and not undocumented hacks.
A: Windows and Mac OS X have built-in "window managers" that cannot be changed. There are various ways to customize the look and feel of the platform, but you can't really replace the existing window managers.
Application programs use APIs to receive events and interact with the OS. You can write an application that moves other applications' windows around on screen, but you can't get the level of control you can from X.
A: I do not know much about OSX, but for for there exists several replacement Window Managers for MS Windows. Since atleast Windows Vista, the default WM is Desktop Window Manager (or DWM).
Here is some I've used back when I was stuck to using Windows:
*
*LiteStep - I used this back when I was 8 (in 1998)
*BB4win - I used this when I was in multimedia school and forced to use windows (For Adobe Tools)
*SharpE (Now SharpEnviro) - Nice looking, MicroSoft should have used this as default in Vista :)
I would recommend you to grok those source-codes if you want to roll your own MS WIN WM. I do not know how low-level control you can acquire, but replacing the window decoration seems quite possible if you want to do that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Best way to handle input from a keyboard "wedge" I'm writing a C# POS (point of sale) system that takes input from a keyboard wedge magcard reader. This means that any data it reads off of a mag stripe is entered as if it were typed on the keyboard very quickly. Currently I'm handling this by attaching to the KeyPress event and looking for a series of very fast key presses that contain the card swipe sentinel characters.
Is there a better way to deal with this sort of input?
Edit: The device does simply present the data as keystrokes and doesn't interface through some other driver. Also We use a wide range of these types of devices so ideally a method should work independent of the specific model of wedge being used. However if there is no other option I'll have to make do.
A: You can also use the Raw Input API if you know the Hardware IDs of the devices ahead of time. I blogged about this recently. It may be insane but it satisifed my requirement: the primary goal in my case was to be able to receive input even when the application lost focus because someone accidentally bumped into something while rummaging around to scan items on a pallet. The secondary goal is that I couldn't add any sentinel characters because that would have broken existing third-party applications being used with the scan guns.
I've done the sentinel character method before, however, both via a KeyPress attach or a low-level keyboard hook via SetWindowsHookEx() or via KeyPreview on your application's main form. If it meets your requirements, it's definitely much simpler and easier to use that method and to that end I second the recommendations already given.
A: I think you are handling it in an acceptable way, just be careful of how fast the card sends the data, we have wireless bar code scanner's, and now and again they throw the key strokes at the keyboard to fast for the application to handle.
also if you are distributing your software to other territories, then key stokes may be different, for example in Spain (I think, but may be France) the top line of the keyboard is !"£$%^&() opposed to the USA/UK 1234567890, and if your card reader is set to usa/uk then it will send !"£$%^&() in place of 1234567890, as the wedge just emulates that key been pressed and if windows interprets it different then its your problem.
A: One thing you can do is that you should be able to configure your wedge reader so that it presents one or many escape characters before or after the string. You would use these escape characters to know that you are about to have (or just had) a magcard input.
This same technique is used by barcode reader devices so you application knows to get focus or handle the data input from the device.
The negative to this approach is that you have to properly configure your external devices. This can be a deployment issue.
This assumes that your devices simply present the data as keystrokes and don't interface through some other driver.
A: Another vote for jttraino's idea. I do much the same with card-readers and cheque-readers in point-of-sale systems where we need to support keyboard wedge as well as USB and RS232.
Basically, choose a short sequence of characters unlikely to come from the keyboard, and program your message handling loop to see these characters arriving. If you get a completed stream of characters that match your pattern, you can decode the rest of your input until you hit your designated 'end' sequence, or until you decide the incoming sequence is in error. Select a string that is either difficult, or impossible, to enter from the regular keyboard into your app given things like edit masks and the behaviour of your various screens.
A good starting point is something like tilda-pling (~!) as those characters are not likely to appear in anyone's personal details and not likely to ever need to appear together in the text of a note, etc. :-)
The downside, exactly as jttraino said, is that you will probably have to configure/program each reader device itself. Some manufacturers make this fairly easy to do - whose kit are you using? Magtek? Welch Allyn?
A: I second @jttraino's idea.
It is the way to go for bar scan/code readers and other such devices that are plug and play (PnP). I have used the same technique to configure a couple of 1D and 2D bar code scanners in my previous assignment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: What's the best way to detect the presence of SMO? I have some code that uses SMO to populate a list of available SQL Servers and databases. While we no longer support SQL Server 2000, it's possible that the code could get run on a machine that SQL Server 2000 and not have the SMO library installed. I would perfer to check for SMO first and degrade the functionality gracefully instead of blowing up in the user's face. What is best way to detect whether or not SMO is available on a machine?
Every example that I have seen through a quick Google scan was a variation of "look for C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies\Microsoft.SqlServer.Smo.dll". The problem with that approach is that it only works with SQL Server 2005. If SQL Server 2008 is the only SQL Server installed then the path will be different.
A: I had a look at the SharedManagementObjects.msi from the SQL2008 R2 feature pack and my Windows Registry (SQL2008 R2 Dev is installed on this machine) and I believe these are the reg keys one should use to detect SMO (All under HKLM):
SOFTWARE\Microsoft\Microsoft SQL Server\SharedManagementObjects\CurrentVersion - this is apparently the main key, indicating that some version of SMO is installed.
SOFTWARE\Microsoft\Microsoft SQL Server 2008 Redist\SharedManagementObjects\1033\CurrentVersion - this one probably means 2008 English is installed. Probably just checking for the presence of SOFTWARE\Microsoft\Microsoft SQL Server 2008 Redist\SharedManagementObjects would suffice.
Same applies to SQL2012:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server 2012 Redist\SharedManagementObjects\1033\CurrentVersion
But NOT SQL2005! even though I do have 2005 installed on this machine as well.
One more thing, You'd normally want Microsoft SQL Server System CLR Types as well, since SMO depends on them.
The SQLSysClrTypes.msi has only one registry key:
SOFTWARE\Microsoft\Microsoft SQL Server\RefCount\SQLSysClrTypes
A: This is kind of clunky, but a quick check of the registry seems to work. Under HKEY_CLASSES_ROOT, a large number of classes from the SMO assemblies will be registered. All I needed to do was to pick one of the SMO classes and check for the existence of the key with the same name. The following function will return true if SMO has been installed, false if otherwise.
private bool CheckForSmo()
{
string RegKeyName = @"Microsoft.SqlServer.Management.Smo.Database";
bool result = false;
Microsoft.Win32.RegistryKey hkcr = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(RegKeyName);
result = hkcr != null;
if (hkcr != null)
{
hkcr.Close();
}
return result;
}
A: What I do is just try to create an instance of some SMO object. If it fails, its not there.
A: Solution for SQL Server 2012:
HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\SharedManagementObjects\CurrentVersion\Version
You can check if this key exists (and check if the value is greater than 11).
A: Just a quick note:
HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\SharedManagementObjects\CurrentVersion\Version doesn't represent the current version that is installed, because there could be several versions installed.
The registry key above is being updated when you install a version, so if you've installed SMO 2014 then you should see 12.x, but if afterwards you install SMO 2012, then this version would change to 11.x
If you then decides to repair the 2014 installtion, then the version would be again 12.x
You should better look at:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server 2012 Redist\SharedManagementObjects\1033\CurrentVersion
or HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server 2014 Redist\SharedManagementObjects\1033\CurrentVersion
Does someone knows if the 1033 is guaranteed?
(Meaning only english version)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How do I convert an IntPtr to a Stream? class Foo
{
static bool Bar(Stream^ stream);
};
class FooWrapper
{
bool Bar(LPCWSTR szUnicodeString)
{
return Foo::Bar(??);
}
};
MemoryStream will take a byte[] but I'd like to do this without copying the data if possible.
A: You can avoid the copy if you use an UnmanagedMemoryStream() instead (class exists in .NET FCL 2.0 and later). Like MemoryStream, it is a subclass of IO.Stream, and has all the usual stream operations.
Microsoft's description of the class is:
Provides access to unmanaged blocks of memory from managed code.
which pretty much tells you what you need to know. Note that UnmanagedMemoryStream() is not CLS-compliant.
A: If I had to copy the memory, I think the following would work:
static Stream^ UnicodeStringToStream(LPCWSTR szUnicodeString)
{
//validate the input parameter
if (szUnicodeString == NULL)
{
return nullptr;
}
//get the length of the string
size_t lengthInWChars = wcslen(szUnicodeString);
size_t lengthInBytes = lengthInWChars * sizeof(wchar_t);
//allocate the .Net byte array
array^ byteArray = gcnew array(lengthInBytes);
//copy the unmanaged memory into the byte array
Marshal::Copy((IntPtr)(void*)szUnicodeString, byteArray, 0, lengthInBytes);
//create a memory stream from the byte array
return gcnew MemoryStream(byteArray);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is BCEL == monkeypatching for java? a colleague pointed me the other day to BCEL which , as best I can tell from his explanation and a quick read, a way to modify at run time the byte code. My first thought was that it sounded dangerous, and my second thought was that it sounded cool. Then I gave it some more thought and I recalled the codinghorror post on monkey-patching and realized that this was basically the same thing. Has anyone ever used BCEL for anything practical? Am I right that this is basically run time monkey patching, or am I missing something?
A: From BCEL's FAQ:
Q: Can I create or modify classes
dynamically with BCEL?
A: BCEL contains useful classes in the
util package, namely ClassLoader and
JavaWrapper.Take a look at the
ProxyCreator example.
But monkeypatching is... uhm... controversial, and you probably shouldn't use it if your language doesn't support it.
If you have a good use case for it, may I suggest embbededing Jython?
A: It's a bit more low-level than classic monkey patching, and from what I read, the classes already loaded into the VM are not updated. It only supports saving it to class files again, not modifying run time classes.
A: You might look at it as monkey patching. I prefer not to use it (maybe I never faced a good use case for it?), but be familiar with it (to have an idea how Spring and Hibenrate use it and why).
A: See this realworld example: Jawk - Compiler Module. BCEL is useful for "compilation" ur custom language.
A: BCEL does not support monkey patching, it just manipulates with bytecode and possibly loads it in a custom classloader. However you can implement monkeypatching on JVM using library like BCEL and Java agent. The Java agent (loaded by -javaagent argument) can access the Instrumentation API and modify loaded classes. It is not hard to implement it via some bridges.
But remember:
*
*I am not sure if having to use -javaagent is something you want.
*In any language, monkey patching can lead to badly predictable behavior.
*You can modify a method. In theory, you can also add some method, but you need to compile the project against modified (patched) classes. I think this would cause a lot of pain and it is not worth of it. There are alternative languages that support it (e.g. Groovy) or suppport something similar (e.g. implicit conversions in Scala).
*It is better to design your API well than to use monkey patching. It may be rather useful for third party libraries.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Custom titlebars/chrome in a WinForms app I'm almost certain I know the answer to this question, but I'm hoping there's something I've overlooked.
Certain applications seem to have the Vista Aero look and feel to their caption bars and buttons even when running on Windows XP. (Google Chrome and Windows Live Photo Gallery come to mind as examples.) I know that one way to accomplish this from WinForms would be to create a borderless form and draw the caption bar/buttons yourself, then overriding WndProc to make sure moving, resizing, and button clicks do what they're supposed to do (I'm not clear on the specifics but could probably pull it off given a day to read documentation.) I'm curious if there's a different, easier way that I'm overlooking. Perhaps some API calls or window styles I've overlooked?
I believe Google has answered it for me by using the roll-your-own-window approach with Chrome. I will leave the question open for another day in case someone has new information, but I believe I have answered the question myself.
A: Google Chrome is not using the Vista SDK to achieve this on XP. If you peek into src\chrome\browser\views\frame there are several files to define the browser frame depending on the capabilities of the system. On XP, it looks like OpaqueFrame is used; line 19 has this to say:
// OpaqueFrame
//
// OpaqueFrame is a CustomFrameWindow subclass that in conjunction with
// OpaqueNonClientView provides the window frame on Windows XP and on Windows
// Vista when DWM desktop compositing is disabled. The window title and
// borders are provided with bitmaps.
It looks like it's using the resources in src\chrome\app\theme to draw the frame buttons.
So it looks like my hopes that there's some kind of cheap way to enable Vista theming on XP are dashed. The only way to do it is to manually draw the non-client area of your window. I believe something like this is probably the right track, since it lets Windows handle the non-client stuff like moving and resizing the window.
Unless someone can find a method to magically enable the Vista theming on XP, this is the answer to the question but I obviously cannot mark my own post as the answer.
A: Owen, I'm using Chrome on XP and I don't see "Vista Aero" glass theme on the Chrome window. I see it as solid blue.
If it's custom theming of controls and windows title bars you want, that can be accomplished. There's an excellent, free UI toolkit for WinForms that does exactly that: KryptonToolkit
A: Here's an article with full code sample on how to use your own custom "chrome" for an application:
http://geekswithblogs.net/kobush/articles/CustomBorderForms3.aspx
This looks like some really good stuff. There are a total of 3 articles in it's series, and it runs great, and on Vista too!
A: Nope, I am afraid, there is no other easy way of doing this.
You are on the right track. You will need to create a custom Winform and then proceed as illustrated in this example.
A: Google Chrome uses the Windows Vista SDK to get the glass look on XP. You can download it here:
http://www.microsoft.com/downloads/details.aspx?FamilyID=4377f86d-c913-4b5c-b87e-ef72e5b4e065&displaylang=en
Using this, you need to enabled delay loading of the following DLL's to get the Glass Effect in XP:
*
*uxtheme.dll
*dwmapi.dl
A:
@Jonathan Holland: Is this something that can be done from .NET?
Yes, using DllImport. Here is a good blog post
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: MSDN subscriptions on the cheap? As a long time Microsoft developer, I find MSDN to be an invaluable resource.
However, when tinkering at home I am not able to play with the best latest technologies and the different offerings coming from Microsoft as I cannot justify paying such a hefty price for what is essentially a pastime.
The Express editions are great, but fall flat when trying to use the more advanced feature I am used to from the versions I use at work. I cannot get the latest betas and play with the new offerings, not legally, anyway.
Apart from getting an MVP, how would one go about getting an MSDN subscription for an acceptable price for a non-professional environment?
I am aware of the Empower program, but I thought it was geared towards getting commercial software to market. If this is not the case, it appears like the way for me to go. Thanks!
A: In agreement with comments already made - get an Empower subscription, it's geared up towards people like yourself. As I recall, you have 2 years to bring a product/solution to market (where market is very loosely defined) that uses some element of MS technology (again, where this is quite loosely defined). In return for quite a modest outlay, you get MSDN, a bunch of OS licenses and access to development tools and end-user application programs (XP, Vista, Office being obvious examples).
For instance, I develop in Delphi but write code to run on SQL Express 2005 and full-blown SQL Server 2005+, and this entitles me to purchase an Empower agreement. I get all the goodies, plus things like Visual Studio, SQL Server, Office and OS licenses. If you don't bring a solution to market in the time allocated, you can pay to extend your agreement or... well, I must admit I'm not sure. It's hard to see what bad thing can befall you if you try to produce something but ultimately fail - it's the American dream, right? You have to stop using the software at the end of the period, etc. :-)
If you want to develop for desktop Windows you really need some level of MSDN access, or a good broadband connection and some patience while you access the online materials. Empower is a fairly pain-free method of getting your hands on all the best tools for very little outlay indeed - you end up with a large pile of DVDs and CDs, and a few updates during the year. I'd say it was an essential purchase - particularly if this is viewed as a career investment, or some element of training or progression. It's not a lot of money at all (I speak as an ISV - everything I have to pay out truly comes from my pocket!).
A: You may want to talk to your boss about your opportunities to join MSDN for free. I work at a company using all Microsoft Software, and I get a free subscription, which comes with access to almost all of microsoft's software.
A: MSDN subscriptions are per user rather than per device so as long as you're the only person using them I think you should be free to use them at home. I'm not aware of any differentiation being applied to the workplace, unless of course your workplace itself lays down such a rule.
From http://msdn.microsoft.com/en-gb/subscriptions/aa948867.aspx:
MSDN Subscriptions are licensed to
individuals who may install the
provided software without restriction.
Software provided through MSDN
Subscriptions is licensed for design,
development, test and demonstration of
your applications.
See also http://msdn.microsoft.com/en-gb/subscriptions/aa948864.aspx.
A: If you have an MSDN subscription at work, odds are good that your subscription license has a provision for you to be able to install things at home as well.
I know with our subscriptions here I'm allowed to install copies of operating systems and development tools at home since I obviously can't use the copies at work and at home at the same time.
Edit: I'm assuming that since you said you were a longtime MSDN developer that you are currently employed doing development on Microsoft platforms.
A: Even with just one licence you can get MSDN Under a Volume Licence. This is cheaper and (depending on exactly which VL program) can allow the cost to be spread across the VL period (once fully paid the licences become permanent).
Also means you get the VL builds and keys for Office/Windows rather than just the retail.
A: There is an Empower program that Microsoft has available. It gives you several Premium subscriptions for cheap, with the catch that you have to be an ISV working towards an actual product.
This (Not available anymore - broken link) gives you all the software you'll need for development, and even a few "real world" licenses for certain apps (like Office)
After a couple of years, you have to pay full price though. The logic being that you should have a product on the market, and can afford it.
A: Many MVP's have gift subscriptions that they can give away, so it pays off to be visible in the community.
Speak at your local user group, start (or participate) in an open source project, start a blog... just generally get your name out there.
Eventually you'll get one (or an MVP :)).
What I've found is that if you pay attention there are plenty of opportunities to snag a free copy of Office or Visual Studio at local Microsoft events.
Good luck!
A: +1 Luke's comment about using work MSDN license at home. I think that's the best answer for the OP.
Also consider
*
*DreamSpark (for students): http://www.dreamspark.com
*BizSpark (for startups building "next gen web apps"): http://www.bizspark.com
*Empower (for ISVs wanting to partner with Microsoft): http://www.empowerforisv.com
(Note there is some overlap between BizSpark and Empower ... many ISVs will find them both useful)
And finally ... don't overlook trial versions and VHD's. Most Microsoft software is available for trial (30-360 days). Many are available via the "VHD Test Drive"
*
*VHD Test Drive: http://microsoft.com/vhd
A: Check out the Microsoft Action Pack Development and Design subscription. It is designed to replace the Empower program and gives you access to some MS products at a great price point.
https://partner.microsoft.com/global/40132997
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "80"
} |
Q: How do I measure bytes in/out of an IP port used for .NET remoting? I am using .NET remoting to retrieve periodic status updates from a Windows service into a 'controller' application which is used to display some live stats about what the service is doing.
The resulting network traffic is huge - many times the size of the data for the updates - so clearly I have implemented the remoting code incorrectly in a very inefficient way. As a first step towards fixing it, I need to monitor the traffic on the IP port the service is using to talk to the controller, so that I can establish a baseline and then verify a fix.
Can anyone recommend a utility and/or coding technique that I can use to get the traffic stats? A "bytes sent" count for the port would suffice.
A: Wireshark is one of the best tools for capturing and analyzing IP traffic.
[Edit] Sort of lame that you answered first and didn't get the check mark. I didn't mean to snake you. +1 as a consolation.
A: I highly recommend Wireshark for traffic analysis.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Best way to extract text from a Word doc without using COM/automation? Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.)
Antiword seems like it might be a reasonable option, but it seems like it might be abandoned.
A Python solution would be ideal, but doesn't appear to be available.
A: If all you want to do is extracting text from Word files (.docx), it's possible to do it only with Python. Like Guy Starbuck wrote it, you just need to unzip the file and then parse the XML. Inspired by python-docx, I have written a simple function to do this:
try:
from xml.etree.cElementTree import XML
except ImportError:
from xml.etree.ElementTree import XML
import zipfile
"""
Module that extract text from MS XML Word document (.docx).
(Inspired by python-docx <https://github.com/mikemaccana/python-docx>)
"""
WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
PARA = WORD_NAMESPACE + 'p'
TEXT = WORD_NAMESPACE + 't'
def get_docx_text(path):
"""
Take the path of a docx file as argument, return the text in unicode.
"""
document = zipfile.ZipFile(path)
xml_content = document.read('word/document.xml')
document.close()
tree = XML(xml_content)
paragraphs = []
for paragraph in tree.getiterator(PARA):
texts = [node.text
for node in paragraph.getiterator(TEXT)
if node.text]
if texts:
paragraphs.append(''.join(texts))
return '\n\n'.join(paragraphs)
A: Using the OpenOffice API, and Python, and Andrew Pitonyak's excellent online macro book I managed to do this. Section 7.16.4 is the place to start.
One other tip to make it work without needing the screen at all is to use the Hidden property:
RO = PropertyValue('ReadOnly', 0, True, 0)
Hidden = PropertyValue('Hidden', 0, True, 0)
xDoc = desktop.loadComponentFromURL( docpath,"_blank", 0, (RO, Hidden,) )
Otherwise the document flicks up on the screen (probably on the webserver console) when you open it.
A: (Same answer as extracting text from MS word files in python)
Use the native Python docx module which I made this week. Here's how to extract all the text from a doc:
document = opendocx('Hello world.docx')
# This location is where most document content lives
docbody = document.xpath('/w:document/w:body', namespaces=wordnamespaces)[0]
# Extract all text
print getdocumenttext(document)
See Python DocX site
100% Python, no COM, no .net, no Java, no parsing serialized XML with regexs.
A: tika-python
A Python port of the Apache Tika library, According to the documentation Apache tika supports text extraction from over 1500 file formats.
Note: It also works charmingly with pyinstaller
Install with pip :
pip install tika
Sample:
#!/usr/bin/env python
from tika import parser
parsed = parser.from_file('/path/to/file')
print(parsed["metadata"]) #To get the meta data of the file
print(parsed["content"]) # To get the content of the file
Link to official GitHub
A: I use catdoc or antiword for this, whatever gives the result that is the easiest to parse. I have embedded this in python functions, so it is easy to use from the parsing system (which is written in python).
import os
def doc_to_text_catdoc(filename):
(fi, fo, fe) = os.popen3('catdoc -w "%s"' % filename)
fi.close()
retval = fo.read()
erroroutput = fe.read()
fo.close()
fe.close()
if not erroroutput:
return retval
else:
raise OSError("Executing the command caused an error: %s" % erroroutput)
# similar doc_to_text_antiword()
The -w switch to catdoc turns off line wrapping, BTW.
A: Open Office has an API
A: For docx files, check out the Python script docx2txt available at
http://cobweb.ecn.purdue.edu/~kak/distMisc/docx2txt
for extracting the plain text from a docx document.
A: This worked well for .doc and .odt.
It calls openoffice on the command line to convert your file to text, which you can then simply load into python.
(It seems to have other format options, though they are not apparenlty documented.)
A: Honestly don't use "pip install tika", this has been developed for mono-user (one developper working on his laptop) and not for multi-users (multi-developpers).
The small class TikaWrapper.py bellow which uses Tika in command line is widely enough to meet our needs.
You just have to instanciate this class with JAVA_HOME path and the Tika jar path, that's all ! And it works perfectly for lot of formats (e.g: PDF, DOCX, ODT, XLSX, PPT, etc.).
#!/bin/python
# -*- coding: utf-8 -*-
# Class to extract metadata and text from different file types (such as PPT, XLS, and PDF)
# Developed by Philippe ROSSIGNOL
#####################
# TikaWrapper class #
#####################
class TikaWrapper:
java_home = None
tikalib_path = None
# Constructor
def __init__(self, java_home, tikalib_path):
self.java_home = java_home
self.tika_lib_path = tikalib_path
def extractMetadata(self, filePath, encoding="UTF-8", returnTuple=False):
'''
- Description:
Extract metadata from a document
- Params:
filePath: The document file path
encoding: The encoding (default = "UTF-8")
returnTuple: If True return a tuple which contains both the output and the error (default = False)
- Examples:
metadata = extractMetadata(filePath="MyDocument.docx")
metadata, error = extractMetadata(filePath="MyDocument.docx", encoding="UTF-8", returnTuple=True)
'''
cmd = self._getCmd(self._cmdExtractMetadata, filePath, encoding)
out, err = self._execute(cmd, encoding)
if (returnTuple): return out, err
return out
def extractText(self, filePath, encoding="UTF-8", returnTuple=False):
'''
- Description:
Extract text from a document
- Params:
filePath: The document file path
encoding: The encoding (default = "UTF-8")
returnTuple: If True return a tuple which contains both the output and the error (default = False)
- Examples:
text = extractText(filePath="MyDocument.docx")
text, error = extractText(filePath="MyDocument.docx", encoding="UTF-8", returnTuple=True)
'''
cmd = self._getCmd(self._cmdExtractText, filePath, encoding)
out, err = self._execute(cmd, encoding)
return out, err
# ===========
# = PRIVATE =
# ===========
_cmdExtractMetadata = "${JAVA_HOME}/bin/java -jar ${TIKALIB_PATH} --metadata ${FILE_PATH}"
_cmdExtractText = "${JAVA_HOME}/bin/java -jar ${TIKALIB_PATH} --encoding=${ENCODING} --text ${FILE_PATH}"
def _getCmd(self, cmdModel, filePath, encoding):
cmd = cmdModel.replace("${JAVA_HOME}", self.java_home)
cmd = cmd.replace("${TIKALIB_PATH}", self.tika_lib_path)
cmd = cmd.replace("${ENCODING}", encoding)
cmd = cmd.replace("${FILE_PATH}", filePath)
return cmd
def _execute(self, cmd, encoding):
import subprocess
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
out = out.decode(encoding=encoding)
err = err.decode(encoding=encoding)
return out, err
A: Just in case if someone wants to do in Java language there is Apache poi api. extractor.getText() will extract plane text from docx . Here is the link https://www.tutorialspoint.com/apache_poi_word/apache_poi_word_text_extraction.htm
A: Textract-Plus
Use textract-plus which can extract text from most of the document extensions including doc , docm , dotx and docx.
(It uses antiword as a backend for doc files)
refer docs
Install-
pip install textract-plus
Sample-
import textractplus as tp
text=tp.process('path/to/yourfile.doc')
A: There is also pandoc the swiss-army-knife of documents. It converts from every format to nearly every other format. From the demos page
pandoc -s input_file.docx -o output_file.txt
A: Like Etienne's answer.
With python 3.9 getiterator was deprecated in ET, so you need to replace it with iter:
def get_docx_text(path):
"""
Take the path of a docx file as argument, return the text in unicode.
"""
document = zipfile.ZipFile(path)
xml_content = document.read('word/document.xml')
document.close()
tree = XML(xml_content)
paragraphs = []
for paragraph in tree.iter(PARA):
texts = [node.text
for node in paragraph.iter(TEXT)
if node.text]
if texts:
paragraphs.append(''.join(texts))
return '\n\n'.join(paragraphs)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: Simulated OLAP We have a client that has Oracle Standard, and a project that would be ten times easier addressed using OLAP. However, Oracle only supports OLAP in the Enterprise version.
Migration to enterprise is not possible
I'm thinking of doing some manual simulation of OLAP, creating relational tables to simulate the technology.
Do you know of some other way I could do this? Maybe an open-source tool for OLAP? Any ideas?
A: I find that it's the schema that causes most of the issues people have with querying a database. OLAP forces you to either a flat table or a Star/snowflake schema which is easy to query and comparably faster to the source oltp tables. So if you ETL your source to a flat table or star schema you should get 80% of what you get from OLAP, the 20% being MDX and analytic functions and performance.
Note that you should get a perf boost with a star schema in relational database as well and Oracle probably has analytic functions in PL/SQL anyways.
A: Try an open-source OLAP server called 'Mondrian'. IIRC the XMLA API on this is sufficiently compatible with AS to fool Pivot Table Services, which would allow you to use it with ProClarity or Excel.
IIRC it was originally designed to work over Oracle - it is a HOLAP architecture using base tables in the underlying relational store and caching aggregates. You can also make use of materialised views and query rewrite in the underlying Oracle database to do aggregates.
A: You can simulate OLAP functionality using client side tools pointed at a relational database.
Personally I think the best tool for the job is probably Tableau Desktop. This is an amazingly sophisticated front end analytics tool that will make your relational data look multidimensional without much effort, and the tool itself is really mind blowing. They have a free trial so you can take it for a spin. We use Tableau heavily for our own analysis and have been very impressed. Of course, this tool also works with multidimensional databases as well, so if you end up with some cubes at the end of the day you can continue to use the Tableau front end.
As for open source, you could try out Palo - an open source MOLAP server and Excel front end.
If you are interesting in building your own reporting front end and use .NET there are a number of components (such as the DevExpress PivotGrid or the several tools from RadarSoft) that will do the same thing, but will require some elbow grease to get wired together.
A: A few more thoughts on this topic:
Actually, Oracle Standard does have an OLAP facility based on a descendent of Express embedded in the database engine and storing its internal data structures in BLOBs in the main tablespaces. Using this is technically possible but not necessarily advisable for the following reasons:
It uses a highly non-standard OLAP query engine with very little third party tool support (AFAIK ArcPlan is the only third-party OLAP front-end supporting 10g+ OLAP), poor documentation for the query language and almost no third party literature describing it. This will work with B.I. Beans if you feel like writing a JSP front-end. It is not compatible with MDX at all. As of early 2006 the best Oracle could do when asked about drillthrough (this functionality was not supported in Discoverer 'Drake') was to recommend building a JSP apllication using B.I. Beans.
The reason that there is no migration path from Standard to Enterprise is that Enterprise is actually what used to be Siebel Analytics. Standard is the old Oracle OLAP/Express descendant which Oracle partners recommended avoiding even before Oracle bought out Seibel. Oracle has not even attempted to support migrating.
From this point of view, Mondrian is actually the most cost-effective OLAP solution for an Oracle Standard Edition shop. You can get a supported version from an outfit called Pentaho1. The next cheapest is Analysis Services, which comes with SQL Server. Following that you are into the likes of Hyperion Essbase, which will be an order of magnitude more expensive than SQL Server or any supported verion of Mondrian.
A: Whilst MS SQL Server offers OLAP, you'll need an Enterprise licence to use a cube in a live environment that is web-facing.
A: You might want as well to give a try to www.icCube.com - we're quite flexible on the data-source used to populate the cube and are quite cost effective compared to the big actors of the market.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to implement a "related" degree measure algorithm? I was going to Ask a Question earlier today when I was presented to a surprising functionality in Stackoverflow. When I wrote my question title stackoverflow suggested me several related questions and I found out that there was already two similar questions. That was stunning!
Then I started thinking how I would implement such function. How I would order questions by relatedness:
*
*Question that have higher number of
words matchs with the new question
*If the number of matchs are the
same, the order of words is considered
*Words that appears in the title has
higher relevancy
That would be a simple workflow or a complex score algortithm?
Some stemming to increase the recall, maybe?
Is there some library the implements this function?
What other aspects would you consider?
Maybe Jeff could answer himself! How did you implemented this in Stackoverflow? :)
A: One such way to implement such an algorithm would involve ranking the questions as per a heuristic function which assigns a 'relevance' weight factor using the following steps:
*
*Apply a noise filter to the 'New' question to remove words that are common across a large number of objects such as: 'the', 'and', 'or', etc.
*Get the number of words contained in the 'New' question which match the words the set of questions already posted on the website. [A]
*Get the number of tag matches between the words in the 'New' question and the available. [B]
*Compute the 'relevance weight' based on [A] and [B] as 'x[A] + y[B]', where x and y are weight multipliers (Assign a higher weight multiplier to [B] as tagging is more relevant than simple word search)
*Get the top 5 questions which have the highest 'relevance weight'.
The heuristic might require tweaking to get optimal results, but it should work.
A: Your question seems similar to this one, which has some additional answers.
A: @marcio
Sorry, I am not aware of any direct API reference that I could suggest here and I have never worked with Lucene.
However, I am aware that Google Desktop uses a Query API to rank and suggest the relevant search results. More information on the API can be found here.
Perhaps others could chime in and guide you.
A: Isn't StackOverflow going to be open sourced at some point? If so, you can always find out how they did it there.
Update: It appears that they say they might open source it. I hope they do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: TFS - Branching for experimental development: Solution fails to load Disclaimer: I'm stuck on TFS and I hate it.
My source control structure looks like this:
*
*/dev
*/releases
*/branches
*/experimental-upgrade
I branched from dev to experimental-upgrade and didn't touch it. I then did some more work in dev and merged to experimental-upgrade. Somehow TFS complained that I had changes in both source and target and I had to resolve them. I chose to "Copy item from source branch" for all 5 items.
I check out the experimental-upgrade to a local folder and try to open the main solution file in there. TFS prompts me:
"Projects have recently been added to this solution. Would you like to get them from source control?
If I say yes it does some stuff but ultimately comes back failing to load a handful of the projects. If I say no I get the same result.
Comparing my sln in both branches tells me that they are equal.
Can anyone let me know what I'm doing wrong? This should be a straightforward branch/merge operation...
TIA.
UPDATE:
I noticed that if I click "yes" on the above dialog, the projects are downloaded to the $/ root of source control... (i.e. out of the dev & branches folders)
If I open up the solution in the branch and remove the dead projects and try to re-add them (by right-clicking sln, add existing project, choose project located in the branch folder, it gives me the error...
Cannot load the project c:\sandbox\my_solution\proj1\proj1.csproj, the file has been removed or deleted. The project path I was trying to add is this: c:\sandbox\my_solution\branches\experimental-upgrade\proj1\proj1.csproj
What in the world is pointing these projects outside of their local root? The solution file is identical to the one in the dev branch, and those projects load just fine. I also looked at the vspscc and vssscc files but didn't find anything.
Ideas?
A: @Ben
You can actually do a full delete in TFS, but it is highly not recommended unless you know what you are doing. You have to do it from the command line with the command tf destroy
tf destroy [/keephistory] itemspec1 [;versionspec]
[itemspec2...itemspecN] [/stopat:versionspec] [/preview]
[/startcleanup] [/noprompt]
Versionspec:
Date/Time Dmm/dd/yyyy
or any .Net Framework-supported format
or any of the date formats of the local machine
Changeset number Cnnnnnn
Label Llabelname
Latest version T
Workspace Wworkspacename;workspaceowner
Just before you do this make sure you try it out with the /preview. Also everybody has their own methodology for branching. Mine is to branch releases, and do all development in the development or root folder. Also it sounded like branching worked fine for you, just the solution file was screwed up, which may be because of a binding issue and the vssss file.
A: @Nick: No changes have been made to this just yet. I may have to delete it and re-branch (however you really can't fully delete in TFS)
And I have to disagree... branching is absolutely a good practice for experimental changes. Shelving is just temporary storage that will get backed up if I don't want to check in yet. But this needs to be developed while we develop real features.
A: Without knowing more about your solution setup I can't be sure. But, if you have any project references that could explain it. Because you have the "experimental-upgrade" subfolder under "branches" your relative paths have changed.
This means when VS used to look for your referenced projects in ..\..\project\whatever it now has to look in ..\..\..\project\whatever. Note the extra ..\
To fix this you have to re-add your project references. I haven't found a better way. You can either remove them and re-add them, or go to the properties window and change the path to them, then reload them. Either way, you'll have to redo your references to them from any projects.
Also, check your working folders to make sure that it didn't download any of your projects into the wrong folders. This can happen sometimes...
A: A couple of things. Are the folder structures the same? Can you delete and readd the project references successfully?
If you create a solution and then manually add all of the projects, does that work. (That may not be feasable - we have solutions with over a hundred projects).
One other thing (and it may be silly) - after you did the branch, did you commit it? I'm wondering if you branched and didn't check it in, and then merged, and then when you tried to check-in then, TFS was mighty confused.
A: @Kevin:
This means when VS used to look for your referenced projects in ....\project\whatever it now has to look in ......\project\whatever. Note the extra ..\
You may be on to something here, however it doesn't explain why some projects load and others do not. I haven't found a correlation between them yet.
I think I'll try to re-add the projects and see if that works.
A: @Cory:
I think that's what I'm going to try... I have about 20 projects and 8 or so aren't loading. The folder structures are identical from root... ie: there aren't any references outside of DEV.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: asp:UpdateProgress - suppressing the line-break I've started working with ASP.net AJAX (finally ☺). and I've got an update panel together with a asp:UpdateProgress. My Problem: The UpdateProgress always forces a line-break, because it renders out as a div-tag.
Is there any way to force it being a span instead? I want to display it on the same line as some other controls without having to use a table or even shudders absolute positioning in CSS.
I'm stuck with ASP.net AJAX 1.0 and .net 3.0 if that makes a difference.
A: I've had the same issue. There is no easy way to tell the updateProgress to render inline. You would be better off to roll your own updateProgress element. You can add a beginRequest listener and endRequest listener to show and hide the element you want to display inline. Here is simple page which shows how to do it:
aspx
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="up1" UpdateMode="Always">
<ContentTemplate>
<asp:Label ID="lblTest" runat="server"></asp:Label>
<asp:Button ID="btnTest" runat="server" Text="Test" OnClick="btnTest_OnClick" />
</ContentTemplate>
</asp:UpdatePanel>
<img id="loadingImg" src="../../../images/loading.gif" style="display:none;"/><span>Some Inline text</span>
<script>
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(function(sender, args) {
if (args.get_postBackElement().id == "btnTest") {
document.getElementById("loadingImg").style.display = "inline";
}
});
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, args) {
if (document.getElementById("loadingImg").style.display != "none") {
document.getElementById("loadingImg").style.display = "none";
}
});
</script>
</div>
</form>
cs
public partial class updateProgressTest : System.Web.UI.Page
{
protected void btnTest_OnClick(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
this.lblTest.Text = "I was changed on the server! Yay!";
}
}
A: My solution:
In CSS
.progress[style*="display: block;"] {
display:inline !important;
}
And ASP
<asp:UpdateProgress class="progress" ID="UpdateProgress1" runat="server">
A: I just blogged about my own solution to this problem.
http://www.joeaudette.com/solving-the-aspnet-updateprogress-div-problem.aspx
What I did was borrow the UpdateProgress control from the Mono project and modified it to render as a span instead of a div. I also copied an modifed the ms-ajax javascript associated with the control and modified it to toggle between display:inline and display:none instead of using display:block
There is a .zip file linked in my post which contains the modified files.
A: simply place your UpdateProgress inside a span with style="position:absolute;"
A: A better and simplest way is use UpdateProgress inside UpdatePanel with span. I've tested this and work properly in IE, FF, Chrome browsers. like this:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
..........
<span style="position:absolute;">
<asp:UpdateProgress ID="UpdateProgress1" runat="server"
AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<img alt="please wait..."src="/Images/progress-dots.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
</span>
</ContentTemplate>
</asp:UpdatePanel>
A: Just apply float:left to your label/textbox etc.
Like this:
in the header:
<style type="text/css">
.tbx
{
float:left;
}
in the body:
<asp:TextBox CssClass="tbx" .... />
A: My solution was to wrap it as follows...
<div class="load-inline">LOADER HERE</div>
And in my CSS I use...
.load-inline {display:inline-block}
A: You can make a div inline like this:
<div style="display:inline">stuff</div>
I'm skeptical of it rendering the div for you though... I don't remember having this problem on my pages...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Thread-safe use of a singleton's members I have a C# singleton class that multiple classes use. Is access through Instance to the Toggle() method thread-safe? If yes, by what assumptions, rules, etc. If no, why and how can I fix it?
public class MyClass
{
private static readonly MyClass instance = new MyClass();
public static MyClass Instance
{
get { return instance; }
}
private int value = 0;
public int Toggle()
{
if(value == 0)
{
value = 1;
}
else if(value == 1)
{
value = 0;
}
return value;
}
}
A: The original impplementation is not thread safe, as Ben points out
A simple way to make it thread safe is to introduce a lock statement. Eg. like this:
public class MyClass
{
private Object thisLock = new Object();
private static readonly MyClass instance = new MyClass();
public static MyClass Instance
{
get { return instance; }
}
private Int32 value = 0;
public Int32 Toggle()
{
lock(thisLock)
{
if(value == 0)
{
value = 1;
}
else if(value == 1)
{
value = 0;
}
return value;
}
}
}
A:
Is access through 'Instance' to the 'Toggle()' class threadsafe? If yes, by what assumptions, rules, etc. If no, why and how can I fix it?
No, it's not threadsafe.
Basically, both threads can run the Toggle function at the same time, so this could happen
// thread 1 is running this code
if(value == 0)
{
value = 1;
// RIGHT NOW, thread 2 steps in.
// It sees value as 1, so runs the other branch, and changes it to 0
// This causes your method to return 0 even though you actually want 1
}
else if(value == 1)
{
value = 0;
}
return value;
You need to operate with the following assumption.
If 2 threads are running, they can and will interleave and interact with eachother randomly at any point. You can be half way through writing or reading a 64 bit integer or float (on a 32 bit CPU) and another thread can jump in and change it out from underneath you.
If the 2 threads never access anything in common, it doesn't matter, but as soon as they do, you need to prevent them from stepping on each others toes. The way to do this in .NET is with locks.
You can decide what and where to lock by thinking about things like this:
For a given block of code, if the value of something got changed out from underneath me, would it matter? If it would, you need to lock that something for the duration of the code where it would matter.
Looking at your example again
// we read value here
if(value == 0)
{
value = 1;
}
else if(value == 1)
{
value = 0;
}
// and we return it here
return value;
In order for this to return what we expect it to, we assume that value won't get changed between the read and the return. In order for this assumption to actually be correct, you need to lock value for the duration of that code block.
So you'd do this:
lock( value )
{
if(value == 0)
... // all your code here
return value;
}
HOWEVER
In .NET you can only lock Reference Types. Int32 is a Value Type, so we can't lock it.
We solve this by introducing a 'dummy' object, and locking that wherever we'd want to lock 'value'.
This is what Ben Scheirman is referring to.
A: Your thread could stop in the middle of that method and transfer control to a different thread. You need a critical section around that code...
private static object _lockDummy = new object();
...
lock(_lockDummy)
{
//do stuff
}
A: I'd also add a protected constructor to MyClass to prevent the compiler from generating a public default constructor.
A:
That is what I thought. But, I I'm
looking for the details... 'Toggle()'
is not a static method, but it is a
member of a static property (when
using 'Instance'). Is that what makes
it shared among threads?
If your application is multi-threaded and you can forsee that multiple thread will access that method, that makes it shared among threads. Because your class is a Singleton you know that the diferent thread will access the SAME object, so be cautioned about the thread-safety of your methods.
And how does this apply to singletons
in general. Would I have to address
this in every method on my class?
As I said above, because its a singleton you know diferent thread will acess the same object, possibly at the same time. This does not mean you have to make every method obtain a lock. If you notice that a simultaneos invocation can lead to corrupted state of the class, then you should apply the method mentioned by @Thomas
A:
Can I assume that the singleton pattern exposes my otherwise lovely thread-safe class to all the thread problems of regular static members?
No. Your class is simply not threadsafe. The singleton has nothing to do with it.
(I'm getting my head around the fact that instance members called on a static object cause threading problems)
It's nothing to do with that either.
You have to think like this: Is it possible in my program for 2 (or more) threads to access this piece of data at the same time?
The fact that you obtain the data via a singleton, or static variable, or passing in an object as a method parameter doesn't matter. At the end of the day it's all just some bits and bytes in your PC's RAM, and all that matters is whether multiple threads can see the same bits.
A:
I was thinking that if I dump the singleton pattern and force everyone to get a new instance of the class it would ease some problems... but that doesn't stop anyone else from initializing a static object of that type and passing that around... or from spinning off multiple threads, all accessing 'Toggle()' from the same instance.
Bingo :-)
I get it now. It's a tough world. I wish I weren't refactoring legacy code :(
Unfortunately, multithreading is hard and you have to be very paranoid about things :-)
The simplest solution in this case is to stick with the singleton, and add a lock around the value, like in the examples.
A: Quote:
if(value == 0) { value = 1; }
if(value == 1) { value = 0; }
return value;
value will always be 0...
A: Well, I actually don't know C# that well... but I am ok at Java, so I will give the answer for that, and hopefully the two are similar enough that it will be useful. If not, I apologize.
The answer is, no, it's not safe. One thread could call Toggle() at the same time as the other, and it is possible, although unlikely with this code, that Thread1 could set value in between the times that Thread2 checks it and when it sets it.
To fix, simply make Toggle() synchronized. It doesn't block on anything or call anything that might spawn another thread which could call Toggle(), so that's all you have to do save it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Deleting a Google App Engine application Is it possible to delete an GAE application after it has been created?
I made a mistake while typing the name and now have a dummy application that I haven't been able to remove.
A: There currently isn't a way to delete a GAE application.
A: I was evaluating if we could use AppEngine and ran the standard tutorial which created a test app for me under my the default project. When I tried to delete the App I was shocked that it can't be done ! The only way is to delete the project which would delete all other GKE and any other services under that account.
After a bunch of research and calling product support of Google this what they suggested: To upgrade to Silver Support for 150$/month and send them an email to delete the app.
Here is the chat session with Google Support. If you were considering using Google AppEngine I would think again.
A: Beyond disabling the App Engine application you can:
*
*Disable it's API permission under APIs & Services
*Remove the App Engine related files from Storage
*Delete App Engine permissions under IAM & Admin
*Delete the App Engine Service account
This will freeze all App Engine related billing charges for the undeletable disabled App engine application. At least it worked for me :)
A: As most of the answers are outdated or contradictive and this is an important question I decided to clarify current possible solutions when intending to delete an application in Google App Engine or having related issues.
Currently, there is no way to delete an existing app in GAE. Once created it cannot be removed, nor its initial settings can be changed (like the region where it was deployed). The only possible workaround is starting a new project and deploying a new application. There were feature requests in Google Issue Tracker regarding these issues: deleting an app and changing zone/region. You can still delete the whole project as described in Steve Armstrong's answer, but bear in mind that this will remove everything you created there (like GCE, GKE etc.), not only GAE.
However, it all depends on why you would like to delete your app. If you would simply like to stop it from serving requests or you don't want it to incur further costs, you can disable the app as described in the GCP docs here.
A: This issue has been fixed; see the docs here:
https://cloud.google.com/appengine/docs/standard/python/console/?csw=1#delete_app
A: Carlos, you're right that the issue has been fixed, and I up-voted you for that. However, your link is a little outdated and an updated link is listed below.
https://developers.google.com/appengine/docs/adminconsole/applicationsettings#Disable_or_Delete_Your_Application
A: open https://console.cloud.google.com/cloud-resource-manager?organizationId=0 ,select the project(or application) to be deleted,then click delete
A: This feature is already logged, please star it:
http://code.google.com/p/googleappengine/issues/detail?id=335
A: To disable /delete your application:
*
*In the Administration Console, click your application to make it the active application.
*Click Application Settings on the left side under Administration.
*Click Disable Application.
*Click Disable Application Now.
*If you want to delete your app:
*
*If billing is enabled for your app, disable billing. You aren't allowed to delete before you do this.
*Click Request Permanent Deletion. The application will be deleted in approximately 72 hours.
To re-enable your disabled application, click Re-Enable Application.
source
A: With the new Google Cloud console, you can still disable GAE applications as before (App Engine --> Settings --> Disable). They cannot currently be deleted. However you can delete the entire project by going to IAM --> Settings --> Shut Down. This button is in the header and a bit tricky to spot. It looks like this:
As of AppEngine SDK 1.2.6 it's possible to delete apps completely. But beware, the app-id won't be usable again.
A: I wanted to delete some legacy Google App Engine applications I made years ago, but when I tried to delete them from the new Google Cloud Platform (like this: https://support.google.com/cloud/answer/6251787#shut-down-a-project) I kept getting "You do not have permission" errors. The solution I found was to sign up for a free trial of Google Cloud Platform, then I was able to delete them.
A: I couldn't find to delete the default app-engine, however if you navigate to App Engine > Settings , there is a button to Disable it and it stop serving. when you click on the button type the project name in the prompt.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "129"
} |
Q: Dealing with Latency in Networked Games I'm thinking about making a networked game. I'm a little new to this, and have already run into a lot of issues trying to put together a good plan for dead reckoning and network latency, so I'd love to see some good literature on the topic. I'll describe the methods I've considered.
Originally, I just sent the player's input to the server, simulated there, and broadcast changes in the game state to all players. This made cheating difficult, but under high latency things were a little difficult to control, since you dont see the results of your own actions immediately.
This GamaSutra article has a solution that saves bandwidth and makes local input appear smooth by simulating on the client as well, but it seems to throw cheat-proofing out the window. Also, I'm not sure what to do when players start manipulating the environment, pushing rocks and the like. These previously neutral objects would temporarily become objects the client needs to send PDUs about, or perhaps multiple players do at once. Whose PDUs would win? When would the objects stop being doubly tracked by each player (to compare with the dead reckoned version)? Heaven forbid two players engage in a sumo match (e.g. start pushing each other).
This gamedev.net bit shows the gamasutra solution as inadequate, but describes a different method that doesn't really fix my collaborative boulder-pushing example. Most other things I've found are specific to shooters. I'd love to see something more geared toward games that play like SNES Zelda, but with a little more physics / momentum involved.
*
*Note: I'm not asking about physics simulation here -- other libraries have that covered. Just strategies for making games smooth and reactive despite network latency.
A: Check out how Valve does it in the Source Engine: http://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking
If it's for a first person shooter you'll probably have to delve into some of the topics they mention such as: prediction, compensation, and interpolation.
A: we have implemented a multiplayer snake game based on a mandatory server and remote players that make predictions. Every 150ms (in most cases) the server sends back a message containing all the consolidated movements sent by each remote player. If remote client movements arrive late to the server, he discards them. The client the will replay last movement.
A: I find this network physics blog post by Glenn Fiedler, and even more so the response/discussion below it, awesome. It is quite lengthy, but worth-while.
In summary
Server cannot keep up with reiterating simulation whenever client input is received in a modern game physics simulation (i.e. vehicles or rigid body dynamics). Therefore the server orders all clients latency+jitter (time) ahead of server so that all incomming packets come in JIT before the server needs 'em.
He also gives an outline of how to handle the type of ownership you are asking for. The slides he showed on GDC are awesome!
On cheating
Mr Fiedler himself (and others) state that this algorithm suffers from not being very cheat-proof. This is not true. This algorithm is no less easy or hard to exploit than traditional client/server prediction (see article regarding traditional client/server prediction in @CD Sanchez' answer).
To be absolutely clear: the server is not easier to cheat simply because it receives network physical positioning just in time (rather than x milliseconds late as in traditional prediction). The clients are not affected at all, since they all receive the positional information of their opponents with the exact same latency as in traditional prediction.
No matter which algorithm you pick, you may want to add cheat-protection if you're releasing a major title. If you are, I suggest adding encryption against stooge bots (for instance an XOR stream cipher where the "keystream is generated by a pseudo-random number generator") and simple sanity checks against cracks. Some developers also implement algorithms to check that the binaries are intact (to reduce risk of cracking) or to ensure that the user isn't running a debugger (to reduce risk of a crack being developed), but those are more debatable.
If you're just making a smaller indie game, that may only be played by some few thousand players, don't bother implementing any anti-cheat algorithms until 1) you need them; or 2) the user base grows.
A: Check out Networking education topics at the XNA Creator's Club website. It delves into topics such as network architecture (peer to peer or client/server), Network Prediction, and a few other things (in the context of XNA of course). This may help you find the answers you're looking for.
http://creators.xna.com/education/catalog/?contenttype=0&devarea=19&sort=1
A: You could try imposing latency to all your clients, depending on the average latency in the area. That way the client can try to work around the latency issues and it will feel similar for most players.
I'm of course not suggesting that you force a 500ms delay on everyone, but people with 50ms can be fine with 150 (extra 100ms added) in order for the gameplay to appear smoother.
In a nutshell; if you have 3 players:
*
*John: 30ms
*Paul: 150ms
*Amy: 80ms
After calculations, instead of sending the data back to the clients all at the same time, you account for their latency and start sending to Paul and Amy before John, for example.
But this approach is not viable in extreme latency situations where dialup connections or wireless users could really mess it up for everybody. But it's an idea.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: How do you rotate a two dimensional array? Inspired by Raymond Chen's post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff.
[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]
Becomes:
[3][9][5][1]
[4][0][6][2]
[5][1][7][3]
[6][2][8][4]
Update: Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000?
A: Nick's answer would work for an NxM array too with only a small modification (as opposed to an NxN).
string[,] orig = new string[n, m];
string[,] rot = new string[m, n];
...
for ( int i=0; i < n; i++ )
for ( int j=0; j < m; j++ )
rot[j, n - i - 1] = orig[i, j];
One way to think about this is that you have moved the center of the axis (0,0) from the top left corner to the top right corner. You're simply transposing from one to the other.
A: Here is one that does the rotation in place instead of using a completely new array to hold the result. I've left off initialization of the array and printing it out. This only works for square arrays but they can be of any size. Memory overhead is equal to the size of one element of the array so you can do the rotation of as large an array as you want.
int a[4][4];
int n = 4;
int tmp;
for (int i = 0; i < n / 2; i++)
{
for (int j = i; j < n - i - 1; j++)
{
tmp = a[i][j];
a[i][j] = a[j][n-i-1];
a[j][n-i-1] = a[n-i-1][n-j-1];
a[n-i-1][n-j-1] = a[n-j-1][i];
a[n-j-1][i] = tmp;
}
}
A: Time - O(N), Space - O(1)
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n / 2; i++) {
int last = n - 1 - i;
for (int j = i; j < last; j++) {
int top = matrix[i][j];
matrix[i][j] = matrix[last - j][i];
matrix[last - j][i] = matrix[last][last - j];
matrix[last][last - j] = matrix[j][last];
matrix[j][last] = top;
}
}
}
A: A common method to rotate a 2D array clockwise or anticlockwise.
*
*clockwise rotate
*
*first reverse up to down, then swap the symmetry
1 2 3 7 8 9 7 4 1
4 5 6 => 4 5 6 => 8 5 2
7 8 9 1 2 3 9 6 3
void rotate(vector<vector<int> > &matrix) {
reverse(matrix.begin(), matrix.end());
for (int i = 0; i < matrix.size(); ++i) {
for (int j = i + 1; j < matrix[i].size(); ++j)
swap(matrix[i][j], matrix[j][i]);
}
}
*
*anticlockwise rotate
*
*first reverse left to right, then swap the symmetry
1 2 3 3 2 1 3 6 9
4 5 6 => 6 5 4 => 2 5 8
7 8 9 9 8 7 1 4 7
void anti_rotate(vector<vector<int> > &matrix) {
for (auto vi : matrix) reverse(vi.begin(), vi.end());
for (int i = 0; i < matrix.size(); ++i) {
for (int j = i + 1; j < matrix[i].size(); ++j)
swap(matrix[i][j], matrix[j][i]);
}
}
A: Here's my Ruby version (note the values aren't displayed the same, but it still rotates as described).
def rotate(matrix)
result = []
4.times { |x|
result[x] = []
4.times { |y|
result[x][y] = matrix[y][3 - x]
}
}
result
end
matrix = []
matrix[0] = [1,2,3,4]
matrix[1] = [5,6,7,8]
matrix[2] = [9,0,1,2]
matrix[3] = [3,4,5,6]
def print_matrix(matrix)
4.times { |y|
4.times { |x|
print "#{matrix[x][y]} "
}
puts ""
}
end
print_matrix(matrix)
puts ""
print_matrix(rotate(matrix))
The output:
1 5 9 3
2 6 0 4
3 7 1 5
4 8 2 6
4 3 2 1
8 7 6 5
2 1 0 9
6 5 4 3
A: O(n^2) time and O(1) space algorithm ( without any workarounds and hanky-panky stuff! )
Rotate by +90:
*
*Transpose
*Reverse each row
Rotate by -90:
Method 1 :
*
*Transpose
*Reverse each column
Method 2 :
*
*Reverse each row
*Transpose
Rotate by +180:
Method 1: Rotate by +90 twice
Method 2: Reverse each row and then reverse each column (Transpose)
Rotate by -180:
Method 1: Rotate by -90 twice
Method 2: Reverse each column and then reverse each row
Method 3: Rotate by +180 as they are same
A: There are tons of good code here but I just want to show what's going on geometrically so you can understand the code logic a little better. Here is how I would approach this.
first of all, do not confuse this with transposition which is very easy..
the basica idea is to treat it as layers and we rotate one layer at a time..
say we have a 4x4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
after we rotate it clockwise by 90 we get
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4
so let's decompose this, first we rotate the 4 corners essentially
1 4
13 16
then we rotate the following diamond which is sort of askew
2
8
9
15
and then the 2nd skewed diamond
3
5
12
14
so that takes care of the outer edge so essentially we do that one shell at a time until
finally the middle square (or if it's odd just the final element which does not move)
6 7
10 11
so now let's figure out the indices of each layer, assume we always work with the outermost layer, we are doing
[0,0] -> [0,n-1], [0,n-1] -> [n-1,n-1], [n-1,n-1] -> [n-1,0], and [n-1,0] -> [0,0]
[0,1] -> [1,n-1], [1,n-2] -> [n-1,n-2], [n-1,n-2] -> [n-2,0], and [n-2,0] -> [0,1]
[0,2] -> [2,n-2], [2,n-2] -> [n-1,n-3], [n-1,n-3] -> [n-3,0], and [n-3,0] -> [0,2]
so on and so on
until we are halfway through the edge
so in general the pattern is
[0,i] -> [i,n-i], [i,n-i] -> [n-1,n-(i+1)], [n-1,n-(i+1)] -> [n-(i+1),0], and [n-(i+1),0] to [0,i]
A: here's a in-space rotate method, by java, only for square. for non-square 2d array, you will have to create new array anyway.
private void rotateInSpace(int[][] arr) {
int z = arr.length;
for (int i = 0; i < z / 2; i++) {
for (int j = 0; j < (z / 2 + z % 2); j++) {
int x = i, y = j;
int temp = arr[x][y];
for (int k = 0; k < 4; k++) {
int temptemp = arr[y][z - x - 1];
arr[y][z - x - 1] = temp;
temp = temptemp;
int tempX = y;
y = z - x - 1;
x = tempX;
}
}
}
}
code to rotate any size 2d array by creating new array:
private int[][] rotate(int[][] arr) {
int width = arr[0].length;
int depth = arr.length;
int[][] re = new int[width][depth];
for (int i = 0; i < depth; i++) {
for (int j = 0; j < width; j++) {
re[j][depth - i - 1] = arr[i][j];
}
}
return re;
}
A: You can do this in 3 easy steps:
1)Suppose we have a matrix
1 2 3
4 5 6
7 8 9
2)Take the transpose of the matrix
1 4 7
2 5 8
3 6 9
3)Interchange rows to get rotated matrix
3 6 9
2 5 8
1 4 7
Java source code for this:
public class MyClass {
public static void main(String args[]) {
Demo obj = new Demo();
/*initial matrix to rotate*/
int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[][] transpose = new int[3][3]; // matrix to store transpose
obj.display(matrix); // initial matrix
obj.rotate(matrix, transpose); // call rotate method
System.out.println();
obj.display(transpose); // display the rotated matix
}
}
class Demo {
public void rotate(int[][] mat, int[][] tran) {
/* First take the transpose of the matrix */
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat.length; j++) {
tran[i][j] = mat[j][i];
}
}
/*
* Interchange the rows of the transpose matrix to get rotated
* matrix
*/
for (int i = 0, j = tran.length - 1; i != j; i++, j--) {
for (int k = 0; k < tran.length; k++) {
swap(i, k, j, k, tran);
}
}
}
public void swap(int a, int b, int c, int d, int[][] arr) {
int temp = arr[a][b];
arr[a][b] = arr[c][d];
arr[c][d] = temp;
}
/* Method to display the matrix */
public void display(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Output:
1 2 3
4 5 6
7 8 9
3 6 9
2 5 8
1 4 7
A: As I said in my previous post, here's some code in C# that implements an O(1) matrix rotation for any size matrix. For brevity and readability there's no error checking or range checking. The code:
static void Main (string [] args)
{
int [,]
// create an arbitrary matrix
m = {{0, 1}, {2, 3}, {4, 5}};
Matrix
// create wrappers for the data
m1 = new Matrix (m),
m2 = new Matrix (m),
m3 = new Matrix (m);
// rotate the matricies in various ways - all are O(1)
m1.RotateClockwise90 ();
m2.Rotate180 ();
m3.RotateAnitclockwise90 ();
// output the result of transforms
System.Diagnostics.Trace.WriteLine (m1.ToString ());
System.Diagnostics.Trace.WriteLine (m2.ToString ());
System.Diagnostics.Trace.WriteLine (m3.ToString ());
}
class Matrix
{
enum Rotation
{
None,
Clockwise90,
Clockwise180,
Clockwise270
}
public Matrix (int [,] matrix)
{
m_matrix = matrix;
m_rotation = Rotation.None;
}
// the transformation routines
public void RotateClockwise90 ()
{
m_rotation = (Rotation) (((int) m_rotation + 1) & 3);
}
public void Rotate180 ()
{
m_rotation = (Rotation) (((int) m_rotation + 2) & 3);
}
public void RotateAnitclockwise90 ()
{
m_rotation = (Rotation) (((int) m_rotation + 3) & 3);
}
// accessor property to make class look like a two dimensional array
public int this [int row, int column]
{
get
{
int
value = 0;
switch (m_rotation)
{
case Rotation.None:
value = m_matrix [row, column];
break;
case Rotation.Clockwise90:
value = m_matrix [m_matrix.GetUpperBound (0) - column, row];
break;
case Rotation.Clockwise180:
value = m_matrix [m_matrix.GetUpperBound (0) - row, m_matrix.GetUpperBound (1) - column];
break;
case Rotation.Clockwise270:
value = m_matrix [column, m_matrix.GetUpperBound (1) - row];
break;
}
return value;
}
set
{
switch (m_rotation)
{
case Rotation.None:
m_matrix [row, column] = value;
break;
case Rotation.Clockwise90:
m_matrix [m_matrix.GetUpperBound (0) - column, row] = value;
break;
case Rotation.Clockwise180:
m_matrix [m_matrix.GetUpperBound (0) - row, m_matrix.GetUpperBound (1) - column] = value;
break;
case Rotation.Clockwise270:
m_matrix [column, m_matrix.GetUpperBound (1) - row] = value;
break;
}
}
}
// creates a string with the matrix values
public override string ToString ()
{
int
num_rows = 0,
num_columns = 0;
switch (m_rotation)
{
case Rotation.None:
case Rotation.Clockwise180:
num_rows = m_matrix.GetUpperBound (0);
num_columns = m_matrix.GetUpperBound (1);
break;
case Rotation.Clockwise90:
case Rotation.Clockwise270:
num_rows = m_matrix.GetUpperBound (1);
num_columns = m_matrix.GetUpperBound (0);
break;
}
StringBuilder
output = new StringBuilder ();
output.Append ("{");
for (int row = 0 ; row <= num_rows ; ++row)
{
if (row != 0)
{
output.Append (", ");
}
output.Append ("{");
for (int column = 0 ; column <= num_columns ; ++column)
{
if (column != 0)
{
output.Append (", ");
}
output.Append (this [row, column].ToString ());
}
output.Append ("}");
}
output.Append ("}");
return output.ToString ();
}
int [,]
// the original matrix
m_matrix;
Rotation
// the current view of the matrix
m_rotation;
}
OK, I'll put my hand up, it doesn't actually do any modifications to the original array when rotating. But, in an OO system that doesn't matter as long as the object looks like it's been rotated to the clients of the class. At the moment, the Matrix class uses references to the original array data so changing any value of m1 will also change m2 and m3. A small change to the constructor to create a new array and copy the values to it will sort that out.
A: Implementation of dimple's +90 pseudocode (e.g. transpose then reverse each row) in JavaScript:
function rotate90(a){
// transpose from http://www.codesuck.com/2012/02/transpose-javascript-array-in-one-line.html
a = Object.keys(a[0]).map(function (c) { return a.map(function (r) { return r[c]; }); });
// row reverse
for (i in a){
a[i] = a[i].reverse();
}
return a;
}
A: In python:
import numpy as np
a = np.array(
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 0, 1, 2],
[3, 4, 5, 6]
]
)
print(a)
print(b[::-1, :].T)
A: I’d like to add a little more detail. In this answer, key concepts are repeated, the pace is slow and intentionally repetitive. The solution provided here is not the most syntactically compact, it is however, intended for those who wish to learn what matrix rotation is and the resulting implementation.
Firstly, what is a matrix? For the purposes of this answer, a matrix is just a grid where the width and height are the same. Note, the width and height of a matrix can be different, but for simplicity, this tutorial considers only matrices with equal width and height (square matrices). And yes, matrices is the plural of matrix.
Example matrices are: 2×2, 3×3 or 5×5. Or, more generally, N×N. A 2×2 matrix will have 4 squares because 2×2=4. A 5×5 matrix will have 25 squares because 5×5=25. Each square is called an element or entry. We’ll represent each element with a period (.) in the diagrams below:
2×2 matrix
. .
. .
3×3 matrix
. . .
. . .
. . .
4×4 matrix
. . . .
. . . .
. . . .
. . . .
So, what does it mean to rotate a matrix? Let’s take a 2×2 matrix and put some numbers in each element so the rotation can be observed:
0 1
2 3
Rotating this by 90 degrees gives us:
2 0
3 1
We literally turned the whole matrix once to the right just like turning the steering wheel of a car. It may help to think of “tipping” the matrix onto its right side. We want to write a function, in Python, that takes a matrix and rotates it once to the right. The function signature will be:
def rotate(matrix):
# Algorithm goes here.
The matrix will be defined using a two-dimensional array:
matrix = [
[0,1],
[2,3]
]
Therefore the first index position accesses the row. The second index position accesses the column:
matrix[row][column]
We’ll define a utility function to print a matrix.
def print_matrix(matrix):
for row in matrix:
print row
One method of rotating a matrix is to do it a layer at a time. But what is a layer? Think of an onion. Just like the layers of an onion, as each layer is removed, we move towards the center. Other analogies is a Matryoshka doll or a game of pass-the-parcel.
The width and height of a matrix dictate the number of layers in that matrix. Let’s use different symbols for each layer:
A 2×2 matrix has 1 layer
. .
. .
A 3×3 matrix has 2 layers
. . .
. x .
. . .
A 4×4 matrix has 2 layers
. . . .
. x x .
. x x .
. . . .
A 5×5 matrix has 3 layers
. . . . .
. x x x .
. x O x .
. x x x .
. . . . .
A 6×6 matrix has 3 layers
. . . . . .
. x x x x .
. x O O x .
. x O O x .
. x x x x .
. . . . . .
A 7×7 matrix has 4 layers
. . . . . . .
. x x x x x .
. x O O O x .
. x O - O x .
. x O O O x .
. x x x x x .
. . . . . . .
You may notice that incrementing the width and height of a matrix by one, does not always increase the number of layers. Taking the above matrices and tabulating the layers and dimensions, we see the number of layers increases once for every two increments of width and height:
+-----+--------+
| N×N | Layers |
+-----+--------+
| 1×1 | 1 |
| 2×2 | 1 |
| 3×3 | 2 |
| 4×4 | 2 |
| 5×5 | 3 |
| 6×6 | 3 |
| 7×7 | 4 |
+-----+--------+
However, not all layers need rotating. A 1×1 matrix is the same before and after rotation. The central 1×1 layer is always the same before and after rotation no matter how large the overall matrix:
+-----+--------+------------------+
| N×N | Layers | Rotatable Layers |
+-----+--------+------------------+
| 1×1 | 1 | 0 |
| 2×2 | 1 | 1 |
| 3×3 | 2 | 1 |
| 4×4 | 2 | 2 |
| 5×5 | 3 | 2 |
| 6×6 | 3 | 3 |
| 7×7 | 4 | 3 |
+-----+--------+------------------+
Given N×N matrix, how can we programmatically determine the number of layers we need to rotate? If we divide the width or height by two and ignore the remainder we get the following results.
+-----+--------+------------------+---------+
| N×N | Layers | Rotatable Layers | N/2 |
+-----+--------+------------------+---------+
| 1×1 | 1 | 0 | 1/2 = 0 |
| 2×2 | 1 | 1 | 2/2 = 1 |
| 3×3 | 2 | 1 | 3/2 = 1 |
| 4×4 | 2 | 2 | 4/2 = 2 |
| 5×5 | 3 | 2 | 5/2 = 2 |
| 6×6 | 3 | 3 | 6/2 = 3 |
| 7×7 | 4 | 3 | 7/2 = 3 |
+-----+--------+------------------+---------+
Notice how N/2 matches the number of layers that need to be rotated? Sometimes the number of rotatable layers is one less the total number of layers in the matrix. This occurs when the innermost layer is formed of only one element (i.e. a 1×1 matrix) and therefore need not be rotated. It simply gets ignored.
We will undoubtedly need this information in our function to rotate a matrix, so let’s add it now:
def rotate(matrix):
size = len(matrix)
# Rotatable layers only.
layer_count = size / 2
Now we know what layers are and how to determine the number of layers that actually need rotating, how do we isolate a single layer so we can rotate it? Firstly, we inspect a matrix from the outermost layer, inwards, to the innermost layer. A 5×5 matrix has three layers in total and two layers that need rotating:
. . . . .
. x x x .
. x O x .
. x x x .
. . . . .
Let’s look at columns first. The position of the columns defining the outermost layer, assuming we count from 0, are 0 and 4:
+--------+-----------+
| Column | 0 1 2 3 4 |
+--------+-----------+
| | . . . . . |
| | . x x x . |
| | . x O x . |
| | . x x x . |
| | . . . . . |
+--------+-----------+
0 and 4 are also the positions of the rows for the outermost layer.
+-----+-----------+
| Row | |
+-----+-----------+
| 0 | . . . . . |
| 1 | . x x x . |
| 2 | . x O x . |
| 3 | . x x x . |
| 4 | . . . . . |
+-----+-----------+
This will always be the case since the width and height are the same. Therefore we can define the column and row positions of a layer with just two values (rather than four).
Moving inwards to the second layer, the position of the columns are 1 and 3. And, yes, you guessed it, it’s the same for rows. It’s important to understand we had to both increment and decrement the row and column positions when moving inwards to the next layer.
+-----------+---------+---------+---------+
| Layer | Rows | Columns | Rotate? |
+-----------+---------+---------+---------+
| Outermost | 0 and 4 | 0 and 4 | Yes |
| Inner | 1 and 3 | 1 and 3 | Yes |
| Innermost | 2 | 2 | No |
+-----------+---------+---------+---------+
So, to inspect each layer, we want a loop with both increasing and decreasing counters that represent moving inwards, starting from the outermost layer. We’ll call this our ‘layer loop’.
def rotate(matrix):
size = len(matrix)
layer_count = size / 2
for layer in range(0, layer_count):
first = layer
last = size - first - 1
print 'Layer %d: first: %d, last: %d' % (layer, first, last)
# 5x5 matrix
matrix = [
[ 0, 1, 2, 3, 4],
[ 5, 6, 6, 8, 9],
[10,11,12,13,14],
[15,16,17,18,19],
[20,21,22,23,24]
]
rotate(matrix)
The code above loops through the (row and column) positions of any layers that need rotating.
Layer 0: first: 0, last: 4
Layer 1: first: 1, last: 3
We now have a loop providing the positions of the rows and columns of each layer. The variables first and last identify the index position of the first and last rows and columns. Referring back to our row and column tables:
+--------+-----------+
| Column | 0 1 2 3 4 |
+--------+-----------+
| | . . . . . |
| | . x x x . |
| | . x O x . |
| | . x x x . |
| | . . . . . |
+--------+-----------+
+-----+-----------+
| Row | |
+-----+-----------+
| 0 | . . . . . |
| 1 | . x x x . |
| 2 | . x O x . |
| 3 | . x x x . |
| 4 | . . . . . |
+-----+-----------+
So we can navigate through the layers of a matrix. Now we need a way of navigating within a layer so we can move elements around that layer. Note, elements never ‘jump’ from one layer to another, but they do move within their respective layers.
Rotating each element in a layer rotates the entire layer. Rotating all layers in a matrix rotates the entire matrix. This sentence is very important, so please try your best to understand it before moving on.
Now, we need a way of actually moving elements, i.e. rotate each element, and subsequently the layer, and ultimately the matrix. For simplicity, we’ll revert to a 3x3 matrix — that has one rotatable layer.
0 1 2
3 4 5
6 7 8
Our layer loop provides the indexes of the first and last columns, as well as first and last rows:
+-----+-------+
| Col | 0 1 2 |
+-----+-------+
| | 0 1 2 |
| | 3 4 5 |
| | 6 7 8 |
+-----+-------+
+-----+-------+
| Row | |
+-----+-------+
| 0 | 0 1 2 |
| 1 | 3 4 5 |
| 2 | 6 7 8 |
+-----+-------+
Because our matrices are always square, we need just two variables, first and last, since index positions are the same for rows and columns.
def rotate(matrix):
size = len(matrix)
layer_count = size / 2
# Our layer loop i=0, i=1, i=2
for layer in range(0, layer_count):
first = layer
last = size - first - 1
# We want to move within a layer here.
The variables first and last can easily be used to reference the four corners of a matrix. This is because the corners themselves can be defined using various permutations of first and last (with no subtraction, addition or offset of those variables):
+---------------+-------------------+-------------+
| Corner | Position | 3x3 Values |
+---------------+-------------------+-------------+
| top left | (first, first) | (0,0) |
| top right | (first, last) | (0,2) |
| bottom right | (last, last) | (2,2) |
| bottom left | (last, first) | (2,0) |
+---------------+-------------------+-------------+
For this reason, we start our rotation at the outer four corners — we’ll rotate those first. Let’s highlight them with *.
* 1 *
3 4 5
* 7 *
We want to swap each * with the * to the right of it. So let’s go ahead a print out our corners defined using only various permutations of first and last:
def rotate(matrix):
size = len(matrix)
layer_count = size / 2
for layer in range(0, layer_count):
first = layer
last = size - first - 1
top_left = (first, first)
top_right = (first, last)
bottom_right = (last, last)
bottom_left = (last, first)
print 'top_left: %s' % (top_left)
print 'top_right: %s' % (top_right)
print 'bottom_right: %s' % (bottom_right)
print 'bottom_left: %s' % (bottom_left)
matrix = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
rotate(matrix)
Output should be:
top_left: (0, 0)
top_right: (0, 2)
bottom_right: (2, 2)
bottom_left: (2, 0)
Now we could quite easily swap each of the corners from within our layer loop:
def rotate(matrix):
size = len(matrix)
layer_count = size / 2
for layer in range(0, layer_count):
first = layer
last = size - first - 1
top_left = matrix[first][first]
top_right = matrix[first][last]
bottom_right = matrix[last][last]
bottom_left = matrix[last][first]
# bottom_left -> top_left
matrix[first][first] = bottom_left
# top_left -> top_right
matrix[first][last] = top_left
# top_right -> bottom_right
matrix[last][last] = top_right
# bottom_right -> bottom_left
matrix[last][first] = bottom_right
print_matrix(matrix)
print '---------'
rotate(matrix)
print_matrix(matrix)
Matrix before rotating corners:
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
Matrix after rotating corners:
[6, 1, 0]
[3, 4, 5]
[8, 7, 2]
Great! We have successfully rotated each corner of the matrix. But, we haven’t rotated the elements in the middle of each layer. Clearly we need a way of iterating within a layer.
The problem is, the only loop in our function so far (our layer loop), moves to the next layer on each iteration. Since our matrix has only one rotatable layer, the layer loop exits after rotating only the corners. Let’s look at what happens with a larger, 5×5 matrix (where two layers need rotating). The function code has been omitted, but it remains the same as above:
matrix = [
[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]
]
print_matrix(matrix)
print '--------------------'
rotate(matrix)
print_matrix(matrix)
The output is:
[20, 1, 2, 3, 0]
[ 5, 16, 7, 6, 9]
[10, 11, 12, 13, 14]
[15, 18, 17, 8, 19]
[24, 21, 22, 23, 4]
It shouldn’t be a surprise that the corners of the outermost layer have been rotated, but, you may also notice the corners of the next layer (inwards) have also been rotated. This makes sense. We’ve written code to navigate through layers and also to rotate the corners of each layer. This feels like progress, but unfortunately we must take a step back. It’s just no good moving onto the next layer until the previous (outer) layer has been fully rotated. That is, until each element in the layer has been rotated. Rotating only the corners won’t do!
Take a deep breath. We need another loop. A nested loop no less. The new, nested loop, will use the first and last variables, plus an offset to navigate within a layer. We’ll call this new loop our ‘element loop’. The element loop will visit each element along the top row, each element down the right side, each element along the bottom row and each element up the left side.
*
*Moving forwards along the top row requires the column
index to be incremented.
*Moving down the right side requires the row index to be
incremented.
*Moving backwards along the bottom requires the column
index to be decremented.
*Moving up the left side requires the row index to be
decremented.
This sounds complex, but it’s made easy because the number of times we increment and decrement to achieve the above remains the same along all four sides of the matrix. For example:
*
*Move 1 element across the top row.
*Move 1 element down the right side.
*Move 1 element backwards along the bottom row.
*Move 1 element up the left side.
This means we can use a single variable in combination with the first and last variables to move within a layer. It may help to note that moving across the top row and down the right side both require incrementing. While moving backwards along the bottom and up the left side both require decrementing.
def rotate(matrix):
size = len(matrix)
layer_count = size / 2
# Move through layers (i.e. layer loop).
for layer in range(0, layer_count):
first = layer
last = size - first - 1
# Move within a single layer (i.e. element loop).
for element in range(first, last):
offset = element - first
# 'element' increments column (across right)
top = (first, element)
# 'element' increments row (move down)
right_side = (element, last)
# 'last-offset' decrements column (across left)
bottom = (last, last-offset)
# 'last-offset' decrements row (move up)
left_side = (last-offset, first)
print 'top: %s' % (top)
print 'right_side: %s' % (right_side)
print 'bottom: %s' % (bottom)
print 'left_side: %s' % (left_side)
Now we simply need to assign the top to the right side, right side to the bottom, bottom to the left side, and left side to the top. Putting this all together we get:
def rotate(matrix):
size = len(matrix)
layer_count = size / 2
for layer in range(0, layer_count):
first = layer
last = size - first - 1
for element in range(first, last):
offset = element - first
top = matrix[first][element]
right_side = matrix[element][last]
bottom = matrix[last][last-offset]
left_side = matrix[last-offset][first]
matrix[first][element] = left_side
matrix[element][last] = top
matrix[last][last-offset] = right_side
matrix[last-offset][first] = bottom
Given the matrix:
0, 1, 2
3, 4, 5
6, 7, 8
Our rotate function results in:
6, 3, 0
7, 4, 1
8, 5, 2
A: Whilst rotating the data in place might be necessary (perhaps to update the physically stored representation), it becomes simpler and possibly more performant to add a layer of indirection onto the array access, perhaps an interface:
interface IReadableMatrix
{
int GetValue(int x, int y);
}
If your Matrix already implements this interface, then it can be rotated via a decorator class like this:
class RotatedMatrix : IReadableMatrix
{
private readonly IReadableMatrix _baseMatrix;
public RotatedMatrix(IReadableMatrix baseMatrix)
{
_baseMatrix = baseMatrix;
}
int GetValue(int x, int y)
{
// transpose x and y dimensions
return _baseMatrix(y, x);
}
}
Rotating +90/-90/180 degrees, flipping horizontally/vertically and scaling can all be achieved in this fashion as well.
Performance would need to be measured in your specific scenario. However the O(n^2) operation has now been replaced with an O(1) call. It's a virtual method call which is slower than direct array access, so it depends upon how frequently the rotated array is used after rotation. If it's used once, then this approach would definitely win. If it's rotated then used in a long-running system for days, then in-place rotation might perform better. It also depends whether you can accept the up-front cost.
As with all performance issues, measure, measure, measure!
A: This a better version of it in Java: I've made it for a matrix with a different width and height
*
*h is here the height of the matrix after rotating
*w is here the width of the matrix after rotating
public int[][] rotateMatrixRight(int[][] matrix)
{
/* W and H are already swapped */
int w = matrix.length;
int h = matrix[0].length;
int[][] ret = new int[h][w];
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
ret[i][j] = matrix[w - j - 1][i];
}
}
return ret;
}
public int[][] rotateMatrixLeft(int[][] matrix)
{
/* W and H are already swapped */
int w = matrix.length;
int h = matrix[0].length;
int[][] ret = new int[h][w];
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
ret[i][j] = matrix[j][h - i - 1];
}
}
return ret;
}
This code is based on Nick Berardi's post.
A: PHP:
<?php
$a = array(array(1,2,3,4),array(5,6,7,8),array(9,0,1,2),array(3,4,5,6));
$b = array(); //result
while(count($a)>0)
{
$b[count($a[0])-1][] = array_shift($a[0]);
if (count($a[0])==0)
{
array_shift($a);
}
}
From PHP5.6, Array transposition can be performed with a sleak array_map() call. In other words, columns are converted to rows.
Code: (Demo)
$array = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 0, 1, 2],
[3, 4, 5, 6]
];
$transposed = array_map(null, ...$array);
$transposed:
[
[1, 5, 9, 3],
[2, 6, 0, 4],
[3, 7, 1, 5],
[4, 8, 2, 6]
]
A: This is my implementation, in C, O(1) memory complexity, in place rotation, 90 degrees clockwise:
#include <stdio.h>
#define M_SIZE 5
static void initMatrix();
static void printMatrix();
static void rotateMatrix();
static int m[M_SIZE][M_SIZE];
int main(void){
initMatrix();
printMatrix();
rotateMatrix();
printMatrix();
return 0;
}
static void initMatrix(){
int i, j;
for(i = 0; i < M_SIZE; i++){
for(j = 0; j < M_SIZE; j++){
m[i][j] = M_SIZE*i + j + 1;
}
}
}
static void printMatrix(){
int i, j;
printf("Matrix\n");
for(i = 0; i < M_SIZE; i++){
for(j = 0; j < M_SIZE; j++){
printf("%02d ", m[i][j]);
}
printf("\n");
}
printf("\n");
}
static void rotateMatrix(){
int r, c;
for(r = 0; r < M_SIZE/2; r++){
for(c = r; c < M_SIZE - r - 1; c++){
int tmp = m[r][c];
m[r][c] = m[M_SIZE - c - 1][r];
m[M_SIZE - c - 1][r] = m[M_SIZE - r - 1][M_SIZE - c - 1];
m[M_SIZE - r - 1][M_SIZE - c - 1] = m[c][M_SIZE - r - 1];
m[c][M_SIZE - r - 1] = tmp;
}
}
}
A: Here is the Java version:
public static void rightRotate(int[][] matrix, int n) {
for (int layer = 0; layer < n / 2; layer++) {
int first = layer;
int last = n - 1 - first;
for (int i = first; i < last; i++) {
int offset = i - first;
int temp = matrix[first][i];
matrix[first][i] = matrix[last-offset][first];
matrix[last-offset][first] = matrix[last][last-offset];
matrix[last][last-offset] = matrix[i][last];
matrix[i][last] = temp;
}
}
}
the method first rotate the mostouter layer, then move to the inner layer squentially.
A: From a linear point of view, consider the matrices:
1 2 3 0 0 1
A = 4 5 6 B = 0 1 0
7 8 9 1 0 0
Now take A transpose
1 4 7
A' = 2 5 8
3 6 9
And consider the action of A' on B, or B on A'.
Respectively:
7 4 1 3 6 9
A'B = 8 5 2 BA' = 2 5 8
9 6 3 1 4 7
This is expandable for any n x n matrix.
And applying this concept quickly in code:
void swapInSpace(int** mat, int r1, int c1, int r2, int c2)
{
mat[r1][c1] ^= mat[r2][c2];
mat[r2][c2] ^= mat[r1][c1];
mat[r1][c1] ^= mat[r2][c2];
}
void transpose(int** mat, int size)
{
for (int i = 0; i < size; i++)
{
for (int j = (i + 1); j < size; j++)
{
swapInSpace(mat, i, j, j, i);
}
}
}
void rotate(int** mat, int size)
{
//Get transpose
transpose(mat, size);
//Swap columns
for (int i = 0; i < size / 2; i++)
{
for (int j = 0; j < size; j++)
{
swapInSpace(mat, i, j, size - (i + 1), j);
}
}
}
A: C# code to rotate [n,m] 2D arrays 90 deg right
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MatrixProject
{
// mattrix class
class Matrix{
private int rows;
private int cols;
private int[,] matrix;
public Matrix(int n){
this.rows = n;
this.cols = n;
this.matrix = new int[this.rows,this.cols];
}
public Matrix(int n,int m){
this.rows = n;
this.cols = m;
this.matrix = new int[this.rows,this.cols];
}
public void Show()
{
for (var i = 0; i < this.rows; i++)
{
for (var j = 0; j < this.cols; j++) {
Console.Write("{0,3}", this.matrix[i, j]);
}
Console.WriteLine();
}
}
public void ReadElements()
{
for (var i = 0; i < this.rows; i++)
for (var j = 0; j < this.cols; j++)
{
Console.Write("element[{0},{1}]=",i,j);
this.matrix[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
// rotate [n,m] 2D array by 90 deg right
public void Rotate90DegRight()
{
// create a mirror of current matrix
int[,] mirror = this.matrix;
// create a new matrix
this.matrix = new int[this.cols, this.rows];
for (int i = 0; i < this.rows; i++)
{
for (int j = 0; j < this.cols; j++)
{
this.matrix[j, this.rows - i - 1] = mirror[i, j];
}
}
// replace cols count with rows count
int tmp = this.rows;
this.rows = this.cols;
this.cols = tmp;
}
}
class Program
{
static void Main(string[] args)
{
Matrix myMatrix = new Matrix(3,4);
Console.WriteLine("Enter matrix elements:");
myMatrix.ReadElements();
Console.WriteLine("Matrix elements are:");
myMatrix.Show();
myMatrix.Rotate90DegRight();
Console.WriteLine("Matrix rotated at 90 deg are:");
myMatrix.Show();
Console.ReadLine();
}
}
}
Result:
Enter matrix elements:
element[0,0]=1
element[0,1]=2
element[0,2]=3
element[0,3]=4
element[1,0]=5
element[1,1]=6
element[1,2]=7
element[1,3]=8
element[2,0]=9
element[2,1]=10
element[2,2]=11
element[2,3]=12
Matrix elements are:
1 2 3 4
5 6 7 8
9 10 11 12
Matrix rotated at 90 deg are:
9 5 1
10 6 2
11 7 3
12 8 4
A: Great answers but for those who are looking for a DRY JavaScript code for this - both +90 Degrees and -90 Degrees:
// Input: 1 2 3
// 4 5 6
// 7 8 9
// Transpose:
// 1 4 7
// 2 5 8
// 3 6 9
// Output:
// +90 Degree:
// 7 4 1
// 8 5 2
// 9 6 3
// -90 Degree:
// 3 6 9
// 2 5 8
// 1 4 7
// Rotate +90
function rotate90(matrix) {
matrix = transpose(matrix);
matrix.map(function(array) {
array.reverse();
});
return matrix;
}
// Rotate -90
function counterRotate90(matrix) {
var result = createEmptyMatrix(matrix.length);
matrix = transpose(matrix);
var counter = 0;
for (var i = matrix.length - 1; i >= 0; i--) {
result[counter] = matrix[i];
counter++;
}
return result;
}
// Create empty matrix
function createEmptyMatrix(len) {
var result = new Array();
for (var i = 0; i < len; i++) {
result.push([]);
}
return result;
}
// Transpose the matrix
function transpose(matrix) {
// make empty array
var len = matrix.length;
var result = createEmptyMatrix(len);
for (var i = 0; i < matrix.length; i++) {
for (var j = 0; j < matrix[i].length; j++) {
var temp = matrix[i][j];
result[j][i] = temp;
}
}
return result;
}
// Test Cases
var array1 = [
[1, 2],
[3, 4]
];
var array2 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
var array3 = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
];
// +90 degress Rotation Tests
var test1 = rotate90(array1);
var test2 = rotate90(array2);
var test3 = rotate90(array3);
console.log(test1);
console.log(test2);
console.log(test3);
// -90 degress Rotation Tests
var test1 = counterRotate90(array1);
var test2 = counterRotate90(array2);
var test3 = counterRotate90(array3);
console.log(test1);
console.log(test2);
console.log(test3);
A: Ruby-way: .transpose.map &:reverse
A: Here it is in C#
int[,] array = new int[4,4] {
{ 1,2,3,4 },
{ 5,6,7,8 },
{ 9,0,1,2 },
{ 3,4,5,6 }
};
int[,] rotated = RotateMatrix(array, 4);
static int[,] RotateMatrix(int[,] matrix, int n) {
int[,] ret = new int[n, n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
ret[i, j] = matrix[n - j - 1, i];
}
}
return ret;
}
A: There are a lot of answers already, and I found two claiming O(1) time complexity. The real O(1) algorithm is to leave the array storage untouched, and change how you index its elements. The goal here is that it does not consume additional memory, nor does it require additional time to iterate the data.
Rotations of 90, -90 and 180 degrees are simple transformations which can be performed as long as you know how many rows and columns are in your 2D array; To rotate any vector by 90 degrees, swap the axes and negate the Y axis. For -90 degree, swap the axes and negate the X axis. For 180 degrees, negate both axes without swapping.
Further transformations are possible, such as mirroring horizontally and/or vertically by negating the axes independently.
This can be done through e.g. an accessor method. The examples below are JavaScript functions, but the concepts apply equally to all languages.
// Get an array element in column/row order
var getArray2d = function(a, x, y) {
return a[y][x];
};
//demo
var arr = [
[5, 4, 6],
[1, 7, 9],
[-2, 11, 0],
[8, 21, -3],
[3, -1, 2]
];
var newarr = [];
arr[0].forEach(() => newarr.push(new Array(arr.length)));
for (var i = 0; i < newarr.length; i++) {
for (var j = 0; j < newarr[0].length; j++) {
newarr[i][j] = getArray2d(arr, i, j);
}
}
console.log(newarr);
// Get an array element rotated 90 degrees clockwise
function getArray2dCW(a, x, y) {
var t = x;
x = y;
y = a.length - t - 1;
return a[y][x];
}
//demo
var arr = [
[5, 4, 6],
[1, 7, 9],
[-2, 11, 0],
[8, 21, -3],
[3, -1, 2]
];
var newarr = [];
arr[0].forEach(() => newarr.push(new Array(arr.length)));
for (var i = 0; i < newarr[0].length; i++) {
for (var j = 0; j < newarr.length; j++) {
newarr[j][i] = getArray2dCW(arr, i, j);
}
}
console.log(newarr);
// Get an array element rotated 90 degrees counter-clockwise
function getArray2dCCW(a, x, y) {
var t = x;
x = a[0].length - y - 1;
y = t;
return a[y][x];
}
//demo
var arr = [
[5, 4, 6],
[1, 7, 9],
[-2, 11, 0],
[8, 21, -3],
[3, -1, 2]
];
var newarr = [];
arr[0].forEach(() => newarr.push(new Array(arr.length)));
for (var i = 0; i < newarr[0].length; i++) {
for (var j = 0; j < newarr.length; j++) {
newarr[j][i] = getArray2dCCW(arr, i, j);
}
}
console.log(newarr);
// Get an array element rotated 180 degrees
function getArray2d180(a, x, y) {
x = a[0].length - x - 1;
y = a.length - y - 1;
return a[y][x];
}
//demo
var arr = [
[5, 4, 6],
[1, 7, 9],
[-2, 11, 0],
[8, 21, -3],
[3, -1, 2]
];
var newarr = [];
arr.forEach(() => newarr.push(new Array(arr[0].length)));
for (var i = 0; i < newarr[0].length; i++) {
for (var j = 0; j < newarr.length; j++) {
newarr[j][i] = getArray2d180(arr, i, j);
}
}
console.log(newarr);
This code assumes an array of nested arrays, where each inner array is a row.
The method allows you to read (or write) elements (even in random order) as if the array has been rotated or transformed. Now just pick the right function to call, probably by reference, and away you go!
The concept can be extended to apply transformations additively (and non-destructively) through the accessor methods. Including arbitrary angle rotations and scaling.
A: Python:
rotated = list(zip(*original[::-1]))
and counterclockwise:
rotated_ccw = list(zip(*original))[::-1]
How this works:
zip(*original) will swap axes of 2d arrays by stacking corresponding items from lists into new lists. (The * operator tells the function to distribute the contained lists into arguments)
>>> list(zip(*[[1,2,3],[4,5,6],[7,8,9]]))
[[1,4,7],[2,5,8],[3,6,9]]
The [::-1] statement reverses array elements (please see Extended Slices or this question):
>>> [[1,2,3],[4,5,6],[7,8,9]][::-1]
[[7,8,9],[4,5,6],[1,2,3]]
Finally, combining the two will result in the rotation transformation.
The change in placement of [::-1] will reverse lists in different levels of the matrix.
A: A couple of people have already put up examples which involve making a new array.
A few other things to consider:
(a) Instead of actually moving the data, simply traverse the "rotated" array differently.
(b) Doing the rotation in-place can be a little trickier. You'll need a bit of scratch place (probably roughly equal to one row or column in size). There's an ancient ACM paper about doing in-place transposes (http://doi.acm.org/10.1145/355719.355729), but their example code is nasty goto-laden FORTRAN.
Addendum:
http://doi.acm.org/10.1145/355611.355612 is another, supposedly superior, in-place transpose algorithm.
A: @dagorym: Aw, man. I had been hanging onto this as a good "I'm bored, what can I ponder" puzzle. I came up with my in-place transposition code, but got here to find yours pretty much identical to mine...ah, well. Here it is in Ruby.
require 'pp'
n = 10
a = []
n.times { a << (1..n).to_a }
pp a
0.upto(n/2-1) do |i|
i.upto(n-i-2) do |j|
tmp = a[i][j]
a[i][j] = a[n-j-1][i]
a[n-j-1][i] = a[n-i-1][n-j-1]
a[n-i-1][n-j-1] = a[j][n-i-1]
a[j][n-i-1] = tmp
end
end
pp a
A: short normal[4][4] = {{8,4,7,5},{3,4,5,7},{9,5,5,6},{3,3,3,3}};
short rotated[4][4];
for (int r = 0; r < 4; ++r)
{
for (int c = 0; c < 4; ++c)
{
rotated[r][c] = normal[c][3-r];
}
}
Simple C++ method, tho there would be a big memory overhead in a big array.
A: For i:= 0 to X do
For j := 0 to X do
graphic[j][i] := graphic2[X-i][j]
X is the size of the array the graphic is in.
A: #transpose is a standard method of Ruby's Array class, thus:
% irb
irb(main):001:0> m = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 1, 2], [3, 4, 5, 6]]
=> [[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 1, 2], [3, 4, 5, 6]]
irb(main):002:0> m.reverse.transpose
=> [[3, 9, 5, 1], [4, 0, 6, 2], [5, 1, 7, 3], [6, 2, 8, 4]]
The implementation is an n^2 transposition function written in C. You can see it here:
http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-transpose
by choosing "click to toggle source" beside "transpose".
I recall better than O(n^2) solutions, but only for specially constructed matrices (such as sparse matrices)
A: C code for matrix rotation 90 degree clockwise IN PLACE for any M*N matrix
void rotateInPlace(int * arr[size][size], int row, int column){
int i, j;
int temp = row>column?row:column;
int flipTill = row < column ? row : column;
for(i=0;i<flipTill;i++){
for(j=0;j<i;j++){
swapArrayElements(arr, i, j);
}
}
temp = j+1;
for(i = row>column?i:0; i<row; i++){
for(j=row<column?temp:0; j<column; j++){
swapArrayElements(arr, i, j);
}
}
for(i=0;i<column;i++){
for(j=0;j<row/2;j++){
temp = arr[i][j];
arr[i][j] = arr[i][row-j-1];
arr[i][row-j-1] = temp;
}
}
}
A: Here is my attempt for matrix 90 deg rotation which is a 2 step solution in C. First transpose the matrix in place and then swap the cols.
#define ROWS 5
#define COLS 5
void print_matrix_b(int B[][COLS], int rows, int cols)
{
for (int i = 0; i <= rows; i++) {
for (int j = 0; j <=cols; j++) {
printf("%d ", B[i][j]);
}
printf("\n");
}
}
void swap_columns(int B[][COLS], int l, int r, int rows)
{
int tmp;
for (int i = 0; i <= rows; i++) {
tmp = B[i][l];
B[i][l] = B[i][r];
B[i][r] = tmp;
}
}
void matrix_2d_rotation(int B[][COLS], int rows, int cols)
{
int tmp;
// Transpose the matrix first
for (int i = 0; i <= rows; i++) {
for (int j = i; j <=cols; j++) {
tmp = B[i][j];
B[i][j] = B[j][i];
B[j][i] = tmp;
}
}
// Swap the first and last col and continue until
// the middle.
for (int i = 0; i < (cols / 2); i++)
swap_columns(B, i, cols - i, rows);
}
int _tmain(int argc, _TCHAR* argv[])
{
int B[ROWS][COLS] = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}
};
matrix_2d_rotation(B, ROWS - 1, COLS - 1);
print_matrix_b(B, ROWS - 1, COLS -1);
return 0;
}
A: private static int[][] rotate(int[][] matrix, int n) {
int[][] rotated = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
rotated[i][j] = matrix[n-j-1][i];
}
}
return rotated;
}
A: here is my In Place implementation in C
void rotateRight(int matrix[][SIZE], int length) {
int layer = 0;
for (int layer = 0; layer < length / 2; ++layer) {
int first = layer;
int last = length - 1 - layer;
for (int i = first; i < last; ++i) {
int topline = matrix[first][i];
int rightcol = matrix[i][last];
int bottomline = matrix[last][length - layer - 1 - i];
int leftcol = matrix[length - layer - 1 - i][first];
matrix[first][i] = leftcol;
matrix[i][last] = topline;
matrix[last][length - layer - 1 - i] = rightcol;
matrix[length - layer - 1 - i][first] = bottomline;
}
}
}
A: Javascript solution for NxN matrix with runtime O(N^2) and memory O(1)
function rotate90(matrix){
var length = matrix.length
for(var row = 0; row < (length / 2); row++){
for(var col = row; col < ( length - 1 - row); col++){
var tmpVal = matrix[row][col];
for(var i = 0; i < 4; i++){
var rowSwap = col;
var colSwap = (length - 1) - row;
var poppedVal = matrix[rowSwap][colSwap];
matrix[rowSwap][colSwap] = tmpVal;
tmpVal = poppedVal;
col = colSwap;
row = rowSwap;
}
}
}
}
A: PHP Solution for clockwise & counterclockwise
$aMatrix = array(
array( 1, 2, 3 ),
array( 4, 5, 6 ),
array( 7, 8, 9 )
);
function CounterClockwise( $aMatrix )
{
$iCount = count( $aMatrix );
$aReturn = array();
for( $y = 0; $y < $iCount; ++$y )
{
for( $x = 0; $x < $iCount; ++$x )
{
$aReturn[ $iCount - $x - 1 ][ $y ] = $aMatrix[ $y ][ $x ];
}
}
return $aReturn;
}
function Clockwise( $aMatrix )
{
$iCount = count( $aMatrix );
$aReturn = array();
for( $y = 0; $y < $iCount; ++$y )
{
for( $x = 0; $x < $iCount; ++$x )
{
$aReturn[ $x ][ $iCount - $y - 1 ] = $aMatrix[ $y ][ $x ];
}
}
return $aReturn;
}
function printMatrix( $aMatrix )
{
$iCount = count( $aMatrix );
for( $x = 0; $x < $iCount; ++$x )
{
for( $y = 0; $y < $iCount; ++$y )
{
echo $aMatrix[ $x ][ $y ];
echo " ";
}
echo "\n";
}
}
printMatrix( $aMatrix );
echo "\n";
$aNewMatrix = CounterClockwise( $aMatrix );
printMatrix( $aNewMatrix );
echo "\n";
$aNewMatrix = Clockwise( $aMatrix );
printMatrix( $aNewMatrix );
A: C code for matrix transpose & rotate (+/-90, +/-180)
*
*Supports square and non-square matrices, has in-place and copy features
*Supports both 2D arrays and 1D pointers with logical rows/cols
*Unit tests; see tests for examples of usage
*tested gcc -std=c90 -Wall -pedantic, MSVC17
`
#include <stdlib.h>
#include <memory.h>
#include <assert.h>
/*
Matrix transpose & rotate (+/-90, +/-180)
Supports both 2D arrays and 1D pointers with logical rows/cols
Supports square and non-square matrices, has in-place and copy features
See tests for examples of usage
tested gcc -std=c90 -Wall -pedantic, MSVC17
*/
typedef int matrix_data_t; /* matrix data type */
void transpose(const matrix_data_t* src, matrix_data_t* dst, int rows, int cols);
void transpose_inplace(matrix_data_t* data, int n );
void rotate(int direction, const matrix_data_t* src, matrix_data_t* dst, int rows, int cols);
void rotate_inplace(int direction, matrix_data_t* data, int n);
void reverse_rows(matrix_data_t* data, int rows, int cols);
void reverse_cols(matrix_data_t* data, int rows, int cols);
/* test/compare fn */
int test_cmp(const matrix_data_t* lhs, const matrix_data_t* rhs, int rows, int cols );
/* TESTS/USAGE */
void transpose_test() {
matrix_data_t sq3x3[9] = { 0,1,2,3,4,5,6,7,8 };/* 3x3 square, odd length side */
matrix_data_t sq3x3_cpy[9];
matrix_data_t sq3x3_2D[3][3] = { { 0,1,2 },{ 3,4,5 },{ 6,7,8 } };/* 2D 3x3 square */
matrix_data_t sq3x3_2D_copy[3][3];
/* expected test values */
const matrix_data_t sq3x3_orig[9] = { 0,1,2,3,4,5,6,7,8 };
const matrix_data_t sq3x3_transposed[9] = { 0,3,6,1,4,7,2,5,8};
matrix_data_t sq4x4[16]= { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };/* 4x4 square, even length*/
const matrix_data_t sq4x4_orig[16] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
const matrix_data_t sq4x4_transposed[16] = { 0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15 };
/* 2x3 rectangle */
const matrix_data_t r2x3_orig[6] = { 0,1,2,3,4,5 };
const matrix_data_t r2x3_transposed[6] = { 0,3,1,4,2,5 };
matrix_data_t r2x3_copy[6];
matrix_data_t r2x3_2D[2][3] = { {0,1,2},{3,4,5} }; /* 2x3 2D rectangle */
matrix_data_t r2x3_2D_t[3][2];
/* matrix_data_t r3x2[6] = { 0,1,2,3,4,5 }; */
matrix_data_t r3x2_copy[6];
/* 3x2 rectangle */
const matrix_data_t r3x2_orig[6] = { 0,1,2,3,4,5 };
const matrix_data_t r3x2_transposed[6] = { 0,2,4,1,3,5 };
matrix_data_t r6x1[6] = { 0,1,2,3,4,5 }; /* 6x1 */
matrix_data_t r6x1_copy[6];
matrix_data_t r1x1[1] = { 0 }; /*1x1*/
matrix_data_t r1x1_copy[1];
/* 3x3 tests, 2D array tests */
transpose_inplace(sq3x3, 3); /* transpose in place */
assert(!test_cmp(sq3x3, sq3x3_transposed, 3, 3));
transpose_inplace(sq3x3, 3); /* transpose again */
assert(!test_cmp(sq3x3, sq3x3_orig, 3, 3));
transpose(sq3x3, sq3x3_cpy, 3, 3); /* transpose copy 3x3*/
assert(!test_cmp(sq3x3_cpy, sq3x3_transposed, 3, 3));
transpose((matrix_data_t*)sq3x3_2D, (matrix_data_t*)sq3x3_2D_copy, 3, 3); /* 2D array transpose/copy */
assert(!test_cmp((matrix_data_t*)sq3x3_2D_copy, sq3x3_transposed, 3, 3));
transpose_inplace((matrix_data_t*)sq3x3_2D_copy, 3); /* 2D array transpose in place */
assert(!test_cmp((matrix_data_t*)sq3x3_2D_copy, sq3x3_orig, 3, 3));
/* 4x4 tests */
transpose_inplace(sq4x4, 4); /* transpose in place */
assert(!test_cmp(sq4x4, sq4x4_transposed, 4,4));
transpose_inplace(sq4x4, 4); /* transpose again */
assert(!test_cmp(sq4x4, sq4x4_orig, 3, 3));
/* 2x3,3x2 tests */
transpose(r2x3_orig, r2x3_copy, 2, 3);
assert(!test_cmp(r2x3_copy, r2x3_transposed, 3, 2));
transpose(r3x2_orig, r3x2_copy, 3, 2);
assert(!test_cmp(r3x2_copy, r3x2_transposed, 2,3));
/* 2D array */
transpose((matrix_data_t*)r2x3_2D, (matrix_data_t*)r2x3_2D_t, 2, 3);
assert(!test_cmp((matrix_data_t*)r2x3_2D_t, r2x3_transposed, 3,2));
/* Nx1 test, 1x1 test */
transpose(r6x1, r6x1_copy, 6, 1);
assert(!test_cmp(r6x1_copy, r6x1, 1, 6));
transpose(r1x1, r1x1_copy, 1, 1);
assert(!test_cmp(r1x1_copy, r1x1, 1, 1));
}
void rotate_test() {
/* 3x3 square */
const matrix_data_t sq3x3[9] = { 0,1,2,3,4,5,6,7,8 };
const matrix_data_t sq3x3_r90[9] = { 6,3,0,7,4,1,8,5,2 };
const matrix_data_t sq3x3_180[9] = { 8,7,6,5,4,3,2,1,0 };
const matrix_data_t sq3x3_l90[9] = { 2,5,8,1,4,7,0,3,6 };
matrix_data_t sq3x3_copy[9];
/* 3x3 square, 2D */
matrix_data_t sq3x3_2D[3][3] = { { 0,1,2 },{ 3,4,5 },{ 6,7,8 } };
/* 4x4, 2D */
matrix_data_t sq4x4[4][4] = { { 0,1,2,3 },{ 4,5,6,7 },{ 8,9,10,11 },{ 12,13,14,15 } };
matrix_data_t sq4x4_copy[4][4];
const matrix_data_t sq4x4_r90[16] = { 12,8,4,0,13,9,5,1,14,10,6,2,15,11,7,3 };
const matrix_data_t sq4x4_l90[16] = { 3,7,11,15,2,6,10,14,1,5,9,13,0,4,8,12 };
const matrix_data_t sq4x4_180[16] = { 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 };
matrix_data_t r6[6] = { 0,1,2,3,4,5 }; /* rectangle with area of 6 (1x6,2x3,3x2, or 6x1) */
matrix_data_t r6_copy[6];
const matrix_data_t r1x6_r90[6] = { 0,1,2,3,4,5 };
const matrix_data_t r1x6_l90[6] = { 5,4,3,2,1,0 };
const matrix_data_t r1x6_180[6] = { 5,4,3,2,1,0 };
const matrix_data_t r2x3_r90[6] = { 3,0,4,1,5,2 };
const matrix_data_t r2x3_l90[6] = { 2,5,1,4,0,3 };
const matrix_data_t r2x3_180[6] = { 5,4,3,2,1,0 };
const matrix_data_t r3x2_r90[6] = { 4,2,0,5,3,1 };
const matrix_data_t r3x2_l90[6] = { 1,3,5,0,2,4 };
const matrix_data_t r3x2_180[6] = { 5,4,3,2,1,0 };
const matrix_data_t r6x1_r90[6] = { 5,4,3,2,1,0 };
const matrix_data_t r6x1_l90[6] = { 0,1,2,3,4,5 };
const matrix_data_t r6x1_180[6] = { 5,4,3,2,1,0 };
/* sq3x3 tests */
rotate(90, sq3x3, sq3x3_copy, 3, 3); /* +90 */
assert(!test_cmp(sq3x3_copy, sq3x3_r90, 3, 3));
rotate(-90, sq3x3, sq3x3_copy, 3, 3); /* -90 */
assert(!test_cmp(sq3x3_copy, sq3x3_l90, 3, 3));
rotate(180, sq3x3, sq3x3_copy, 3, 3); /* 180 */
assert(!test_cmp(sq3x3_copy, sq3x3_180, 3, 3));
/* sq3x3 in-place rotations */
memcpy( sq3x3_copy, sq3x3, 3 * 3 * sizeof(matrix_data_t));
rotate_inplace(90, sq3x3_copy, 3);
assert(!test_cmp(sq3x3_copy, sq3x3_r90, 3, 3));
rotate_inplace(-90, sq3x3_copy, 3);
assert(!test_cmp(sq3x3_copy, sq3x3, 3, 3)); /* back to 0 orientation */
rotate_inplace(180, sq3x3_copy, 3);
assert(!test_cmp(sq3x3_copy, sq3x3_180, 3, 3));
rotate_inplace(-180, sq3x3_copy, 3);
assert(!test_cmp(sq3x3_copy, sq3x3, 3, 3));
rotate_inplace(180, (matrix_data_t*)sq3x3_2D, 3);/* 2D test */
assert(!test_cmp((matrix_data_t*)sq3x3_2D, sq3x3_180, 3, 3));
/* sq4x4 */
rotate(90, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);
assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_r90, 4, 4));
rotate(-90, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);
assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_l90, 4, 4));
rotate(180, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);
assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_180, 4, 4));
/* r6 as 1x6 */
rotate(90, r6, r6_copy, 1, 6);
assert(!test_cmp(r6_copy, r1x6_r90, 1, 6));
rotate(-90, r6, r6_copy, 1, 6);
assert(!test_cmp(r6_copy, r1x6_l90, 1, 6));
rotate(180, r6, r6_copy, 1, 6);
assert(!test_cmp(r6_copy, r1x6_180, 1, 6));
/* r6 as 2x3 */
rotate(90, r6, r6_copy, 2, 3);
assert(!test_cmp(r6_copy, r2x3_r90, 2, 3));
rotate(-90, r6, r6_copy, 2, 3);
assert(!test_cmp(r6_copy, r2x3_l90, 2, 3));
rotate(180, r6, r6_copy, 2, 3);
assert(!test_cmp(r6_copy, r2x3_180, 2, 3));
/* r6 as 3x2 */
rotate(90, r6, r6_copy, 3, 2);
assert(!test_cmp(r6_copy, r3x2_r90, 3, 2));
rotate(-90, r6, r6_copy, 3, 2);
assert(!test_cmp(r6_copy, r3x2_l90, 3, 2));
rotate(180, r6, r6_copy, 3, 2);
assert(!test_cmp(r6_copy, r3x2_180, 3, 2));
/* r6 as 6x1 */
rotate(90, r6, r6_copy, 6, 1);
assert(!test_cmp(r6_copy, r6x1_r90, 6, 1));
rotate(-90, r6, r6_copy, 6, 1);
assert(!test_cmp(r6_copy, r6x1_l90, 6, 1));
rotate(180, r6, r6_copy, 6, 1);
assert(!test_cmp(r6_copy, r6x1_180, 6, 1));
}
/* test comparison fn, return 0 on match else non zero */
int test_cmp(const matrix_data_t* lhs, const matrix_data_t* rhs, int rows, int cols) {
int r, c;
for (r = 0; r < rows; ++r) {
for (c = 0; c < cols; ++c) {
if ((lhs + r * cols)[c] != (rhs + r * cols)[c])
return -1;
}
}
return 0;
}
/*
Reverse values in place of each row in 2D matrix data[rows][cols] or in 1D pointer with logical rows/cols
[A B C] -> [C B A]
[D E F] [F E D]
*/
void reverse_rows(matrix_data_t* data, int rows, int cols) {
int r, c;
matrix_data_t temp;
matrix_data_t* pRow = NULL;
for (r = 0; r < rows; ++r) {
pRow = (data + r * cols);
for (c = 0; c < (int)(cols / 2); ++c) { /* explicit truncate */
temp = pRow[c];
pRow[c] = pRow[cols - 1 - c];
pRow[cols - 1 - c] = temp;
}
}
}
/*
Reverse values in place of each column in 2D matrix data[rows][cols] or in 1D pointer with logical rows/cols
[A B C] -> [D E F]
[D E F] [A B C]
*/
void reverse_cols(matrix_data_t* data, int rows, int cols) {
int r, c;
matrix_data_t temp;
matrix_data_t* pRowA = NULL;
matrix_data_t* pRowB = NULL;
for (c = 0; c < cols; ++c) {
for (r = 0; r < (int)(rows / 2); ++r) { /* explicit truncate */
pRowA = data + r * cols;
pRowB = data + cols * (rows - 1 - r);
temp = pRowA[c];
pRowA[c] = pRowB[c];
pRowB[c] = temp;
}
}
}
/* Transpose NxM matrix to MxN matrix in O(n) time */
void transpose(const matrix_data_t* src, matrix_data_t* dst, int N, int M) {
int i;
for (i = 0; i<N*M; ++i) dst[(i%M)*N + (i / M)] = src[i]; /* one-liner version */
/*
expanded version of one-liner: calculate XY based on array index, then convert that to YX array index
int i,j,x,y;
for (i = 0; i < N*M; ++i) {
x = i % M;
y = (int)(i / M);
j = x * N + y;
dst[j] = src[i];
}
*/
/*
nested for loop version
using ptr arithmetic to get proper row/column
this is really just dst[col][row]=src[row][col]
int r, c;
for (r = 0; r < rows; ++r) {
for (c = 0; c < cols; ++c) {
(dst + c * rows)[r] = (src + r * cols)[c];
}
}
*/
}
/*
Transpose NxN matrix in place
*/
void transpose_inplace(matrix_data_t* data, int N ) {
int r, c;
matrix_data_t temp;
for (r = 0; r < N; ++r) {
for (c = r; c < N; ++c) { /*start at column=row*/
/* using ptr arithmetic to get proper row/column */
/* this is really just
temp=dst[col][row];
dst[col][row]=src[row][col];
src[row][col]=temp;
*/
temp = (data + c * N)[r];
(data + c * N)[r] = (data + r * N)[c];
(data + r * N)[c] = temp;
}
}
}
/*
Rotate 1D or 2D src matrix to dst matrix in a direction (90,180,-90)
Precondition: src and dst are 2d matrices with dimensions src[rows][cols] and dst[cols][rows] or 1D pointers with logical rows/cols
*/
void rotate(int direction, const matrix_data_t* src, matrix_data_t* dst, int rows, int cols) {
switch (direction) {
case -90:
transpose(src, dst, rows, cols);
reverse_cols(dst, cols, rows);
break;
case 90:
transpose(src, dst, rows, cols);
reverse_rows(dst, cols, rows);
break;
case 180:
case -180:
/* bit copy to dst, use in-place reversals */
memcpy(dst, src, rows*cols*sizeof(matrix_data_t));
reverse_cols(dst, cols, rows);
reverse_rows(dst, cols, rows);
break;
}
}
/*
Rotate array in a direction.
Array must be NxN 2D or 1D array with logical rows/cols
Direction can be (90,180,-90,-180)
*/
void rotate_inplace( int direction, matrix_data_t* data, int n) {
switch (direction) {
case -90:
transpose_inplace(data, n);
reverse_cols(data, n, n);
break;
case 90:
transpose_inplace(data, n);
reverse_rows(data, n, n);
break;
case 180:
case -180:
reverse_cols(data, n, n);
reverse_rows(data, n, n);
break;
}
}
`
A: #include <iostream>
#include <iomanip>
using namespace std;
const int SIZE=3;
void print(int a[][SIZE],int);
void rotate(int a[][SIZE],int);
void main()
{
int a[SIZE][SIZE]={{11,22,33},{44,55,66},{77,88,99}};
cout<<"the array befor rotate\n";
print(a,SIZE);
rotate( a,SIZE);
cout<<"the array after rotate\n";
print(a,SIZE);
cout<<endl;
}
void print(int a[][SIZE],int SIZE)
{
int i,j;
for(i=0;i<SIZE;i++)
for(j=0;j<SIZE;j++)
cout<<a[i][j]<<setw(4);
}
void rotate(int a[][SIZE],int SIZE)
{
int temp[3][3],i,j;
for(i=0;i<SIZE;i++)
for(j=0;j<SIZE/2.5;j++)
{
temp[i][j]= a[i][j];
a[i][j]= a[j][SIZE-i-1] ;
a[j][SIZE-i-1] =temp[i][j];
}
}
A: All the current solutions have O(n^2) overhead as scratch space (this excludes those filthy OOP cheaters!). Here's a solution with O(1) memory usage, rotating the matrix in-place 90 degress right. Screw extensibility, this sucker runs fast!
#include <algorithm>
#include <cstddef>
// Rotates an NxN matrix of type T 90 degrees to the right.
template <typename T, size_t N>
void rotate_matrix(T (&matrix)[N][N])
{
for(size_t i = 0; i < N; ++i)
for(size_t j = 0; j <= (N-i); ++j)
std::swap(matrix[i][j], matrix[j][i]);
}
DISCLAIMER: I didn't actually test this. Let's play whack-a-bug!
A: Here is a recursive PHP way:
$m = array();
$m[0] = array('a', 'b', 'c');
$m[1] = array('d', 'e', 'f');
$m[2] = array('g', 'h', 'i');
$newMatrix = array();
function rotateMatrix($m, $i = 0, &$newMatrix)
{
foreach ($m as $chunk) {
$newChunk[] = $chunk[$i];
}
$newMatrix[] = array_reverse($newChunk);
$i++;
if ($i < count($m)) {
rotateMatrix($m, $i, $newMatrix);
}
}
rotateMatrix($m, 0, $newMatrix);
echo '<pre>';
var_dump($newMatrix);
echo '<pre>';
A: My version of rotation:
void rotate_matrix(int *matrix, int size)
{
int result[size*size];
for (int i = 0; i < size; ++i)
for (int j = 0; j < size; ++j)
result[(size - 1 - i) + j*size] = matrix[i*size+j];
for (int i = 0; i < size*size; ++i)
matrix[i] = result[i];
}
In it we change last column to first row and so further. It is may be not optimal but clear for understanding.
A: Here is a Javascript solution:
const transpose = m => m[0].map((x,i) => m.map(x => x[i]));
a: // original matrix
123
456
789
transpose(a).reverse(); // rotate 90 degrees counter clockwise
369
258
147
transpose(a.slice().reverse()); // rotate 90 degrees clockwise
741
852
963
transpose(transpose(a.slice().reverse()).slice().reverse())
// rotate 180 degrees
987
654
321
A: Based on the plethora of other answers, I came up with this in C#:
/// <param name="rotation">The number of rotations (if negative, the <see cref="Matrix{TValue}"/> is rotated counterclockwise;
/// otherwise, it's rotated clockwise). A single (positive) rotation is equivalent to 90° or -270°; a single (negative) rotation is
/// equivalent to -90° or 270°. Matrices may be rotated by 90°, 180°, or 270° only (or multiples thereof).</param>
/// <returns></returns>
public Matrix<TValue> Rotate(int rotation)
{
var result = default(Matrix<TValue>);
//This normalizes the requested rotation (for instance, if 10 is specified, the rotation is actually just +-2 or +-180°, but all
//correspond to the same rotation).
var d = rotation.ToDouble() / 4d;
d = d - (int)d;
var degree = (d - 1d) * 4d;
//This gets the type of rotation to make; there are a total of four unique rotations possible (0°, 90°, 180°, and 270°).
//Each correspond to 0, 1, 2, and 3, respectively (or 0, -1, -2, and -3, if in the other direction). Since
//1 is equivalent to -3 and so forth, we combine both cases into one.
switch (degree)
{
case -3:
case +1:
degree = 3;
break;
case -2:
case +2:
degree = 2;
break;
case -1:
case +3:
degree = 1;
break;
case -4:
case 0:
case +4:
degree = 0;
break;
}
switch (degree)
{
//The rotation is 0, +-180°
case 0:
case 2:
result = new TValue[Rows, Columns];
break;
//The rotation is +-90°
case 1:
case 3:
result = new TValue[Columns, Rows];
break;
}
for (uint i = 0; i < Columns; ++i)
{
for (uint j = 0; j < Rows; ++j)
{
switch (degree)
{
//If rotation is 0°
case 0:
result._values[j][i] = _values[j][i];
break;
//If rotation is -90°
case 1:
//Transpose, then reverse each column OR reverse each row, then transpose
result._values[i][j] = _values[j][Columns - i - 1];
break;
//If rotation is +-180°
case 2:
//Reverse each column, then reverse each row
result._values[(Rows - 1) - j][(Columns - 1) - i] = _values[j][i];
break;
//If rotation is +90°
case 3:
//Transpose, then reverse each row
result._values[i][j] = _values[Rows - j - 1][i];
break;
}
}
}
return result;
}
Where _values corresponds to a private two-dimensional array defined by Matrix<TValue> (in the form of [][]). result = new TValue[Columns, Rows] is possible via implicit operator overload and converts the two-dimensional array to Matrix<TValue>.
The two properties Columns and Rows are public properties that get the number of columns and rows of the current instance:
public uint Columns
=> (uint)_values[0].Length;
public uint Rows
=> (uint)_values.Length;
Assuming, of course, that you prefer to work with unsigned indices ;-)
All of this allows you to specify how many times it should be rotated and whether it should be rotated left (if less than zero) or right (if greater than zero). You can improve this to check for rotation in actual degrees, but then you'd want to throw an exception if the value isn't a multiple of 90. With that input, you could change the method accordingly:
public Matrix<TValue> Rotate(int rotation)
{
var _rotation = (double)rotation / 90d;
if (_rotation - Math.Floor(_rotation) > 0)
{
throw new NotSupportedException("A matrix may only be rotated by multiples of 90.").
}
rotation = (int)_rotation;
...
}
Since a degree is more accurately expressed by double than int, but a matrix can only rotate in multiples of 90, it is far more intuitive to make the argument correspond to something else that can be accurately represented by the data structure used. int is perfect because it can tell you how many times to rotate it up to a certain unit (90) as well as the direction. double may very well be able to tell you that also, but it also includes values that aren't supported by this operation (which is inherently counter-intuitive).
A: Based on the community wiki algorithm and this SO answer for transposing arrays, here is a Swift 4 version to rotate some 2D array 90 degrees counter-clockwise. This assumes matrix is a 2D array:
func rotate(matrix: [[Int]]) -> [[Int]] {
let transposedPoints = transpose(input: matrix)
let rotatedPoints = transposedPoints.map{ Array($0.reversed()) }
return rotatedPoints
}
fileprivate func transpose<T>(input: [[T]]) -> [[T]] {
if input.isEmpty { return [[T]]() }
let count = input[0].count
var out = [[T]](repeating: [T](), count: count)
for outer in input {
for (index, inner) in outer.enumerated() {
out[index].append(inner)
}
}
return out
}
A: This solution doesn't care square or rectangle dimension, you can rotate 4x5 or 5x4 or even 4x4, it doesn't care the size as well.
Note that this implementation creates a new array every time you call rotate90 method, it doesn't mutate the original array at all.
public static void main(String[] args) {
int[][] a = new int[][] {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 0, 1, 2 },
{ 3, 4, 5, 6 },
{ 7, 8, 9, 0 }
};
int[][] rotate180 = rotate90(rotate90(a));
print(rotate180);
}
static int[][] rotate90(int[][] a) {
int[][] ret = new int[a[0].length][a.length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
ret[j][a.length - i - 1] = a[i][j];
}
}
return ret;
}
static void print(int[][] array) {
for (int i = 0; i < array.length; i++) {
System.out.print("[");
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
System.out.print(" ");
}
System.out.println("]");
}
}
A: I was able to do this with a single loop. The time complexity seems like O(K) where K is all items of the array.
Here's how I did it in JavaScript:
First off, we represent the n^2 matrix with a single array. Then, iterate through it like this:
/**
* Rotates matrix 90 degrees clockwise
* @param arr: the source array
* @param n: the array side (array is square n^2)
*/
function rotate (arr, n) {
var rotated = [], indexes = []
for (var i = 0; i < arr.length; i++) {
if (i < n)
indexes[i] = i * n + (n - 1)
else
indexes[i] = indexes[i - n] - 1
rotated[indexes[i]] = arr[i]
}
return rotated
}
Basically, we transform the source array indexes:
[0,1,2,3,4,5,6,7,8] => [2,5,8,1,4,7,0,3,6]
Then, using this transformed indexes array, we place the actual values in the final rotated array.
Here are some test cases:
//n=3
rotate([
1, 2, 3,
4, 5, 6,
7, 8, 9], 3))
//result:
[7, 4, 1,
8, 5, 2,
9, 6, 3]
//n=4
rotate([
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16], 4))
//result:
[13, 9, 5, 1,
14, 10, 6, 2,
15, 11, 7, 3,
16, 12, 8, 4]
//n=5
rotate([
1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15,
16, 17, 18, 19, 20,
21, 22, 23, 24, 25], 5))
//result:
[21, 16, 11, 6, 1,
22, 17, 12, 7, 2,
23, 18, 13, 8, 3,
24, 19, 14, 9, 4,
25, 20, 15, 10, 5]
A: In Eigen (C++):
Eigen::Matrix2d mat;
mat << 1, 2,
3, 4;
std::cout << mat << "\n\n";
Eigen::Matrix2d r_plus_90 = mat.transpose().rowwise().reverse();
std::cout << r_plus_90 << "\n\n";
Eigen::Matrix2d r_minus_90 = mat.transpose().colwise().reverse();
std::cout << r_minus_90 << "\n\n";
Eigen::Matrix2d r_180 = mat.colwise().reverse().rowwise().reverse(); // +180 same as -180
std::cout << r_180 << "\n\n";
Output:
1 2
3 4
3 1
4 2
2 4
1 3
4 3
2 1
A: The O(1) memory algorithm:
*
*rotate the outer-most data, then you can get below result:
[3][9][5][1]
[4][6][7][2]
[5][0][1][3]
[6][2][8][4]
To do this rotation, we know
dest[j][n-1-i] = src[i][j]
Observe below:
a(0,0) -> a(0,3)
a(0,3) -> a(3,3)
a(3,3) -> a(3,0)
a(3,0) -> a(0,0)
Therefore it's a circle, you can rotate N elements in one loop. Do this N-1 loop then you can rotate the outer-most elements.
*
*Now you can the inner is a same question for 2X2.
Therefore we can conclude it like below:
function rotate(array, N)
{
Rotate outer-most data
rotate a new array with N-2 or you can do the similar action following step1
}
A: Try My library abacus-common:
@Test
public void test_42519() throws Exception {
final IntMatrix matrix = IntMatrix.range(0, 16).reshape(4);
N.println("======= original =======================");
matrix.println();
// print out:
// [0, 1, 2, 3]
// [4, 5, 6, 7]
// [8, 9, 10, 11]
// [12, 13, 14, 15]
N.println("======= rotate 90 ======================");
matrix.rotate90().println();
// print out:
// [12, 8, 4, 0]
// [13, 9, 5, 1]
// [14, 10, 6, 2]
// [15, 11, 7, 3]
N.println("======= rotate 180 =====================");
matrix.rotate180().println();
// print out:
// [15, 14, 13, 12]
// [11, 10, 9, 8]
// [7, 6, 5, 4]
// [3, 2, 1, 0]
N.println("======= rotate 270 ======================");
matrix.rotate270().println();
// print out:
// [3, 7, 11, 15]
// [2, 6, 10, 14]
// [1, 5, 9, 13]
// [0, 4, 8, 12]
N.println("======= transpose =======================");
matrix.transpose().println();
// print out:
// [0, 4, 8, 12]
// [1, 5, 9, 13]
// [2, 6, 10, 14]
// [3, 7, 11, 15]
final IntMatrix bigMatrix = IntMatrix.range(0, 10000_0000).reshape(10000);
// It take about 2 seconds to rotate 10000 X 10000 matrix.
Profiler.run(1, 2, 3, "sequential", () -> bigMatrix.rotate90()).printResult();
// Want faster? Go parallel. 1 second to rotate 10000 X 10000 matrix.
final int[][] a = bigMatrix.array();
final int[][] c = new int[a[0].length][a.length];
final int n = a.length;
final int threadNum = 4;
Profiler.run(1, 2, 3, "parallel", () -> {
IntStream.range(0, n).parallel(threadNum).forEach(i -> {
for (int j = 0; j < n; j++) {
c[i][j] = a[n - j - 1][i];
}
});
}).printResult();
}
A: It is not possible to do it quicker than O(n^2) for in place rotation, for the reason that if we want to rotate the matrix, we have to touch all the n^2 element at least once, no matter what algorithm you are implementing.
A: For Novice programmers, in plain C++ . (Borland stuff)
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
int arr[10][10]; // 2d array that holds input elements
int result[10][10]; //holds result
int m,n; //rows and columns of arr[][]
int x,y; //rows and columns of result[][]
int i,j; //loop variables
int t; //temporary , holds data while conversion
cout<<"Enter no. of rows and columns of array: ";
cin>>m>>n;
cout<<"\nEnter elements of array: \n\n";
for(i = 0; i < m; i++)
{
for(j = 0; j<n ; j++)
{
cin>>arr[i][j]; // input array elements from user
}
}
//rotating matrix by +90 degrees
x = n ; //for non-square matrix
y = m ;
for(i = 0; i < x; i++)
{ t = m-1; // to create required array bounds
for(j = 0; j < y; j++)
{
result[i][j] = arr[t][i];
t--;
}
}
//print result
cout<<"\nRotated matrix is: \n\n";
for(i = 0; i < x; i++)
{
for(j = 0; j < y; j++)
{
cout<<result[i][j]<<" ";
}
cout<<"\n";
}
getch();
return 0;
}
A: #!/usr/bin/env python
original = [ [1,2,3],
[4,5,6],
[7,8,9] ]
# Rotate matrix 90 degrees...
for i in map(None,*original[::-1]):
print str(i) + '\n'
This causes the sides to be rotated 90 degrees (ie. 123 (top side) is now 741 (left side).
This Python solution works because it uses slicing with a negative step to reverse the row orders (bringing 7 to top)
original = [ [7,8,9],
[4,5,6],
[1,2,3] ]
It then uses map (along with the implied identity function which is the result of map with None as first arg) along with * to unpack all elements in sequence, to regroup the columns (ie. the first elements are put in a tuple together, the 2nd elements are put in a tuple together, and so forth). You effectively get get returned the following regrouping:
original = [[7,8,9],
[4,5,6],
[1,2,3]]
A: PHP:
array_unshift($array, null);
$array = call_user_func_array("array_map", $array);
If you need to rotate rectangular two-dimension array on 90 degree, add the following line before or after (depending on the rotation direction you need) the code above:
$array = array_reverse($array);
A: JavaScript solution to rotate matrix by 90 degrees in place:
function rotateBy90(m) {
var length = m.length;
//for each layer of the matrix
for (var first = 0; first < length >> 1; first++) {
var last = length - 1 - first;
for (var i = first; i < last; i++) {
var top = m[first][i]; //store top
m[first][i] = m[last - i][first]; //top = left
m[last - i][first] = m[last][last - i]; //left = bottom
m[last][last - i] = m[i][last]; //bottom = right
m[i][last] = top; //right = top
}
}
return m;
}
A: /* 90-degree clockwise:
temp_array = left_col
left_col = bottom_row
bottom_row = reverse(right_col)
reverse(right_col) = reverse(top_row)
reverse(top_row) = temp_array
*/
void RotateClockwise90(int ** arr, int lo, int hi) {
if (lo >= hi)
return;
for (int i=lo; i<hi; i++) {
int j = lo+hi-i;
int temp = arr[i][lo];
arr[i][lo] = arr[hi][i];
arr[hi][i] = arr[j][hi];
arr[j][hi] = arr[lo][j];
arr[lo][j] = temp;
}
RotateClockwise90(arr, lo+1, hi-1);
}
A: In place clock wise 90 degrees rotation using vector of vectors..
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
//Rotate a Matrix by 90 degrees
void rotateMatrix(vector<vector<int> > &matrix){
int n=matrix.size();
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
swap(matrix[i][j],matrix[j][i]);
}
}
for(int i=0;i<n;i++){
reverse(matrix[i].begin(),matrix[i].end());
}
}
int main(){
int n;
cout<<"enter the size of the matrix:"<<endl;
while (cin >> n) {
vector< vector<int> > m;
cout<<"enter the elements"<<endl;
for (int i = 0; i < n; i++) {
m.push_back(vector<int>(n));
for (int j = 0; j < n; j++)
scanf("%d", &m[i][j]);
}
cout<<"the rotated matrix is:"<<endl;
rotateMatrix(m);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << m[i][j] << ' ';
cout << endl;
}
}
return 0;
}
A: This is an overrated interview question these days.
My suggestion is: Do not let the interviewer confuse you with their crazy suggestion about solving this problem. Use the whiteboard to draw the indexing of input array then draw the indexing of output array. Samples of column indexing before and after rotation shown below:
30 --> 00
20 --> 01
10 --> 02
00 --> 03
31 --> 10
21 --> 11
11 --> 12
01 --> 13
Notice the number pattern after rotation.
Provided below a clean cut Java solution. It is tested, and it works:
Input:
M A C P
B N L D
Y E T S
I W R Z
Output:
I Y B M
W E N A
R T L C
Z S D P
/**
* (c) @author "G A N MOHIM"
* Oct 3, 2015
* RotateArrayNintyDegree.java
*/
package rotatearray;
public class RotateArrayNintyDegree {
public char[][] rotateArrayNinetyDegree(char[][] input) {
int k; // k is used to generate index for output array
char[][] output = new char[input.length] [input[0].length];
for (int i = 0; i < input.length; i++) {
k = 0;
for (int j = input.length-1; j >= 0; j--) {
output[i][k] = input[j][i]; // note how i is used as column index, and j as row
k++;
}
}
return output;
}
public void printArray(char[][] charArray) {
for (int i = 0; i < charArray.length; i++) {
for (int j = 0; j < charArray[0].length; j++) {
System.out.print(charArray[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
char[][] input =
{ {'M', 'A', 'C', 'P'},
{'B', 'N', 'L', 'D'},
{'Y', 'E', 'T', 'S'},
{'I', 'W', 'R', 'Z'}
};
char[][] output = new char[input.length] [input[0].length];
RotateArrayNintyDegree rotationObj = new RotateArrayNintyDegree();
rotationObj.printArray(input);
System.out.println("\n");
output = rotationObj.rotateArrayNinetyDegree(input);
rotationObj.printArray(output);
}
}
A: Here it is in Java:
public static void rotateInPlace(int[][] m) {
for(int layer = 0; layer < m.length/2; layer++){
int first = layer;
int last = m.length - 1 - first;
for(int i = first; i < last; i ++){
int offset = i - first;
int top = m[first][i];
m[first][i] = m[last - offset][first];
m[last - offset][first] = m[last][last - offset];
m[last][last - offset] = m[i][last];
m[i][last] = top;
}
}
}
A: This is simple C code to rotate an array 90degrees. Hope this helps.
#include <stdio.h>
void main(){
int arr[3][4] = {85, 2, 85, 4,
85, 6, 7, 85,
9, 85, 11, 12};
int arr1[4][3];
int i = 0, j = 0;
for(i=0;i<4;i++){
int k = 2;//k = (number of columns in the new array arr1 - 1)
for(j=0;j<3;j++){
arr1[i][j]=arr[k][i];
k--;
}
}
int l, m;
for(l=0;l<4;l++){
for(m=0;m<3;m++){
printf("%d ", arr1[l][m]);
}
printf("\n");
}
}//end main
A: My C# example code for the great Algorithm sent by @dimple:
/* Author: Dudi,
* http://www.tutorialspoint.com/compile_csharp_online.php?PID=0Bw_CjBb95KQMYm5qU3VjVGNuZFU */
using System.IO;
using System;
class Program
{
static void Main()
{
Console.WriteLine("Rotating this matrix by 90+ degree:");
int[,] values=new int[3,3]{{1,2,3}, {4,5,6}, {7,8,9}};
//int[,] values=new int[4,4]{{101,102,103, 104}, {105,106, 107,108}, {109, 110, 111, 112}, {113, 114, 115, 116}};
print2dArray(ref values);
transpose2dArray(ref values);
//print2dArray(ref values);
reverse2dArray(ref values);
Console.WriteLine("Output:");
print2dArray(ref values);
}
static void print2dArray(ref int[,] matrix){
int nLen = matrix.GetLength(0);
int mLen = matrix.GetLength(1);
for(int n=0; n<nLen; n++){
for(int m=0; m<mLen; m++){
Console.Write(matrix[n,m] +"\t");
}
Console.WriteLine();
}
Console.WriteLine();
}
static void transpose2dArray(ref int[,] matrix){
int nLen = matrix.GetLength(0);
int mLen = matrix.GetLength(1);
for(int n=0; n<nLen; n++){
for(int m=0; m<mLen; m++){
if(n>m){
int tmp = matrix[n,m];
matrix[n,m] = matrix[m,n];
matrix[m,n] = tmp;
}
}
}
}
static void reverse2dArray(ref int[,] matrix){
int nLen = matrix.GetLength(0);
int mLen = matrix.GetLength(1);
for(int n=0; n<nLen; n++){
for(int m=0; m<mLen/2; m++){
int tmp = matrix[n,m];
matrix[n,m] = matrix[n, mLen-1-m];
matrix[n,mLen-1-m] = tmp;
}
}
}
}
/*
Rotating this matrix by 90+ degree:
1 2 3
4 5 6
7 8 9
Output:
7 4 1
8 5 2
9 6 3
*/
A: Here is a C# static generic method that does the work for you. Variables are well-named, so you can easily catch the idea of the algorythm.
private static T[,] Rotate180 <T> (T[,] matrix)
{
var height = matrix.GetLength (0);
var width = matrix.GetLength (1);
var answer = new T[height, width];
for (int y = 0; y < height / 2; y++)
{
int topY = y;
int bottomY = height - 1 - y;
for (int topX = 0; topX < width; topX++)
{
var bottomX = width - topX - 1;
answer[topY, topX] = matrix[bottomY, bottomX];
answer[bottomY, bottomX] = matrix[topY, topX];
}
}
if (height % 2 == 0)
return answer;
var centerY = height / 2;
for (int leftX = 0; leftX < Mathf.CeilToInt(width / 2f); leftX++)
{
var rightX = width - 1 - leftX;
answer[centerY, leftX] = matrix[centerY, rightX];
answer[centerY, rightX] = matrix[centerY, leftX];
}
return answer;
}
A: public static void rotateMatrix(int[,] matrix)
{
//C#, to rotate an N*N matrix in place
int n = matrix.GetLength(0);
int layers = n / 2;
int temp, temp2;
for (int i = 0; i < layers; i++) // for a 5 * 5 matrix, layers will be 2, since at layer three there would be only one element, (2,2), and we do not need to rotate it with itself
{
int offset = 0;
while (offset < n - 2 * i - 1)
{
// top right <- top left
temp = matrix[i + offset, n - i - 1]; //top right value when offset is zero
matrix[i + offset, n - i - 1] = matrix[i, i + offset];
//bottom right <- top right
temp2 = matrix[n - i - 1, n - i - 1 - offset]; //bottom right value when offset is zero
matrix[n - i - 1, n - i - 1 - offset] = temp;
//bottom left <- bottom right
temp = matrix[n - i - 1 - offset, i];
matrix[n - i - 1 - offset, i] = temp2;
//top left <- bottom left
matrix[i, i + offset] = temp;
offset++;
}
}
}
A: Can be done recursively quite cleanly, here is my implementation in golang!
rotate nxn matrix in go golang recursively in place with no additional memory
func rot90(a [][]int) {
n := len(a)
if n == 1 {
return
}
for i := 0; i < n; i++ {
a[0][i], a[n-1-i][n-1] = a[n-1-i][n-1], a[0][i]
}
rot90(a[1:])
}
A: In Java
public class Matrix {
/* Author Shrikant Dande */
private static void showMatrix(int[][] arr,int rows,int col){
for(int i =0 ;i<rows;i++){
for(int j =0 ;j<col;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
private static void rotateMatrix(int[][] arr,int rows,int col){
int[][] tempArr = new int[4][4];
for(int i =0 ;i<rows;i++){
for(int j =0 ;j<col;j++){
tempArr[i][j] = arr[rows-1-j][i];
System.out.print(tempArr[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] arr = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 1, 2, 5},
{7, 4, 8, 9}};
int rows = 4,col = 4;
showMatrix(arr, rows, col);
System.out.println("------------------------------------------------");
rotateMatrix(arr, rows, col);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "355"
} |
Q: How do I call ::CreateProcess in c++ to launch a Windows executable? Looking for an example that:
*
*Launches an EXE
*Waits for the EXE to finish.
*Properly closes all the handles when the executable finishes.
A: Something like this:
STARTUPINFO info={sizeof(info)};
PROCESS_INFORMATION processInfo;
if (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
WaitForSingleObject(processInfo.hProcess, INFINITE);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}
A: if your exe happens to be a console app, you might be interested in reading the stdout and stderr -- for that, I'll humbly refer you to this example:
http://support.microsoft.com/default.aspx?scid=kb;EN-US;q190351
It's a bit of a mouthful of code, but I've used variations of this code to spawn and read.
A: On a semi-related note, if you want to start a process that has more privileges than your current process (say, launching an admin app, which requires Administrator rights, from the main app running as a normal user), you can't do so using CreateProcess() on Vista since it won't trigger the UAC dialog (assuming it is enabled). The UAC dialog is triggered when using ShellExecute(), though.
A: Here is a new example that works on windows 10. When using the windows10 sdk you have to use CreateProcessW instead. This example is commented and hopefully self explanatory.
#ifdef _WIN32
#include <Windows.h>
#include <iostream>
#include <stdio.h>
#include <tchar.h>
#include <cstdlib>
#include <string>
#include <algorithm>
class process
{
public:
static PROCESS_INFORMATION launchProcess(std::string app, std::string arg)
{
// Prepare handles.
STARTUPINFO si;
PROCESS_INFORMATION pi; // The function returns this
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
//Prepare CreateProcess args
std::wstring app_w(app.length(), L' '); // Make room for characters
std::copy(app.begin(), app.end(), app_w.begin()); // Copy string to wstring.
std::wstring arg_w(arg.length(), L' '); // Make room for characters
std::copy(arg.begin(), arg.end(), arg_w.begin()); // Copy string to wstring.
std::wstring input = app_w + L" " + arg_w;
wchar_t* arg_concat = const_cast<wchar_t*>( input.c_str() );
const wchar_t* app_const = app_w.c_str();
// Start the child process.
if( !CreateProcessW(
app_const, // app path
arg_concat, // Command line (needs to include app path as first argument. args seperated by whitepace)
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ) // Pointer to PROCESS_INFORMATION structure
)
{
printf( "CreateProcess failed (%d).\n", GetLastError() );
throw std::exception("Could not create child process");
}
else
{
std::cout << "[ ] Successfully launched child process" << std::endl;
}
// Return process handle
return pi;
}
static bool checkIfProcessIsActive(PROCESS_INFORMATION pi)
{
// Check if handle is closed
if ( pi.hProcess == NULL )
{
printf( "Process handle is closed or invalid (%d).\n", GetLastError());
return FALSE;
}
// If handle open, check if process is active
DWORD lpExitCode = 0;
if( GetExitCodeProcess(pi.hProcess, &lpExitCode) == 0)
{
printf( "Cannot return exit code (%d).\n", GetLastError() );
throw std::exception("Cannot return exit code");
}
else
{
if (lpExitCode == STILL_ACTIVE)
{
return TRUE;
}
else
{
return FALSE;
}
}
}
static bool stopProcess( PROCESS_INFORMATION &pi)
{
// Check if handle is invalid or has allready been closed
if ( pi.hProcess == NULL )
{
printf( "Process handle invalid. Possibly allready been closed (%d).\n");
return 0;
}
// Terminate Process
if( !TerminateProcess(pi.hProcess,1))
{
printf( "ExitProcess failed (%d).\n", GetLastError() );
return 0;
}
// Wait until child process exits.
if( WaitForSingleObject( pi.hProcess, INFINITE ) == WAIT_FAILED)
{
printf( "Wait for exit process failed(%d).\n", GetLastError() );
return 0;
}
// Close process and thread handles.
if( !CloseHandle( pi.hProcess ))
{
printf( "Cannot close process handle(%d).\n", GetLastError() );
return 0;
}
else
{
pi.hProcess = NULL;
}
if( !CloseHandle( pi.hThread ))
{
printf( "Cannot close thread handle (%d).\n", GetLastError() );
return 0;
}
else
{
pi.hProcess = NULL;
}
return 1;
}
};//class process
#endif //win32
A: Perhaps this is the most complete?
http://goffconcepts.com/techarticles/createprocess.html
A: Bear in mind that using WaitForSingleObject can get you into trouble in this scenario. The following is snipped from a tip on my website:
The problem arises because your application has a window but isn't pumping messages. If the spawned application invokes SendMessage with one of the broadcast targets (HWND_BROADCAST or HWND_TOPMOST), then the SendMessage won't return to the new application until all applications have handled the message - but your app can't handle the message because it isn't pumping messages.... so the new app locks up, so your wait never succeeds.... DEADLOCK.
If you have absolute control over the spawned application, then there are measures you can take, such as using SendMessageTimeout rather than SendMessage (e.g. for DDE initiations, if anybody is still using that). But there are situations which cause implicit SendMessage broadcasts over which you have no control, such as using the SetSysColors API for instance.
The only safe ways round this are:
*
*split off the Wait into a separate thread, or
*use a timeout on the Wait and use PeekMessage in your Wait loop to ensure that you pump messages, or
*use the MsgWaitForMultipleObjects API.
A: There is an example at http://msdn.microsoft.com/en-us/library/ms682512(VS.85).aspx
Just replace the argv[1] with your constant or variable containing the program.
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
void _tmain( int argc, TCHAR *argv[] )
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if( argc != 2 )
{
printf("Usage: %s [cmdline]\n", argv[0]);
return;
}
// Start the child process.
if( !CreateProcess( NULL, // No module name (use command line)
argv[1], // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ) // Pointer to PROCESS_INFORMATION structure
)
{
printf( "CreateProcess failed (%d).\n", GetLastError() );
return;
}
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
A: If you application is a Windows GUI application then using the code below to do the waiting is not ideal as messages for your application will not be getting processing. To the user it will look like your application has hung.
WaitForSingleObject(&processInfo.hProcess, INFINITE)
Something like the untested code below might be better as it will keep processing the windows message queue and your application will remain responsive:
//-- wait for the process to finish
while (true)
{
//-- see if the task has terminated
DWORD dwExitCode = WaitForSingleObject(ProcessInfo.hProcess, 0);
if ( (dwExitCode == WAIT_FAILED )
|| (dwExitCode == WAIT_OBJECT_0 )
|| (dwExitCode == WAIT_ABANDONED) )
{
DWORD dwExitCode;
//-- get the process exit code
GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode);
//-- the task has ended so close the handle
CloseHandle(ProcessInfo.hThread);
CloseHandle(ProcessInfo.hProcess);
//-- save the exit code
lExitCode = dwExitCode;
return;
}
else
{
//-- see if there are any message that need to be processed
while (PeekMessage(&message.msg, 0, 0, 0, PM_NOREMOVE))
{
if (message.msg.message == WM_QUIT)
{
return;
}
//-- process the message queue
if (GetMessage(&message.msg, 0, 0, 0))
{
//-- process the message
TranslateMessage(&pMessage->msg);
DispatchMessage(&pMessage->msg);
}
}
}
}
A: Here is a solution for CreateProcessA
STARTUPINFOW initInfo = { 0 };
initInfo.cb = sizeof(initInfo);
PROCESS_INFORMATION procInfo = { 0 };
CreateProcessA(PATH_FOR_EXE, NULL, NULL, NULL, FALSE, 0, NULL, NULL, (LPSTARTUPINFOA)&initInfo, &procInfo);
A: #include <Windows.h>
void my_cmd()
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
// CMD command here
char arg[] = "cmd.exe /c E:/Softwares/program.exe";
// Convert char string to required LPWSTR string
wchar_t text[500];
mbstowcs(text, arg, strlen(arg) + 1);
LPWSTR command = text;
// Run process
CreateProcess (NULL, command, NULL, NULL, 0,
CREATE_NO_WINDOW, NULL, NULL, &si, &pi);
}
This works fine for me. No popup windows and cmd command runs as expected. Just needed to convert the CHAR pointer into WCHAR pointer and add extra "cmd.exe /c" before every command.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "60"
} |
Q: How can I draw a curve that varies in thickness along its path? I'm capturing data from a tablet using Java (JPen library rocks) and would like to be able to paint a penstroke in a more natural way.
Currently I'm drawing the pen stroke as straight line segments each with a different Stroke thickness.
There has to be something in Java's Graphics Library that lets me to this more efficiently.
Right?
A: I've never done this, but here are a couple things you could try. First, you could implement a custom Stroke that creates skinny trapezoids. The width of the end caps would be a function of the pressure at the end points. If that works, you could try to make the line segments look more natural by using Bezier curves to form "curvy trapezoids". You might be able to use QuadCurve2D to help.
A: There's a more general solution available at least. The feature was added to Inkscape based on a recent algorithm. You can see it applied directly to your problem in some screenshots. It can extrude any shape brush along the path to mimic a paintbrush for example, but you'd have to port it to Java from the algorithm in the first link or from the Inkscape sources. Also, it's covered by patents so you'd have to release your code under the GPL (the author gives explicit permission) or buy a patent license.
A: PostScript RIPs often convert circles to curves and curves to a series of straight line segments. The number of segments depends on the flatness setting which defaults to one suitable for the raster display resolution.
A thick line or thick line segments can be converted to a skinny filled polygon.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Extract Address Information from a Web Page I need to take a web page and extract the address information from the page. Some are easier than others. I'm looking for a firefox plugin, windows app, or VB.NET code that will help me get this done.
Ideally I would like to have a web page on our admin (ASP.NET/VB.NET) where you enter a URL and it scraps the page and returns a Dataset that I can put in a Grid.
A: What type of address information are you referring to?
There are a couple FireFox plugins Operator & Tails that allow you to extract and view microformats from web pages.
A: Aza Raskin has talked about recognising when selected text is an address in his Firefox Proposal: A Better New Tab Screen. No code yet, but I mention it as there may be code in firefox to do this in the future.
Alternatively, you could look at using the map command in Ubiquity, although you'd have to select the addresses yourself.
A: If you know the format of the page (for instance, if they're all like that ashnha.com page) then it's fairly easy to write VB.NET code that does this:
*
*Create a System.Net.WebRequest and read the response into a string.
*Then create a
System.Text.RegularExpressions.Regex
and iterate over the collection of
Matches between that and the string
you just retrieved. For each match,
create a new row in a DataTable.
The tough bit is writing the regex, which is a bit of a black art. See regexlib.com for loads of tools, books etc about regexes.
If the HTML format isn't well-defined enough for a regex, then you're probably going to have to rely on some amount of user intervention in order to identify which bits are the addresses...
A: For general HTML screen scraping in VB.NET, check out HTML Agility Pack. Much easier than trying to Regex it (unless you happen to be a Regex ninja already!)
The page you mentioned in your answer would be easy to automate, as the addresses are in a consistent format.
But to allow the users to point to any page, that's a much harder job. The data could be in any format at all. You could write something to dump all the text, guess how they are divided, try and recognise bits like country and state names, telephone numbers etc, and get then show your results with an interface that will let the users complete missing sections, move the dividers, and identify the bits you missed or they didn't want.
It's not simple though, and making an interface that provides a big advantage over simply cutting and pasting into validated form fields would be quite an achievement I think - I'd be interested to know how you get on!
EDIT: Just noticed this other question that might cover quite a bit of what you want to do:
Parse usable Street Address, City, State, Zip from a string
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Can't get my event to fire When loading a page for the first time (!IsPostback), I am creating a button in code and adding it to my page, then adding an event handler to the click event.
However, when clicking the button, after the page reloads, my event handler does not fire.
Can anyone explain why?
A: @Brad: Your answer isn't complete; he's most likely doing it too late in the page lifecycle, during the Page_Load event.
Okay, here's what you're missing.
ASP.NET is stateless. That means, after your page is rendered and sent to the browser, the page object and everything on it is destroyed. There is no link that remains on the server between that page and what is on the user's browser.
When the user clicks a button, that event is sent back to the server, along with other information, like the hidden viewstate field.
On the server side, ASP.NET determines what page handles the request, and rebuilds the page from scratch. New instances of server controls are created and linked together according to the .aspx page. Once it is reassembled, the postback data is evaluated. The viewstate is used to populate controls, and events are fired.
This all happens in a specific order, called the Page Lifecycle. In order to do more complex things in ASP.NET, such as creating dynamic controls and adding them to the web page at runtime, you MUST understand the page lifecycle.
With your issue, you must create that button every single time that page loads. In addition, you must create that button BEFORE events are fired on the page. Control events fire between Page_Load and Page_LoadComplete.
You want your controls loaded before ViewState information is parsed and added to controls, and before control events fire, so you need to handle the PreInit event and add your button at that point. Again, you must do this EVERY TIME the page is loaded.
One last note; page event handling is a bit odd in ASP.NET because the events are autowired up. Note the Load event handler is called Page_Load...
A: You need to add the button always not just for non-postbacks.
A: If you are not reattaching the event handler on every postback, then the event will not exist for the button. You need top make sure the event handler is attached every time the page is refreshed. So, here is the order of events for your page:
*
*Page is created with button and event handler is attached
*Button is clicked, causing a postback
*On postback, the page_load event skips the attaching of the event handler becaue of your !IsPostback statement
*At this point, there is no event handler for the button, so clicking it will not fire your event
A: That is because the event binding that happens needs to be translated in to HTML. This postback that happens if bound to the page between OnInit and OnLoad. So if you want the button to bind events correclty make sure you do the work in OnInit.
See the Page Life Cycle explaination.
http://msdn.microsoft.com/en-us/library/ms178472.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Best way to incorporate spell checkers with a build process I try to externalize all strings (and other constants) used in any application I write, for many reasons that are probably second-nature to most stack-overflowers, but one thing I would like to have is the ability to automate spell checking of any user-visible strings. This poses a couple problems:
*
*Not all strings are user-visible, and it's non-trivial to spearate them, and keep that separation in place (but it is possible)
*Most, if not all, string externalization methods I've used involve significant text that will not pass a spell checker such as aspell/ispell (eg: theStrName="some string." and comments)
*Many spellcheckers (once again, aspell/ispell) don't handle many words out of the box (generally technical terms, proper nouns, or just 'new' terminology, like metadata).
How do you incorporate something like this into your build procedures/test suites? It is not feasible to have someone manually spell check all the strings in an application each time they are changed -- and there is no chance that they will all be spelled correctly the first time.
A: We do it manually, if errors aren't picked up during testing then they're picked up by the QA team, or during localization by the translators, or during localization QA. Then we lodge a bug.
Most of our developers are not native English speakers, so it's not an uncommon problem for us. The number that slip through the cracks is so small that this is a satisfactory solution for us.
Nothing over a few hundred lines is ever 100% bug-free (well... maybe the odd piece of embedded code), just think of spelling mistakes as bugs and don't waste too much time on it.
As soon as your application matures, over 90% of strings won't change between releases and it would be a reasonably trivial exercise to compare two versions of your resources, figure out what'ts new (check them first), what's changed/updated (check next) and what hasn't changed (no need to check these)
So think of it more like I need to check ALL of these manually the first time, and I'm only going to have to check 10% of them next time. Now ask yourself if you still really need to automate spell checking.
A: I can think of two ways to approach this semi-automatically:
Have the compiler help you differentiate between strings used in the UI and strings used elsewhere. Overload different variants of the string datatype depending on it's purpose, and overload the output methods to only accept that type - that way you can create a fake UI that just outputs the UI strings, and do the spell checking on that.
If this is doable of course depends on the platform and the overall architecture of the application.
Another approach could be to simply update the spell checkers database with all the strings that appear in the code - comments, xpaths, table names, you name it - and regard them as perfectly cromulent. This will of course reduce the precision of the spell checking.
A: First thing, regarding string externalization - GNU GetText (if used properly) creates string files that are contain almost no text other then the actual content of the strings (there are some headers but its easy to cause a spell checker to ignore them).
Second thing, what I would do is to run the spell checker in a continuous integration environment and have the errors fed externally, probably through a web interface but email will also work. Developers can then review the errors and either fix them in the code or use some easy interface to let the spell check know that a misspelling should be ignored (a web interface can integrate both the error view and the spell checker interface).
A: If you're using java and are storing your localized strings in resource bundles then you could check the Bundle.properties files and validate the bundle strings. You could also add a special comment annotation that your processor could use to determine if an entry should be skipped.
This method will allow you to give a hint as to the locale and provide a way of checking multiple languages within the one build process.
I can't answer how you would perform the actual spell checking itself, though I think what I've presented will guid you as for the method of performing the spell checking.
A: Use aspell. It's a programme, it's available for unixoids and cygwin, it can be run over lots of kinds of source code. Use it.
A: First point, please don't put it into you build process. I would be a vengeful coder if I (meaning my computer) had to spell check all the content on the site every time I tried to debug or build a new feature. I don't even think this kind of operation belongs as a unit test (you're testing a human interface, not a computerised one).
Second point, don't write a script. You're going to have so many false positives fall through the cracks that people will stop reading the reports and you are no better off than when you started.
Third point, this is probably most easily solved by having humans do it: QA team, copy writers, beta testers, translators, etc. All the big sites with internationalised content that I've built had the same process: we took the copy from the copy writers, sent it to the translating service/agency, put it into the persistence layer, and deployed it. Testers (QA, developers, PMs, designers, etc.) would find spelling or grammatical mistakes and lodge bug reports. There is just too much red tape and pairs of eyes for that many spelling/grammar errors to slip through.
Fourth point, there will always be spelling and grammar mistakes on your page. Even major newspaper web sites haven't gotten around this and they have whole office buildings filled with editors.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Python and the Singleton Pattern What is the best way to implement the singleton pattern in Python? It seems impossible to declare the constructor private or protected as is normally done with the Singleton pattern...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "92"
} |
Q: Getting the Hostname or IP in Ruby on Rails I'm in the process of maintaining a Ruby on Rails app and am looking for an easy way to find the hostname or IP address of the box I'm on (since it's a VM and new instances may have different hostnames or IP addresses). Is there a quick and easy way to do this in Ruby on Rails?
Edit: The answer below is correct but the clarification Craig provided is useful (see also provided link in answer):
The [below] code does NOT make a
connection or send any packets (to
64.233.187.99 which is google). Since UDP is a stateless protocol connect()
merely makes a system call which
figures out how to route the packets
based on the address and what
interface (and therefore IP address)
it should bind to. addr() returns an
array containing the family (AF_INET),
local port, and local address (which
is what we want) of the socket.
A: This IP address used here is Google's, but you can use any accessible IP.
require "socket"
local_ip = UDPSocket.open {|s| s.connect("64.233.187.99", 1); s.addr.last}
A: From coderrr.wordpress.com:
require 'socket'
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
# irb:0> local_ip
# => "192.168.0.127"
A: Similar to the answer using hostname, using the external uname command on UNIX/LINUX:
hostname = `uname -n`.chomp.sub(/\..*/,'') # stripping off "\n" and the network name if present
for the IP addresses in use (your machine could have multiple network interfaces),
you could use something like this:
# on a Mac:
ip_addresses = `ifconfig | grep 'inet ' | grep -v 127.0.0.1 | cut -d' ' -f 2`.split
=> ['10.2.21.122','10.8.122.12']
# on Linux:
ip_addresses = `ifconfig -a | grep 'inet ' | grep -v 127.0.0.1 | cut -d':' -f 2 | cut -d' ' -f 1`.split
=> ['10.2.21.122','10.8.122.12']
A: Try this:
host = `hostname`.strip # Get the hostname from the shell and removing trailing \n
puts host # Output the hostname
A: Put the highlighted part in backticks:
`dig #{request.host} +short`.strip # dig gives a newline at the end
Or just request.host if you don't care whether it's an IP or not.
A: The accepted answer works but you have to create a socket for every request and it does not work if the server is on a local network and/or not connected to the internet. The below, I believe will always work since it is parsing the request header.
request.env["SERVER_ADDR"]
A: Hostname
A simple way to just get the hostname in Ruby is:
require 'socket'
hostname = Socket.gethostname
The catch is that this relies on the host knowing its own name because it uses either the gethostname or uname system call, so it will not work for the original problem.
Functionally this is identical to the hostname answer, without invoking an external program. The hostname may or may not be fully qualified, depending on the machine's configuration.
IP Address
Since ruby 1.9, you can also use the Socket library to get a list of local addresses. ip_address_list returns an array of AddrInfo objects. How you choose from it will depend on what you want to do and how many interfaces you have, but here's an example which simply selects the first non-loopback IPV4 IP address as a string:
require 'socket'
ip_address = Socket.ip_address_list.find { |ai| ai.ipv4? && !ai.ipv4_loopback? }.ip_address
A: A server typically has more than one interface, at least one private and one public.
Since all the answers here deal with this simple scenario, a cleaner way is to ask Socket for the current ip_address_list() as in:
require 'socket'
def my_first_private_ipv4
Socket.ip_address_list.detect{|intf| intf.ipv4_private?}
end
def my_first_public_ipv4
Socket.ip_address_list.detect{|intf| intf.ipv4? and !intf.ipv4_loopback? and !intf.ipv4_multicast? and !intf.ipv4_private?}
end
Both return an Addrinfo object, so if you need a string you can use the ip_address() method, as in:
ip= my_first_public_ipv4.ip_address unless my_first_public_ipv4.nil?
You can easily work out the more suitable solution to your case changing the Addrinfo methods used to filter the required interface address.
A: Simplest is host_with_port in controller.rb
host_port= request.host_with_port
A: You will likely find yourself having multiple IP addresses on each machine (127.0.0.1, 192.168.0.1, etc). If you are using *NIX as your OS, I'd suggest using hostname, and then running a DNS look up on that. You should be able to use /etc/hosts to define the local hostname to resolve to the IP address for that machine. There is similar functionality on Windows, but I haven't used it since Windows 95 was the bleeding edge.
The other option would be to hit a lookup service like WhatIsMyIp.com. These guys will kick back your real-world IP address to you. This is also something that you can easily setup with a Perl script on a local server if you prefer. I believe 3 lines or so of code to output the remote IP from %ENV should cover you.
A: io = IO.popen('hostname')
hostname = io.readlines
io = IO.popen('ifconfig')
ifconfig = io.readlines
ip = ifconfig[11].scan(/\ \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\ /)
The couple of answers with require 'socket' look good. The ones with request.blah_blah_blah
assume that you are using Rails.
IO should be available all the time. The only problem with this script would be that if ifconfig is output in a different manor on your systems, then you would get different results for the IP. The hostname look up should be solid as Sears.
A: try: Request.remote_ip
remote_ip()
Determine originating IP address. REMOTE_ADDR is the standard but will
fail if the user is behind a proxy. HTTP_CLIENT_IP and/or
HTTP_X_FORWARDED_FOR are set by proxies so check for these if
REMOTE_ADDR is a proxy. HTTP_X_FORWARDED_FOR may be a comma- delimited
list in the case of multiple chained proxies; the last address which
is not trusted is the originating IP.
Update:
Oops, sorry I misread the documentation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "83"
} |
Q: Troubleshoot Java Lucene ignoring Field We're currently using Lucene 2.1.0 for our site search and we've hit a difficult problem: one of our index fields is being ignored during a targeted search. Here is the code for adding the field to a document in our index:
// Add market_local to index
contactDocument.add(
new Field(
"market_local"
, StringUtils.objectToString(
currClip.get(
"market_local"
)
)
, Field.Store.YES
, Field.Index.UN_TOKENIZED
)
);
Running a query ( * ) against the index will return the following results:
Result 1:
title: Foo Bar
market_local: Local
Result 2:
title: Bar Foo
market_local: National
Running a targeted query:
+( market_local:Local )
won't find any results.
I realize this is a highly specific question, I'm just trying to get information on where to start debugging this issue, as I'm a Lucene newbie.
UPDATE
Installed Luke, checking out latest index... the Field market_local is available in searches, so if I execute something like:
market_local:Local
The search works correctly (in Luke). I'm going over our Analyzer code now, is there any way I could chalk this issue up to the fact that our search application is using Lucene 2.1.0 and the latest version of Luke is using 2.3.0?
A: For debugging Lucene, the best tool to use is Luke, which lets you poke around in the index itself to see what got indexed, carry out searches, etc. I recommend downloading it, pointing it at your index, and seeing what's in there.
A: The section on "Why am I getting no hits?" in the Lucene FAQ has some suggestions you might find useful. You're using Field.Index.UN_TOKENIZED, so no Analyzer will be used for indexing (I think). If you're using an Analyzer when you're searching then that might be the root of your problem - the indexing and searching Analyzers should be the same to make sure you get the right hits.
A: Another simple thing to do would be to use a debugger or logging statement to check the value of
StringUtils.objectToString(currClip.get("market_local"))
to make sure it is what you think it is.
A: Luke is bundled with Lucene, but you can tell Luke to use another version of Lucene. Say "lucene-core-2.1.0.jar" contains Lucene 2.1.0 that you want to use and "luke.jar" contains Luke with Lucene 2.3.0. Then you can start Luke with the following command.
java -classpath lucene-core-2.1.0.jar;luke.jar org.getopt.luke.Luke
(The trick is to put your version of Lucene before Luke on the classpath. Also, This is on Windows. On Unix, replace ";" with ":".)
As you can check in Luke,
+( market_local:Local )
gets rewritten to
market_local:Local
if the rewrite(IndexReader) method of the Query object is called. The two queries should be equivalent so there might be a bug in 2.1. If you have to use 2.1, you can try to manually call that method before passing the Query object to the IndexSearcher.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Python re.sub with a flag does not replace all occurrences The Python docs say:
re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string...
So what's going on when I get the following unexpected result?
>>> import re
>>> s = """// The quick brown fox.
... // Jumped over the lazy dog."""
>>> re.sub('^//', '', s, re.MULTILINE)
' The quick brown fox.\n// Jumped over the lazy dog.'
A: The full definition of re.sub is:
re.sub(pattern, repl, string[, count, flags])
Which means that if you tell Python what the parameters are, then you can pass flags without passing count:
re.sub('^//', '', s, flags=re.MULTILINE)
or, more concisely:
re.sub('^//', '', s, flags=re.M)
A: Look at the definition of re.sub:
re.sub(pattern, repl, string[, count, flags])
The 4th argument is the count, you are using re.MULTILINE (which is 8) as the count, not as a flag.
Either use a named argument:
re.sub('^//', '', s, flags=re.MULTILINE)
Or compile the regex first:
re.sub(re.compile('^//', re.MULTILINE), '', s)
A: re.sub('(?m)^//', '', s)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "71"
} |
Q: What View Engine are you using with ASP.NET MVC? I know you can use several different view engines with ASP.NET MVC:
*
*ASPX, obviously
*NVelocity
*Brail
*NHaml
*et al...
The default ASPX view engine seems to make the most sense to me, coming from an ASP.NET WebForms background.
But, I wanted to get an idea of the pros and cons of each and see what most people are using.
Which does StackOverflow use?
A: NHaml is my favorite for its terseness. People either love it or hate it, given that it looks very different from a traditional "HTML with inserted code" template system like ASPX or NVelocity.
Edit:
@Ben,
There are other view engines which compile down (NHaml is one), so those do support custom HTML helpers. I wouldn't be surprised to see the currently interpreted view engines all eventually end up with a compilation model eventually.
A: "Which does StackOverflow use?"
Web Forms.
I asked Jeff Atwood about his decision on his Tag Soup post. He didn't reply - I think he was busy hunting down a missing closing tag ;-)
A: Microsoft has recently announced a new view engine: Razor.
Looks pretty interesting:
http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx
A: Most people on the planet will just use ASPX because that's what they know. Another excellent benefit is the compiled-nature... so you not only get type-safety and intellisense, but you can get the perf benefit as well.
The drawback that I see is that it's so flippin' verbose. I converted an app to NVelocity and was astounded at how clean it looked. The problem is that there were a lot of things that didn't work with NVelocity (like your own custom view helpers) and there was a severe lack of documentation.
I added a feature to MvcContrib where you can register your own HtmlExtension types to it, but it's more of a bandaid until a better solution comes out.
A: I use Spark. It has nice flow between HTML and code. Scott Hanselman also did a post on it with his weekly source code review posts. I am really digging it a lot. One of the major features is pre-compilation of your views.
A: I've used NVelocity in the past. For the most part it makes the code really clean and simple to follow; however, it normally ends up just being a few ViewData variables which have been filled up by XSLT files before hand. So I guess really my View Engine would be both XSLT (which is a love/hate thing - Extension Methods make it really useful) and NVelocity.
A: I've used NVelocity with MonoRail for some time but have recently switched to Spark for both Asp.Net MVC and MonoRail. The syntax seems very natural to me, but I guess that's to be expected. ;)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Double dispatch in C#? I have heard/read the term but don't quite understand what it means.
When should I use this technique and how would I use it? Can anyone provide a good code sample?
A: C# 4 introduces the pseudo type dynamic which resolves the function call at runtime (instead of compile time). (That is, the runtime type of the expression is used). Double- (or multi-dispatch) can be simplified to:
class C { }
static void Foo(C x) => Console.WriteLine(nameof(Foo));
static void Foo(object x) => Console.WriteLine(nameof(Object));
public static void Main(string[] args)
{
object x = new C();
Foo((dynamic)x); // prints: "Foo"
Foo(x); // prints: "Object"
}
Note also by using dynamic you prevent the static analyzer of the compiler to examine this part of the code. You should therefore carefully consider the use of dynamic.
A: The other answers use generics and the runtime type system. But to be clear the use of generics and runtime type system doesn't have anything to do with double dispatch. They can be used to implement it but double dispatch is just dependent on using the concrete type at runtime to dispatch calls. It's illustrated more clearly I think in the wikipedia page. I'll include the translated C++ code below. The key to this is the virtual CollideWith on SpaceShip and that it's overridden on ApolloSpacecraft. This is where the "double" dispatch takes place and the correct asteroid method is called for the given spaceship type.
class SpaceShip
{
public virtual void CollideWith(Asteroid asteroid)
{
asteroid.CollideWith(this);
}
}
class ApolloSpacecraft : SpaceShip
{
public override void CollideWith(Asteroid asteroid)
{
asteroid.CollideWith(this);
}
}
class Asteroid
{
public virtual void CollideWith(SpaceShip target)
{
Console.WriteLine("Asteroid hit a SpaceShip");
}
public virtual void CollideWith(ApolloSpacecraft target)
{
Console.WriteLine("Asteroid hit ApolloSpacecraft");
}
}
class ExplodingAsteroid : Asteroid
{
public override void CollideWith(SpaceShip target)
{
Console.WriteLine("ExplodingAsteroid hit a SpaceShip");
}
public override void CollideWith(ApolloSpacecraft target)
{
Console.WriteLine("ExplodingAsteroid hit ApolloSpacecraft");
}
}
class Program
{
static void Main(string[] args)
{
Asteroid[] asteroids = new Asteroid[] { new Asteroid(), new ExplodingAsteroid() };
ApolloSpacecraft spacecraft = new ApolloSpacecraft();
spacecraft.CollideWith(asteroids[0]);
spacecraft.CollideWith(asteroids[1]);
SpaceShip spaceShip = new SpaceShip();
spaceShip.CollideWith(asteroids[0]);
spaceShip.CollideWith(asteroids[1]);
}
}
A: The visitor pattern is a way of doing double-dispatch in an object-oriented way.
It's useful for when you want to choose which method to use for a given argument based on its type at runtime rather than compile time.
Double dispatch is a special case of multiple dispatch.
When you call a virtual method on an object, that's considered single-dispatch because which actual method is called depends on the type of the single object.
For double dispatch, both the object's type and the method sole argument's type is taken into account. This is like method overload resolution, except that the argument type is determined at runtime in double-dispatch instead of statically at compile-time.
In multiple-dispatch, a method can have multiple arguments passed to it and which implementation is used depends on each argument's type. The order that the types are evaluated depends on the language. In LISP, it checks each type from first to last.
Languages with multiple dispatch make use of generic functions, which are just function delcarations and aren't like generic methods, which use type parameters.
To do double-dispatch in C#, you can declare a method with a sole object argument and then specific methods with specific types:
using System.Linq;
class DoubleDispatch
{
public T Foo<T>(object arg)
{
var method = from m in GetType().GetMethods()
where m.Name == "Foo"
&& m.GetParameters().Length==1
&& arg.GetType().IsAssignableFrom
(m.GetParameters()[0].GetType())
&& m.ReturnType == typeof(T)
select m;
return (T) method.Single().Invoke(this,new object[]{arg});
}
public int Foo(int arg) { /* ... */ }
static void Test()
{
object x = 5;
Foo<int>(x); //should call Foo(int) via Foo<T>(object).
}
}
A: The code posted by Mark isn't complete and what ever is there isn't working.
So tweaked and complete.
class DoubleDispatch
{
public T Foo<T>(object arg)
{
var method = from m in GetType().GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic)
where m.Name == "Foo"
&& m.GetParameters().Length == 1
//&& arg.GetType().IsAssignableFrom
// (m.GetParameters()[0].GetType())
&&Type.GetType(m.GetParameters()[0].ParameterType.FullName).IsAssignableFrom(arg.GetType())
&& m.ReturnType == typeof(T)
select m;
return (T)method.Single().Invoke(this, new object[] { arg });
}
public int Foo(int arg)
{
return 10;
}
public string Foo(string arg)
{
return 5.ToString();
}
public static void Main(string[] args)
{
object x = 5;
DoubleDispatch dispatch = new DoubleDispatch();
Console.WriteLine(dispatch.Foo<int>(x));
Console.WriteLine(dispatch.Foo<string>(x.ToString()));
Console.ReadLine();
}
}
Thanks Mark and others for nice explanation on Double Dispatcher pattern.
A: Full listing of working code
using System;
using System.Linq;
namespace TestConsoleApp
{
internal class Program
{
public static void Main(string[] args)
{
const int x = 5;
var dispatch = new DoubleDispatch();
Console.WriteLine(dispatch.Foo<int>(x));
Console.WriteLine(dispatch.Foo<string>(x.ToString()));
Console.ReadLine();
}
}
public class DoubleDispatch
{
public T Foo<T>(T arg)
{
var method = GetType()
.GetMethods()
.Single(m =>
m.Name == "Foo" &&
m.GetParameters().Length == 1 &&
arg.GetType().IsAssignableFrom(m.GetParameters()[0].ParameterType) &&
m.ReturnType == typeof(T));
return (T) method.Invoke(this, new object[] {arg});
}
public int Foo(int arg)
{
return arg;
}
public string Foo(string arg)
{
return arg;
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "68"
} |
Q: Metalanaguage to describe the Model from MVC to generate identical client and server side code I am looking for a powerful meta-language to describa behaviour for an application i intend to use in offline mode (google-gears + javascript) and server side sqlite + (php/ruby/java etc) and looking for a good format to describe the model's behaviour which can be easily converted to the target languages.
Am I completely off track, and there is a much better way?
A: Have you looked at Google Web Toolkit? GWT allows you to write server side Java objects which get translated into Javascript for you. This allows you to not deal with the browser quirks at all.
I'm not sure how well integrated the Gears and GWT projects are, however. If it isn't integrated yet, I'm sure it will be in fairly short order.
Edit: This is probably more of an alternate way of doing what you're looking for, rather than a suggestion for a meta language.
A: This may be out of your scope, but maybe you should consider sproutcore. From what I understand, it's a bundled up MVC architecture that can be backend-agnostic.
I don't have much experience with it, but it sounds like some of the consumers (apple's MobileMe for instance) want to do the same thing you do.
A: Maybe you should consider using Script#?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SQL Server Views, blessing or curse? I once worked with an architect who banned the use of SQL views. His main reason was that views made it too easy for a thoughtless coder to needlessly involve joined tables which, if that coder tried harder, could be avoided altogether. Implicitly he was encouraging code reuse via copy-and-paste instead of encapsulation in views.
The database had nearly 600 tables and was highly normalised, so most of the useful SQL was necessarily verbose.
Several years later I can see at least one bad outcome from the ban - we have many hundreds of dense, lengthy stored procs that verge on unmaintainable.
In hindsight I would say it was a bad decision, but what are your experiences with SQL views? Have you found them bad for performance? Any other thoughts on when they are or are not appropriate?
A: My current database was completely awash with countless small tables of no more than 5 rows each. Well, I could count them but it was cluttered. These tables simply held constant type values (think enum) and could very easily be combined into one table. I then made views that simulated each of the tables I deleted to ensure backward compactability. Worked great.
A: Like all power, views have its own dark side. However, you cannot blame views for somebody writing bad performing code. Moreover views can limit the exposure of some columns and provide extra security.
A: One thing that hasn't been mentioned thus far is use of views to provide a logical picture of the data to end users for ad hoc reporting or similar.
This has two merits:
*
*To allow the user to single "tables" containing the data they expect rather requiring relatively non technical users to work out potentially complex joins (because the database is normalised)
*It provides a means to allow some degree of ah hoc access without exposing the data or the structure to the end users.
Even with non ad-hoc reporting its sometimes signicantly easier to provide a view to the reporting system that contains the relveant data, neatly separating production of data from presentation of same.
A: There are some very good uses for views; I have used them a lot for tuning and for exposing less normalized sets of information, or for UNION-ing results from multiple selects into a single result set.
Obviously any programming tool can be used incorrectly, but I can't think of any times in my experience where a poorly tuned view has caused any kind of drawbacks from a performance standpoint, and the value they can provide by providing explicitly tuned selects and avoiding duplication of complex SQL code can be significant.
Incidentally, I have never been a fan of architectural "rules" that are based on keeping developers from hurting themselves. These rules often have unintended side-effects -- the last place I worked didn't allow using NULLs in the database, because developers might forget to check for null. This ended up forcing us to work around "1/1/1900" dates and integers defaulted to "0" in all the software built against the databases, and introducing a litany of bugs caused by devs working around places where NULL was the appropriate value.
A: Views are good for ad-hoc queries, the kind that a DBA does behind the scenes when he/she needs quick access to data to see what's going on with the system.
But they can be bad for production code. Part of the reason is that it's sort of unpredictable what indexes you will need with a view, since the where clause can be different, and therefore hard to tune. Also, you are generally returning a lot more data than is actually necesary for the individual queries that are using the view. Each of these queries could be tightened up and tuned individually.
There are specific uses of views in cases of data partitioning that can be extremely useful, so I'm not saying they should avoided altogether. I'm just saying that if a view can be replaced by a few stored procedures, you will be better off without the view.
A: You've answered your own question:
he was encouraging code reuse via copy-and-paste
Reuse the code by creating a view. If the view performs poorly, it will be much easier to track down than if you have the same poorly performing code in several places.
A: Not a big fan of views (Can't remember the last time I wrote one) but wouldn't ban them entirely either. If your database allows you to put indexes on the views and not just on the table, you can often improve performance a good bit which makes them better. If you are using views, make sure to look into indexing them.
I really only see the need for views for partitioning data and for extremely complex joins that are really critical to the application (thinking of financial reports here where starting from the same dataset for everything might be critical). I do know some reporting tools seem to prefer views over stored procs.
I am a big proponent of never returning more records or fields than you need in a specific instance and the overuse of views tends to make people return more fields (and in way too many cases, too many joins) than they need which wastes system resources.
I also tend to see that people who rely on views (not the developer of the view - the people who only use them) often don't understand the database very well (so they would get the joins wrong if not using the view) and that to me is critical to writing good code against the database. I want people to understand what they are asking the db to do, not rely on some magic black box of a view. That is all personal opinion of course, your mileage may vary.
Like BlaM I personally haven't found them easier to maintain than stored procs.
Edited in Oct 2010 to add:
Since I orginally wrote this, I have had occasion to work with a couple of databases designed by people who were addicted to using views. Even worse they used views that called views that called views (to the point where eventually we hit the limit of the number of tables that can be called). This was a performance nightmare. It took 8 minutes to get a simple count(*) of the records in one view and much longer to get data. If you use views, be very wary of using views that call other views. You will be building a system that will very probably not work under the normal performance load on production. In SQL Server you can only index views that do not call other views, so what ends up happening when you use views in a chain, is that the entire record set has to be built for each view and it is not until you get to the last one that the where clause criteria are applied. You may need to generate millions of records just to see three. You may join to the same table 6 times when you really only need to join to it once, you may return many many more columns than you need in the final results set.
A: We use views for all of our simple data exports to csv files. This simplifies the process of writing a package and embedding the sql within the package which becomes cumbersome and hard to debug against.
Using views, we can execute a view and see exactly what was exported, no cruft or unknowns. It greatly helps in troubleshooting problems with improper data exports and hides any complex joins behind the view. Granted, we use a very old legacy system from a TERMS based system that exports to sql, so the joins are a little more complex than usual.
A: Some time ago I've tried to maintain code that used views built from views built from views... That was a pain in the a**, so I got a little allergic to views :)
I usually prefer working with tables directly, especially for web applications where speed is a main concern. When accessing tables directly you have the chance to tweak your SQL-Queries to achieve the best performance. "Precompiled"/cached working plans might be one advantage of views, but in many cases just-in-time compilation with all given parameters and where clauses in consideration will result in faster processing over all.
However that does not rule out views totally, if used adequately. For example you can use a view with the "users" table joined with the "users_status" table to get an textual explanation for each status - if you need it. However if you don't need the explanation: use the "users" table, not the view. As always: Use your brain!
A: Views have been helpful to us in their role for use by public web based applications that dip from a production database. Simplified security is the primary advantage we see since the table design in the database may combine sensitive and non-sensitive data within the same table. A stored procedure shares much of this advantage, but the view is read-only, has potential interop advantages, and is a less complex thing for junior people to implement.
This security abstraction advantage also applies when views are used for end-user ad-hoc queries; this would be less of an advantage if we had a proper, flattened, data warehouse representation of our data.
A: From an application stand point which uses an ORM, it's a lot harder to execute a custom query than doing a select on a discretely mapped type (eg, the view).
For example, if you need just 5 fields of a table that has many (say 30 or 40) an ORM framework will create an entity to represent the table.
That means that even though you only need a few properties of the entity, the select query generated by the ORM framework will bring the entire entity in its full glory. A view on the other hand, although also mapped to an entity with the ORM framework, will only bring the data you need.
Second, since ORM frameworks map entities to tables, relationships between entities are generated (and hydrated) on the client side, meaning that the query has to execute and return to the app before linking of those entities can happen at runtime within the app.
Some frameworks bypass that by returning the data from multiple linked entities in a giant select (with multiple joins), bringing in the columns of all related tables in one call. Internally the framework disassembles the giant result set and structures the logical presentation of the linked entities before returning those entities to the caller app.
Point being is that views are a life saver for apps using ORM. The alternative is to manually make db calls, and manually passing the resulting recordsets into usable entities/models.
While this approach is good and definitely produces a result, it has lots of negative facets. Manual code... is manual; hard to maintain, cumbersome in implementation, and causes devs to worry more about the specifics of the DB provider API vs the logical domain model. Not to mention that it increases time to production (its a lot more labourious) costs for development, maintenance, surface area of bugs, etc.
So for anyone saying views are bad, please consider the other side of things; The stuff the high and mighty DBA's most often have no clue about.
A: Let's see if I can come up with a lame analogy ...
"I don't need a phillips screwdriver. I carry a flat head and a grinder!"
Dismissing views out of hand will cause pain long term. For one, it's easier to debug and modify a single view definition than it is to ship modified code.
A: Views can also reduce the size of complex queries (in the same way stored procs can).
This can reduce network bandwith for very busy databases.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: Best practices for portable C# I am looking to write some C# code for linux/windows/mac/any other platform, and am looking for best practices for portable code.
Project mono has some great porting resources.
What are the best practices for portable C#?
A: Don't use Windows.Forms for GUIs, but Mono probably mentioned that already. Gtk# is much more consistent and reliable for cross platform GUIs.
A: A few years ago I would have advised you to buy yourself a copy of my book on cross-platform .NET, but as the book's somewhat out-of-date now you really need to stick to the info of the Mono site.
The Mono Migration Analyzer (MoMA) tool is pretty good for analyzing an exsisting .NET application and warning you of portability problems, but the best bet for new code is to use the latest stable version of Mono for your development work.
As Orion said you need to be careful when using 3rd party DLLs, although my co-author wrote a NativeProbe tool to analyze DLLs for P/Invoke dependenecies if you do want to quickly check 3rd party software.
If you are determined to develop on MS .NET then you should try and ensure you also build and unit test on Mono, and you should also watch out for a number of Windows specific namespaces such as the Microsoft.Win32 and System.Management namespaces.
A: I hate the term "Best practice" because it seems that some practices can be the best in any context, which is a risky thing, but I'll tell what I consider a "Good practice" for multi-platform code (and for most other type of development):
Use a continuous integration engine and build for all the target platforms all the time.
Sounds too complex? Well, if you really need to support multiple platforms, better to do it. No matter how careful you are with your code and library usage, if you test too late, you'll find yourself spending looong hours reworking big portions of the app.
A: I've actually used winforms and it was fine. It was BUTT UGLY, but it worked.
Obviously, don't use P/Invoke, or any win32 stuff like the registry. Also be aware of any third party DLL's. For example, we use a third party SQLite dll which actually contains native code in it which we have to swap out if we want to run on OSX/linux.
A: Watch out for anything to do with filename and path manipulation and make use of the portable .NET methods in System.IO.Path ie.
instead of:
string myfile = somepath + "\\file.txt";
do:
string myfile = Path.Combine(somepath, "file.txt");
If you need to specify a path separator then you would use Path.Separator etc
A: Don't use "\r\n" for a new line. Use Environment.NewLine
Remember :
*
**NIX uses just the newline character ("\n")
*Windows uses "\r\n"
*MacIntosh uses "\r" (I am not really sure about this - feel free to correct me).
L.E.: It seems that some newer MacOSes don't use the "\r" line separator anymore.
A: If you want the code to be portable, you need to closely review the list of completed features on the Mono site. They go into detail on each class in the framework, and the level of completeness. You will have to take these things into consideration during the design process so that you don't go too far down a path and discover that a critical feature has not yet been implemented.
A: There are some other simple things. Like don't assume path characters. Or newlines.
I'm one of the people who regularly compiles NUnit on Mono on Linux or OSX.
Also, don't assume that the compilers work exactly the same. We've found an issue recently where the MS C# compiler appears to be including things that the Mono one doesn't, requiring extra references in our build script.
Other than that, it has been pretty straightforward. I remember the first time we got the GUI running on Mono/Linux - it was pretty exciting (even if it was pretty ugly)
A: One missing item: Make sure that file names are case sensitive. File.Open ("MyFile.txt"); isn't going to work on Unix if your file is named myfile.txt.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Scripting the Visual Studio IDE I'd like to create a script that will configure the Visual Studio IDE the way I like it. Nothing vastly complicated, just a few Tools/Options settings, adding some External Tools, that kind of thing.
I know that this can be done inside VS with Import/Export Settings, but I'd like to be able to automate it from outside of VS. Is this possible, and if so, how?
Edited to add: doing it from outside of VS is important to me -- I'm hoping to use this as part of a more general "configure this newly-Ghosted PC just the way I like it" script.
Edited again: the solution seems to be to hack CurrentSettings.vssettings, or use AutoIt. Details below.
A: Answering my own question, in two ways:
*
*In VS2005/8, the things I mentioned (Tools/Options, External Tools) are all stored in the CurrentSettings.vssettings file, in the folder "Visual Studio 200{5|8}\Settings". This file is just XML, and it can be edited programmatically by anything that knows how to parse XML. You can also just paste a new vssettings file over the top of the default one (at least, this works for me).
*The larger question of configuring a virgin PC. It turns out that not everything I want to change has an API, so I need some way of pretending to be a user who is actually sitting there clicking on things. The best approach to this seems to be AutoIt, whose scripting language I will now have to learn in my Copious Free Time.
A: An easy way is to use the macro recorder to do something simple, then look at the code it produces and edit it as you see fit.
A: On my machine Visual Studio stores it's local settings in a file called VCComponents.dat. Its a text file, so perhaps you could find a way of placing your settings directly in there.
The file is stored in my users local AppData\Local\Microsoft\VC folder
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to get the identity of an inserted row? How am I supposed to get the IDENTITY of an inserted row?
I know about @@IDENTITY and IDENT_CURRENT and SCOPE_IDENTITY, but don't understand the implications or impacts attached to each.
Can someone please explain the differences and when I would be using each?
A: The best (read: safest) way to get the identity of a newly-inserted row is by using the output clause:
create table TableWithIdentity
( IdentityColumnName int identity(1, 1) not null primary key,
... )
-- type of this table's column must match the type of the
-- identity column of the table you'll be inserting into
declare @IdentityOutput table ( ID int )
insert TableWithIdentity
( ... )
output inserted.IdentityColumnName into @IdentityOutput
values
( ... )
select @IdentityValue = (select ID from @IdentityOutput)
A: Add
SELECT CAST(scope_identity() AS int);
to the end of your insert sql statement, then
NewId = command.ExecuteScalar()
will retrieve it.
A: One other way to guarantee the identity of the rows you insert is to specify the identity values and use the SET IDENTITY_INSERT ON and then OFF. This guarantees you know exactly what the identity values are! As long as the values are not in use then you can insert these values into the identity column.
CREATE TABLE #foo
(
fooid INT IDENTITY NOT NULL,
fooname VARCHAR(20)
)
SELECT @@Identity AS [@@Identity],
Scope_identity() AS [SCOPE_IDENTITY()],
Ident_current('#Foo') AS [IDENT_CURRENT]
SET IDENTITY_INSERT #foo ON
INSERT INTO #foo
(fooid,
fooname)
VALUES (1,
'one'),
(2,
'Two')
SET IDENTITY_INSERT #foo OFF
SELECT @@Identity AS [@@Identity],
Scope_identity() AS [SCOPE_IDENTITY()],
Ident_current('#Foo') AS [IDENT_CURRENT]
INSERT INTO #foo
(fooname)
VALUES ('Three')
SELECT @@Identity AS [@@Identity],
Scope_identity() AS [SCOPE_IDENTITY()],
Ident_current('#Foo') AS [IDENT_CURRENT]
-- YOU CAN INSERT
SET IDENTITY_INSERT #foo ON
INSERT INTO #foo
(fooid,
fooname)
VALUES (10,
'Ten'),
(11,
'Eleven')
SET IDENTITY_INSERT #foo OFF
SELECT @@Identity AS [@@Identity],
Scope_identity() AS [SCOPE_IDENTITY()],
Ident_current('#Foo') AS [IDENT_CURRENT]
SELECT *
FROM #foo
This can be a very useful technique if you are loading data from another source or merging data from two databases etc.
A: From MSDN
@@IDENTITY, SCOPE_IDENTITY, and IDENT_CURRENT are similar functions in that they return the last value inserted into the IDENTITY column of a table.
@@IDENTITY and SCOPE_IDENTITY will return the last identity value generated in any table in the current session. However, SCOPE_IDENTITY returns the value only within the current scope; @@IDENTITY is not limited to a specific scope.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT.
*
*IDENT_CURRENT is a function which takes a table as a argument.
*@@IDENTITY may return confusing result when you have an trigger on the table
*SCOPE_IDENTITY is your hero most of the time.
A: When you use Entity Framework, it internally uses the OUTPUT technique to return the newly inserted ID value
DECLARE @generated_keys table([Id] uniqueidentifier)
INSERT INTO TurboEncabulators(StatorSlots)
OUTPUT inserted.TurboEncabulatorID INTO @generated_keys
VALUES('Malleable logarithmic casing');
SELECT t.[TurboEncabulatorID ]
FROM @generated_keys AS g
JOIN dbo.TurboEncabulators AS t
ON g.Id = t.TurboEncabulatorID
WHERE @@ROWCOUNT > 0
The output results are stored in a temporary table variable, joined back to the table, and return the row value out of the table.
Note: I have no idea why EF would inner join the ephemeral table back to the real table (under what circumstances would the two not match).
But that's what EF does.
This technique (OUTPUT) is only available on SQL Server 2008 or newer.
Edit - The reason for the join
The reason that Entity Framework joins back to the original table, rather than simply use the OUTPUT values is because EF also uses this technique to get the rowversion of a newly inserted row.
You can use optimistic concurrency in your entity framework models by using the Timestamp attribute:
public class TurboEncabulator
{
public String StatorSlots)
[Timestamp]
public byte[] RowVersion { get; set; }
}
When you do this, Entity Framework will need the rowversion of the newly inserted row:
DECLARE @generated_keys table([Id] uniqueidentifier)
INSERT INTO TurboEncabulators(StatorSlots)
OUTPUT inserted.TurboEncabulatorID INTO @generated_keys
VALUES('Malleable logarithmic casing');
SELECT t.[TurboEncabulatorID], t.[RowVersion]
FROM @generated_keys AS g
JOIN dbo.TurboEncabulators AS t
ON g.Id = t.TurboEncabulatorID
WHERE @@ROWCOUNT > 0
And in order to retrieve this Timetsamp you cannot use an OUTPUT clause.
That's because if there's a trigger on the table, any Timestamp you OUTPUT will be wrong:
*
*Initial insert. Timestamp: 1
*OUTPUT clause outputs timestamp: 1
*trigger modifies row. Timestamp: 2
The returned timestamp will never be correct if you have a trigger on the table. So you must use a separate SELECT.
And even if you were willing to suffer the incorrect rowversion, the other reason to perform a separate SELECT is that you cannot OUTPUT a rowversion into a table variable:
DECLARE @generated_keys table([Id] uniqueidentifier, [Rowversion] timestamp)
INSERT INTO TurboEncabulators(StatorSlots)
OUTPUT inserted.TurboEncabulatorID, inserted.Rowversion INTO @generated_keys
VALUES('Malleable logarithmic casing');
The third reason to do it is for symmetry. When performing an UPDATE on a table with a trigger, you cannot use an OUTPUT clause. Trying do UPDATE with an OUTPUT is not supported, and will give an error:
*
*Cannot use UPDATE with OUTPUT clause when a trigger is on the table
The only way to do it is with a follow-up SELECT statement:
UPDATE TurboEncabulators
SET StatorSlots = 'Lotus-O deltoid type'
WHERE ((TurboEncabulatorID = 1) AND (RowVersion = 792))
SELECT RowVersion
FROM TurboEncabulators
WHERE @@ROWCOUNT > 0 AND TurboEncabulatorID = 1
A: I believe the safest and most accurate method of retrieving the inserted id would be using the output clause.
for example (taken from the following MSDN article)
USE AdventureWorks2008R2;
GO
DECLARE @MyTableVar table( NewScrapReasonID smallint,
Name varchar(50),
ModifiedDate datetime);
INSERT Production.ScrapReason
OUTPUT INSERTED.ScrapReasonID, INSERTED.Name, INSERTED.ModifiedDate
INTO @MyTableVar
VALUES (N'Operator error', GETDATE());
--Display the result set of the table variable.
SELECT NewScrapReasonID, Name, ModifiedDate FROM @MyTableVar;
--Display the result set of the table.
SELECT ScrapReasonID, Name, ModifiedDate
FROM Production.ScrapReason;
GO
A: I can't speak to other versions of SQL Server, but in 2012, outputting directly works just fine. You don't need to bother with a temporary table.
INSERT INTO MyTable
OUTPUT INSERTED.ID
VALUES (...)
By the way, this technique also works when inserting multiple rows.
INSERT INTO MyTable
OUTPUT INSERTED.ID
VALUES
(...),
(...),
(...)
Output
ID
2
3
4
A: Create a uuid and also insert it to a column. Then you can easily identify your row with the uuid. Thats the only 100% working solution you can implement. All the other solutions are too complicated or are not working in same edge cases.
E.g.:
1) Create row
INSERT INTO table (uuid, name, street, zip)
VALUES ('2f802845-447b-4caa-8783-2086a0a8d437', 'Peter', 'Mainstreet 7', '88888');
2) Get created row
SELECT * FROM table WHERE uuid='2f802845-447b-4caa-8783-2086a0a8d437';
A: @@IDENTITY is the last identity inserted using the current SQL Connection. This is a good value to return from an insert stored procedure, where you just need the identity inserted for your new record, and don't care if more rows were added afterward.
SCOPE_IDENTITY is the last identity inserted using the current SQL Connection, and in the current scope -- that is, if there was a second IDENTITY inserted based on a trigger after your insert, it would not be reflected in SCOPE_IDENTITY, only the insert you performed. Frankly, I have never had a reason to use this.
IDENT_CURRENT(tablename) is the last identity inserted regardless of connection or scope. You could use this if you want to get the current IDENTITY value for a table that you have not inserted a record into.
A: *
*@@IDENTITY returns the last identity value generated for any table in the current session, across all scopes. You need to be careful here, since it's across scopes. You could get a value from a trigger, instead of your current statement.
*SCOPE_IDENTITY() returns the last identity value generated for any table in the current session and the current scope. Generally what you want to use.
*IDENT_CURRENT('tableName') returns the last identity value generated for a specific table in any session and any scope. This lets you specify which table you want the value from, in case the two above aren't quite what you need (very rare). Also, as @Guy Starbuck mentioned, "You could use this if you want to get the current IDENTITY value for a table that you have not inserted a record into."
*The OUTPUT clause of the INSERT statement will let you access every row that was inserted via that statement. Since it's scoped to the specific statement, it's more straightforward than the other functions above. However, it's a little more verbose (you'll need to insert into a table variable/temp table and then query that) and it gives results even in an error scenario where the statement is rolled back. That said, if your query uses a parallel execution plan, this is the only guaranteed method for getting the identity (short of turning off parallelism). However, it is executed before triggers and cannot be used to return trigger-generated values.
A: I'm saying the same thing as the other guys, so everyone's correct, I'm just trying to make it more clear.
@@IDENTITY returns the id of the last thing that was inserted by your client's connection to the database.
Most of the time this works fine, but sometimes a trigger will go and insert a new row that you don't know about, and you'll get the ID from this new row, instead of the one you want
SCOPE_IDENTITY() solves this problem. It returns the id of the last thing that you inserted in the SQL code you sent to the database. If triggers go and create extra rows, they won't cause the wrong value to get returned. Hooray
IDENT_CURRENT returns the last ID that was inserted by anyone. If some other app happens to insert another row at an unforunate time, you'll get the ID of that row instead of your one.
If you want to play it safe, always use SCOPE_IDENTITY(). If you stick with @@IDENTITY and someone decides to add a trigger later on, all your code will break.
A: ALWAYS use scope_identity(), there's NEVER a need for anything else.
A: Even though this is an older thread, there is a newer way to do this which avoids some of the pitfalls of the IDENTITY column in older versions of SQL Server, like gaps in the identity values after server reboots. Sequences are available in SQL Server 2016 and forward which is the newer way is to create a SEQUENCE object using TSQL. This allows you create your own numeric sequence object in SQL Server and control how it increments.
Here is an example:
CREATE SEQUENCE CountBy1
START WITH 1
INCREMENT BY 1 ;
GO
Then in TSQL you would do the following to get the next sequence ID:
SELECT NEXT VALUE FOR CountBy1 AS SequenceID
GO
Here are the links to CREATE SEQUENCE and NEXT VALUE FOR
A: Complete solution in SQL and ADO.NET
const string sql = "INSERT INTO [Table1] (...) OUTPUT INSERTED.Id VALUES (...)";
using var command = connection.CreateCommand();
command.CommandText = sql;
var outputIdParameter = new SqlParameter("@Id", SqlDbType.Int) { Direction = ParameterDirection.Output };
command.Parameters.Add(outputIdParameter);
await connection.OpenAsync();
var outputId= await command.ExecuteScalarAsync();
await connection.CloseAsync();
int id = Convert.ToInt32(outputId);
A: After Your Insert Statement you need to add this. And Make sure about the table name where data is inserting.You will get current row no where row affected just now by your insert statement.
IDENT_CURRENT('tableName')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1337"
} |
Q: Can you recommend a database that scales horizontally? Generally the database server is the biggest, most expensive box we have to buy as scaling vertically is the only option. Are there any databases that scale well horizontally (i.e. across multiple commodity machines) and what are the limitations in this approach?
A: Oracle RAC is not horizontally scalable at all, because all Oracle instances share the same data storage. Yes, with SAN stuff u can get a large size DB, but it's just not scalable at all. In other words, Oracle RAC is still a scale-up approach. So for scaling-out or horizontally scaling, you have to partition your data by function that means put different groups of tables in different databases; or partition your data per table that means partition one table into multiple subtables with the same schema but store in different databases. In this way, you get a scaling-out solution. There are many resources on that. Sharding has been a buzz word for a while in web 2.0 website architecture blog sphere.
Because Sharding is not directly supported by database itself, you have to build your own solution. But as I said, there are many lessons already. For oracle, partitioning table is possible. For mysql, check this question
A: Oracle RAC -- Real Application Cluster
This works nicely, you just add boxes to your cluster. You can fail over from one box to the other. It's not replication, all the boxes are part of the same logical unit.
It's pretty spendy, of course.
A: Don't worry, good solutions are coming!
Couchdb and Hypertable are open source and still in alpha, but they are clearly designed to make scaling on commodity software simple. They work pretty well, and may change how you think about databases.
Also, if it's okay to let someone else do the distributing for you, Google AppEngine and Amazon SimpleDB are extremely cheap distributed database services, though they're both in beta right now so strict limitations are imposed.
A: There are storage techniques such as JavaSpaces (or a commercial implementation such as Gigaspaces) which provide highly scalable, fast & secure access to objects.
There are also distributed cacheing systems such as memcached, which offer a similar approach.
Of course, neither of these are true databases, but they are things that can work in conjunction with databases to offer a large amount of horizontal scalability, given a suitable architecture. The real problem is that if you want all of the ACID goodness that comes with a database, there are certain unavoidable performance penalties. The only way out is to figure out the bits where you don't need ACID, and use other technologies to service those bits.
A: Oracle RAC is the Rolls Royce of databases allowing extra hardware nodes to be added relatively easily and hardware failover.
However, your commodity hardware costs will be dwarfed by the licence costs.
Why dod you feel you need horizontal scaling. A multi CPU core server with 40GB RAM and SAN storage can support very sizeable DB installation.
Can you provide any sizing and expected activity information to allow better understanding of your problem?
A: If you do go down the RAC route it's worth remembering that it doesnt scale horizontally forever. Even the sales guys admit 90% of rac customers are 4 nodes or less. Once you go more than that you get diminishing returns. So rac may work for you, but it's not guaranteed to be the answer.
A: MySQL: http://www.mysql.com/why-mysql/scaleout.html
Limitations are that it works best with read-mostly workloads. You typically have one 'master' that receives all the writes, and many 'slaves' that replicate the writes. Then you distribute the reads over all the databases.
MySQL replication is asynchronous, so you will probably have to deal with time lag problems (you write to the master, and then read from a slave before the write has been replicated).
A: Netezza and other datawarehouse appliances scale this way, but they are not good for OLTP and web app workloads.
A: The Oracle route for scaling across multiple machines is called Real Application Clusters (Oracle RAC). There's no end of documentation on this elsewhere; you might try starting at http://www.oracle.com/database/rac_home.html.
A: MongoDB
is one of the best database that scales horizontally.
A: Oracle Real Application Clusters. If you want the best then take a look at it.
A: If you seriously think you will out scale a decent multicore "Big Iron" box, then you think about partitioning your data. This is a good, database agnostic way to scale out.
All databases which horizontally will come at a serious cost.
Unless you have mega $$'s to throw at the problem, forget about RAC. While its very good, its VERY expensive once you scale beyond 2 nodes.
A: You might look at DashDB for OLAP -- IBM pairs it with Cloudant for OLTP.
https://www.ibm.com/developerworks/community/blogs/5things/entry/5_things_to_know_about_dashdb_placeholder?lang=en
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: How do I SCP a file programmatically using C? What would be the best way to do an scp or sftp copy in a Unix environment using C?
I'm interested in knowing the best library to use and an example if at all possible. I'm working on a Solaris server with the Sun tools installed.
A: Try Libcurl
libcurl is a free and easy-to-use client-side URL transfer library, supporting DICT, FILE, > FTP, FTPS, Gopher, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, Telnet and TFTP. libcurl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, Kerberos), file transfer resume, http proxy tunneling and more!
libcurl is highly portable, it builds and works identically on numerous platforms, including Solaris, NetBSD, FreeBSD, OpenBSD, Darwin, HPUX, IRIX, AIX, Tru64, Linux, UnixWare, HURD, Windows, Amiga, OS/2, BeOs, Mac OS X, Ultrix, QNX, OpenVMS, RISC OS, Novell NetWare, DOS and more...
A: In the past, I've simply called a shell script that contained the file transfer code.
int transferFile()
{
// Declare the transfer command
char transferCommand[50] = "/home/tyler/transferFile.shl";
// Execute the command
return system(transferCommand);
}
This will return 1 if the transfer command returns successfully.
A: I'm not really a C expert, but I think you can use system() to run OS commands. This would assume that you don't actually want to re-implement scp, just use it.
A: I've always just used the system() command. Of course doing this requires that you have SSH keys properly installed between the client and target machine so that it doesn't prompt for the password.
A: You can use libssh for sftp. I put some code here for you which has Pause/Resume and works on Windows. For Linux, you need to replace local file handling functions. I cannot copy the entire class because it will exceed this website limit. Change username and password and hostname to proper equivalents of your SFTP server:
int main(array<System::String ^> ^args)
{
//Console::WriteLine(L"Hello World");
pSFTPConnector sshc = new SFTPConnector(L".\\", L"127.0.0.1", 22, L"iman", L"iman"); // Change the hostname, port, username, password to your SFTP server, your credentials
//FILE *nullfile = fopen("null", "w");
//sshc->setLogFile(nullfile);
sshc->setVerbosity(SSH_LOG_RARE); // You can change the verbosity as appropriate for you
int i = sshc->InitSession();
i = sshc->ConnectSession();
i = sshc->InitSFTP();
//i = sshc->SFTPrename("renamed_myfile.txt", "myfile.txt"); // Change these file names
//i = sshc->Makedir("sftpdir");
//i = sshc->testUploadFile("myfile2.txt", "1234567890testfile");
// Change these file names to whatever appropriate
//i = sshc->SFTPget("c:\\testdir\\Got_CAR_HIRE_FINAL_test.jpg", "CAR_HIRE_FINAL_test.jpg", 64*1024);
i = sshc->SFTPget("c:\\testdir\\get_downloaded_CAR_HIRE_FINAL.jpg", "CAR_HIRE_FINAL.jpg", 64 *1024);
i = sshc->SFTPreget("c:\\testdir\\reget_downloaded_CAR_HIRE_FINAL.jpg", "CAR_HIRE_FINAL.jpg", 64 * 1024);
i = sshc->SFTPput("c:\\testdir\\CAR_HIRE_FINAL.jpg", "put_CAR_HIRE_FINAL.jpg", 64 * 1024);
i = sshc->SFTPreput("c:\\testdir\\CAR_HIRE_FINAL.jpg", "reput_CAR_HIRE_FINAL.jpg", 64 * 1024);
delete sshc;
return 0;
}
typedef enum sshconerr {
E_OK = 1, E_SESSION_ALOC = -1, E_SSH_CONNECT_ERR = -2, E_SFTP_ALLOC = -3, E_INIT_SFTP = -4, E_CREATE_DIR = -5, E_FILEOPEN_WRITE = -6, E_WRITE_ERR = -7,
E_FILE_CLOSE = -8, E_FILE_OPEN_READ = -9, E_INVALID_PARAMS = -10, E_SFTP_ERR = -11, E_SFTP_READ_ERR = -12, E_SFTP_READBYTES_ERR = -13, E_GET_FILEINF = -14,
E_LOCAL_FILE_NOTFOUND = -15, E_RENAME_ERR = -16, E_MEM_ALLOC = -17, E_LOCAL_FILE_READ = -18, E_LOCAL_FILE_RDWR = -19, E_REMOTEFILE_SEEK = -20,
E_REMOTE_FILE_OPEN = -21, E_DELETE_ERR = -22, E_RENAME_LOCAL_FILE = -23, E_LOCAL_DELETE_FILE = -24, E_FILEOPEN_RDONLY = -25, E_SFTP_READ_EOF = -26,
E_UNKNOWN = -999
} ESSHERR;
// Status of transfers;
typedef enum sftpstat{ES_DONE=0, ES_INPROGRESS, ES_FAILED, ES_STARTING, ES_PAUSED, ES_RESUMING, ES_CANCELLED, ES_NONE } ESFTPSTAT;
using namespace std;
// Statistics about the transfer;
typedef struct transferstatstruct {
string remote_file_name;
string local_file_name;
__int64 total_size;
__int64 transferred;
__int64 averagebps;
long long seconds_elapsed;
long long seconds_remained;
int percent;
ESFTPSTAT transferstate;
} TTransStat;
#define E_SESSION_NEW -1
// These libraries are required
#pragma comment(lib, "ssh.lib")
// This is the main class that does the majority of the work
typedef class CSFTPConnector {
private:
ssh_session session; // SSH session
sftp_session sftp; // SFTP session
sftp_file file; // Structure for a remote file
FILE *localfile; // Not used on Windows, but it could be local file pointer in Unix
FILE *logfile; // The file for writing logs, default is set to stderr
string filename; // File name of the transfer;
string localfilename; // File name of local file;
string tempfilename; // A temporary file name will be used during the transfer which is renamed when transfer is completed.
ESFTPSTAT transferstatus; // State of the transfer which has one of the above values (ESFTPSTAT)
time_t transferstarttime; // Time of start of the transfer
wchar_t username[SHORT_BUFF_LEN];
wchar_t password[SHORT_BUFF_LEN];
wchar_t hostname[SHORT_BUFF_LEN]; // Hostname of the SFTP server
wchar_t basedir[SHORT_BUFF_LEN]; // This base directory is the directory of the public and private key structure (NOT USED IN THIS VERSION)
int port; // Port of the server;
int verbosity; // Degree of verbosity of libssh
__int64 filesize; // Total number of bytes to be transferred;
DWORD local_file_size_hiDWORD; // Bill Gates cannot accept the file size
// without twisting the programmers, so
// he accepts them in two separate words
// like this
DWORD local_file_size_lowDWORD; // These two DWORDs when connected together comprise a 64 bit file size.
__int64 lfilesize; // Local file size
__int64 rfilesize; // Remote file size
__int64 transferred; // Number of bytes already transferred
bool pause; // Pause flag
TTransStat stats; // Statistics of the transfer
HANDLE localfilehandle; // Windows uses handles to manipulate files. this is the handle to local file.
ESSHERR CSFTPConnector::rwopen_existing_SFTPfile(char *fn); // Open a file on remote (server) read/write for upload
ESSHERR CSFTPConnector::rdopen_existing_SFTPfile(char *fn); // Open a file on remote (server) read only for download
ESSHERR createSFTPfile(char *fn); // Create a file on server;
ESSHERR writeSFTPfile(char *block, size_t blocksize); // Write a block of data to the open remote file
ESSHERR readSFTPfile(char *block, size_t len, size_t *bytesread); // Read a block of data from the open remote file
ESSHERR readSFTPfile(char *block, __int64 len, DWORD *bytesread);
ESSHERR closeSFTPfile(); // Closes the remote file;
ESSHERR openSFTPfile(char *fn); // Opens the remote file
ESSHERR getSFTPfileinfo(); // Gets information about the remote file
public:
wstring errstring; // The string describing last error
ESSHERR Err; // Error code of last error
CSFTPConnector(); // Default constructor;
CSFTPConnector(wchar_t *dir, wchar_t *hn, int hostport, wchar_t *un, wchar_t *pass); // Constructor
void setVerbosity(int v);
int getVerbosity();
ESSHERR InitSession(); // Must be called before doing any transfer
ESSHERR ConnectSession(); // Connects to the SSH server
ESSHERR InitSFTP(); // Must be called before doing any transfer
ESSHERR Makedir(char *newdir);
ESSHERR testUploadFile(char *fn, char *block); // Do not use this, only for test purposes for myself
ESSHERR SFTPput(char *lfn, char *rfn, size_t blocksize); // Upload a file from start
ESSHERR SFTPreput(char *lfn, char *rfn, size_t blocksize); // Checks for previouse interrupted transfer, then
// either continues the previous transfer (if
// there was any) or starts a new one (UPLOAD)
ESSHERR SFTPrename(char *newname, char *oldname); // Renames a remote file( must be closed)
ESSHERR CSFTPConnector::SFTPdelete(char *remfile); // Deletes a remote file
TTransStat getStatus(); // Gets statistics of the transfer
ESSHERR CSFTPConnector::SFTPget(char *lfn, char *rfn, size_t blocksize); // Downloads a file from the SFTP server
ESSHERR CSFTPConnector::SFTPreget(char *lfn, char *rfn, size_t blocksize); // Checks for a previous interrupted transfer,
// then either continues the previous transfer
// (if there was any) or starts a new one (DOWNLOAD).
void CancelTransfer();
void PauseTransfer();
void setLogFile(FILE *logf); // Sets the log file. If not set, standard
// error will be used. By default.
void CloseLocalFile();
void CloseRemoteFile();
~CSFTPConnector();
} SFTPConnector, *pSFTPConnector;
void CSFTPConnector::CloseLocalFile()
{
CloseHandle(localfilehandle);
}
void CSFTPConnector::CloseRemoteFile()
{
sftp_close(file);
}
void CSFTPConnector::setLogFile(FILE *logf)
{
logfile = logf;
}
void CSFTPConnector::CancelTransfer()
{
transferstatus = ES_CANCELLED;
}
void CSFTPConnector::PauseTransfer()
{
transferstatus = ES_PAUSED;
pause = true;
}
//----------------------------------------
ESSHERR CSFTPConnector::SFTPget(char *lfn, char *rfn, size_t blocksize)
{
DWORD result;
int rc;
BOOL bresult;
DWORD bytesread;
filesize = 0;
transferred = 0;
pause = false;
transferstatus = ES_NONE;
char *block;
struct stat st;
wchar_t temp[SHORT_BUFF_LEN];
size_t tempsize;
wstring wlfn;
int loopcounter = 0;
localfilename = lfn;
filename = rfn;
tempfilename = string(lfn) + ".sftp_temp";
mbstowcs_s(&tempsize, temp, tempfilename.c_str(), SHORT_BUFF_LEN);
localfilehandle = CreateFile(temp, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (localfilehandle == INVALID_HANDLE_VALUE)
{
transferstatus = ES_FAILED;
errstring = L"Could not open local file:" + wstring(temp) + L" for read and write";
Err = E_LOCAL_FILE_RDWR;
return E_LOCAL_FILE_RDWR;
}
lfilesize = 0;
transferred = 0;
block = (char*)malloc(blocksize + 1);
if (block == NULL) {
Err = E_MEM_ALLOC;
transferstatus = ES_FAILED;
errstring = L"Could not allocate memory for file block size";
CloseLocalFile();
return E_MEM_ALLOC;
}
result = rdopen_existing_SFTPfile((char *)rfn);
if (result == E_OK) {
getSFTPfileinfo();
filesize = rfilesize;
}
else
{
Err = E_REMOTE_FILE_OPEN;
transferstatus = ES_FAILED;
errstring = L"Could not open remote file";
CloseLocalFile();
delete block;
return E_REMOTEFILE_SEEK;
}
transferstatus = ES_STARTING;
sftp_file_set_blocking(file);
transferstarttime = time(NULL);
transferstatus = ES_INPROGRESS;
while (transferstatus != ES_FAILED &&
transferstatus != ES_PAUSED &&
transferstatus != ES_CANCELLED &&
transferstatus != ES_DONE)
{
loopcounter++;
result = readSFTPfile(block, blocksize, (size_t *)&bytesread);
if (result != E_OK && result!= E_SFTP_READ_EOF)
{
errstring = L"Error reading from remote SFTP server file.";
Err = (ESSHERR)result;
transferstatus = ES_FAILED;
CloseRemoteFile();
CloseLocalFile();
delete block;
return (ESSHERR)result;
}
if (result == E_SFTP_READ_EOF)
transferstatus = ES_DONE;
fprintf(logfile, "Read %d bytes from input file. Number of packets: %d, %llu from %llu bytes\n", bytesread, loopcounter, transferred, filesize);
bresult = WriteFile(localfilehandle, (LPVOID)block, bytesread, &bytesread, NULL);
if (bytesread < blocksize)
{
if (bresult == FALSE)
{
errstring = L"Error writing to local file.";
Err = E_LOCAL_FILE_RDWR;
transferstatus = ES_FAILED;
CloseRemoteFile();
CloseLocalFile();
delete block;
return E_LOCAL_FILE_RDWR;
}
else if (bytesread == 0)
{
errstring = L"Transfer done.";
Err = E_OK;
transferstatus = ES_DONE;
continue;
}
}
Err = E_OK;
if (pause == true)
transferstatus = ES_PAUSED;
if (bresult == TRUE && bytesread == 0)
{
// At the end of the file
transferstatus = ES_DONE;
}
Sleep(BLOCKTRANSDELAY);
if (loopcounter % 331 == 0)
Sleep(77 * BLOCKTRANSDELAY);
if (loopcounter % 3331 == 0)
Sleep(777 * BLOCKTRANSDELAY);
}
// Closing files
result = closeSFTPfile();
CloseHandle(localfilehandle);
Sleep(1000);
if (transferstatus == ES_DONE)
{
wchar_t temp2[SHORT_BUFF_LEN];
mbstowcs_s(&tempsize, temp2, lfn, SHORT_BUFF_LEN);
bresult = MoveFile(temp, temp2);
if (bresult != TRUE)
{
Err = E_RENAME_LOCAL_FILE;
errstring = L"Could not rename local file: " + wstring(temp);
transferstatus = ES_FAILED;
delete block;
return E_RENAME_LOCAL_FILE;
}
}
if (transferstatus == ES_CANCELLED)
{
wchar_t temp2[SHORT_BUFF_LEN];
mbstowcs_s(&tempsize, temp2, lfn, SHORT_BUFF_LEN);
bresult = DeleteFile(temp);
if (bresult != TRUE)
{
Err = E_LOCAL_DELETE_FILE;
errstring = L"Could not rename local file: " + wstring(temp);
transferstatus = ES_FAILED;
delete block;
return E_LOCAL_DELETE_FILE;
}
}
delete block;
return (ESSHERR) result;
}
TTransStat CSFTPConnector::getStatus()
{
stats.seconds_elapsed = time(NULL) - transferstarttime;
stats.averagebps = (transferred * 8) / stats.seconds_elapsed;
if (filesize > 0) {
stats.percent = (transferred *100)/ filesize;
stats.seconds_remained = ((filesize - transferred) * 8) / stats.averagebps;
}
else
{
stats.percent = -1;
stats.seconds_remained = -1;
}
stats.total_size = filesize;
stats.transferstate = transferstatus;
stats.remote_file_name = filename;
stats.local_file_name = localfilename;
return stats;
}
ESSHERR CSFTPConnector::SFTPrename(char *newname, char *oldname)
{
int rc = sftp_rename(sftp, oldname, newname);
if (rc != SSH_OK) {
return E_RENAME_ERR;
}
return E_OK;
}
ESSHERR CSFTPConnector::SFTPdelete(char *remfile)
{
int rc = sftp_unlink(sftp, remfile);
if (rc != SSH_OK) {
return E_DELETE_ERR;
}
return E_OK;
}
ESSHERR CSFTPConnector::SFTPreput(char *lfn, char *rfn, size_t blocksize)
{
ESSHERR result;
BOOL bresult;
DWORD bytesread;
filesize = 0;
transferred = 0;
pause = false;
transferstatus = ES_NONE;
char *block;
struct stat st;
wchar_t temp[SHORT_BUFF_LEN];
size_t tempsize;
wstring wlfn;
int loopcounter = 0;
localfilename = lfn;
//wlfn = wstring(lfn);
//localfile = fopen(lfn, L"r");
filename = rfn;
mbstowcs_s(&tempsize, temp, lfn, SHORT_BUFF_LEN);
//filesize = getFileSize(localfilename);
/*if (filesize < 0) {
transferstatus = ES_FAILED;
Err = E_LOCAL_FILE_NOTFOUND;
return E_LOCAL_FILE_NOTFOUND;
}*/
localfilehandle = CreateFile(temp, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (localfilehandle == INVALID_HANDLE_VALUE)
{
transferstatus = ES_FAILED;
Err = E_LOCAL_FILE_NOTFOUND;
return E_LOCAL_FILE_NOTFOUND;
}
local_file_size_lowDWORD = GetFileSize(localfilehandle, &local_file_size_hiDWORD);
filesize = (local_file_size_hiDWORD * 0x100000000) + local_file_size_lowDWORD;
if (filesize < 0) {
transferstatus = ES_FAILED;
Err = E_LOCAL_FILE_NOTFOUND;
CloseLocalFile();
return E_LOCAL_FILE_NOTFOUND;
}
block = (char*)malloc(blocksize + 1);
if (block == NULL) {
Err = E_MEM_ALLOC;
transferstatus = ES_FAILED;
errstring = L"Could not allocate memory for file block size";
CloseLocalFile();
return E_MEM_ALLOC;
}
tempfilename = string(rfn) + ".sftp_temp";
result = rwopen_existing_SFTPfile((char *)tempfilename.c_str());
if (result == E_OK) {
getSFTPfileinfo();
sftp_seek64(file, rfilesize);
__int64 tempi64 = rfilesize & 0x00000000FFFFFFFF;
DWORD dwlow = tempi64;
tempi64 = (rfilesize & 0x7FFFFFFF00000000);
tempi64 = tempi64 >> 32;
long dwhi = tempi64;
DWORD dwResult = SetFilePointer(localfilehandle, dwlow, &dwhi, FILE_BEGIN);
if (dwResult == INVALID_SET_FILE_POINTER)
{
transferstatus = ES_FAILED; Err = result; return result;
}
transferstatus = ES_RESUMING;
transferred = rfilesize;
}
else{
result = createSFTPfile((char *)tempfilename.c_str());
transferstatus = ES_STARTING;
if (result != E_OK) {
transferstatus = ES_FAILED;
Err = result;
CloseLocalFile();
return result;
}
}
sftp_file_set_blocking(file);
transferstarttime = time(NULL);
transferstatus = ES_INPROGRESS;
while (transferstatus != ES_FAILED &&
transferstatus != ES_PAUSED &&
transferstatus != ES_DONE)
{
loopcounter++;
bresult = ReadFile(localfilehandle, (LPVOID)block, blocksize, &bytesread, NULL);
fprintf(logfile, "Read %d bytes from input file. Number of packets: %d, %llu from %llu bytes\n", bytesread, loopcounter, transferred, filesize);
if (bytesread < blocksize)
{
if (bresult == FALSE)
{
errstring = L"Error reading from local file.";
Err = E_LOCAL_FILE_READ;
transferstatus = ES_FAILED;
CloseRemoteFile();
CloseLocalFile();
return E_LOCAL_FILE_READ;
}
else if (bytesread == 0)
{
errstring = L"Transfer done.";
Err = E_OK;
transferstatus = ES_DONE;
continue;
}
}
result = writeSFTPfile(block, bytesread);
if (result != E_OK && bytesread>0)
{
errstring = L"Error transmitting to remote SFTP server file.";
Err = result;
transferstatus = ES_FAILED;
CloseRemoteFile();
CloseLocalFile();
return result;
}
Err = E_OK;
//transferred = transferred + bytesread;
if (pause == true)
transferstatus = ES_PAUSED;
if (bresult == TRUE && bytesread == 0)
{
// At the end of the file
transferstatus = ES_DONE;
}
Sleep(BLOCKTRANSDELAY);
if (loopcounter % 331 == 0)
Sleep(77 * BLOCKTRANSDELAY);
if (loopcounter % 3331 == 0)
Sleep(777 * BLOCKTRANSDELAY);
}
CloseRemoteFile();
CloseLocalFile();
Sleep(1000);
if (transferstatus == ES_CANCELLED)
{
result = SFTPdelete((char *)tempfilename.c_str());
if (bresult != E_OK)
{
Err = E_DELETE_ERR;
errstring = L"Could not delete remote file.";
transferstatus = ES_FAILED;
return E_DELETE_ERR;
}
}
if (transferstatus == ES_DONE)
result = SFTPrename(rfn, (char *)tempfilename.c_str());
delete block;
return result;
}
ESSHERR CSFTPConnector::getSFTPfileinfo()
{
sftp_attributes fileinf = sftp_fstat(file);
if (fileinf == NULL) {
return E_GET_FILEINF;
}
rfilesize = fileinf->size;
sftp_attributes_free(fileinf);
return E_OK;
}
ESSHERR CSFTPConnector::closeSFTPfile()
{
int rc = sftp_close(file);
if (rc != SSH_OK)
{
fprintf(logfile, "Can't close the written file: %s\n",
ssh_get_error(session));
return E_FILE_CLOSE;
}
return E_OK;
}
ESSHERR CSFTPConnector::writeSFTPfile(char *block, size_t blocksize)
{
size_t nwritten = sftp_write(file, block, blocksize);
if (nwritten != blocksize)
{
fprintf(logfile, "Can't write data to file: %s\n",
ssh_get_error(session));
//sftp_close(file);
transferred = transferred + nwritten;
return E_WRITE_ERR;
}
transferred = transferred + nwritten;
return E_OK;
}
ESSHERR CSFTPConnector::readSFTPfile(char *block, size_t len, size_t *bytesread)
{
DWORD readbytes;
*bytesread = 0;
if (len <= 0)
return E_INVALID_PARAMS;
if (bytesread == NULL || block == NULL)
return E_INVALID_PARAMS;
readbytes = sftp_read(file, block, len);
if (readbytes < 0)
{
fprintf(logfile, "Can't read from remote file: %s %s\n", filename.c_str(), ssh_get_error(session));
*bytesread = 0;
return E_SFTP_READ_ERR;
}
if (readbytes < len)
{
*bytesread = readbytes;
transferred = transferred + readbytes;
return E_SFTP_READ_EOF;
}
*bytesread = readbytes;
transferred = transferred + readbytes;
return E_OK;
}
ESSHERR CSFTPConnector::readSFTPfile(char *block, __int64 len, DWORD *bytesread)
{
DWORD readbytes;
*bytesread = 0;
if (len <= 0)
return E_INVALID_PARAMS;
if (bytesread == NULL || block == NULL)
return E_INVALID_PARAMS;
readbytes = sftp_read(file, block, len);
if (readbytes < 0)
{
fprintf(logfile, "Can't read from remote file: %s %s\n", filename.c_str(), ssh_get_error(session));
*bytesread = 0;
return E_SFTP_READ_ERR;
}
if (readbytes < len)
{
*bytesread = readbytes;
return E_SFTP_READ_EOF;
}
*bytesread = readbytes;
transferred = transferred + readbytes;
return E_OK;
}
ESSHERR CSFTPConnector::createSFTPfile(char *fn)
{
int access_type = O_CREAT | O_RDWR;
int rc, nwritten;
filename = string(fn);
file = sftp_open(sftp, fn,
access_type, S_IWRITE);
if (file == NULL)
{
fprintf(logfile, "Can't open file for writing: %s\n",
ssh_get_error(session));
return E_FILEOPEN_WRITE;
}
return E_OK;
}
ESSHERR CSFTPConnector::rdopen_existing_SFTPfile(char *fn)
{
int access_type = O_RDONLY;
int rc, nwritten;
filename = string(fn);
file = sftp_open(sftp, fn,
access_type, S_IREAD);
if (file == NULL)
{
fprintf(logfile, "Can't open file for writing: %s\n",
ssh_get_error(session));
return E_FILEOPEN_RDONLY;
}
return E_OK;
}
ESSHERR CSFTPConnector::openSFTPfile(char *fn)
{
int access_type = O_RDONLY;
int rc, nwritten;
filename = string(fn);
file = sftp_open(sftp, fn,
access_type, S_IWRITE);
if (file == NULL)
{
fprintf(logfile, "Can't open file for writing: %s\n",
ssh_get_error(session));
return E_FILE_OPEN_READ;
}
return E_OK;
}
ESSHERR CSFTPConnector::Makedir(char *newdir)
{
int rc;
rc = sftp_mkdir(sftp, newdir, S_IFDIR);
if (rc != SSH_OK)
{
if (sftp_get_error(sftp) != SSH_FX_FILE_ALREADY_EXISTS)
{
fprintf(logfile, "Can't create directory: %s\n",
ssh_get_error(session));
return E_CREATE_DIR;
}
}
return E_OK;
}
SFTPConnector::CSFTPConnector()
{
//libssh2_init(0);
session = ssh_new();
if (session == NULL)
{
Err = E_SESSION_ALOC;
errstring = L"Could not allocate a session.";
}
wcscpy(hostname, L"localhost");
wcscpy(username, L"User");
wcscpy(password, L"Password");
wcscpy(basedir, L".\\");
port = 22;
verbosity = SSH_LOG_RARE;
filesize = 0;
transferred = 0;
pause = false;
transferstatus = ES_NONE;
logfile = stderr;
}
CSFTPConnector::CSFTPConnector(wchar_t *dir, wchar_t *hn, int hostport, wchar_t *un, wchar_t *pass)
{
session = ssh_new();
if (session == NULL)
{
Err = E_SESSION_ALOC;
errstring = L"Could not allocate a session.";
}
wcscpy(hostname, hn);
wcscpy(username, un);
wcscpy(password, pass);
wcscpy(basedir, dir);
port = hostport;
verbosity = SSH_LOG_RARE;
filesize = 0;
transferred = 0;
pause = false;
transferstatus = ES_NONE;
logfile = stderr;
}
ESSHERR CSFTPConnector::InitSFTP()
{
int rc;
sftp = sftp_new(session);
if (session == NULL)
{
Err = E_SFTP_ALLOC;
errstring = L"Could not allocate a sftp session.";
}
rc = sftp_init(sftp);
if (rc != SSH_OK)
{
fprintf(logfile, "Error initializing SFTP session: %s.\n",
sftp_get_error(sftp));
sftp_free(sftp);
return E_INIT_SFTP;
}
return E_OK;
}
ESSHERR CSFTPConnector::ConnectSession()
{
char temp[SHORT_BUFF_LEN];
size_t n_of_chars;
wcstombs_s(&n_of_chars, temp, SHORT_BUFF_LEN, (const wchar_t *)password, SHORT_BUFF_LEN);
int ir;
ir = ssh_connect(session);
if (ir != SSH_OK) {
errstring = L"Could not connect the ssh session.";
return E_SSH_CONNECT_ERR;
}
ir = ssh_userauth_password(session, NULL, temp);
if (ir != SSH_OK) {
errstring = L"Could not connect the ssh session.";
return E_SSH_CONNECT_ERR;
}
return E_OK;
}
ESSHERR CSFTPConnector::InitSession()
{
char temp[SHORT_BUFF_LEN];
size_t n_of_chars;
wcstombs_s(&n_of_chars, temp, SHORT_BUFF_LEN, (const wchar_t *) hostname, SHORT_BUFF_LEN);
ssh_options_set(session, SSH_OPTIONS_HOST, temp);
ssh_options_set(session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);
ssh_options_set(session, SSH_OPTIONS_PORT, &port);
wcstombs_s(&n_of_chars, temp, SHORT_BUFF_LEN, (const wchar_t *)username, SHORT_BUFF_LEN);
ssh_options_set(session, SSH_OPTIONS_USER, temp);
wcstombs_s(&n_of_chars, temp, SHORT_BUFF_LEN, (const wchar_t *)basedir, SHORT_BUFF_LEN);
ssh_options_set(session, SSH_OPTIONS_SSH_DIR, temp);
return E_OK;
}
CSFTPConnector::~CSFTPConnector()
{
sftp_free(sftp);
ssh_disconnect(session);
ssh_free(session);
return;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Which Dynamic .NET language makes more sense to learn, Iron Ruby or Iron Python? I'd like to take some time to learn more about dynamic languages built on top of the DLR and I'm not sure which language would be better to learn.
Having limited time, I really only have time to look learn one of them.
Any opinions on which of the two (Iron Ruby or Iron Python) would be more useful in the long run?
A: Without getting into the relative merits of the languages (which would be an entire pissing contest in itself), IronPython (stable 1.1.1, beta 2.0) is further along in development than IronRuby (alpha)
A: If this is 'Which language runs better on the CLR,' then right now, IronPython wins hands down.
For the long term though, 'which language will teach me more, and serve me better in my career as a programmer', I would definitely say IronRuby (this would be true of CPython vs CRuby also)
Ruby will expose you to more 'concepts' than python does, due to it being more liberal in how it handles things like lambda functions, code blocks, eval, and so on.
Anyway, this is probably going to descend into a flame-war. Sorry
A: Whichever you choose, take a look at IronEditor -- it's great for playing around. I'm currently using it to try and pick up those languages myself...
A: I would go for IronPython at the moment since there are plenty of books/information around for it (IronPython In Action is just getting finished up).
I would personally learn IronRuby because I prefer the way Ruby works over Python and since it's one of the same then choose which language you prefer.
A: I just want to mention that there is also a DLR version of Javascript(JScript), which is my personal fav. If you are looking for a new language to learn for dlr use, I'd suggest ironpython as mentioned, it is farther along in terms of the dlr. Python is also fairly popular outside the dlr for gui programming, and offers Django for mvc web apps.
This is purely subjective, but I think that ruby popularity is waning a bit. In the long run I feel it will be like perl, used and respected, but a drop in the bucket compared to other options. I happen to really like ruby (and perl), but wouldn't suggest it as a new path for your intended purpose.
A: As other said, IronPython is more stable and mature, and you can find more samples and lots of regular Python code that you will be able to try out.
IronRuby is great but beware: to try it you need to get the code right from the SVN and compile it by yourself. Or you can download the Dynamic Silverlight SDK and get it that way, but you'll have to spend sometime learning this environment also.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Best way to get user input for a menu-driven CLI in C What's the best way to get user input in a C program where the choices are of a limited number?
Say for example the choices are:
A) Print the list.
B) Add 99 to the end of the list.
C) Delete all duplicates.
5) Reset 5 times.
Entering "A" and then Enter is OK.
Or, just a single keystroke would work as well.
A: getchar(), or cgetc(), depending on the platform
A: I have used something simple like the following:
int intput()
{
char input = 0;
int ret_val = 0;
read(0, &input, 1);
switch(input) {
case 'c':
// Do c
break;
case 'p':
// Do p
break;
case 'd':
// Do d
break;
case 'q':
quit = 1;
break;
case '?':
PRINT(ENABLE, "c - connect\n");
PRINT(ENABLE, "p - ping\n");
PRINT(ENABLE, "d - disconnect\n");
PRINT(ENABLE, "q - quit\n");
PRINT(ENABLE, "? - this message\n");
break;
}
return 0;
}
A: Instead of using
switch(input)
use...
switch (toupper(input))
{
case 'A':
This will allow the user to enter 'a' or 'A' and saves you having to check for upper and lower case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: sp_send_dbmail attachment encoding I am using sp_send_dbmail in SQL2005 to send an email with the results in an attachment. When the attachment is sent it is UCS-2 Encoded, I want it to be ANSI or UTF-8.
Here is the SQL
EXEC msdb.dbo.sp_send_dbmail
@recipients = '[email protected]'
, @query = 'DECLARE @string_to_trim varchar(60);SET @string_to_trim = ''1234''; select rtrim(@string_to_trim), ''tom'''
, @query_result_header=0
, @subject = 'see attach'
, @body= 'temp body'
, @profile_name= N'wksql01tAdmin'
, @body_format = 'HTML'
,@query_result_separator = ','
,@query_attachment_filename = 'results.csv'
,@query_no_truncate = '0'
,@attach_query_result_as_file = 1
I have seen some comments on the internet that this is fixed with sql2005 SP2, but do not find it to be the case.
A: After some research on SQL Server 2008 R2:
*
*Add to sp_send_dbmail:
@ANSI_Attachment BIT = 0
WITH EXECUTE AS 'dbo'
*Replace
IF(@AttachmentsExist = 1)
BEGIN
.......
END
with:
IF(@AttachmentsExist = 1)
BEGIN
if (@ANSI_Attachment = 1)
begin
--Copy temp attachments to sysmail_attachments
INSERT INTO sysmail_attachments(mailitem_id, filename, filesize, attachment)
SELECT @mailitem_id, filename, filesize,
convert(varbinary(max),
substring( -- remove BOM mark from unicode
convert(varchar(max), CONVERT (nvarchar(max), attachment)),
2, DATALENGTH(attachment)/2
)
)
FROM sysmail_attachments_transfer
WHERE uid = @temp_table_uid
end else begin
--Copy temp attachments to sysmail_attachments
INSERT INTO sysmail_attachments(mailitem_id, filename, filesize, attachment)
SELECT @mailitem_id, filename, filesize, attachment
FROM sysmail_attachments_transfer
WHERE uid = @temp_table_uid
end
END
A: I think the only way to get around what you are seeing is to use BCP to dump the data to a flat file and then attach that file. Sorry I couldn't be more help. :(
A: In order to have the file be ANSI/UTF-8
alter the sp_send_dbmail that lives in the msdb with this line along with the other variables: @ANSI_Attachment BIT = 0
i.e.
@mailitem_id INT = NULL OUTPUT,
@ANSI_Attachment BIT = 0
WITH EXECUTE AS 'dbo'
and then add this line to your call to sp_send_dbmail:
@ansi_attachment = 1
then it should give you an ansi attachment instead of unicode.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Dependency Injection Addiction? Is there a down side? I feel almost dependent on it now. Whenever a project gets past a certain size almost feel an allergic reaction to standard patterns and immediately re-wire it with a Dependency Injection framework.
The largest issue I've found is it can be confusing for other developers who are just learning it.
Also, I'd feel much better if it were a part of the language I was using. Though, for Java at least, there are a couple very lightweight libraries which are quite good.
Thoughts? Bad experiences? Or just stop worrying about it?
[EDIT] Re: Description of Dependency Injection itself
Sorry for being vague. Martin Fowler probably describes it FAR better than I ever could... no need to waste the effort.
Coincidentally, this confirms one point about it, that it's still not widely practiced and might tend to be a barrier when working with teams if everyone is not up to speed on it.
A: The problem I have with DI is the same problem I have with COM and with any code that looks something like:
i = GetServiceOrInterfaceOrObject(...)
The problem is that such a system cannot be understood from the code. There must be documentation somewhere [else] that defines what service/interface/object can be requested by service/interface/object X. This documention must not only be maintained, but available as easily as the source.
Unless the document is very well written, it's often still not easy to see the relationships between objects. Sometimes relationships are temporal which makes them even harder to discover.
I like the KISS principle, and I'm a strong believer in using the right tool for the job. If the benefit of DI, for a given project, outweighs the need to write comprehensible code, than use it.
A: I am big beleaver in IO however I saw some projects with huge xml configuration files which no one understand. So beware of programming in xml.
A:
Also, I'd feel much better if it were
a part of the language I was using.
FYI there is a very simple and functional dependecy injection as part of JDK 6. If you need lightweight, straightforward dependency injection, then use it.
Using ServiceLoader class you can request a service (or many implementations of the service) based on a class:
package dependecyinjection;
import java.util.ServiceLoader;
public abstract class FooService {
public static FooService getService() {
ServiceLoader<FooService> loader = ServiceLoader.load(FooService.class);
for (FooService service : loader) {
return provider;
}
throw new Exception ("No service");
}
public abstract int fooOperation();
}
package dependecyinjection;
public class FooImpl extends FooService {
@Override
public int fooOperation() {
return 2;
}
}
How does ServiceLoader defines the service implementations that are returned?
In your project folder create a folder named META-INF/services and create a file named dependencyinjection.FooService. This file contain a line pointing to the service implementation. In that case: dependecyinjection.FooImpl
This is not widely known yet.
A: In my opinion, the major drawbacks are the learning curve (as you point out) and the potential for the added abstraction to make it more difficult to debug (which is really part of the learning curve as well).
To me, DI seems to me to be more appropriate for larger, complex systems -- for small one-off apps, it may result in the app being over-architected, basically, having the architecture take more development time to adhere to than it can ever make up for in the value it provides.
A: Just stop worrying about it. It's my opinion that in time IoC techniques will be second nature to most developers. I'm trying to teach devs here at work about it and I find it difficult to get the message across because it feels so unnatural to the way we've always done things.. which just so happened to have been the wrong way. Also, developers both new to IoC and new to a project I find have an even more hard time. They're use to using the IDE to follow the trail of dependencies to gain an understanding of how the whole thing "hangs together". That information is often written into arcane XML.
A: Could you add a link or two to explain what Dependency Injection actually is, for those of us playing along at home? The wikipedia article is entertaining, but not very enlightening.
A: I've taken a stab at describing some of the possible downsides in a blog post here: http://kevin-berridge.blogspot.com/2008/06/ioc-and-di-complexity.html
A: The only down side I can think of is tiny performance decrease through constant virtual calls :)
A: @Blorgbeard: http://www.martinfowler.com/articles/injection.html is probably one of the best articles on the subject
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Efficient synthesis of a 4-to-1 function in Verilog I need to implement a 4-to-1 function in Veriog. The input is 4 bits, a number from 0-15. The output is a single bit, 0 or 1. Each input gives a different output and the mapping from inputs to outputs is known, but the inputs and outputs themselves are not. I want vcs to successfully optimizing the code and also have it be as short/neat as possible. My solution so far:
wire [3:0] a;
wire b;
wire [15:0] c;
assign c = 16'b0100110010111010; //for example but could be any constant
assign b = c[a];
Having to declare c is ugly and I don't know if vcs will recognize the K-map there. Will this work as well as a case statement or an assignment in conjunctive normal form?
A: What you have is fine. A case statement would also work equally well. It's just a matter of how expressive you wish to be.
Your solution, indexing, works fine if the select encodings don't have any special meaning (a memory address selector for example). If the select encodings do have some special semantic meaning to you the designer (and there aren't too many of them), then go with a case statement and enums.
Synthesis wise, it doesn't matter which one you use. Any decent synthesis tool will produce the same result.
A: I totally agree with Dallas. Use a case statement - it makes your intent clearer. The synthesis tool will build it as a look-up table (if it's parallel) and will optimise whatever it can.
Also, I wouldn't worry so much about keeping your RTL code short. I'd shoot for clarity first. Synthesis tools are cleverer than you think...
A: My preference - if it makes sense for your problem - is for a case statement that makes use of enums or `defines. Anything to make code review, maintenance and verification easier.
A: For things like this, RTL clarity trumps all by a wide margin. SystemVerilog has special always block directives to make it clear when the block should synthesize to combinational logic, latches, or flops (and your synthesis tool should throw an error if you've written RTL that conflicts with that (e.g. not including all signals in the sensitivity list of an always block). Also be aware that the tool will probably replace whatever encoding you have with the most hardware-efficient encoding (the one that minimizes the area of your total design), unless the encoding itself propagates out to the pins of your top-level module.
This advice goes in general, as well. Make your code easy to understand by humans, and it will probably be more understandable to the synthesis tool as well, which allows it to more effectively bring literally thousands of man-years of algorithms research to bear on your RTL.
You can also code it using ternary operators if you like, but i'd prefer something like:
always_comb //or "always @*" if you don't have an SV-enabled tool flow
begin
case(a)
begin
4'b0000: b = 1'b0;
4'b0001: b = 1'b1;
...
4'b1111: b = 1'b0;
//If you don't specify a "default" clause, your synthesis tool
//Should scream at you if you didn't specify all cases,
//Which is a good thing (tm)
endcase //a
end //always
A: Apparently I am using a lousy synthesis tool. :-) I just synthesized both versions (just the module using a model based on fan-outs for wire delays) and the indexing version from the question gave better timing and area results than the case statements. Using Synopsys DC Z-2007.03-SP.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Override Working Folder with Starteam/CruiseControl For some reason, I can't seem to get CruiseControl.net to checkout code to anywhere but the starteam working folder for a specificed view.
I've tried both overrideViewWorkingDir and overrideFolderWorkingDir, and neither seem to work.
Has anyone been able to do this?
A: Are you looking for the project's workingDirectory element instead of the starteam override?
A: <sourcecontrol type="starteam">
<executable>C:\Program Files\starbase\StarTeam 5.4\stcmd.exe</executable>
<project>ProjectName/ViewName</project>
<username>UserName</username>
<password>Password</password>
<host>127.0.0.1</host>
<port>49201</port>
<autoGetSource>true</autoGetSource>
<overrideViewWorkingDir>C:\temp\ProjectName</overrideViewWorkingDir>
</sourcecontrol>
A: Works fine for me with ccnet 1.4.3 and Startem Cross-Platform Client 2008 R2. Make sure XML is valid. I had overrideViewWorkingDir tag not properly closed and ccnet was ignoring it. Found it by running ccnet.exe from the command line instead of as a service. Also you can use Process Explorer from SysInternals to view command line arguments passed to stcmd.exe
A: Make sure your working folder properties are set to a relative and not a full path (ex: MyFolder instead of C:\MyProject\MyFolder) or it will override the override. I've seen files checked out to some very odd places in the past when people mistakenly put in full paths when adding a folder to a view.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to catch unhandled exceptions when using .NET Remoting I want to catch all unhandled exceptions thrown in a remote object on the server and log them there before I translate them into some custom exception so that specific exceptions do not cross the client/server boundary.
I think I have to use a custom channel sync, but can anyone confirm this and/or have any other advice to give?
A: I would use the Microsoft Enterprise Library Exception Handling app block -- it lets you handle errors and convert specific types of exception to a different type of exception before rethrowing to the client.
A: After finding Eliyahu Baker's helpful blog post and reading chapter 12 of Rammer's Advanced .NET Remoting I wrote a custom channel sink that does what I want. This intercepts any exception and logs it locally before sending it on to the client.
Ideally, I'd like to log the exception and raise a more generic one for the client, but I haven't cracked that nut yet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is WCF in simple terms? What is WCF in simple terms?
It's hard to distill the meaning from the Wikipedia page.
A: WCF allows you to create "services" without specifying that it's a Windows service or a Web service, or which protocols are used to communicate with it or how the data is serialized.
All those details may be specified externally, either programmatically in a service host or via the config file.
A: I would recommed you to read about Indigo (the first WCF name). This is the case when an old article can explain the definition better than wikipedia.
Here is the complete article.
"Indigo," Microsoft's unified programming model for building
service-oriented applications.
But what does "service-oriented" mean?
Choosing the best abstractions for building software is an ongoing
process. Objects are the dominant approach today for building an
application's business logic, but modeling application-to-application
communication using objects hasn't been as successful. A better
approach is to explicitly model interactions between discrete chunks
of software as services.
Plenty of support already (2005) exists for building object-oriented applications, but thinking of services as a fundamental software building block is a more recent idea. Because of this, technologies explicitly designed to create service-oriented applications haven't been widely available.
1. Indigo is also a combination of 5 techonologies.
All of these options had value, yet the diversity was certainly confusing to developers. Why have so many choices? A better solution would be to have one technology that addresses all of these problems. That is WCF.
2. Interoperability with Non-Microsoft Applications
Making life easier for Windows developers by unifying disparate technologies is a good thing. But with the universal agreement among vendors on Web services, the long-standing problem of application interoperability can also be solved. (example is communication of .NET windows application with Java application on Linux or other operating systems).
A: WCF stands for Windows Communication Foundation. It's Microsoft's attempt to sort out and simplify network programming. It provides an easy to use level of abstraction over different communication protocols and transportation methods. It allows you to concentrate more on what you want to implement rather than thinking on how to implement it. Read Microsoft's WCF FAQ for more info.
A: WCF - Windows Communication Framework - is Microsoft's framework to make inter-process communication easier. It let's you do this communication through various means, plain old asmx web services, Remoting, MS Message Queuing, and a couple more.
It let's you talk with other .NET apps, or non-Microsoft technologies (like J2EE). It's extensible enough to allow for newer stuff, like REST too (I don't think REST is built-in).
A: WCF is Microsoft's new .NET do-all extensible communications framework meant to replace functionality previously available in DCOM, .NET Remoting and ASMX web services.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: Does the Iphone 1/2 have a compass inside? Can one be simulated by periodicly syncing with GPS and in the meen while working with the accelerometer? I know for example that the N95 accelerometer is invarient to rotation on the Y axis (while beeing face up/down).
A: The original iPhone and the iPhone 3G use GPS to calculate the heading, however the iPhone 3GS now has a 3-dimensional magnetometer compass in it.
This can only be done taking two GPS coordinates (while moving) and determining the direction from point A to B.
A: iPhone doesn't have a built in compass; but there is one created in software. It's called Compass Free, and unsurprisingly perhaps, it's free.
A: Extra info: The IPHONE 1 did not have GPS or compass.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I get markdown to format this code properly? Here is some code I could not get to format properly in markdown, this is straight C code, pasted into the text box with the '4 spaces' format to denote code:
#define PRINT(x, format, ...) \
if ( x ) { \
if ( debug_fd != NULL ) { \
fprintf(debug_fd, format, ##__VA_ARGS__); \
} \
else { \
fprintf(stdout, format, ##__VA_ARGS__); \
} \
}
It seems as though the '\' causes the newlines to be ignored. Ok fine, I am used to this in bash, but if I put '\' the second one doesn't show up. As if the second one is absorbed. Am I missing something?
A: Add at least four spaces or a hard tab before each line of the code. Like this:
#define PRINT(x, format, ...) \
if ( x ) { \
if ( debug_fd != NULL ) { \
fprintf(debug_fd, format, ##VA_ARGS); \
} \
else { \
fprintf(stdout, format, ##VA_ARGS); \
} \
}
A: You can also use the HTML tags <pre><code> in succession. I find this easier for pasting code into the window.
#define PRINT(x, format, ...)
if ( x )
{
if ( debug_fd != NULL )
{
fprintf(debug_fd, format, ##VA_ARGS);
}
else
{
fprintf(stdout, format, ##VA_ARGS);
}
}
A: #define PRINT(x, format, ...)
if ( x )
{
if ( debug_fd != NULL )
{
fprintf(debug_fd, format, ##VA_ARGS);
}
else
{
fprintf(stdout, format, ##VA_ARGS);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a max number of options (values) in HTML drop down control? Does anyone know how many options a drop down list can have? Is it unlimited? How many before performance degrades?
A: I've used right around 500 in a list with no noticeable performance impact if that helps!
A: Yes, the maximum for Chrome and Safari is 10000 items for select elements at least.
The relevant lines in the Chrome source can be found here:
Defined max of 10000, Code that enforces limit and puts error in console
Firefox seems to have no practical limit from my testing.
A: In my experience the performance degradation is generally on the side of the user, my golden rule (learned somewhere) is seven options, give or take a few.
On a more SW related basis, probably the top range of Integer.
EDIT: BTW This is kind of relevant from Atwood
A:
Does anyone know how many options a drop down list can have? Is it unlimited?
I imagine it is unlimited in theory, obviously not in practice as a computer's RAM and the specific browser's limitations come into play.
How many before performance degrades?
Again, this would depend on a few factors, at the least the specific browser, the computer's memory and processing power.
EDIT: From experience, I have had drop down lists with thousands of options. It wasn't ideal though because who wants to scroll through all of those? This is why an auto-complete of some type is more desirable for numerous reasons, especially the end user's experience.
A: Update: Based on DannyG, tested on Ubuntu with Firefox on a 4GB mem pc, limit was far beyond 10k tags. My current Firefox is set to use up to 3GB and it has reached a 100k options, but for that, you'd have to change the default config of the browser I guess.
We opted to use an Ajax autocomplete as replacement in all cases that 30+ options where given.
Both Firefox and Chrome limited to 10k options in Windows 64b with 4GB ram on default config.
Tested with JSFiddle
http://jsfiddle.net/Mare6/
for (var i=0; i<10000; i++) {
var name = "Option "+i;
var sel = document.getElementById("list");
sel.options[sel.options.length] = new Option(name,i);
}
<a>Testing Select</a>
<select id="list"></select>
Regards,
A: In theory, there is no limit, but some browsers will implement limits. (Similar to using document.write in an infinite loop.)
But, at the end of the day, the most I would ever recommend in a drop-down-list, is about 50, just because no-one wants to do that much scrolling. That said, if organized, say by alphabetical order, it may be appropriate to have as many as 200 items in a drop-down-list. (Like for a sign-up form where you must select you country of birth.)
Also, when you have many different set choices, a drop-down-list is normally the best option, regardless.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: Writing/Using C++ Libraries I am looking for basic examples/tutorials on:
*
*How to write/compile libraries in C++ (.so files for Linux, .dll files for Windows).
*How to import and use those libraries in other code.
A: The code
r.cc :
#include "t.h"
int main()
{
f();
return 0;
}
t.h :
void f();
t.cc :
#include<iostream>
#include "t.h"
void f()
{
std::cout << "OH HAI. I'M F." << std::endl;
}
But how, how, how?!
~$ g++ -fpic -c t.cc # get t.o
~$ g++ -shared -o t.so t.o # get t.so
~$ export LD_LIBRARY_PATH="." # make sure t.so is found when dynamically linked
~$ g++ r.cc t.so # get an executable
The export step is not needed if you install the shared library somewhere along the global library path.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How can I disable a hotkey in GreaseMonkey while editing? I'm using Ctrl+Left / Ctrl+Right in a GreaseMonkey script as a hotkey to turn back / forward pages. It seems to works fine, but I want to disable this behavior if I'm in a text edit area. I'm trying to use document.activeElement to get the page active element and test if it's an editable area, but it always returns "undefined".
A: document.activeElement works for me in FF3 but the following also works
(function() {
var myActiveElement;
document.onkeypress = function(event) {
if ((myActiveElement || document.activeElement || {}).tagName != 'INPUT')
// do your magic
};
if (!document.activeElement) {
var elements = document.getElementsByTagName('input');
for(var i=0; i<elements.length; i++) {
elements[i].addEventListener('focus',function() {
myActiveElement = this;
},false);
elements[i].addEventListener('blur',function() {
myActiveElement = null;
},false);
}
}
})();
A: element.activeElement is part of HTML5 spec but is not supported by most browsers. It was first introduced by IE.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Which Perl database interface should I use? Is CPAN DBI the best database interface to use in Perl for general database use? Are there some better options?
A: It's worth pointing out that the vast majority of the "higher-level" interfaces (like SQL::Abstract) and (DBIx::Simple) use DBI itself when actually performing the queries. DBI is pretty much the accepted standard method for database connection in Perl.
A: If you want to work with objects (with introspection!), take a look at Fey::ORM which implements ORM based on Moose. It's also has very SQL like syntax so it fits my RDBMS-based brain a bit better than some of other ORM frameworks.
A: If you're just looking for low-level database access—you feed it any SQL string (optionally with place-holders and bind values) and it runs your query and gives you back the results—then yes, DBI is your best bet, by far.
If you want a higher-level interface (i.e., one that requires little or no use of raw SQL in your code) then there are several ORMs (object-relational mappers) available for Perl. Check out the ORM page at the Perl Foundation's Perl 5 wiki for more information and links. (If you want help choosing among them or have specific questions, you could narrow the focus of this question or perhaps post another one.)
A: DBI is the "low level" interface between Perl and an DBMS. It's pretty much the only realistic choice for doing that. Comparable to JDBC in Java. You would be crazy (or have a very specific use case) to pick anything other than DBI for you low level interface between Perl and a database.
On top of DBI, there are various object/relational mappers which make working with a database much easier and cleaner.
Some of the common/more popular ones are
*
*DBIx::Class
*Class::DBI
*Rose::DB::Object
A: If you chose to use plain DBI for a task that doesn't need an ORM, I
strongly suggest you take a look at DBIx::Simple.
It's not a replacement, but a very well designed API on top of DBI
that makes simple things simple and complex things possible, without
losing any of the flexibilty of DBI.
Did you ever found you had to look up apparently simple things in the DBI
documentation, like getting the results of a query as an arrayref (rows)
of hashes (columns and their values)?
With DBIx::Simple this is straightforward:
# DBI
my $rows = $dbh->selectall_arrayref($sql, { Slice => {} });
# tell it we want "hashes" (yuck!) ^^^^
# DBIx::Simple
my $rows = $db->query($sql)->hashes; # does the same as the above code underneath!
Take a look at the examples for more. Also, the integration with SQL::Abstract makes simple queries a breeze. It use it in all of my code where I would have used DBI before, and
I'm not looking back.
A: Have a look at Class::DBI as well.
A: In my opinion, DBI is a really good choice. I've used DBD::mysql actively and found it to be a really good solution.
A: We use the DBI module in all of our projects as well. Many times we build a custom package on top of it for the specific application but underneath that is the core DBI module. And often it is just easier to use the DBI module functions directly.
A: DBI is great, but the quality of the DBD modules can vary. I was bitten by a 'feature' in one of the versions of DBD:pg. It liked to load the full data of your result into memory, rather than interate over it with cursors.
As per usual - Caveat programmor.
A: DBI rocks! but for a proper fully-featured ORM that is fast go for DBIx::Class all the time.
A: Basically you should be used to using only DBI firstly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: How do you retrofit unit tests into a code base? Do you have any strategies for retrofitting unit tests onto a code base that currently has no unit tests ?
A: The best way to retrofit an existing project without any unit tests is to do it when fixing bugs. Write a test that fails on the logic that has the bug in it with the steps to reproduce the bug. Then refactor the code until the tests pass. Now you can have confidence that the bug is fixed and it will not be introduced later on in the cycle and you started introducing unit tests into the project.
A: Here's another great article on testing. In particular, a somewhat relevant quote from it:
Here’s a terrible idea - decide you are going to spend a whole week building a test suite for your project. First of all, you’ll likely just get frustrated and burn out on testing. Secondly, you’ll probably write bad tests at first, so even if you get a bunch of tests written, you’re going to need to go back and rewrite them one you figure out how slow, brittle, or unreadable they are.
I think you are better off building tests 1 at a time as you are fixing bugs or adding new functionality... don't try to build missing test cases, you should have an end goal for each test, rather than just to improve coverage.
A: Dale gets voted up. Yes, there is no gain for adding unit tests to code that's working. Lets say there are two unknown bugs X & Y. At some point X is revealed by typical field use. You fix it, add a unit test, and move on. Now lets assume Y is never uncovered over the entire lifetime of the program. Since Y never revealed itself it's as if it never existed; no need to waste the resources. Multiply this by hundreds or thousands of dormant bugs and you save yourself a great deal of superfluous maintenance.
A: If ever you are trying to add unit tests to old perl code I strongly recommend
Perl Testing: A Developer's Notebook by Ian Langworth and chromatic.
It has some very nice trick on testing legacy and "untestable" code.
A: Why do you want to add unit tests? Do you feel the code has bugs? Do you just want something to do? Are you about to embark on a new feature?
If it is an older product that has been released for quite some time then I'd agree with the others and only add the tests when I find a bug or add a new feature.
If it is a product that is still being developed and not released or only recently released, then I'd start by reviewing the code. If I saw something not quite right then I'd add a test for it. I'd probably make some tests to create some sample data. Creating sample data seems to offer quite a bang for your buck, and it can be useful too.
I think there is benefit to writing the tests even when you don't have a bug to test - when you're adding new features or fixing bugs later, your tests confirm that you haven't introduced new bugs.
A: Read Working Effectively With Legacy Code by Feathers.
Jimmy Bogard has a good blog series on SOC.
A: Is it possible that we are in a panic and are getting confused between unit tests and performance tests? Is it that your application works fine with few users, but starts throwing errors when under heavier load? If so, unit tests are not the answer. Unit tests != Load tests.
If unit tests are in fact the answer, retrofitting unit tests is a good idea as it will help clean up the code. Just be prepared to refactor a lot. Code written with TDD turns out looking a lot different than code written without TDD. In my case, I had a method HandleDisposition() which took care of a lot of cases. This kind of method would not have existed if we had written the code with TDD. When retrofitting unit tests, we refactored that function and now have methods like XDisposition(), YDisposition(), ZDisposition(), which are a lot easier to write unit tests against.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: GUI design techniques to enhance user experience What techniques do you know\use to create user-friendly GUI ?
I can name following techniques that I find especially useful:
*
*Non-blocking notifications (floating dialogs like in Firefox3 or Vista's pop-up messages in tray area)
*Absence of "Save" button
MS OneNote as an example.
IM clients can save conversation history automatically
*Integrated search
Search not only through help files but rather make UI elements searchable.
Vista made a good step toward such GUI.
Scout addin Microsoft Office was a really great idea.
*Context oriented UI (Ribbon bar in MS Office 2007)
Do you implement something like listed techniques in your software?
Edit:
As Ryan P mentioned, one of the best way to create usable app is to put yourself in user's place. I totally agree with it, but what I want to see in this topic is specific techniques (like those I mentioned above) rather than general recommendations.
A: A useful technique which I never see anyone use is to add a tooltip for a disabled UI control explaining why the control is disabled. So if there's a listbox which is disabled and it's not clear why it is disabled, I want to hover over it and it tells me why it's disabled. I want to see something like "It's disabled because two textboxes on the screen were left blank or because I didn't enter enough characters in some field or because I didn't make a certain action.".
I get into sooooo many such situations and it's frustrating. Sometimes I end up posting in the software's forum asking why a control is greyed out when a tooltip could have helped me in a second! Most of these software have help files which are useless in these kinds of scenarios.
Try to pretend you know nothing about your software and try using it. However this is not practical because you already have a certain mind set towards the app. So watch fellow developers or friends use the app and look out for the pain points and ask for feedback.
A: One of the classic books to help you think about design is "The Design of Everyday Things" by Donald Norman. He gives great real-world examples. For example, if you design a door well, you should never have to add labels that say "push" and "pull." If you want them to pull, put a handle; if you want them to push, put a flat plate. There's no way to do it wrong, and they don't even have to think about it.
This is a good goal: make things obvious. So obvious that it never occurs to the user to do the wrong thing. If there are four knobs on a stove, each one next to an eye, it's obvious that each knob controls the eye it's next to. If the knobs are in a straight line, all on the left side, you have to label them and the user has to stop and think. Bad design. Don't make them think.
Another principle: if the user does make a mistake, it should be very easy to undo. Google's image software, Picasa, is a good example. You can crop, recolor, and touch up your photos all you like, and if you ever change your mind - even a month later - you can undo your changes. Even if you explicitly save your changes, Picasa makes a backup. This frees up the user to play and explore, because you're not going to hurt anything.
A: If you do give the user a question, don't make it a yes/no question. Take the time to make a new form and put the verbs as choices like in mac.
For example:
Would you like to save?
Yes No
Should Be:
Would you like to save?
Save Don't Save
There is a more detailed explanation here.
A: I've found UI Patterns to be a useful reference for this sort of thing. It's arranged much like the classic GoF Design Patterns book, with each pattern description containing:
*
*The problem the pattern solves
*An example of the pattern in action
*Sample use cases for the pattern
*The solution to implement the pattern
*Rationale for the solution
A: Check out the great book Don't make me think by Steve Krug.
It's web focused but many of the conepts can apply to anything from blenders to car dashboards.
Topics covered:
*
*User patterns
*Designing for scanning
*Wise use of copy
*Navigation design
*Home page layout
*Usability testing
He also has a blog called Advanced Common Sense
And some random UI related links:
- User Interface Design for Programmers by Joel Spolsky
- 10 Usability Nightmares You Should Be Aware Of
A: If you implement a search, make it a live search like what Locate32 and Google Suggest does now. I am so used to not pressing "Enter" at the search box now.
A: Well, one thing that may be obvious: don't change (even slightly) the position, color, font size, etc. of buttons, menus, links, etc. between screens if they do the same type of action.
A: Really good feedback is extremely important. Even simple things like making it obvious what can and cannot be clicked can be overlooked or too subtle. Feedback when something might happen in the background is great. In gmail, it's great that there's a status ribbon appearing at the top that let's you know if something is sending or loading, but it's even better that it lets you know that something has sent successfully or is still loading.
The "yellow fade" technique is something else made popular amongst the RoR crowd that accomplishes something similar. You never want the user to ask the question, "What just happened?" or "What will happen when I do this?".
Another trick that has become more popular lately that I've been using a lot is editing in place. Instead of having a view of some data with a separate "edit" screen (or skipping the view and only having an edit screen), it can often be more user friendly to have a nicely laid out view of some data and just click to edit parts of it. This technique is really only appropriate when reading the data happens more often than editing, and is not appropriate for serious data-entry.
A:
First Principles: Wilfred James Hansen
*
*Know the User
*Minimize Memorization
*Optimize Operations
*Engineer for Errors
Subsequent Expansions: Dr. Theo Mandel
Place Users in Control
*
*Use Modes Judiciously (modeless)
*Allow Users to use either the Keyboard or Mouse (flexible)
*Allow Users to Change Focus (interruptible)
*Display Descriptive Messages and Text (helpful)
*Provide Immediate and Reversible Actions, and Feedback (forgiving)
*Provide meaningful Paths and Exits (navigable)
*Accommodate Users with Different Skill Levels (accessible)
*Make the User Interface Transparent (facilitative)
*Allow Users to Customize the Interface (preferences)
*Allow Users to Directly Manipulate Interface Objects (interactive)
Reduce Users' Memory Load
*
*Relieve Short-term Memory (remember)
*Rely on Recognition, not Recall (recognition)
*Provide Visual Cues (inform)
*Provide Defaults, Undo, and Redo (forgiving)
*Provide Interface Shortcuts (frequency)
*Promote an Object-action Syntax (intuitive)
*Use Real-world Metaphors (transfer)
*User Progressive Disclosure (context)
*Promote Visual Clarity (organize)
Make the Interface Consistent
*
*Sustain the Context of Users’ Tasks (continuity)
*Maintain Consistency within and across Products (experience)
*Keep Interaction Results the Same (expectations)
*Provide Aesthetic Appeal and Integrity (attitude)
*Encourage Exploration (predictable)
A: To add to your list, aku, I would put explorability as one of my highest priorities. Basically, I want the user to feel safe trying out the features. They should never back away from using something for fear that their action might be irreversible. Most commonly, this is implemented using undo/redo commands, but other options are no doubt available e.g. automatic backups.
Also, for applications that are more process-oriented (rather than data-entry applications), I would consider implementing an interface that guide the user a bit more. Microsoft's Inductive User Interface guidelines can help here, although you need to be very careful not to overdo it, as you can easily slow the user down too much.
Finally, as with anything that includes text, make the user interface as scannable as possible. For example, if you have headings under which commands/options appear, consider putting the action word at the start, rather than a question word. The point that Maudite makes is a good example of scannability too, as the "Don't Save" button text doesn't rely on the context of the preceding paragraph.
A: If you are doing enterprise software, a lot of users will have small monitors at low resolution. Or if they are old they will have it at a low res so they can see giant buttons ( I have seen an 800x600 on a 24"ish monitor). I have an old 15" monitor at a low resolution (800 x 600) so i can see what the program will look likes in less than idle conditions every now and then. I know that enterprise users pretty much have to accept what they are given but if you design a winform that doesn't fit into an 800x600 screen, it's not helping anyone.
A: Here is a great DotNetRocks podcast episode where Mark Miller talks about how to create Good UI; Even though the show title is .NET rocks, this episode talks about a general rule of thumbs on how to create a UI to increase program user's productivity.
Here is an episode exerpt
Good user interface design can be done by sticking to some good rules and avoiding common mistakes. You don't need to be a latte-sippin tattoo-wearin macbook-carrying designer to create user interfaces that work.
A: Try to think about your user's end goals first before deciding what individual tasks they would carry out when using your software. The book About Face has excellent discussions on this sort of thing and though quite long is very interesting and insightful. It's interesting to note how many of their suggestions about improving software design seem to used in google docs...
One other thing, keep your user interface as simple and clean as possible.
A: I like to follow these 3 guidelines:
*
*Standard - follow known standards/patterns, reuse ideas from all products you respect
*Simple - keep your solutions simple and easy to change (if needed)
*Elegant - use less to accomplish more
A: The best technique I found is to put your self in the users shoes. What would you like to see from the GUI and put that in front. This also gives you the ability to prioritize as those things should be done first then work from there.
To do this I try to find "layers of usefulness" and add / subtract from the layers until it seems clean. Basically to find the layers I make a list of all the functions the GUI needs to have, all the functions it should have, and all the functions it would be neat to have. Then I group those so that every thing has logical ordering and the groupings become the "layers". From the layers I then add the most important functionality (or what would be used for Day to Day operation) and that becomes the most prominent part, and I work things into the feature around those items.
One of the toughest things is navigation as you have so much to give the use how do you make it helpful and this is where the layers really help. It makes it easy to see how to layout menus, how other pieces interact, what pieces can be hidden, etc.
I have found the easiest way to do this is to start by see what and how your users function on a day to day basis this which will make it easier to get in their shoes (even better is to do their job for a few days). Then make some demonstrations and put them in front of users even if they are Paper Prototypes (there is a book on this process called Paper Prototyping by Carolyn Snyder). Then begin building it and put it in front of users as it is built often.
I will also recommended the book Designing Interfaces by Jenifer Tidwell published by O'Reilly
A: The items in the list you presented are really situation dependent - they will vary from application to application. Some applications will need a save button, some won't. Some conditions will warrant a modal dialog box, some won't.
My top rule for designing a usable interface: Follow existing UI conventions. Nothing confuses a user more than a UI that doesn't work like anything they've ever used. Lotus Notes has one of the worst user interfaces ever created, and it is almost entirely because they went against common UI conventions with just about everything that they did.
If you're questioning how you should design a certain piece of your UI, think of a few standard/well-known applications that provide similar functionality and see how they do it.
A: If your UI involves data entry or manipulation (typical of business apps) then I recommend affording your users the ability to act on sets of data items as much as possible. Also try to design in such a way that experienced users can interact with the UI in a very random, as opposed to sequential way (accelerator keys, hyperlinks, etc).
A: Sung Meister mentioned Mark Miller. You can find some of his blog posts regarding great UI on the Developer express blog. Here's a screencast of his Science of great UI presentation: part1 and part2. (both require Veoh player).
You can also find him on dnrTV: Science of great user experience: part1 and part2.
Here's a google techtalks about user experience by Jen Fitzpatrick.
Cheers
A: When using a dropdown, the default dropdown height is usually too low (default is 8 items for winforms, for example).
Increasing it will either save the user a click if the number of items is low or make it easier to search the dropdown if there are a lot of items.
In fact, I see little point in not using all the available space !
This is so obvious to me now, but for example, it seems even VisualStudio designers haven't figured it out (btw, if you manually increase Intellisense's height, it will stay this way, but that's offtopic:))
A: I'll give one of my personal favorites: avoid dialog boxes at all costs. A truly good U I should almost never need to pop up a dialog box. Add them to your program only as a truly last resort.
For more, you might want to check out easily digestible ui tips for developers.
A: The Coding Horror Blog regularly gives great ideas. Just some examples:
*
*Exploratory and incremental learning
*Self-documenting user interface
*Incremental search of features/Smart keyboard access
*Task-oriented design (ribbon instead of menus and toolbars)
*Providing undo instead of constant confirmation
Another aspect: use scalable icons to solve the problem of multiple user screen resolutions without maintaining different resolution bitmaps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
} |
Q: What is a good deployment tool for websites on Windows? I'm looking for something that can copy (preferably only changed) files from a development machine to a staging machine and finally to a set of production machines.
A "what if" mode would be nice as would the capability to "rollback" the last deployment. Database migrations aren't a necessary feature.
UPDATE: A free/low-cost tool would be great, but cost isn't the only concern. A tool that could actually manage deployment from one environment to the next (dev->staging->production instead of from a development machine to each environment) would also be ideal.
The other big nice-to-have is the ability to only copy changed files - some of our older sites contain hundreds of .asp files.
A: @Sean Carpenter can you tell us a little more about your environment? Should the solution be free? simple?
I find robocopy to be pretty slick for this sort of thing. Wrap in up in a batch file and you are good to go. It's a glorified xcopy, but deploying my website isn't really hard. Just copy out the files.
As far as rollbacks... You are using source control right? Just pull the old source out of there. Or, in your batch file, ALSO copy the deployment to another folder called website yyyy.mm.dd so you have a lovely folder ready to go in an emergency.
look at the for command for details on how to get the parts of the date.
robocopy.exe
for /?
Yeah, it's a total "hack" but it moves the files nicely.
A: For some scenarios I used a freeware product called SyncBack (Download here).
It provides complex, multi-step file synchronization (filesystem or FTP etc., compression etc.). The program has a nice graphical user interface. You can define profiles and group/execute them together.
You can set filter on file types, names etc. and execute commands/programs after the job execution. There is also a job log provided as html report, which can be sent as email to you if you schedule the job.
There is also a professional version of the software, but for common tasks the freeware should do fine.
A: You don't specify if you are using Visual Studio .NET, but there are a few built-in tools in Visual Studio 2005 and 2008:
Copy Website tool -- basically a visual synchronization tool, it highlights files and lets you copy from one to the other. Manual, built into Visual Studio.
aspnet_compiler.exe -- lets you precompile websites.
Of course you can create a web deployment package and deploy as an MSI as well.
I have used a combination of Cruise Control.NET, nant and MSBuild to compile, and swap out configuration files for specific environments and copy the files to a build output directory. Then we had another nant script to do the file copying (and run database scripts if necessary).
For a rollback, we would save all prior deployments, so theoretically rolling back just involved redeploying the last working build (and restoring the database).
A: We used UnleashIt (unfortunate name I know) which was nicely customizable and allowed you to save profiles for deploying to different servers. It also has a "backup" feature which will backup your production files before deployment so rollback should be pretty easy.
A: I've given up trying to find a good free product that works.
I then found Microsoft's Sync Toy 2.0 which while lacking in options works well.
BUT I need to deploy to a remote server.
Since I connect with terminal services I realized I can select my local hard drive when I connect and then in explorer on the remote server i can open \\tsclient\S\MyWebsite on the remote server.
I then use synctoy with that path and synchronize it with my server. Seems to work pretty well and fast so far...
A: Maybe rsync plus some custom scripts will do the trick.
A: Try repliweb. It handles full rollback to previous versions of files. I've used it whilst working for a client who demanded its use and I;ve become a big fan of it, partiularily:
*
*Rollback to previous versions of code
*Authentication and rules for different user roles
*Deploy to multiple environments
*Full reporting to the user via email / logs statiing what has changed, what the current version is etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Chrome tabs and processes I was reading googlebooks on chrome, where they talk about why they decided to spin up a process to host browser tab, every time you created a new tab.'
So
2 tabs = 2 chrome processes
3 tabs = 3 chrome processes and so on .. right??
But i opened up some 20 or so tabs, but in task manager, i could only find 3 chrome processes..
What is going on??
I was taught that creating a process is an expensive proposition in terms of resources needed, and there are other light weight options available (like app domains in .net for ex)..
So is chrome taking some hybrid approach?? Create few processes and then start hosting additional tabs inside those limited set of processes??
A: it's being hosted in the first process. open up chrome. you'll see 2 processes (manager and initial tab). then open 10 more tabs, you'll notice the second process's memory jump a lot. then type in google.com or something into the first tab, and you'll see a new process get spawned.
also notice, if you do shift+esc and brink up the task manager in chrome, all those tabs will be grouped together, one w/ memory, the others without.
A: Don't forget that if two sites share a session, they share a process. So following a link from one site that opens a new page will be in the same session (and thus the same process).
For each tab created with Ctrl+T, you should get a new process.
A: I've also noticed that tabs browsing the same domain ar grouped in the same process. So if you have 3 tab browsing stackoverflow.com, those three tabs will appread as one process
A: Process creation is relatively expensive, certainly compared to thread creation. But the frequency of process creation in Chrome is very slow, so the real issue is the amount of resource overhead vs other techniques.
The Google team figured that the benefits of a separate process model justified the resource costs. Given the current resources on desktop machines this trade off makes a lot of sense.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: MAC address in Compact Framework How can I get the MAC Address using only the compact framework?
A: 1.4 of the OpenNETCF code gets the information from the following P/Invoke call:
[DllImport ("iphlpapi.dll", SetLastError=true)]
public static extern int GetAdaptersInfo( byte[] ip, ref int size );
The physical address (returned as MAC address) I think is around about index 400 - 408 of the byte array after the call. So you can just use that directly if you don't want to use OpenNETCF (why though? OpenNETCF rocks more than stone henge!)
Wonderful P/Invoke.net gives a full example here.
Oh and to properly answer your question:
only using the Compact Framework
You cant. That's life with CF, if you want some fun try sending data with a socket synchronously with a timeout. :D
A: Here are the first three hits from a Google search for "MAC address in Compact Framework:
*
*http://arjunachith.blogspot.com/2007/08/retrieving-mac-address-in-compact.html
*http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=920417&SiteID=1
*http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=188787&SiteID=1
Did none of those help?
Two out of three point to OpenNETCF as a way to do it.
A: If you can access the registry, try to find your adapter MAC Address under the LOCAL_MACHINE\Comm\PCI\***\Parms\MacAddress.
It may be a quick and dirty solution that doesn't involve the use of WMI or OpenNETCF ...
A: Add a reference to System.Management.dll and use something like:
Dim mc As System.Management.ManagementClass
Dim mo As ManagementObject
mc = New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim moc As ManagementObjectCollection = mc.GetInstances()
For Each mo In moc
If mo.Item("IPEnabled") = True Then
ListBox1.Items.Add("MAC address " & mo.Item("MacAddress").ToString())
End If
Next
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: "Out of Band" Processing Techiniques for asp.net applications Jeff has previously blogged about using the cache to perform "out of band" processing on his websites, however I was wondering what other techniques people are using to process these sorts of tasks?
A: Years ago, I saw Rob Howard describe a way to use an HttpModule to process tasks in the background. It doesn't seem as slick as using the Cache, but it might be better for certain circumstances.
This blog post has the details, and there are many others that capture the same information if you look around.
A: Windows Service
A: You may want to look at how DotNetNuke does it. I know it is written in VB.NET, but I retrofitted the code into C#. I was perusing the source and noticed they had a feature in their admin area to setup scheduled tasks. These tasks get setup thru the admin interface and stored in the database. When the site starts, thru the Global.asax file, they either created another thread to run this service that then runs the scheduled tasks at their scheduled time. I can't remember the exact logic, it's been a while, but it is definitely a good resource on how other people have done out of band processes for Asp.Net applications. This technique still keeps the logic within the Asp.Net application, but it runs out of band in my opinion.
A: if it's primarily data processing tasks and you're using MSSQL, how about scheduled SSIS tasks?
A: *
*Scheduled tasks using http://www.codeproject.com/KB/cs/tsnewlib.aspx or schtasks.exe.
*Quartz.NET
*MSMQ
*SQL Server jobs
*Windows service
*System.Threading.Timer or System.Timers.Timer
*System.ComponentModel.BackgroundWorker
*Asynchronous calls and callbacks
A: Scheduled tasks, or cron jobs.
A: The problem with scheduled tasks or cron jobs is that they don't share memory space with the web server. You could set up a scheduled task that requested pages from the web server, but that might create problems with long running tasks. It would be nice to have some low priority threads running on the actual ASP.Net application stack to do simple utility tasks like cleaning up caches, monitoring resources, and just to deal with general housekeeping.
A: Simple queue files along with a separate agent. For each type of out of band process write a separate agent .exe which watches a directory for queue files that include whatever data is needed to perform the specified process.
This may seem dirty but in the real world I find it gives a lot of flexibility, you aren't doing a lot of processing in ASP.net process space and you could easily adapt this style to farm processing out to cheap Linux servers running the agent process on Mono for when you start needing more RAM/CPU/disk.
A: If you are most comfortable with asp.net pages you can write a small app to handle your job and then "ping" the app with an outside service that monitors your web site. This will keep the app alive.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Where to start with Entity Framework Anyone know a good book or post about how to start in EF? I have seen the DnrTV any other place?
A: Mike Taulty's Blog: http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/category/1024.aspx
A great EF intro deck: http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2008/03/13/10235.aspx
And these ADO.NET Data Services screencasts are nice too: http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2008/01/25/10152.aspx
ADO.NET Entity Framework MSDN: http://msdn.microsoft.com/en-us/library/bb399572.aspx
ADO.NET Entity Framework forums: http://forums.microsoft.com/msdn/ShowForum.aspx?ForumID=533&SiteID=1
ADO.NET team blog: http://blogs.msdn.com/adonet/archive/tags/Entity+Framework/default.aspx
Programming LINQ and the ADO.NET Entity Framework Webcast: http://blogs.msdn.com/adonet/archive/2008/01/28/programming-linq-and-the-ado-net-entity-framework-webcast.aspx
A: Jason's DotNet Architecture Blog has a tutorial that gets you started with the basics, using the MS SQL Server AdventureWorks sample database.
A: Alex James, Program Manager on the ADO.Net team at microsoft also has the odd good post on EF especially around Metadata.
A: This is a very decent article on EF http://www.codeguru.com/csharp/.net/net_general/netframeworkclasses/article.php/c15489/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Mixing jsp and jsf I will elaborate somewhat. Jsf is kind-of extremely painful for working with from designer's perspective, somewhat in the range of trying to draw a picture while having hands tied at your back, but it is good for chewing up forms and listing lots of data. So sites we are making in my company are jsf admin pages and jsp user pages. Problem occurs when user pages have some complicated forms and stuff and jsf starts kickin' in.
Here is the question: I'm on pure jsp page. I need to access some jsf page that uses session bean. How can I initialize that bean? If I was on jsf page, I could have some commandLink which would prepare data. Only thing I can come up with is having dummy jsf page that will do the work and redirect me to needed jsf page, but that's kind of ugly, and I don't want to end up with 50 dummy pages. I would rather find some mechanism to reinitialize bean that is already in session with some wanted parameters.
Edit: some more details. In this specific situation, I have a tests that are either full or filtered. It's a same test with same logic and everything, except if test is filtered, it should eliminate some questions depending on answers. Upon a clicking a link, it should start a requested test in one of the two modes. Links are parts of main menu-tree and are visible on many sibling jsp pages. My task is to have 4 links: testA full, testA filtered, testB full, testB filtered, that all lead on same jsf page and TestFormBean should be reinitialized accordingly.
Edit: I've researched facelets a bit, and while it won't help me now, I'll definitely keep that in mind for next project.
A: have you looked into using facelets? It lets you get rid of the whole JSF / JSP differences (it's an alternate and superior view controller).
It also supports great design-time semantics with the jsfc tag...
<input type="text" jsfc="#{SomeBean.property}" class="foo" />
gets translated internally to the correct JSF stuff, so you can work with your existing tools.
A: You can retrieve a managed bean inside of a tag library using something like this:
FacesContext context = FacesContext.getCurrentInstance();
Object myBean = context.getELContext().getELResolver().getValue(context.getELContext(), null, "myBeanName");
However, you'd need to use the tag library from one of your JSF pages. FacesContext.getCurrentInstance() returns null when it's called outside of the FacesServlet.
A: To solve this one I'd probably create a JSF fragment that only includes your form, then use a <c:import> tag to include it in my JSF page.
That solution is probably a little fragile depending on your environment though.
EDIT: See Chris Hall's answer, FacesContext is not available outside the FacesServlet.
A: Create a custom JSP tag handler. You can then retrieve the bean from session scope and then initialize it on the fly. See this tutorial for more details.
A: Actually, I've resolved this by removing bean from session, so it has to be generated again when jsf page is called. Then I pick up get parameters from a request in constructor.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Setting Focus with ASP.NET AJAX Control Toolkit I'm using the AutoComplete control from the ASP.NET AJAX Control Toolkit and I'm experiencing an issue where the AutoComplete does not populate when I set the focus to the assigned textbox.
I've tried setting the focus in the Page_Load, Page_PreRender, and Page_Init events and the focus is set properly but the AutoComplete does not work. If I don't set the focus, everything works fine but I'd like to set it so the users don't have that extra click.
Is there a special place I need to set the focus or something else I need to do to make this work? Thanks.
A: We had exactly the same problem. What we had to do is write a script at the bottom of the page that quickly blurs then refocuses to the textbox. You can have a look at the (terribly hacky) solution here: http://www.drive.com.au
The textbox id is MainSearchBox_SearchTextBox. Have a look at about line 586 & you can see where I'm wiring up all the events (I'm actually using prototype for this bit.
Basically on the focus event of the textbox I set a global var called textBoxHasFocus to true and on the blur event I set it to false. The on the load event of the page I call this script:
if (textBoxHasFocus) {
$get("MainSearchBox_SearchTextBox").blur();
$get("MainSearchBox_SearchTextBox").focus();
}
This resets the textbox. It's really dodgy, but it's the only solution I could find
A: this is waste , its simple
this is what you need to do
controlId.focus(); in C#
controlID.focus() in VB
place this in page load or button_click section
eg. panel1.focus(); if panel1 has model popup extender attached to it, then we put this code in page load section
A: How are you setting focus? I haven't tried the specific scenario you've suggested, but here's how I set focus to my controls:
Public Sub SetFocus(ByVal ctrl As Control)
Dim sb As New System.Text.StringBuilder
Dim p As Control
p = ctrl.Parent
While (Not (p.GetType() Is GetType(System.Web.UI.HtmlControls.HtmlForm)))
p = p.Parent
End While
With sb
.Append("<script language='JavaScript'>")
.Append("function SetFocus()")
.Append("{")
.Append("document.")
.Append(p.ClientID)
.Append("['")
.Append(ctrl.UniqueID)
.Append("'].focus();")
.Append("}")
.Append("window.onload = SetFocus;")
.Append("")
.Append("</script")
.Append(">")
End With
ctrl.Page.RegisterClientScriptBlock("SetFocus", sb.ToString())
End Sub
So, I'm not sure what method you're using, but if it's different than mine, give that a shot and see if you still have a problem or not.
A: What I normally do is register a clientside script to run the below setFocusTimeout method from my codebehind method. When this runs, it waits some small amount of time and then calls the method that actually sets focus (setFocus). It's terribly hackish, but it seems you have to go a route like this to stop AJAX from stealing your focus.
function setFocusTimeout(controlID) {
focusControlID = controlID;
setTimeout("setFocus(focusControlID)", 100);
}
function setFocus() {
document.getElementById(focusControlID).focus();
}
A: I found the answers from Glenn Slaven and from Kris/Alex to get me closer to a solution to my particular problem with setting focus on an ASP.NET TextBox control that had an AutoCompleteExtender attached. The document.getElementById(focusControlID).focus() kept throwing a javascript error that implied document.getElementById was returning a null object. The focusControlID variable was returning the correct runtime ClientID value for the TextBox control. But for whatever reason, the document.getElementById function didn't like it.
My solution was to throw jQuery into the mix, as I was already using it to paint the background of any control that had focus, plus forcing the Enter key to tab through the form instead of firing a postback.
My setFocus function ended up looking like this:
function setFocus(focusControlID) {
$('#' + focusControlID).blur();
$('#' + focusControlID).focus();
}
This got rid of the javascript runtime error, put focus on the desired TextBox control, and placed the cursor within the control as well. Without first blurring then focusing, the control would be highlighted as if it had focus, but the cursor would not be sitting in the control yet. The user would still have to click inside the control to begin editing, which would be an UX annoyance.
I also had to increase the timeout from 100 to 300. Your mileage my vary...
I agree with everyone that this is a hack. But from the end-user's perspective, they don't see this code. The hack for them is if they have to manually click inside the control instead of just being automatically placed inside the control already and typing the first few letters to trigger the auto lookup functionality. So, hats off to all who provided their hacks.
I hope this is helpful to someone else.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How do I avoid having the database password stored in plaintext in sourcecode? In the web-application I'm developing I currently use a naive solution when connecting to the database:
Connection c = DriverManager.getConnection("url", "username", "password");
This is pretty unsafe. If an attacker gains access to the sourcecode he also gains access to the database itself. How can my web-application connect to the database without storing the database-password in plaintext in the sourcecode?
A: In .NET, the convention is to store connectionstrings in a separate config file.
Thereon, the config file can be encrypted.
If you are using Microsoft SQL Server, this all becomes irrelevant if you use a domain account to run the application, which then uses a trusted connection to the database. The connectionstring will not contain any usernames and passwords in that case.
A: You can store the connection string in Web.config or App.config file and encrypt the section that holds it. Here's a very good article I used in a previous project to encrypt the connection string:
http://www.ondotnet.com/pub/a/dotnet/2005/02/15/encryptingconnstring.html
A: I can recommend these techniques for .NET programmers:
*
*Encrypt password\connection string in config file
*Setup trusted connection between client and server (i.e. use windows auth, etc)
Here is useful articles from CodeProject:
*
*Encrypt and Decrypt of ConnectionString in app.config and/or web.config
A: Unless I am missing the point the connection should be managed by the server via a connection pool, therefore the connection credentials are held by the server and not by the app.
Taking this further I generally build to a convention where the frontend web application (in a DMZ) only talks to the DB via a web service (in domain), therefore providing complete separation and enhanced DB security.
Also, never give priviliges to the db account over or above what is essentially needed.
An alternative approach is to perform all operations via stored procedures, and grant the application user access only to these procs.
A: Assuming that you are using MS SQL, you can take advantage of windows authentication which requires no ussername/pass anywhere in source code. Otherwise I would have to agree with the other posters recommending app.config + encryption.
A: *
*Create an O/S user
*Put the password in an O/S environment variable for that user
*Run the program as that user
Advantages:
*
*Only root or that user can view that user's O/S environment variables
*Survives reboot
*You never accidentally check password in to source control
*You don't need to worry about screwing up file permissions
*You don't need to worry about where you store an encryption key
*Works x-platform
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: How do I figure out what I need to know? I am a novice programmer who is trying to teach myself to code, specifically in C#. I've taken on a project from a friend of mine and I am not sure what I need to know to get the project done. I suppose the issue is I don't know what I need to know to even get the project started.
I do have many of the basics of object oriented programming, classes, methods and what-not, but when I sit down to code-I don't know where to begin looking to accomplish even basic tasks. I don't know syntax or what the language is capable of with the tools provided. I have read some books, but they mostly seem to be about the concepts and theories about OOP within C# with minimal syntax.
I guess the question is where do I look to learn the syntax-is there some sort of repository of classes and methods that I am missing with examples of how to use the tools it contains? I am stuck in a place of not knowing where to go/look next.
Thanks for any help
A: Getting started with Visual C#.
A: One of the things I usually recommend to Junior Developers on my projects who are looking for a better picture of how things work is to get familiar with your F10/F11 keys in Visual Studio by stepping through open source projects written in C#.
Pick something you find interesting from Codeplex or Sourceforge or Google code (there's a topic here about good code to read) and download the source code. Open it in Visual Studio and choose "Debug -> Step Into". From there, let the debugger be your guide through the code.
F11 lets you dig deeper, SHIFT+F11 steps you back a level.
It really can teach you a lot about how functioning code is structured because it leads you through the flow and provides a pretty good tour of functionality in the code.
It also works well with books and other materials because, when you see something you don't understand, you can go looking for a better explanation.
This is something I do myself quite often to familiarize myself with a given codebase, whether it's open source or a paying project with existing code.
A: I don't use C# myself but for just getting a handle on the syntax of a language as well as basic programming techniques you almost can't go wrong with the O'Reilly books. You might want to check out their Learning C# book.
A: As a general rule, split the project into multiple task. If you still don't know how to start with each task, then further split it into smaller subtask.
Until you can say, "Ah, I can code this task", do it and move on to the next task.
A: I started with the C# Station tutorials. "Getting started with Visual C#" gives me the creeps...
A: MSDN. Go straight to the horses mouth.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: What metrics for GUI usability do you know? Of course the best metric would be a happiness of your users.
But what metrics do you know for GUI usability measurements?
For example, one of the common metrics is a average click count to perform action.
What other metrics do you know?
A: Jakob Nielsen has several articles regarding usability metrics, including one that is entitled, well, Usability Metrics:
The most basic measures are based on the definition of usability as a quality metric:
*
*success rate (whether users can perform the task at all),
*the time a task requires,
*the error rate, and
*users' subjective satisfaction.
A: I just look at where I want users to go and where (physically) they are going on screen, I do this with data from Google Analytics.
A: Not strictly usability, but we sometimes measure the ratio of the GUI and the backend code. This is for the managers, to remind them, that while functionality is importaint, the GUI should get a proportional budget for user testing and study too.
A: check:
http://www.iqcontent.com/blog/2007/05/a-really-simple-metric-for-measuring-user-interfaces/
Here is a simple pre-launch check you
should do on all your web
applications. It only takes about 5
seconds and one screeshot
Q: “What percentage of your interface contains stuff that your customers
want to see?”
*
*10%
*25%
*100%
If you answer a, or b then you might
do well, but you’ll probably get blown
out of the water once someone decides
to enter the market with option c.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: PHP, Arrays, and References Why does the following code not work as I was expecting?
<?php
$data = array(
array('Area1', null, null),
array(null, 'Section1', null),
array(null, null, 'Location1'),
array('Area2', null, null),
array(null, 'Section2', null),
array(null, null, 'Location2')
);
$root = array();
foreach ($data as $row) {
if ($row[0]) {
$area = array();
$root[$row[0]] =& $area;
} elseif ($row[1]) {
$section = array();
$area[$row[1]] =& $section;
} elseif ($row[2]) {
$section[] = $row[2];
}
}
print_r($root);
Expected result:
Array(
[Area1] => Array(
[Section1] => Array(
[0] => Location1
)
)
[Area2] => Array(
[Section2] => Array(
[0] => Location2
)
)
)
Actual result:
Array(
[Area1] => Array(
[Section2] => Array(
[0] => Location2
)
)
[Area2] => Array(
[Section2] => Array(
[0] => Location2
)
)
)
A: If you modify your code on two lines as follows:
$area = array();
$section = array();
to this:
unset($area);
$area = array();
unset($section);
$section = array();
it will work as expected.
In the first version, $area and $section are acting as "pointers" to the value inside the $root array. If you reset the values first, those variables can then be used to create brand new arrays instead of overwriting the previous arrays.
A: This will also works:
$root[$row[0]] = array();
$area =& $root[$row[0]];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Suggestions for migrating ASP.net app from 1.1 forward I am recently in charge of an older app written in C# using asp.net 1.1.
*
*Are there any resources to guide me in converting the application to a newer version of of the .NET Framework.
My main pause is that there are ton's of customized DataGrids in the app as it is written now and since so much of the code needs to be rewritten to use GridViews ...
*is it worth trying to convert the grids in the application to use Silverlight in the attempt to move this code into the future.
A: I had a similar experience, and the only thing that we had to replace was a third-party control that we were using in the 1.1 app, and the vendor had gone out of business an never released a version that worked with .NET 2.0. We ended up replacing it fairly easily with an AJAX Control Toolkit control.
Other than that, the compiler does a pretty good job of telling you what to do with respect to deprecated method calls.
I'd suggest making a copy of the code and upgrading the site in Visual Studio and see what happens. Just open the solution in Visual Studio 2005 or 2008, the IDE will walk you through the upgrade automatically. Get it to compile, then if you have any documented tests you should run through them. If not, you'll want to plan testing to make sure all your functionality still works like it did before the upgrade.
Migrating to Silverlight sounds like fun, but if you can get it upgraded and working, I'd probably push that off until a later release -- my experience tells me that you might get into trouble if you bite off too much at once if there is no show-stopping technical reason.
A: This MSDN document may be useful to you as you upgrade your application, it contains lists of breaking changes between 1.1 and 2.0, and work arounds for resolving them:
Breaking Changes in .NET Framework 2.0
A: I would suggest that as part of the upgrade you opt to move to a Web Application Project rather than a Web Site Project, as the former is conceptually similar to the VS2003 web project model.
Here's a nice short post summarising the differences:
http://maordavid.blogspot.com/2007/06/aspnet-20-web-site-vs-web-application.html
As others have said, don't worry too much about the DataGrids, the upgraded site should be backwards-compatible in this respect.
A: Regarding DataGrids - I don't think you have too much to worry about, DataGrids still work in current versions. It's just that going forward, you should use GridViews.
I am sure there are other things you may want to check into though, deeper framework issues. But I don't know enough about those things to speak to that particular point.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: HTML blockquote vs div Is there any benefit in using a <blockquote> element over a <div>? I was looking at a website's markup to learn CSS and I couldn't figure out why the <blockquote> was being used.
EDIT: Yeah sorry I didn't clarify, it was used to hold the <div> tag with username as 'text' and an input tag. There was clearly no quote.
A: In theory, HTML should be as "semantic" as possible - meaning that every element should indicate something about its content. <h1>s should enclose the most important headline; <p>s should surround paragraphs; <em> should indicate emphasis, etc.
That way the code makes sense when you - or a screen reader, or whatever - look at it. This also helps for devices that don't understand all (or any) of your CSS rules.
A: <blockquote> should be used when the text it contains is a block quote. This sounds very obvious to me, so is there another aspect to your question?
A: Semantically, a blockquote tag makes sense when you're quoting something. Sure, a stylized div can do the same thing, but why not use the right tag for the job?
Additionally, the blockquote tag allows you to include a citation with the cite attribute.
A: As mentioned, <blockquote> is for quoting. Similarly you will use several <p> blocks for paragraphs within one <div> that holds page content or whatever. HTML5 proposal will have lot more block elements (i.e same as divs) which purpose will be to add a semantic info about it, such as header, footer, menu, etc.
A: As mentioned earlier, blockquotes are for quotes. Just like tables are (arguably) for tabular data, lists are for listings, divs for divisions, p for paragraphs, etc.
Sure, you could almost everything with divs. That's the beauty of using HTML with CSS: you can make anything look however you want it to look (in theory, in the real world browser quirks mess that up sometimes).
Using divs for anything you can think of is commonly known as 'divitis'. See this article for a little explanation :)
A: The likely reason they're using blockquote is that many people dabbling in HTML don't know enough about CSS to know that a div can be given the same left-margin as blockquote renders with by default.
A: Easy peasy, right? Nothing has really changed. Remember that as is a ‘block-level element’ (flow content) we can put most anything in it, including headers, images, and tables, in addition to the usual paragraphs of text. There are a couple of slight differences in HTML5 though. is a sectioning root, meaning that any - elements it contains don’t become part of the document’s outline. Also, adding a single paragraph of text with no enclosing tags is now completely kosher. Here are some simple examples (apologies for the fake content):
The suggestions in my article came directly from writing and editing a few megs worth of raw text used on my website, which bought up lots of edge-cases and curious questions about semantics; so whilst I wouldn’t say my choices would suit everybody, they have at least been trialed in a background of the text.
My complaint about the ABBR article you published here on HTML5Doctor was essential that you weren’t following your own advice, as I know that I practically went insane trying to use those rules on megs of text before I came up with my own to take back control of my sanity.
But, I will definitely say that cite still remains the weaker out of the three and I appreciate this article for being far more square.
If you would like, my article could be further adapted with feedback from the doctors to better suit a broader audience. I strongly believe that a key part of learning HTML5 is learning HTML4 properly and eschewing spans and divs for semantics where possible
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: RDMS for C language newbie? What database should a beginner use in the C language?
Can I use MySQL?
Thanks
A: You can use SQLite, MySQL, PostgreSQL, or any other DBMS with a C language binding.
*
*SQLite In 5 Minutes Or Less
*MySQL C API
*PostgreSQL C API
A: If you question is "What RDBMS do you recommend for beginner?" I agree that MySQL is not a bad choice. It's easy to install and configure. I think that most RDMS can be accessed from C code now days
A: MySQL has C bindings, so you could use that; libmysql usually installs the necessary headers and library files. You might also experiment with something like SQLite if you just want to mess about with a DBMS in C.
A: As pointed out, most have C bindings, so would be suitable. MySQL is open source and has lots of online docs and books in print, so this is a good start.
SQLite has a growing number of fans but I have yet to use it. It would be much easier to setup/install so could be good for learning about tables and SQL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Where is the chink in Google Chrome's armor? While browsing with Chrome, I noticed that it responds extremely fast (in comparison with IE and Firefox on my laptop) in terms of rendering pages, including JavaScript heavy sites like gmail.
This is what googlebook on Chrome has to say
*
*tabs are hosted in process rather than thread.
*compile javascript using V8 engine as opposed to interpreting.
*Introduce new virtual machine to support javascript heavy apps
*introduce "hidden class transitions" and apply dynamic optimization to speed up things.
*Replace inefficient "Conservative garbage colllection" scheme with more precise garbage collection scheme.
*Introduce their own task scheduler and memory manager to manage the browser environment.
All this sounds so familiar, and Microsoft has been doing such things for long time.. Windows os, C++, C# etc compilers, CLR, and so on.
So why isn't Microsoft or any other browser vendor taking Chrome's approach? Is there a flaw in Chrome's approach? If not, is the rest of browser vendor community caught unaware with Google's approach?
A: They have crossed over from a web browser as a tool to view web pages, to a tool optimized to work for web applications. There may be some flaws in this initial release, but they are changing the game.
A: IE8 uses a similar individual process per tab module, though they do not use a single process per tab, but instead spread all tabs across a process pool.
A:
@pix0r but they added a little thing in the bottom right corner so you can expand the text box any direction you want, which I love because I use a wide display and prefer to type in a wider screen.
Thats actually a WebKit feature, Chrome just inherited it.
A: Virtually all of these features existed in other browsers before Chrome. IE8 had process isolation for tabs. Firefox / Safari had most of the JavaScript stuff. Most browsers do their own memory management.
Chrome has a few unique features (hyperrestricted render processes, etc) which are difficult to put into other browsers due to add-on/application compatibility concerns.
The primary thing Chrome has going for it is an extremely hardcore focus on minimalism and high-performance. By focusing on these as their competitive advantages, they can appeal to users who find this area of focus compelling.
A: Chrome's approach is difficult to write, and requires forethought from the developers. IE and Firefox are both attempting to move to a process-per-tab model, but due to backwards compatibility are not able to transition quickly. Chrome, being an entirely new browser build on a clean rendering engine (WebKit), was easier to write in this way.
A: As time passes, I'm sure you will see the homogenization of features as the browsers attempt to one-up each other.
In the meanwhile, I still stick with Firefox over Chrome for the simple reason that Firefox is (i) non-profit and has a (ii) huge addon community.
Addons such as NoScript and AdBlockPlus are almost essential for me.
A: One chink in Chrome's armor is the fact that it renders these darned textareas on StackOverflow are so small that it's making my eyes bleed!
A:
One chink in Chrome's armor is the fact that it renders these darned textareas on StackOverflow are so small that it's making my eyes bleed!
Yeah. I mentioned this on uservoice and got declined because the current size is evidently the default under webkit. Every other site I've tried with Chrome that uses textboxes to compose content manages to have a decent sized font. The default definitely doesn't work, but there's obviously some way to override it. Jeff needs to fix this!
Edit:
Jeff was nice enough to point out how to fix this problem yourself.
A: @pix0r but they added a little thing in the bottom right corner so you can expand the text box any direction you want, which I love because I use a wide display and prefer to type in a wider screen.
I also wanted to point out that Google completely built Chrome from the ground up, with the exception of using webkit, so they have some of the advantages of not having to not deal with old-code. And of course there is the INSANLELY cool/smart developers.
A: The biggest chink I've found is its lousy proxy support compared to IE, FF and Opera. So it's pretty much useless at work, render pages at random, and requesting authentication for the proxy, where the others pass it seamlessly.
That said on my home machine it works great, if it wasn't for the OTT EULA I'd use it now.
thing2k
A: One "flaw" about Chrome is that it uses more memory upfront than all of the other browsers. I'm just guessing that this is due to the overhead associated with all the separate tab management.
After it's been open for some time, however, it doesn't use more memory than other browsers.
A: Many companies play a game of "What's the least we can do to get the leg up?" Marketing creates a laundry list of features needed to be better than the competitors. Project management ensures engineers stick to those features for fear that the project will exceed the time allocated... which of course it will. There's not a whole lot of room in such a system for a big picture leap-ahead. The incremental improvements you see in products, and browsers, is a consequence.
A: You have to keep in mind that Microsoft primary business is Rich environement (GUI) Application. Web tool is a threat to them as it is platform independant (not promoting they main product).
Of course the IE team probably had figured something like that but... Microsoft definetly won't invest a lot of money in IE if what they are selling is a Rich application platform.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: What do people find so appealing about dynamic languages? It seems that everybody is jumping on the dynamic, non-compiled bandwagon lately. I've mostly only worked in compiled, static typed languages (C, Java, .Net). The experience I have with dynamic languages is stuff like ASP (Vb Script), JavaScript, and PHP. Using these technologies has left a bad taste in my mouth when thinking about dynamic languages. Things that usually would have been caught by the compiler such as misspelled variable names and assigning an value of the wrong type to a variable don't occur until runtime. And even then, you may not notice an error, as it just creates a new variable, and assigns some default value. I've also never seen intellisense work well in a dynamic language, since, well, variables don't have any explicit type.
What I want to know is, what people find so appealing about dynamic languages? What are the main advantages in terms of things that dynamic languages allow you to do that can't be done, or are difficult to do in compiled languages. It seems to me that we decided a long time ago, that things like uncompiled asp pages throwing runtime exceptions was a bad idea. Why is there is a resurgence of this type of code? And why does it seem to me at least, that Ruby on Rails doesn't really look like anything you couldn't have done with ASP 10 years ago?
A: I believe that the "new found love" for dynamically-typed languages have less to do with whether statically-typed languages are better or worst - in the absolute sense - than the rise in popularity of certain dynamic languages. Ruby on Rails was obviously a big phenomenon that cause the resurgence of dynamic languages. The thing that made rails so popular and created so many converts from the static camp was mainly: very terse and DRY code and configuration. This is especially true when compared to Java web frameworks which required mountains of XML configuration. Many Java programmers - smart ones too - converted over, and some even evangelized ruby and other dynamic languages. For me, three distinct features allow dynamic languages like Ruby or Python to be more terse:
*
*Minimalist syntax - the big one is that type annotations are not required, but also the the language designer designed the language from the start to be terse
*inline function syntax(or the lambda) - the ability to write inline functions and pass them around as variables makes many kinds of code more brief. In particular this is true for list/array operations. The roots of this ideas was obviously - LISP.
*Metaprogramming - metaprogramming is a big part of what makes rails tick. It gave rise to a new way of refactoring code that allowed the client code of your library to be much more succinct. This also originate from LISP.
All three of these features are not exclusive to dynamic languages, but they certainly are not present in the popular static languages of today: Java and C#. You might argue C# has #2 in delegates, but I would argue that it's not widely used at all - such as with list operations.
As for more advanced static languages... Haskell is a wonderful language, it has #1 and #2, and although it doesn't have #3, it's type system is so flexible that you will probably not find the lack of meta to be limiting. I believe you can do metaprogramming in OCaml at compile time with a language extension. Scala is a very recent addition and is very promising. F# for the .NET camp. But, users of these languages are in the minority, and so they didn't really contribute to this change in the programming languages landscape. In fact, I very much believe the popularity of Ruby affected the popularity of languages like Haskell, OCaml, Scala, and F# in a positive way, in addition to the other dynamic languages.
A: Don't forget that you need to write 10x code coverage in unit tests to replace what your compiler does :D
I've been there, done that with dynamic languages, and I see absolutely no advantage.
A: Personally, I think it's just that most of the "dynamic" languages you have used just happen to be poor examples of languages in general.
I am way more productive in Python than in C or Java, and not just because you have to do the edit-compile-link-run dance. I'm getting more productive in Objective-C, but that's probably more due to the framework.
Needless to say, I am more productive in any of these languages than PHP. Hell, I'd rather code in Scheme or Prolog than PHP. (But lately I've actually been doing more Prolog than anything else, so take that with a grain of salt!)
A: My appreciation for dynamic languages is very much tied to how functional they are. Python's list comprehensions, Ruby's closures, and JavaScript's prototyped objects are all very appealing facets of those languages. All also feature first-class functions--something I can't see living without ever again.
I wouldn't categorize PHP and VB (script) in the same way. To me, those are mostly imperative languages with all of the dynamic-typing drawbacks that you suggest.
Sure, you don't get the same level of compile-time checks (since there ain't a compile time), but I would expect static syntax-checking tools to evolve over time to at least partially address that issue.
A: One of the advantages pointed out for dynamic languages is to just be able to change the code and continue running. No need to recompile. In VS.Net 2008, when debugging, you can actually change the code, and continue running, without a recompile. With advances in compilers and IDEs, is it possible that this and other advantages of using dynamic languages will go away.
A: Ah, I didn't see this topic when I posted similar question
Aside from good features the rest of the folks mentioned here about dynamic languages, I think everybody forget one, the most basic thing: metaprogramming.
Programming the program.
Its pretty hard to do in compiled languages, generally, take for example .Net. To make it work you have to make all kind of mambo jumbo and it usualy ends with code that runs around 100 times slower.
Most dynamic languages have a way to do metaprogramming and that is something that keeps me there - ability to create any kind of code in memory and perfectly integrate it into my applicaiton.
For instance to create calculator in Lua, all I have to do is:
print( loadstring( "return " .. io.read() )() )
Now, try to do that in .Net.
A: My main reason for liking dynamic (typed, since that seems to be the focus of the thread) languages is that the ones I've used (in a work environment) are far superior to the non-dynamic languages I've used. C, C++, Java, etc... they're all horrible languages for getting actual work done in. I'd love to see an implicitly typed language that's as natural to program in as many of the dynamically typed ones.
That being said, there's certain constructs that are just amazing in dynamically typed languages. For example, in Tcl
lindex $mylist end-2
The fact that you pass in "end-2" to indicate the index you want is incredibly concise and obvious to the reader. I have yet to see a statically typed language that accomplishes such.
A: I think this kind of argument is a bit stupid: "Things that usually would have been caught by the compiler such as misspelled variable names and assigning an value of the wrong type to a variable don't occur until runtime" yes thats right as a PHP developer I don't see things like mistyped variables until runtime, BUT runtime is step 2 for me, in C++ (Which is the only compiled language I have any experience) it is step 3, after linking, and compiling.
Not to mention that it takes all of a few seconds after I hit save to when my code is ready to run, unlike in compiled languages where it can take literally hours. I'm sorry if this sounds a bit angry, but I'm kind of tired of people treating me as a second rate programmer because I don't have to compile my code.
A: When reading other people's responses, it seems that there are more or less three arguments for dynamic languages:
1) The code is less verbose.
I don't find this valid. Some dynamic languages are less verbose than some static ones. But F# is statically typed, but the static typing there does not add much, if any, code. It is implicitly typed, though, but that is a different thing.
2) "My favorite dynamic language X has my favorite functional feature Y, so therefore dynamic is better". Don't mix up functional and dynamic (I can't understand why this has to be said).
3) In dynamic languages you can see your results immediately. News: You can do that with C# in Visual Studio (since 2005) too. Just set a breakpoint, run the program in the debugger and modify the program while debbuging. I do this all the time and it works perfectly.
Myself, I'm a strong advocate for static typing, for one primary reason: maintainability. I have a system with a couple 10k lines of JavaScript in it, and any refactoring I want to do will take like half a day since the (non-existent) compiler will not tell me what that variable renaming messed up. And that's code I wrote myself, IMO well structured, too. I wouldn't want the task of being put in charge of an equivalent dynamic system that someone else wrote.
I guess I will be massively downvoted for this, but I'll take the chance.
A: The argument is more complex than this (read Yegge's article "Is Weak Typing Strong Enough" for an interesting overview).
Dynamic languages don't necessarily lack error checking either - C#'s type inference is possibly one example. In the same way, C and C++ have terrible compile checks and they are statically typed.
The main advantages of dynamic languages are a) capability (which doesn't necessarily have to be used all the time) and b) Boyd's Law of Iteration.
The latter reason is massive.
A: Although I'm not a big fan of Ruby yet, I find dynamic languages to be really wonderful and powerful tools.
The idea that there is no type checking and variable declaration is not too big an issue really. Admittedly, you can't catch these errors until run time, but for experienced developers this is not really an issue, and when you do make mistakes, they're usually easily fixed.
It also forces novices to read what they're writing more carefully. I know learning PHP taught me to be more attentive to what I was actually typing, which has improved my programming even in compiled languages.
Good IDEs will give enough intellisense for you to know whether a variable has been "declared" and they also try to do some type inference for you so that you can tell what a variable is.
The power of what can be done with dynamic languages is really what makes them so much fun to work with in my opinion. Sure, you could do the same things in a compiled language, but it would take more code. Languages like Python and PHP let you develop in less time and get a functional codebase faster most of the time.
And for the record, I'm a full-time .NET developer, and I love compiled languages. I only use dynamic languages in my free time to learn more about them and better myself as a developer..
A: I think that we need the different types of languages depending on what we are trying to achieve, or solve with them. If we want an application that creates, retrieves, updates and deletes records from the database over the internet, we are better off doing it with one line of ROR code (using the scaffold) than writing it from scratch in a statically typed language. Using dynamic languages frees up the minds from wondering about
*
*which variable has which type
*how to grow a string dynamically as needs be
*how to write code so that if i change type of one variable, i dont have to rewrite all the function that interact with it
to problems that are closer to business needs like
*
*data is saving/updating etc in the database, how do i use it to drive traffic to my site
Anyway, one advantage of loosely typed languages is that we dont really care what type it is, if it behaves like what it is supposed to. That is the reason we have duck-typing in dynamically typed languages. it is a great feature and i can use the same variable names to store different types of data as the need arises. also, statically typed languages force you to think like a machine (how does the compiler interact with your code, etc etc) whereas dynamically typed languages, especially ruby/ror, force the machine to think like a human.
These are some of the arguments i use to justify my job and experience in dynamic languages!
A: VBScript sucks, unless you're comparing it to another flavor of VB.
PHP is ok, so long as you keep in mind that it's an overgrown templating language.
Modern Javascript is great. Really. Tons of fun. Just stay away from any scripts tagged "DHTML".
I've never used a language that didn't allow runtime errors. IMHO, that's largely a red-herring: compilers don't catch all typos, nor do they validate intent. Explicit typing is great when you need explicit types, but most of the time, you don't. Search for the questions here on generics or the one about whether or not using unsigned types was a good choice for index variables - much of the time, this stuff just gets in the way, and gives folks knobs to twiddle when they have time on their hands.
But, i haven't really answered your question. Why are dynamic languages appealing? Because after a while, writing code gets dull and you just want to implement the algorithm. You've already sat and worked it all out in pen, diagrammed potential problem scenarios and proved them solvable, and the only thing left to do is code up the twenty lines of implementation... and two hundred lines of boilerplate to make it compile. Then you realize that the type system you work with doesn't reflect what you're actually doing, but someone else's ultra-abstract idea of what you might be doing, and you've long ago abandoned programming for a life of knicknack tweaking so obsessive-compulsive that it would shame even fictional detective Adrian Monk.
That's when you go get plastered start looking seriously at dynamic languages.
A: I am a full-time .Net programmer fully entrenched in the throes of statically-typed C#. However, I love modern JavaScript.
Generally speaking, I think dynamic languages allow you to express your intent more succinctly than statically typed languages as you spend less time and space defining what the building blocks are of what you are trying to express when in many cases they are self evident.
I think there are multiple classes of dynamic languages, too. I have no desire to go back to writing classic ASP pages in VBScript. To be useful, I think a dynamic language needs to support some sort of collection, list or associative construct at its core so that objects (or what pass for objects) can be expressed and allow you to build more complex constructs. (Maybe we should all just code in LISP ... it's a joke ...)
I think in .Net circles, dynamic languages get a bad rap because they are associated with VBScript and/or JavaScript. VBScript is just a recalled as a nightmare for many of the reasons Kibbee stated -- anybody remember enforcing type in VBScript using CLng to make sure you got enough bits for a 32-bit integer. Also, I think JavaScript is still viewed as the browser language for drop-down menus that is written a different way for all browsers. In that case, the issue is not language, but the various browser object models. What's interesting is that the more C# matures, the more dynamic it starts to look. I love Lambda expressions, anonymous objects and type inference. It feels more like JavaScript everyday.
A:
Here is a statically typed QuickSort in two lines of Haskell (from haskell.org):
qsort [] = []
qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)
And here is a dynamically typed QuickSort in LISP (from swisspig.net):
(defun quicksort (lis) (if (null lis) nil
(let* ((x (car lis)) (r (cdr lis)) (fn (lambda (a) (< a x))))
(append (quicksort (remove-if-not fn r)) (list x)
(quicksort (remove-if fn r))))))
I think you're biasing things with your choice of language here. Lisp is notoriously paren-heavy. A closer equivelent to Haskell would be Python.
if len(L) <= 1: return L
return qsort([lt for lt in L[1:] if lt < L[0]]) + [L[0]] + qsort([ge for ge in L[1:] if ge >= L[0]])
Python code from here
A: For me, the advantage of dynamic languages is how much more readable the code becomes due to less code and functional techniques like Ruby's block and Python's list comprehension.
But then I kind of miss the compile time checking (typo does happen) and IDE auto complete. Overall, the lesser amount of code and readability pays off for me.
Another advantage is the usually interpreted/non compiled nature of the language. Change some code and see the result immediately. It's really a time saver during development.
Last but not least, I like the fact that you can fire up a console and try out something you're not sure of, like a class or method that you've never used before and see how it behaves. There are many uses for the console and I'll just leave that for you to figure out.
A: Your arguments against dynamic languages are perfectly valid. However, consider the following:
*
*Dynamic languages don't need to be compiled: just run them. You can even reload the files at run time without restarting the application in most cases.
*Dynamic languages are generally less verbose and more readable: have you ever looked at a given algorithm or program implemented in a static language, then compared it to the Ruby or Python equivalent? In general, you're looking at a reduction in lines of code by a factor of 3. A lot of scaffolding code is unnecessary in dynamic languages, and that means the end result is more readable and more focused on the actual problem at hand.
*Don't worry about typing issues: the general approach when programming in dynamic languages is not to worry about typing: most of the time, the right kind of argument will be passed to your methods. And once in a while, someone may use a different kind of argument that just happens to work as well. When things go wrong, your program may be stopped, but this rarely happens if you've done a few tests.
I too found it a bit scary to step away from the safe world of static typing at first, but for me the advantages by far outweigh the disadvantages, and I've never looked back.
A: I think the reason is that people are used to statically typed languages that have very limited and inexpressive type systems. These are languages like Java, C++, Pascal, etc. Instead of going in the direction of more expressive type systems and better type inference, (as in Haskell, for example, and even SQL to some extent), some people like to just keep all the "type" information in their head (and in their tests) and do away with static typechecking altogether.
What this buys you in the end is unclear. There are many misconceived notions about typechecking, the ones I most commonly come across are these two.
Fallacy: Dynamic languages are less verbose. The misconception is that type information equals type annotation. This is totally untrue. We all know that type annotation is annoying. The machine should be able to figure that stuff out. And in fact, it does in modern compilers. Here is a statically typed QuickSort in two lines of Haskell (from haskell.org):
qsort [] = []
qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)
And here is a dynamically typed QuickSort in LISP (from swisspig.net):
(defun quicksort (lis) (if (null lis) nil
(let* ((x (car lis)) (r (cdr lis)) (fn (lambda (a) (< a x))))
(append (quicksort (remove-if-not fn r)) (list x)
(quicksort (remove-if fn r))))))
The Haskell example falsifies the hypothesis statically typed, therefore verbose. The LISP example falsifies the hypothesis verbose, therefore statically typed. There is no implication in either direction between typing and verbosity. You can safely put that out of your mind.
Fallacy: Statically typed languages have to be compiled, not interpreted. Again, not true. Many statically typed languages have interpreters. There's the Scala interpreter, The GHCi and Hugs interpreters for Haskell, and of course SQL has been both statically typed and interpreted for longer than I've been alive.
You know, maybe the dynamic crowd just wants freedom to not have to think as carefully about what they're doing. The software might not be correct or robust, but maybe it doesn't have to be.
Personally, I think that those who would give up type safety to purchase a little temporary liberty, deserve neither liberty nor type safety.
A: I think both styles have their strengths. This either/or thinking is kind of crippling to our community in my opinion. I've worked in architectures that were statically-typed from top to bottom and it was fine. My favorite architecture is for dynamically-typed at the UI level and statically-typed at the functional level. This also encourages a language barrier that enforces the separation of UI and function.
To be a cynic, it may be simply that dynamic languages allow the developer to be lazier and to get things done knowing less about the fundamentals of computing. Whether this is a good or bad thing is up to the reader :)
A: FWIW, Compiling on most applications shouldn't take hours. I have worked with applications that are between 200-500k lines that take minutes to compile. Certainly not hours.
I prefer compiled languages myself. I feel as though the debugging tools (in my experience, which might not be true for everything) are better and the IDE tools are better.
I like being able to attach my Visual Studio to a running process. Can other IDEs do that? Maybe, but I don't know about them. I have been doing some PHP development work lately and to be honest it isn't all that bad. However, I much prefer C# and the VS IDE. I feel like I work faster and debug problems faster.
So maybe it is more a toolset thing for me than the dynamic/static language issue?
One last comment... if you are developing with a local server saving is faster than compiling, but often times I don't have access to everything on my local machine. Databases and fileshares live elsewhere. It is easier to FTP to the web server and then run my PHP code only to find the error and have to fix and re-ftp.
A: Productivity in a certain context. But that is just one environment I know, compared to some others I know or have seen used.
Smalltalk on Squeak/Pharo with Seaside is a much more effective and efficient web platform than ASP.Net(/MVC), RoR or Wicket, for complex applications. Until you need to interface with something that has libraries in one of those but not smalltalk.
Misspelled variable names are red in the IDE, IntelliSense works but is not as specific. Run-time errors on webpages are not an issue but a feature, one click to bring up the debugger, one click to my IDE, fix the bug in the debugger, save, continue. For simple bugs, the round-trip time for this cycle is less than 20 seconds.
A: Dynamic Languages Strike Back
http://www.youtube.com/watch?v=tz-Bb-D6teE
A talk discussing Dynamic Languages, what some of the positives are, and how many of the negatives aren't really true.
A: Put yourself in the place of a brand new programmer selecting a language to start out with, who doesn't care about dynamic versus staic versus lambdas versus this versus that etc.; which language would YOU choose?
C#
using System;
class MyProgram
{
public static void Main(string[] args)
{
foreach (string s in args)
{
Console.WriteLine(s);
}
}
}
Lua:
function printStuff(args)
for key,value in pairs(args) do
print value .. " "
end
end
strings = {
"hello",
"world",
"from lua"
}
printStuff(strings)
A: Because I consider stupid having to declare the type of the box.
The type stays with the entity, not with the container. Static typing had a sense when the type of the box had a direct consequence on how the bits in memory were interpreted.
If you take a look at the design patterns in the GoF, you will realize that a good part of them are there just to fight with the static nature of the language, and they have no reason whatsoever to exist in a dynamic language.
Also, I'm tired of having to write stuff like MyFancyObjectInterface f = new MyFancyObject(). DRY principle anyone ?
A: This all comes down to partially what's appropriate for the particular goals and what's a common personal preference. (E.G. Is this going to be a huge code base maintained by more people than can conduct a reasonable meeting together? You want type checking.)
The personal part is about trading off some checks and other steps for development and testing speed (while likely giving up some cpu performance). There's some people for which this is liberating and a performance boost, and there's some for which this is quite the opposite, and yes it does sort of depend on the particular flavor of your language too. I mean no one here is saying Java rocks for speedy, terse development, or that PHP is a solid language where you'll rarely make a hard to spot typo.
A: I have love for both static and dynamic languages. Every project that I've been involved in since about 2002 has been a C/C++ application with an embedded Python interpret. This gives me the best of both worlds:
*
*The components and frameworks that make up the application are, for a given release of an application, immutable. They must also be very stable, and hence, well tested. A Statically typed language is the right choice for building these parts.
*The wiring up of components, loading of component DLLs, artwork, most of the GUI, etc... can vary greatly (say, to customise the application for a client) with no need to change any framework or components code. A dynamic language is perfect for this.
I find that the mix of a statically typed language to build the system and a dynamically type language to configure it gives me flexibility, stability and productivity.
To answer the question of "What's with the love of dynamic languages?" For me it's the ability to completely re-wire a system at runtime in any way imaginable. I see the scripting language as "running the show", therefore the executing application may do anything you desire.
A: I don't have much experience with dynamic languages in general, but the one dynamic language I do know, JavaScript(aka ECMAScript), I absolutely love.
Well, wait, what's the discussion here? Dynamic compilation? Or dynamic typing? JavaScript covers both bases so I guess I'll talk about both:
Dynamic compilation:
To begin, dynamic languages are compiled, the compilation is simply put off until later. And Java and .NET really are compiled twice. Once to their respective intermediate languages, and again, dynamically, to machine code.
But when compilation is put off you can see results faster. That's one advantage. I do enjoy simply saving the file and seeing my program in action fairly quick.
Another advantage is that you can write and compile code at runtime. Whether this is possible in statically compiled code, I don't know. I imagine it must be, since whatever compiles JavaScript is ultimately machine code and statically compiled. But in a dynamic language this is a trivial thing to do. Code can write and run itself. (And I'm pretty sure .NET can do this, but the CIL that .NET compiles to is dynamically compiled on the fly anyways, and it's not so trivial in C#)
Dynamic typing:
I think dynamic typing is more expressive than static typing. Note that I'm using the term expressive informally to say that dynamic typing can say more with less. Here's some JavaScript code:
var Person = {};
Do you know what Person is now? It's a generic dictionary. I can do this:
Person["First_Name"] = "John";
Person["Last_Name"] = "Smith";
But it's also an object. I could refer to any of those "keys" like this:
Person.First_Name
And add any methods I deem necessary:
Person.changeFirstName = function(newName) {
this.First_Name = newName;
};
Sure, there might be problems if newName isn't a string. It won't be caught right away, if ever, but you can check yourself. It's a matter of trading expressive power and flexibility for safety. I don't mind adding code to check types, etc, myself, and I've yet to run into a type bug that gave me much grief (and I know that isn't saying much. It could be a matter of time :) ). I very much enjoy, however, that ability to adapt on the fly.
A: Nice blog post on the same topic: Python Makes Me Nervous
Method signatures are virtually
useless in Python. In Java, static
typing makes the method signature into
a recipe: it's all the shit you need
to make this method work. Not so in
Python. Here, a method signature will
only tell you one thing: how many
arguments you need to make it work.
Sometimes, it won't even do that, if
you start fucking around with
**kwargs.
A: Because it's fun fun fun. It's fun to not worry about memory allocation, for one. It's fun not waiting for compilation. etc etc etc
A: Weakly typed languages allow flexibility in how you manage your data.
I used VHDL last spring for several classes, and I like their method of representing bits/bytes, and how the compiler catches errors if you try to assign a 6-bit bus to a 9-bit bus. I tried to recreate it in C++, and I'm having a fair struggle to neatly get the typing to work smoothly with existing types. Steve Yegge does a very nice job of describing the issues involved with strong type systems, I think.
Regarding verbosity: I find Java and C# to be quite verbose in the large(let's not cherry-pick small algorithms to "prove" a point). And, yes, I've written in both. C++ struggles in the same area as well; VHDL succumbs here.
Parsimony appears to be a virtue of the dynamic languages in general(I present Perl and F# as examples).
A: Theoretically it's possible for a statically typed languages to have the benefits of dynamic languages, and theoretically it's also possible for dynamic languages to suck and cause more headache than pleasure.
However, in practice, dynamic languages allow you to write code quickly, without too much boilerplate, without worrying about low level details.
Yes, in theory a c-style language can provide similar features (D tries, with auto type discovery and dmdr which compiles modules and runs them on the fly as if they were scripts),
So yes, the naysayers are right, in that being dynamic doesn't necessarily mean easier/cleaner code.
but, in practice, Python > Java
Try w = "my string here".split()[1] in C, or even Java.
A: To me it is a matter of situation. I spend a lot of time writing Perl code for websites and C++ for graphics engines. Two completely different realms of programming with two very different languages.
Dynamic languages, for me anyways, are faster to work out as I spend less time making sure the framework is in place and more on the actual problem at hand.
However static languages offer more fine-tuned control which can be necessary in some application such as real-time graphics rendering. I can do things in C++ that run far more efficiently and faster than what I would write for Perl, but for the size of most Perl scripts the loss in efficiency is negligible.
In the end it really comes down to the problem statement and what your target goals are. If you have a lot of simple things to do where speed and memory efficiency aren't a big deal, use a dynamic language. If you have a megalithic project that needs to squeeze every last cycle out of your system, go static.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "81"
} |
Q: Load readonly database tables into memory In one of my applications I have a 1gb database table that is used for reference data. It has a huge amounts of reads coming off that table but there are no writes ever. I was wondering if there's any way that data could be loaded into RAM so that it doesn't have to be accessed from disk?
I'm using SQL Server 2005
A: If you have enough RAM, SQL will do an outstanding job determining what to load into RAM and what to seek on disk.
This question is asked a lot and it reminds me of people trying to manually set which "core" their process will run on -- let the OS (or in this case the DB) do what it was designed for.
If you want to verify that SQL is in fact reading your look-up data out of cache, then you can initiate a load test and use Sysinternals FileMon, Process Explorer and Process Monitor to verify that the 1GB table is not being read from. For this reason, we sometimes put our "lookup" data onto a separate filegroup so that it is very easy to monitor when it is being accessed on disk.
Hope this helps.
A: You're going to want to take a look at memcached. It's what a lot of huge (and well-scaled) sites used to handle problems just like this. If you have a few spare servers, you can easily set them up to keep most of your data in memory.
http://en.wikipedia.org/wiki/Memcached
http://www.danga.com/memcached/
http://www.socialtext.net/memcached/
A: Just to clarify the issue for the sql2005 and up:
This functionality was introduced for
performance in SQL Server version 6.5.
DBCC PINTABLE has highly unwanted
side-effects. These include the
potential to damage the buffer pool.
DBCC PINTABLE is not required and has
been removed to prevent additional
problems. The syntax for this command
still works but does not affect the
server.
A: DBCC PINTABLE will explicitly pin a table in core if you want to make sure it remains cached.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: URL Rewrite Module for IIS 7 Does anyone have experience using the URL Rewrite Module (see here)?
Can it be used to do reverse proxy?
A: No it can not. You have to use a tool like .NET URL Rewriter and Reverse Proxy
http://codeplex.com/urlrewriter
It also supports IIS 6.0, and is accomplished completely through the .NET Framework.
A: That http://codeplex.com/urlrewriter is quite cool, as it supports the standard mod_rewrite syntax.
We use the Microsoft IIS7 URL Rewriter here at SO with great success, though we did have to update to the newer Go-Live license version to get rid of some preview exceptions. Also it doesn't support mod_rewrite syntax, but there is a tool included to convert back and forth to Microsoft's XML based routing table format. (sigh, XML).
However it does not do reverse proxy as Nick noted. You may need to install Application Request Routing for IIS7 which apparently offers this feature..
A: You can implement the reverse proxy by using both URL Rewrite Module and Application Request Routing module as explained in the article "Reverse Proxy with URL Rewrite and Application Request Routing".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to get the last day of the month? Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?
If the standard library doesn't support that, does the dateutil package support this?
A: import datetime
now = datetime.datetime.now()
start_month = datetime.datetime(now.year, now.month, 1)
date_on_next_month = start_month + datetime.timedelta(35)
start_next_month = datetime.datetime(date_on_next_month.year, date_on_next_month.month, 1)
last_day_month = start_next_month - datetime.timedelta(1)
A: Here is another answer. No extra packages required.
datetime.date(year + int(month/12), month%12+1, 1)-datetime.timedelta(days=1)
Get the first day of the next month and subtract a day from it.
A: That's my way - a function with only two lines:
from dateutil.relativedelta import relativedelta
def last_day_of_month(date):
return date.replace(day=1) + relativedelta(months=1) - relativedelta(days=1)
Example:
from datetime import date
print(last_day_of_month(date.today()))
>> 2021-09-30
A: The easiest & most reliable way I've found so Far is as:
from datetime import datetime
import calendar
days_in_month = calendar.monthrange(2020, 12)[1]
end_dt = datetime(2020, 12, days_in_month)
A: EDIT: see my other answer. It has a better implementation than this one, which I leave here just in case someone's interested in seeing how one might "roll your own" calculator.
@John Millikin gives a good answer, with the added complication of calculating the first day of the next month.
The following isn't particularly elegant, but to figure out the last day of the month that any given date lives in, you could try:
def last_day_of_month(date):
if date.month == 12:
return date.replace(day=31)
return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)
>>> last_day_of_month(datetime.date(2002, 1, 17))
datetime.date(2002, 1, 31)
>>> last_day_of_month(datetime.date(2002, 12, 9))
datetime.date(2002, 12, 31)
>>> last_day_of_month(datetime.date(2008, 2, 14))
datetime.date(2008, 2, 29)
A: you can use relativedelta
https://dateutil.readthedocs.io/en/stable/relativedelta.html
month_end = <your datetime value within the month> + relativedelta(day=31)
that will give you the last day.
A: This is the simplest solution for me using just the standard datetime library:
import datetime
def get_month_end(dt):
first_of_month = datetime.datetime(dt.year, dt.month, 1)
next_month_date = first_of_month + datetime.timedelta(days=32)
new_dt = datetime.datetime(next_month_date.year, next_month_date.month, 1)
return new_dt - datetime.timedelta(days=1)
A: Using dateutil.relativedelta
dt + dateutil.relativedelta.relativedelta(months=1, day=1, days=-1)
months=1 and day=1 would shift dt to the first date of next month, then days=-1 would shift the new date to previous date which is exactly the last date of current month.
A: For me it's the simplest way:
selected_date = date(some_year, some_month, some_day)
if selected_date.month == 12: # December
last_day_selected_month = date(selected_date.year, selected_date.month, 31)
else:
last_day_selected_month = date(selected_date.year, selected_date.month + 1, 1) - timedelta(days=1)
A: You can calculate the end date yourself. the simple logic is to subtract a day from the start_date of next month. :)
So write a custom method,
import datetime
def end_date_of_a_month(date):
start_date_of_this_month = date.replace(day=1)
month = start_date_of_this_month.month
year = start_date_of_this_month.year
if month == 12:
month = 1
year += 1
else:
month += 1
next_month_start_date = start_date_of_this_month.replace(month=month, year=year)
this_month_end_date = next_month_start_date - datetime.timedelta(days=1)
return this_month_end_date
Calling,
end_date_of_a_month(datetime.datetime.now().date())
It will return the end date of this month. Pass any date to this function. returns you the end date of that month.
A: The easiest way (without having to import calendar), is to get the first day of the next month, and then subtract a day from it.
import datetime as dt
from dateutil.relativedelta import relativedelta
thisDate = dt.datetime(2017, 11, 17)
last_day_of_the_month = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)
print last_day_of_the_month
Output:
datetime.datetime(2017, 11, 30, 0, 0)
PS: This code runs faster as compared to the import calendarapproach; see below:
import datetime as dt
import calendar
from dateutil.relativedelta import relativedelta
someDates = [dt.datetime.today() - dt.timedelta(days=x) for x in range(0, 10000)]
start1 = dt.datetime.now()
for thisDate in someDates:
lastDay = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)
print ('Time Spent= ', dt.datetime.now() - start1)
start2 = dt.datetime.now()
for thisDate in someDates:
lastDay = dt.datetime(thisDate.year,
thisDate.month,
calendar.monthrange(thisDate.year, thisDate.month)[1])
print ('Time Spent= ', dt.datetime.now() - start2)
OUTPUT:
Time Spent= 0:00:00.097814
Time Spent= 0:00:00.109791
This code assumes that you want the date of the last day of the month (i.e., not just the DD part, but the entire YYYYMMDD date)
A: The simplest way is to use datetime and some date math, e.g. subtract a day from the first day of the next month:
import datetime
def last_day_of_month(d: datetime.date) -> datetime.date:
return (
datetime.date(d.year + d.month//12, d.month % 12 + 1, 1) -
datetime.timedelta(days=1)
)
Alternatively, you could use calendar.monthrange() to get the number of days in a month (taking leap years into account) and update the date accordingly:
import calendar, datetime
def last_day_of_month(d: datetime.date) -> datetime.date:
return d.replace(day=calendar.monthrange(d.year, d.month)[1])
A quick benchmark shows that the first version is noticeably faster:
In [14]: today = datetime.date.today()
In [15]: %timeit last_day_of_month_dt(today)
918 ns ± 3.54 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [16]: %timeit last_day_of_month_calendar(today)
1.4 µs ± 17.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
A: Using dateutil.relativedelta you would get last date of month like this:
from dateutil.relativedelta import relativedelta
last_date_of_month = datetime(mydate.year, mydate.month, 1) + relativedelta(months=1, days=-1)
The idea is to get the first day of the month and use relativedelta to go 1 month ahead and 1 day back so you would get the last day of the month you wanted.
A: This does not address the main question, but one nice trick to get the last weekday in a month is to use calendar.monthcalendar, which returns a matrix of dates, organized with Monday as the first column through Sunday as the last.
# Some random date.
some_date = datetime.date(2012, 5, 23)
# Get last weekday
last_weekday = np.asarray(calendar.monthcalendar(some_date.year, some_date.month))[:,0:-2].ravel().max()
print last_weekday
31
The whole [0:-2] thing is to shave off the weekend columns and throw them out. Dates that fall outside of the month are indicated by 0, so the max effectively ignores them.
The use of numpy.ravel is not strictly necessary, but I hate relying on the mere convention that numpy.ndarray.max will flatten the array if not told which axis to calculate over.
A: Here is a long (easy to understand) version but takes care of leap years.
def last_day_month(year, month):
leap_year_flag = 0
end_dates = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31
}
# Checking for regular leap year
if year % 4 == 0:
leap_year_flag = 1
else:
leap_year_flag = 0
# Checking for century leap year
if year % 100 == 0:
if year % 400 == 0:
leap_year_flag = 1
else:
leap_year_flag = 0
else:
pass
# return end date of the year-month
if leap_year_flag == 1 and month == 2:
return 29
elif leap_year_flag == 1 and month != 2:
return end_dates[month]
else:
return end_dates[month]
A: How about more simply:
import datetime
now = datetime.datetime.now()
datetime.date(now.year, 1 if now.month==12 else now.month+1, 1) - datetime.timedelta(days=1)
A: If you don't want to import the calendar module, a simple two-step function can also be:
import datetime
def last_day_of_month(any_day):
# The day 28 exists in every month. 4 days later, it's always next month
next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
# subtracting the number of the current day brings us back one month
return next_month - datetime.timedelta(days=next_month.day)
Outputs:
>>> for month in range(1, 13):
... print(last_day_of_month(datetime.date(2022, month, 1)))
...
2022-01-31
2022-02-28
2022-03-31
2022-04-30
2022-05-31
2022-06-30
2022-07-31
2022-08-31
2022-09-30
2022-10-31
2022-11-30
2022-12-31
A: >>> import datetime
>>> import calendar
>>> date = datetime.datetime.now()
>>> print date
2015-03-06 01:25:14.939574
>>> print date.replace(day = 1)
2015-03-01 01:25:14.939574
>>> print date.replace(day = calendar.monthrange(date.year, date.month)[1])
2015-03-31 01:25:14.939574
A: from datetime import timedelta
(any_day.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1)
A: In Python 3.7 there is the undocumented calendar.monthlen(year, month) function:
>>> calendar.monthlen(2002, 1)
31
>>> calendar.monthlen(2008, 2)
29
>>> calendar.monthlen(2100, 2)
28
It is equivalent to the documented calendar.monthrange(year, month)[1] call.
A: If you want to make your own small function, this is a good starting point:
def eomday(year, month):
"""returns the number of days in a given month"""
days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
d = days_per_month[month - 1]
if month == 2 and (year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
d = 29
return d
For this you have to know the rules for the leap years:
*
*every fourth year
*with the exception of every 100 year
*but again every 400 years
A: import calendar
from time import gmtime, strftime
calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]
Output:
31
This will print the last day of whatever the current month is. In this example it was 15th May, 2016. So your output may be different, however the output will be as many days that the current month is. Great if you want to check the last day of the month by running a daily cron job.
So:
import calendar
from time import gmtime, strftime
lastDay = calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]
today = strftime("%d", gmtime())
lastDay == today
Output:
False
Unless it IS the last day of the month.
A: I prefer this way
import datetime
import calendar
date=datetime.datetime.now()
month_end_date=datetime.datetime(date.year,date.month,1) + datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1] - 1)
A: I've managed to find interesting solution here. It's possible to get last day of the month providing those relativedelta args: day=31, days=+1 and seconds=-1 (which gives you last second of previous day):
import datetime
from dateutil.relativedelta import relativedelta
day_of_febuary = datetime.datetime(2022, 2, 21)
last_day_of_febuary = day_of_febuary + relativedelta(day=31, days=+1, seconds=-1)
print(last_day_of_febuary)
# Output: 2022-02-28 23:59:59
A: My approach:
def get_last_day_of_month(mon: int, year: int) -> str:
'''
Returns last day of the month.
'''
### Day 28 falls in every month
res = datetime(month=mon, year=year, day=28)
### Go to next month
res = res + timedelta(days=4)
### Subtract one day from the start of the next month
res = datetime.strptime(res.strftime('%Y-%m-01'), '%Y-%m-%d') - timedelta(days=1)
return res.strftime('%Y-%m-%d')
>>> get_last_day_of_month(mon=10, year=2022)
... '2022-10-31'
A: Another solution would be to do something like this:
from datetime import datetime
def last_day_of_month(year, month):
""" Work out the last day of the month """
last_days = [31, 30, 29, 28, 27]
for i in last_days:
try:
end = datetime(year, month, i)
except ValueError:
continue
else:
return end.date()
return None
And use the function like this:
>>>
>>> last_day_of_month(2008, 2)
datetime.date(2008, 2, 29)
>>> last_day_of_month(2009, 2)
datetime.date(2009, 2, 28)
>>> last_day_of_month(2008, 11)
datetime.date(2008, 11, 30)
>>> last_day_of_month(2008, 12)
datetime.date(2008, 12, 31)
A: calendar.monthrange provides this information:
calendar.monthrange(year, month)
Returns weekday of first day of the month and number of days in month, for the specified year and month.
>>> import calendar
>>> calendar.monthrange(2002, 1)
(1, 31)
>>> calendar.monthrange(2008, 2) # leap years are handled correctly
(4, 29)
>>> calendar.monthrange(2100, 2) # years divisible by 100 but not 400 aren't leap years
(0, 28)
so:
calendar.monthrange(year, month)[1]
seems like the simplest way to go.
A: To get the last date of the month we do something like this:
from datetime import date, timedelta
import calendar
last_day = date.today().replace(day=calendar.monthrange(date.today().year, date.today().month)[1])
Now to explain what we are doing here we will break it into two parts:
first is getting the number of days of the current month for which we use monthrange which Blair Conrad has already mentioned his solution:
calendar.monthrange(date.today().year, date.today().month)[1]
second is getting the last date itself which we do with the help of replace e.g
>>> date.today()
datetime.date(2017, 1, 3)
>>> date.today().replace(day=31)
datetime.date(2017, 1, 31)
and when we combine them as mentioned on the top we get a dynamic solution.
A: EDIT: See @Blair Conrad's answer for a cleaner solution
>>> import datetime
>>> datetime.date(2000, 2, 1) - datetime.timedelta(days=1)
datetime.date(2000, 1, 31)
A: if you are willing to use an external library, check out http://crsmithdev.com/arrow/
U can then get the last day of the month with:
import arrow
arrow.utcnow().ceil('month').date()
This returns a date object which you can then do your manipulation.
A: To me the easier way is using pandas (two lines solution):
from datetime import datetime
import pandas as pd
firstday_month = datetime(year, month, 1)
lastday_month = firstday_month + pd.offsets.MonthEnd(1)
Another way to do it is: Taking the first day of the month, then adding one month and discounting one day:
from datetime import datetime
import pandas as pd
firstday_month = datetime(year, month, 1)
lastday_month = firstday_month + pd.DateOffset(months=1) - pd.DateOffset(days=1)
A: This is actually pretty easy with dateutil.relativedelta. day=31 will always always return the last day of the month:
import datetime
from dateutil.relativedelta import relativedelta
date_in_feb = datetime.datetime(2013, 2, 21)
print(datetime.datetime(2013, 2, 21) + relativedelta(day=31)) # End-of-month
# datetime.datetime(2013, 2, 28, 0, 0)
Install dateutil with
pip install python-datetutil
A: Use pandas!
def isMonthEnd(date):
return date + pd.offsets.MonthEnd(0) == date
isMonthEnd(datetime(1999, 12, 31))
True
isMonthEnd(pd.Timestamp('1999-12-31'))
True
isMonthEnd(pd.Timestamp(1965, 1, 10))
False
A: If you pass in a date range, you can use this:
def last_day_of_month(any_days):
res = []
for any_day in any_days:
nday = any_day.days_in_month -any_day.day
res.append(any_day + timedelta(days=nday))
return res
A: Here is a solution based python lambdas:
next_month = lambda y, m, d: (y, m + 1, 1) if m + 1 < 13 else ( y+1 , 1, 1)
month_end = lambda dte: date( *next_month( *dte.timetuple()[:3] ) ) - timedelta(days=1)
The next_month lambda finds the tuple representation of the first day of the next month, and rolls over to the next year. The month_end lambda transforms a date (dte) to a tuple, applies next_month and creates a new date. Then the "month's end" is just the next month's first day minus timedelta(days=1).
A: In the code below 'get_last_day_of_month(dt)' will give you this, with date in string format like 'YYYY-MM-DD'.
import datetime
def DateTime( d ):
return datetime.datetime.strptime( d, '%Y-%m-%d').date()
def RelativeDate( start, num_days ):
d = DateTime( start )
return str( d + datetime.timedelta( days = num_days ) )
def get_first_day_of_month( dt ):
return dt[:-2] + '01'
def get_last_day_of_month( dt ):
fd = get_first_day_of_month( dt )
fd_next_month = get_first_day_of_month( RelativeDate( fd, 31 ) )
return RelativeDate( fd_next_month, -1 )
A: Considering there are unequal number of days in different months, here is the standard solution that works for every month.
import datetime
ref_date = datetime.today() # or what ever specified date
end_date_of_month = datetime.strptime(datetime.strftime(ref_date + relativedelta(months=1), '%Y-%m-01'),'%Y-%m-%d') + relativedelta(days=-1)
In the above code we are just adding a month to our selected date and then navigating to the first day of that month and then subtracting a day from that date.
A: This one worked for me:
df['daysinmonths'] = df['your_date_col'].apply(lambda t: pd.Period(t, freq='S').days_in_month)
took reference from:
https://stackoverflow.com/a/66403016/16607636
A: If you need to get the first day of the month with 0:00 time and don't want to import any special library you can write like this
import pytz
from datetime import datetime, timedelta
# get now time with timezone (optional)
now = datetime.now(pytz.UTC)
# get first day on this month, get last day on prev month and after get first day on prev month with min time
fist_day_with_time = datetime.combine((now.replace(day=1) - timedelta(days=1)).replace(day=1), datetime.min.time())
Works fine with February 28/29, December - January, and another problem date.
A: If it only matters if today is the last day of the month and the date does not really matter, then I prefer to use the condition below.
The logic is quite simple. If tomorrow is the first day of the next month, then today is the last day of the actual month. Below two examples of an if-else condition.
from datetime import datetime, timedelta
if (datetime.today()+timedelta(days=1)).day == 1:
print("today is the last day of the month")
else:
print("today isn't the last day of the month")
If timezone awareness is important.
from datetime import datetime, timedelta
import pytz
set(pytz.all_timezones_set)
tz = pytz.timezone("Europe/Berlin")
dt = datetime.today().astimezone(tz=tz)
if (dt+timedelta(days=1)).day == 1:
print("today is the last day of the month")
else:
print("today isn't the last day of the month")
A: I think this is more readable than some of the other answers:
from datetime import timedelta as td
from datetime import datetime as dt
today = dt.now()
a_day_next_month = dt(today.year, today.month, 27) + td(days=5)
first_day_next_month = dt(a_day_next_month.year, a_day_next_month.month, 1)
last_day_this_month = first_day_next_month - td(days=1)
A: Another option is to use a recursive function.
Is the next day in a different month? If so, then the current day is the last day of the month. If the next day is in the same month, try again using that next day.
from datetime import timedelta
def last_day_of_month(date):
if date.month != (date + timedelta(days=1)).month:
return date
else:
return last_day_of_month(date + timedelta(days=1))
A: Use datetime-month package.
$ pip install datetime-month
$ python
>>> from month import XMonth
>>> Xmonth(2022, 11).last_date()
datetime.date(2022, 11, 30)
A: If you don't mind using Pandas, using Timestamp.days_in_month is probably the simplest:
import pandas as pd
> pd.Timestamp(year=2020, month=2, day=1).days_in_month
29
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "860"
} |
Q: Backward Converting SQL Databases Does anyone know of any free tools that can assist in converting an SQL2005 database back to SQL2000 format? I know that you can script all the objects and then do a dump of the data, but this is a lot of work to do manually.
A: Reviewing some other related questions I just found Microsoft's Database Publishing Wizard. It does most of what I need, although I have used nVarChar(max) in a couple of places and it simply fails to handle those cases and bombs out without generating anything.
A: Have you considered using DTS to transfer the data across? It should be independant of the version.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Google Suggestish text box (autocomplete) What would be the best way to develop a text box that remembers the last x number of entries that were put into it. This is a standalone app written with C#.
A: This is actually fairly easy, especially in terms of showing the "AutoComplete" part of it. In terms of remembering the last x number of entries, you are just going to have to decide on a particular event (or events) that you consider as an entry being completed and write that entry off to a list... an AutoCompleteStringCollection to be precise.
The TextBox class has the 3 following properties that you will need:
*
*AutoCompleteCustomSource
*AutoCompleteMode
*AutoCompleteSource
Set AutoCompleteMode to SuggestAppend and AutoCompleteSource to CustomSource.
Then at runtime, every time a new entry is made, use the Add() method of AutoCompleteStringCollection to add that entry to the list (and pop off any old ones if you want). You can actually do this operation directly on the AutoCompleteCustomSource property of the TextBox as long as you've already initialized it.
Now, every time you type in the TextBox it will suggest previous entries :)
See this article for a more complete example: http://www.c-sharpcorner.com/UploadFile/mahesh/AutoCompletion02012006113508AM/AutoCompletion.aspx
AutoComplete also has some built in features like FileSystem and URLs (though it only does stuff that was typed into IE...)
A: @Ethan
I forgot about the fact that you would want to save that so it wasn't a per session only thing :P But yes, you are completely correct.
This is easily done, especially since it's just basic strings, just write out the contents of AutoCompleteCustomSource from the TextBox to a text file, on separate lines.
I had a few minutes, so I wrote up a complete code example...I would've before as I always try to show code, but didn't have time. Anyway, here's the whole thing (minus the designer code).
namespace AutoComplete
{
public partial class Main : Form
{
//so you don't have to address "txtMain.AutoCompleteCustomSource" every time
AutoCompleteStringCollection acsc;
public Main()
{
InitializeComponent();
//Set to use a Custom source
txtMain.AutoCompleteSource = AutoCompleteSource.CustomSource;
//Set to show drop down *and* append current suggestion to end
txtMain.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
//Init string collection.
acsc = new AutoCompleteStringCollection();
//Set txtMain's AutoComplete Source to acsc
txtMain.AutoCompleteCustomSource = acsc;
}
private void txtMain_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Only keep 10 AutoComplete strings
if (acsc.Count < 10)
{
//Add to collection
acsc.Add(txtMain.Text);
}
else
{
//remove oldest
acsc.RemoveAt(0);
//Add to collection
acsc.Add(txtMain.Text);
}
}
}
private void Main_FormClosed(object sender, FormClosedEventArgs e)
{
//open stream to AutoComplete save file
StreamWriter sw = new StreamWriter("AutoComplete.acs");
//Write AutoCompleteStringCollection to stream
foreach (string s in acsc)
sw.WriteLine(s);
//Flush to file
sw.Flush();
//Clean up
sw.Close();
sw.Dispose();
}
private void Main_Load(object sender, EventArgs e)
{
//open stream to AutoComplete save file
StreamReader sr = new StreamReader("AutoComplete.acs");
//initial read
string line = sr.ReadLine();
//loop until end
while (line != null)
{
//add to AutoCompleteStringCollection
acsc.Add(line);
//read again
line = sr.ReadLine();
}
//Clean up
sr.Close();
sr.Dispose();
}
}
}
This code will work exactly as is, you just need to create the GUI with a TextBox named txtMain and hook up the KeyDown, Closed and Load events to the TextBox and Main form.
Also note that, for this example and to make it simple, I just chose to detect the Enter key being pressed as my trigger to save the string to the collection. There is probably more/different events that would be better, depending on your needs.
Also, the model used for populating the collection is not very "smart." It simply deletes the oldest string when the collection gets to the limit of 10. This is likely not ideal, but works for the example. You would probably want some sort of rating system (especially if you really want it to be Google-ish)
A final note, the suggestions will actually show up in the order they are in the collection. If for some reason you want them to show up differently, just sort the list however you like.
Hope that helps!
A: I store the completion list in the registry.
The code I use is below. It's reusable, in three steps:
*
*replace the namespace and classname in this code with whatever you use.
*Call the FillFormFromRegistry() on the Form's Load event, and call SaveFormToRegistry on the Closing event.
*compile this into your project.
You need to decorate the assembly with two attributes: [assembly: AssemblyProduct("...")] and [assembly: AssemblyCompany("...")] . (These attributes are normally set automatically in projects created within Visual Studio, so I don't count this as a step.)
Managing state this way is totally automatic and transparent to the user.
You can use the same pattern to store any sort of state for your WPF or WinForms app. Like state of textboxes, checkboxes, dropdowns. Also you can store/restore the size of the window - really handy - the next time the user runs the app, it opens in the same place, and with the same size, as when they closed it. You can store the number of times an app has been run. Lots of possibilities.
namespace Ionic.ExampleCode
{
public partial class NameOfYourForm
{
private void SaveFormToRegistry()
{
if (AppCuKey != null)
{
// the completion list
var converted = _completions.ToList().ConvertAll(x => x.XmlEscapeIexcl());
string completionString = String.Join("¡", converted.ToArray());
AppCuKey.SetValue(_rvn_Completions, completionString);
}
}
private void FillFormFromRegistry()
{
if (!stateLoaded)
{
if (AppCuKey != null)
{
// get the MRU list of .... whatever
_completions = new System.Windows.Forms.AutoCompleteStringCollection();
string c = (string)AppCuKey.GetValue(_rvn_Completions, "");
if (!String.IsNullOrEmpty(c))
{
string[] items = c.Split('¡');
if (items != null && items.Length > 0)
{
//_completions.AddRange(items);
foreach (string item in items)
_completions.Add(item.XmlUnescapeIexcl());
}
}
// Can also store/retrieve items in the registry for
// - textbox contents
// - checkbox state
// - splitter state
// - and so on
//
stateLoaded = true;
}
}
}
private Microsoft.Win32.RegistryKey AppCuKey
{
get
{
if (_appCuKey == null)
{
_appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(AppRegistryPath, true);
if (_appCuKey == null)
_appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(AppRegistryPath);
}
return _appCuKey;
}
set { _appCuKey = null; }
}
private string _appRegistryPath;
private string AppRegistryPath
{
get
{
if (_appRegistryPath == null)
{
// Use a registry path that depends on the assembly attributes,
// that are presumed to be elsewhere. Example:
//
// [assembly: AssemblyCompany("Dino Chiesa")]
// [assembly: AssemblyProduct("XPathVisualizer")]
var a = System.Reflection.Assembly.GetExecutingAssembly();
object[] attr = a.GetCustomAttributes(typeof(System.Reflection.AssemblyProductAttribute), true);
var p = attr[0] as System.Reflection.AssemblyProductAttribute;
attr = a.GetCustomAttributes(typeof(System.Reflection.AssemblyCompanyAttribute), true);
var c = attr[0] as System.Reflection.AssemblyCompanyAttribute;
_appRegistryPath = String.Format("Software\\{0}\\{1}",
p.Product, c.Company);
}
return _appRegistryPath;
}
}
private Microsoft.Win32.RegistryKey _appCuKey;
private string _rvn_Completions = "Completions";
private readonly int _MaxMruListSize = 14;
private System.Windows.Forms.AutoCompleteStringCollection _completions;
private bool stateLoaded;
}
public static class Extensions
{
public static string XmlEscapeIexcl(this String s)
{
while (s.Contains("¡"))
{
s = s.Replace("¡", "¡");
}
return s;
}
public static string XmlUnescapeIexcl(this String s)
{
while (s.Contains("¡"))
{
s = s.Replace("¡", "¡");
}
return s;
}
public static List<String> ToList(this System.Windows.Forms.AutoCompleteStringCollection coll)
{
var list = new List<String>();
foreach (string item in coll)
{
list.Add(item);
}
return list;
}
}
}
Some people shy away from using the Registry for storing state, but I find it's really easy and convenient. If you like, You can very easily build an installer that removes all the registry keys on uninstall.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.