text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Fixed Legend in Google Maps Mashup I have a page with a Google Maps mashup that has pushpins that are color-coded by day (Monday, Tuesday, etc.) The IFrame containing the map is dynamically sized, so it gets resized when the browser window is resized.
I'd like to put a legend in the corner of the map window that tells the user what each color means. The Google Maps API includes a GScreenOverlay class that has the behavior that I want, but it only lets you specify an image to use as an overlay, and I'd prefer to use a DIV with text in it. What's the easiest way to position a DIV over the map window in (for example) the lower left corner that'll automatically stay in the same place relative to the corner when the browser window is resized?
A: I would use HTML like the following:
<div id="wrapper">
<div id="map" style="width:400px;height:400px;"></div>
<div id="legend"> ... marker descriptions in here ... </div>
</div>
You can then style this to keep the legend in the bottom right:
div#wrapper { position: relative; }
div#legend { position: absolute; bottom: 0px; right: 0px; }
position: relative will cause any contained elements to be positioned relative to the #wrapper container, and position: absolute will cause the #legend div to be "pulled" out of the flow and sit above the map, keeping it's bottom right edge at the bottom of the #wrapper and stretching as required to contain the marker descriptions.
A: You can add your own Custom Control and use it as a legend.
This code will add a box 150w x 100h (Gray Border/ with White Background) and the words "Hello World" inside of it. You swap out the text for any HTML you would like in the legend. This will stay Anchored to the Top Right (G_ANCHOR_TOP_RIGHT) 10px down and 50px over of the map.
function MyPane() {}
MyPane.prototype = new GControl;
MyPane.prototype.initialize = function(map) {
var me = this;
me.panel = document.createElement("div");
me.panel.style.width = "150px";
me.panel.style.height = "100px";
me.panel.style.border = "1px solid gray";
me.panel.style.background = "white";
me.panel.innerHTML = "Hello World!";
map.getContainer().appendChild(me.panel);
return me.panel;
};
MyPane.prototype.getDefaultPosition = function() {
return new GControlPosition(
G_ANCHOR_TOP_RIGHT, new GSize(10, 50));
//Should be _ and not _
};
MyPane.prototype.getPanel = function() {
return me.panel;
}
map.addControl(new MyPane());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Vista speech recognition in multiple languages my primary language is spanish, but I use all my software in english, including windows; however I'd like to use speech recognition in spanish.
Do you know if there's a way to use vista's speech recognition in other language than the primary os language?
A: Citation from Vista speech recognition blog:
In Windows Vista, Windows Speech
Recognition works in the current
language of the OS. That means that
in order to use another language for
speech recognition, you have to have
the appropriate language pack
installed. Language packs are
available as free downloads through
Windows Update for the Ultimate and
Enterprise versions of Vista. Once
you have the language installed,
you’ll need to change the display
language of the OS to the language you
want to use. Both of these are
options on the “Regional and Language
Options” control panel. You can look
in help for “Install a display
language” or “Change the display
language”.
A: To complete aku's answer, you have here different methods to have a "multilingual use in Vista".
*
*Installing a language pack
*Switching to a different language (and back)
Creating computer users. Create a user for each language and change the display language for that user to the language of your preference. A new Speech profile will be automatically created for that user. Switch between your languages by the normal procedure of “switching to another user” (Log offà Switch users).
Note: You can create a speech recognition profile for each user with any name you prefer. Change the name, or create a new user, in the Advanced Speech panel.
COMMENTS:
The advantage of the Separate Users method is that you can switch back and forth without changing any computer defaults.
The disadvantages are that it takes more disk space and more attention must be given to user management, and that you may not have access to files opened or saved by your other users unless you know how to give yourself such an access via the new permission dialogues of Windows Vista.
A: You should look at System.Speech.Recognition.SpeechRecognitionEngine - it's an 'in-proc' recognizer that will let you specify the language you want.
Your next problem is that en-US Vista doesn't ship with the spanish recognition engine. For that, you'll need the Spanish Language Pack. Once you install that, you should be able to instantiate a spanish recognition engine like this:
using System.Speech.Recognition;
SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine(new CultureInfo("es-ES"));
At that point, you can install grammars & do recognitions, etc.
A:
Sure, but I want to do it without
changing the display language... no
way then?
No, not officially, if you believe this KB article: The Windows Speech Recognition language must be the same as the operating system language in Windows Vista.
So try to change it automatically, there some scripts on the internet, I found them via yahoo with Windows Speech Recognition "change language".
This one looks interesting, but it is not tested. I don't know, if it's malware or whatever, so be carefull:
Vistalizator
Good luck!
A: You can install the language pack, but not apply it on your user. Then you might be able to change the language of the speech recognition, although I haven't tried it since I don't have Vista Ultimate.
A: It will work fine as I had by changing lanuguage support.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Website Hardware Scaling So I was listening to the latest Stackoverflow podcast (episode 19), and Jeff and Joel talked a bit about scaling server hardware as a website grows. From what Joel was saying, the first few steps are pretty standard:
*
*One server running both the webserver and the database (the current Stackoverflow setup)
*One webserver and one database server
*Two load-balanced webservers and one database server
They didn't talk much about what comes next though. Do you add more webservers? Another database server? Replicate this three-machine cluster in a different datacenter for redundancy? Where does a web startup go from here in the hardware department?
A: plenty of fish Architecture
some interesitng videos:
Youtube scalibility
Inteview with Dan Farino, System Architect at Myspace
A: Joel mentioned adding a second datacenter, with the same setup, and then assigning your users randomly to each. Changes to the data are logged and sent from one location to the other, so that both locations contain all the data.
A: A reasonable setup supporting an "average" web application might evolve as follows:
*
*Single combined application/database server
*Separate database on a different machine
*Second application server with DNS round-robin (poor man's load balancing) or, e.g. Perlbal
*Second, replicated database server (for read loads, requires some application logic changes so eligible database reads go to a slave)
At this point, evaluating the current state of affairs would help to determine a better scaling path. For example, if read load is high and content doesn't change too often, it might be better to emphasise caching and introduce dedicated front-end caches, e.g. Squid to avoid un-needed database reads, although you will need to consider how to maintain cache coherency, typically in the application.
On the other hand, if content changes reasonably often, then you will probably prefer a more spread-out solution; introduce a few more application servers and database slaves to help mitigate the effects, and use object caching, such as memcached to avoid hitting the database for the less volatile content.
For most sites, this is probably enough, although if you do become a global phenomenon, then you'll probably want to start considering having hardware in regional data centres, and using tricks such as geographic load balancing to direct visitors to the closest "cluster". By that point, you'll probably be in a position to hire engineers who can really fine-tune things.
Probably the most valuable scaling advice I can think of would be to avoid worrying about it all far too soon; concentrate on developing a service people are going to want to use, and making the application reasonably robust. Some easy early optimisations are to make sure your database design is fairly solid, and that indexes are set up so you're not doing anything painfully crazy; also, make sure the application emits cache-control headers that direct browsers on how to cache the data. Doing this sort of work early on in the design can yield benefits later, especially when you don't have to rework the entire thing to deal with cache coherency issues.
The second most valuable piece of advice I want to put across is that you shouldn't assume what works for some other web site will work for you; check your logs, run some analysis on your traffic and profile your application - see where your bottlenecks are and resolve them.
A: The talk Scalable Web Architectures Common Patterns & Approaches from Cal Henderson (Yahoo) on Web 2.0 Expo was quite interesting. I thought there was an video, but I could not find it. But here are the slides:
http://www.slideshare.net/techdude/scalable-web-architectures-common-patterns-and-approaches
A: A certain next step would be a cluster of webservers (a web farm) and a clustered system of database servers (replication or Oracle RAC etc. etc.)
A: If your interested in caching and using .Net, look into the application caching block in enterprise library (of course use this along with the other points above).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: MySQL shell on Windows The command line interface to MySQL works perfectly well in itself, but when using my local copy I'm forced to interact with it using the old-fashioned DOS windows. Is there some way I can redirect it through a better shell?
A: Have you tried the MySQL Query Browser? Works cross platform and is much nicer than the plain shell.
A: It sounds like a GUI is not really what you were after, but maybe HeidiSQL would be worth a look. It's a GUI frontend for MySQL which I wouldn't say I quite enjoyed using, but I've certainly come across worse ways to talk with a database.
A: You should give a try to SQLyog. It has very powerfull query editor with features including Auto-complete, Auto-indentation, Customize foreground and background colours, Flexibiility to execute multiple MySQL queries in one go, and a long list to go... SQLyog Documentation for Query Tab
Hope it helps...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there an easy way to do transparent forms in a VB .NET app? I'm writing a simple app that's going to have a tiny form sitting in one corner of the screen, updating itself.
I'd really love for that form to be transparent and to have the transparency be user-configurable.
Is there any easy way to achieve this?
A: You could try using the Opacity property of the Form. Here's the relevant snippet from the MSDN page:
private Sub CreateMyOpaqueForm()
' Create a new form.
Dim form2 As New Form()
' Set the text displayed in the caption.
form2.Text = "My Form"
' Set the opacity to 75%.
form2.Opacity = 0.75
' Size the form to be 300 pixels in height and width.
form2.Size = New Size(300, 300)
' Display the form in the center of the screen.
form2.StartPosition = FormStartPosition.CenterScreen
' Display the form as a modal dialog box.
form2.ShowDialog()
End Sub
A: You can set the Form.Opacity property. It should do what you want.
A: Set Form.Opacity = 0.0 on page load
I set something like what your talking about on an app about a year ago. Using a While loop with a small Sleep you can setup a nice fading effect.
A: I don't know exactly what you mean by transparent, but if you use WPF you can set AllowTransparency = True on your form and then remove the form's style/border and then set the background to a color that has a zero alpha channel. Then, you can draw on the form all you want and the background will be see-through and the other stuff will be fully visible. Additionally, you could set the background to a low-opacity layer so you can half see through the form.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Beginner Digital Synth I'm looking into writing a audio syntesizer in Java, and was wondering if anybody has any advice or good resources for writing such a program. I'm looking for info on generating raw sound waves, how to output them into a usable form (playing over speakers), as well as general theory on the topic. Thanks guys.
A: *
*This problem is basically about mapping functions to arrays of numbers. A language that supports first-class functions would come in really handy here.
*Check out
http://www.harmony-central.com/Computer/Programming and
http://www.developer.com/java/other/article.php/3071021 for some Java-related info.
*If you don't know the basic concepts of encoding sound data, then read http://en.wikipedia.org/wiki/Sampling_rate
*The canonical WAVE format is very simple, see http://www.lightlink.com/tjweber/StripWav/Canon.html. A header (first 44 bytes) + the wave-data. You don't need any library to implement that.
In C/C++, the corresponding data structure would look something like this:
typedef struct _WAVstruct
{
char headertag[4];
unsigned int remnantlength;
char fileid[4];
char fmtchunktag[4];
unsigned int fmtlength;
unsigned short fmttag;
unsigned short channels;
unsigned int samplerate;
unsigned int bypse;
unsigned short ba;
unsigned short bipsa;
char datatag[4];
unsigned int datalength;
void* data; //<--- that's where the raw sound-data goes
}* WAVstruct;
I'm not sure about Java. I guess you'll have to substitute "struct" with "class" and "void* data" with "char[] data" or "short[] data" or "int[] data", corresponding to the number of bits per sample, as defined in the field bipsa.
To fill it with data, you would use something like that in C/C++:
int data2WAVstruct(unsigned short channels, unsigned short bipsa, unsigned int samplerate, unsigned int datalength, void* data, WAVstruct result)
{
result->headertag[0] = 'R';
result->headertag[1] = 'I';
result->headertag[2] = 'F';
result->headertag[3] = 'F';
result->remnantlength = 44 + datalength - 8;
result->fileid[0] = 'W';
result->fileid[1] = 'A';
result->fileid[2] = 'V';
result->fileid[3] = 'E';
result->fmtchunktag[0] = 'f';
result->fmtchunktag[1] = 'm';
result->fmtchunktag[2] = 't';
result->fmtchunktag[3] = ' ';
result->fmtlength = 0x00000010;
result->fmttag = 1;
result->channels = channels;
result->samplerate = samplerate;
result->bipsa = bipsa;
result->ba = channels*bipsa / 8;
result->bypse = samplerate*result->ba;
result->datatag[0] = 'd';
result->datatag[1] = 'a';
result->datatag[2] = 't';
result->datatag[3] = 'a';
result->datalength = datalength;
result->data = data; // <--- that's were the data comes in
return 0; // an error code, not implemented, yet ...; in Java: return result
}
Again, I'm not sure about Java but the conversion should be straightforward if you convert the void-pointer to an array corresponding to the bitrate.
Then simply write the entire structure to a file to get a playable wave file.
A: Check out Frinika. It's a full-featured music workstation implemented in Java (open source). Using the API, you can run midi events through the synthesizer, read the raw sound output, and write it to a WAV file (see source code link below).
Additional information:
*
*Frinika Developer Area
*Source code for midi renderer tool
A: While studying for my degree, my dissertation project was the creation of a Java based modular synthesizer, and the University at which I studied saw fit to make my report publicly available:
A Software Based Modular Synthesiser in Java
A: I dont't know if that helps, but if you can use MIDI for anything, you should check out JFuge.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Automated Builds I currently use subversion for my version control via AhnkSVN and Visual Studio. I recently started using Tree Surgeon to set up my projects. It creates a build script automatically using NAnt. I would like to be able to automate builds regularly projects within SVN. I like the idea of doing a build on every check in but nightly builds would work as well. I would give more information or more of my thoughts but figured I would leave it open and see what the SO community has to say.
A: You could use CruiseControl.Net, which can do a build on every check in, nightly builds, or however you want to do it. A quick google search suggests CC.Net has some integration with NAnt already.
A: As other's have mentioned we use CCNET here, which we don't usually work on a nightly build, but instead go with a Continuous Integration strategy (every check-in).
I would advise doing the same, whether it be by yourself or within a team, because you can very easily set up unit testing to run on every checkin as well, FXCop testing, and a slew of other products.
If it's just you in a one man team, and you don't have too many projects on the go, I would also advise checking out Team City as an option, because it has a free version, and the reporting and setup is reportedly much simpler (it does look nice to me).
That said, we started with CCNET, and have grown several products too large to look at Team City on the free version and are very happy with what we have.
Features that help with CCNET include:
*
*XML based configuration - you can usually copy and paste most of what you need.
*More or less you'll be able to plug your treesurgeon script in as your build script, and point CCNET at that as an executable task to run the compilation.
*Lots of documentation and very easy to set up nunit, ncover, fxcop, etc.
*Taskbar app that will let you know the status of your projects at any time, and it can also fire off an email or keep an RSS feed with the same information.
But I'd definitely go with running a CI build on every check-in - for the most part will run the unit tests before checking in, but let the CCNET server handle run any applications/assemblies that would have dependencies on the assembly we're checking in, and they get re-built, and re-tested on every checkin.
Given it's free and takes very little time to set up - I'd highly recommend just going for it.
A: CruiseControl.NET is your best option, in my opinion. It is fairly easy to extend with custom tasks if needed, works with both NAnt and MSBuild out of the box, and is very actively maintained.
A: There's also Draco.NET, which was inspired by CruiseControl.NET and is a little more lightweight. See this article for more information on both continuous integration solutions.
A: I suggest TeamCity. :)
A: I am very fond of buildbot. It is open source, written in python and very easy to deploy, develop and maintain. It integrates easily with svn and a majority of other source control systems. All of your build scripting is python code so you have a lot of flexibility in terms of what your core Build Master scripts can do. You can of course also use it to fire off any other type of script or batch file.
You might check out some examples of buildbot in action:
*
*GNOME
*Python
*Topographica
A: You might want to consider CI-Factory. It's a continuous integration environment builder that uses CruiseControl.NET and a dozen other tools. There's an excellent screencast here: http://www.dnrtv.com/default.aspx?showID=64
A: We use CruiseControl.NET with both NAnt and MsBuild for our build server. We configured it so that it would have builds everytime we check code in, as well as nightly builds.
A: Cascade supports doing a build on every single change committed to the repository.
A: I have been using FinalBuilder for a few years now. The advantage of FinalBuilder is that it does much more than just builds. I have it setup to do some analysis of the results, make archives of the builds, send out error logs etc. The latest version has a web interface that allows not experts to kick of builds with a click.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Add service reference to Amazon service fails Add service reference to Amazon service fails, saying
"Could not load file or assembly "System.Core, Version=3.5.0.0,...' or
one or more of it dependencies. The module was expected to contain an
assembly manifest."
This is in VS 2008, haven't installed SP1 on this machine yet.
Any ideas?
A: This can happen if ASP.NET isn't installed. Go to Add/Remove Windows Components and look under IIS; make sure that ASP.NET is checked (meaning that it's installed.) That should clear up your problem!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What SQL-server function can I use to get the character or byte length of a nvarchar(max) column? I have a column which is of type nvarchar(max). How do I find the length of the string (or the number of bytes) for the column for each row in the table?
A:
SELECT LEN(columnName) AS MyLength
FROM myTable
A: If you want to find out the max there should be a way for you to get the schema of the table. Normally you can do something like SHOW COLUMNS in SQL or a DESCRIBE style command. In a mysql shell that can be shortened to:
desc tablename;
Then if you want to determine the length of a string there is normally a function like LENGTH (for bytes) or CHAR_LENGTH (for characters).
SELECT *, LENGTH(fieldname) AS len FROM tablename
A: SELECT LEN(columnName) AS MyLength FROM myTable
I used this query for my table. It displays the size of each row in a particular column.
I need that field name size maximum it allow the characters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Viewing DirectX application remotely We're working on an application that displays information through a Direct3D visualisation. A late client request is the ability to view this application via some Remote Desktop solution.
Has anyone done anything similar? What options are available / unavailable? I'm thinking RDC, VNC, Citrix...
Any advice?
A: I think you can still use all of the normal D3D tools, but you won't be able to render to a surface associated with the screen. You'll have to render to a DIB (or some such) and Blt it with GDI to a normal window HDC. RDC/VNC/Citrix should all work with this technique.
Performance will definitely suffer - but that's going to be the case over remote desktop anyway. In fact, if I were you, I would mock up a VERY simple prototype and demonstrate the performance before committing to it.
Good luck!
A: I think Windows 7 has D3D remoting stuff - probably requires both client and server to be W7 though.
A: The build-in remote desktop works. (You don't have to do anything special)
But it is extremely slow, because when in doubt, it just sends the contents of a window as a bitmap.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: IE 6 CSS Hover non Anchor Tag What is the simplest and most elegant way to simulate the hover pseudo-class for non-Anchor tags in IE6?
I am specifically trying to change the cursor in this instance to that of a pointer.
A: Regarding your request -- I am specifically trying to change the cursor in this instance to that of a pointer -- the easiest way is to specify cursor:pointer in your css. I think you will find that works in IE 6.
Try this to verify (where div can be any element):
<div style="background:orange; cursor:pointer; height:100px; width:100px;">
Hover
</div>
A: I would say that the simplest method would be to add onmouseover/out Javascript functions.
A: Another alternative that will fix many more issues in one go is to use IE7.js.
A: I think the simplest way is to use the hover.htc approach. You add the hover.htc file to your site, then reference it in your stylesheet:
body { behavior:url("csshover.htc"); }
If you want to keep things as clean as possible, you can use IE conditional comments so that line is only rendered users with IE6.
A: Another approach, depending on what the item is, is to add a non link anchor and set its display to block. Either put the anchor within or surrounding the item you want the pseudo hover behavior on.
A: Aside:
I actually already needed to swap the image anyhow
Make sure you take a look at Image Sprites. Sometimes its much nicer to use one image and "shift" the image then to use two separate images and "toggle" or "swap" between them. In my experience its been much nice when as user interacts with it is sometimes an advantage that there is a single request for the 1 image then multiple requests for multiple images.
A: I liked the mouseover/out best since I actually already needed to swap the image anyhow. I really should have thought of doing this with javascript to begin with.
Thanks for the quick answers.
@Joseph
Thanks for that link. I had never heard of this technique before and really like the idea.
I will definitely try that out and see how I fare with it.
A: If your willing to use JQuery, I would use Set Hover Class for Anything technique.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How can I count the number of records that have a unique value in a particular field in ROR? I have a record set that includes a date field, and want to determine how many unique dates are represented in the record set.
Something like:
Record.find(:all).date.unique.count
but of course, that doesn't seem to work.
A: As I mentioned here, in Rails 4, using (...).uniq.count(:user_id) as mentioned in other answers (for this question and elsewhere on SO) will actually lead to an extra DISTINCT being in the query:
SELECT DISTINCT COUNT(DISTINCT user_id) FROM ...
What we actually have to do is use a SQL string ourselves:
(...).count("DISTINCT user_id")
Which gives us:
SELECT COUNT(DISTINCT user_id) FROM ...
A: What you're going for is the following SQL:
SELECT COUNT(DISTINCT date) FROM records
ActiveRecord has this built in:
Record.count('date', :distinct => true)
A: Also, make sure you have an index on the field in your db, or else that query will quickly become sloooow.
(It's much better to do this in SQL, otherwise you pull the entire db table into memory just to answer the count.)
A: Outside of SQL:
Record.find(:all).group_by(&:date).count
ActiveSupport's Enumerable#group_by is indispensable.
A: the latest #count on rails source code only accept 1 parameter.
see: http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-count
so I achieved the requirement by
Record.count('DISTINCT date')
A: This has changed slightly in rails 4 and above :distinct => true is now deprecated. Use:
Record.distinct.count('date')
Or if you want the date and the number:
Record.group(:date).distinct.count(:date)
A: Detailing the answer:
Post.create(:user_id => 1, :created_on => '2010-09-29')
Post.create(:user_id => 1, :created_on => '2010-09-29')
Post.create(:user_id => 2, :created_on => '2010-09-29')
Post.create(:user_id => null, :created_on => '2010-09-29')
Post.group(:created_on).count
# => {'2010-09-29' => 4}
Post.group(:created_on).count(:user_id)
# => {'2010-09-29' => 3}
Post.group(:created_on).count(:user_id, :distinct => true) # Rails <= 3
Post.group(:created_on).distinct.count(:user_id) # Rails = 4
# => {'2010-09-29' => 2}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "68"
} |
Q: How to catch undefined functions with set_error_handler in PHP I'm taking the leap: my PHP scripts will ALL fail gracefully!
At least, that's what I'm hoping for...`
I don't want to wrap (practically) every single line in try...catch statements, so I think my best bet is to make a custom error handler for the beginning of my files.
I'm testing it out on a practice page:
function customError($level,$message,$file,$line,$context) {
echo "Sorry, an error has occured on line $line.<br />";
echo "The function that caused the error says $message.<br />";
die();
}
set_error_handler("customError");
echo($imAFakeVariable);
This works fine, returning:
Sorry, an error has occurred on line 17. The function that caused the
error says Undefined variable: imAFakeVariable.
However, this setup doesn't work for undefined functions.
function customError($level,$message,$file,$line,$context) {
echo "Sorry, an error has occured on line $line.<br />";
echo "The function that caused the error says $message.<br />";
die();
}
set_error_handler("customError");
imAFakeFunction();
This returns:
Fatal error: Call to undefined function: imafakefunction() in
/Library/WebServer/Documents/experimental/errorhandle.php on line 17
Why isn't my custom error handler catching undefined functions? Are there other problems that this will cause?
A: I guess you needs to use register_shutdown_function also
For example:
register_shutdown_function( array( $this, 'customError' ));.
function customError()
{
$arrStrErrorInfo = error_get_last();
print_r( $arrStrErrorInfo );
}
A: From the documentation (emphasis added):
The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.
Calling undefined functions triggers an E_ERROR, thus it can not be handled by the error callback (or by exception handlers for that matter). All that you can do is set error_reporting to 0.
PS, if you are rolling your own error handler, you should take care to handle correctly the @ operator. From the documentation (emphasis added):
It is important to remember that the standard PHP error handler is completely bypassed. error_reporting() settings will have no effect and your error handler will be called regardless - however you are still able to read the current value of error_reporting and act appropriately. Of particular note is that this value will be 0 if the statement that caused the error was prepended by the @ error-control operator.
A: set_error_handler is designed to handle errors with codes of: E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE. This is because set_error_handler is meant to be a method of reporting errors thrown by the user error function trigger_error.
However, I did find this comment in the manual that may help you:
"The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called."
This is not exactly true. set_error_handler() can't handle them, but ob_start() can handle at least E_ERROR.
<?php
function error_handler($output)
{
$error = error_get_last();
$output = "";
foreach ($error as $info => $string)
$output .= "{$info}: {$string}\n";
return $output;
}
ob_start('error_handler');
will_this_undefined_function_raise_an_error();
?>
Really though these errors should be silently reported in a file, for example. Hopefully you won't have many E_PARSE errors in your project! :-)
As for general error reporting, stick with Exceptions (I find it helpful to make them tie in with my MVC system). You can build a pretty versatile Exception to provide options via buttons and add plenty of description to let the user know what's wrong.
A:
Why isn't my custom error handler catching undefinedd functions? Are there other problems that this will cause?
At a guess, I'd say that undefined function errors travel through a different execution path than other error types. Perhaps the PHP designers could tell you more, except I doubt PHP is in any way designed.
If you'd like your scripts to fail gracefully while still writing them PHP-style, try putting the entire page in a function and then call it within a try..catch block.
A: I've been playing around with error handling for some time and it seems like it works for the most part.
function fatalHandler() {
global $fatalHandlerError, $fatalHandlerTitle;
$fatalHandlerError = error_get_last();
if( $fatalHandlerError !== null ) {
print($fatalHandlerTitle="{$fatalHandlerTitle} | ".join(" | ", $fatalHandlerError).
(preg_match("/memory/i", $fatalHandlerError["message"]) ? " | Mem: limit ".ini_get('memory_limit')." / peak ".round(memory_get_peak_usage(true)/(1024*1024))."M" : "")."\n".
"GET: ".var_export($_GET,1)."\n".
"POST: ".var_export($_POST,1)."\n".
"SESSION: ".var_export($_SESSION,1)."\n".
"HEADERS: ".var_export(getallheaders(),1));
}
return $fatalHandlerTitle;
}
function fatalHandlerInit($title="phpError") {
global $fatalHandlerError, $fatalHandlerTitle;
$fatalHandlerTitle = $title;
$fatalHandlerError = error_get_last();
set_error_handler( "fatalHandler" );
}
Now I have an issue where if the memory is exhausted, it doesn't report it every time. It seems like it depends on how much memory is being used.
I did a script to load a large file (takes ~6.6M of memory) in an infinite loop.
Setup1:
ini_set('memory_limit', '296M');
fatalHandlerInit("testing");
$file[] = file("large file"); // copy paste a bunch of times
In this case I get the error to be reports and it dies on 45 file load.
Setup2 - same but change:
ini_set('memory_limit', '299M');
This time I don't get an error and it doesn't even call my custom error function. The script dies on the same line.
Does anyone have a clue why and how to go around that?
A: Very interesting thing that I've discovered today as I was facing the similar problem. If you use the following - it will catch the error with your custom error handler function / method:
ini_set('display_errors', 'Off');
error_reporting(-1);
set_error_handler(array("Cmd\Exception\Handler", "getError"), -1 & ~E_NOTICE & ~E_USER_NOTICE);
By setting 'display_errors' to 'Off' you can catch still catch them with the handler.
A: At a guess, I'd say that undefined function errors travel through a different execution path than other error types. Perhaps the PHP designers could tell you more, except I doubt PHP is in any way designed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: What is a 'Closure'? I asked a question about Currying and closures were mentioned.
What is a closure? How does it relate to currying?
A: First of all, contrary to what most of the people here tell you, closure is not a function! So what is it?
It is a set of symbols defined in a function's "surrounding context" (known as its environment) which make it a CLOSED expression (that is, an expression in which every symbol is defined and has a value, so it can be evaluated).
For example, when you have a JavaScript function:
function closed(x) {
return x + 3;
}
it is a closed expression because all the symbols occurring in it are defined in it (their meanings are clear), so you can evaluate it. In other words, it is self-contained.
But if you have a function like this:
function open(x) {
return x*y + 3;
}
it is an open expression because there are symbols in it which have not been defined in it. Namely, y. When looking at this function, we can't tell what y is and what does it mean, we don't know its value, so we cannot evaluate this expression. I.e. we cannot call this function until we tell what y is supposed to mean in it. This y is called a free variable.
This y begs for a definition, but this definition is not part of the function – it is defined somewhere else, in its "surrounding context" (also known as the environment). At least that's what we hope for :P
For example, it could be defined globally:
var y = 7;
function open(x) {
return x*y + 3;
}
Or it could be defined in a function which wraps it:
var global = 2;
function wrapper(y) {
var w = "unused";
return function(x) {
return x*y + 3;
}
}
The part of the environment which gives the free variables in an expression their meanings, is the closure. It is called this way, because it turns an open expression into a closed one, by supplying these missing definitions for all of its free variables, so that we could evaluate it.
In the example above, the inner function (which we didn't give a name because we didn't need it) is an open expression because the variable y in it is free – its definition is outside the function, in the function which wraps it. The environment for that anonymous function is the set of variables:
{
global: 2,
w: "unused",
y: [whatever has been passed to that wrapper function as its parameter `y`]
}
Now, the closure is that part of this environment which closes the inner function by supplying the definitions for all its free variables. In our case, the only free variable in the inner function was y, so the closure of that function is this subset of its environment:
{
y: [whatever has been passed to that wrapper function as its parameter `y`]
}
The other two symbols defined in the environment are not part of the closure of that function, because it doesn't require them to run. They are not needed to close it.
More on the theory behind that here:
https://stackoverflow.com/a/36878651/434562
It's worth to note that in the example above, the wrapper function returns its inner function as a value. The moment we call this function can be remote in time from the moment the function has been defined (or created). In particular, its wrapping function is no longer running, and its parameters which has been on the call stack are no longer there :P This makes a problem, because the inner function needs y to be there when it is called! In other words, it requires the variables from its closure to somehow outlive the wrapper function and be there when needed. Therefore, the inner function has to make a snapshot of these variables which make its closure and store them somewhere safe for later use. (Somewhere outside the call stack.)
And this is why people often confuse the term closure to be that special type of function which can do such snapshots of the external variables they use, or the data structure used to store these variables for later. But I hope you understand now that they are not the closure itself – they're just ways to implement closures in a programming language, or language mechanisms which allows the variables from the function's closure to be there when needed. There's a lot of misconceptions around closures which (unnecessarily) make this subject much more confusing and complicated than it actually is.
A: Variable scope
When you declare a local variable, that variable has a scope. Generally, local variables exist only within the block or function in which you declare them.
function() {
var a = 1;
console.log(a); // works
}
console.log(a); // fails
If I try to access a local variable, most languages will look for it in the current scope, then up through the parent scopes until they reach the root scope.
var a = 1;
function() {
console.log(a); // works
}
console.log(a); // works
When a block or function is done with, its local variables are no longer needed and are usually blown out of memory.
This is how we normally expect things to work.
A closure is a persistent local variable scope
A closure is a persistent scope which holds on to local variables even after the code execution has moved out of that block. Languages which support closure (such as JavaScript, Swift, and Ruby) will allow you to keep a reference to a scope (including its parent scopes), even after the block in which those variables were declared has finished executing, provided you keep a reference to that block or function somewhere.
The scope object and all its local variables are tied to the function and will persist as long as that function persists.
This gives us function portability. We can expect any variables that were in scope when the function was first defined to still be in scope when we later call the function, even if we call the function in a completely different context.
For example
Here's a really simple example in JavaScript that illustrates the point:
outer = function() {
var a = 1;
var inner = function() {
console.log(a);
}
return inner; // this returns a function
}
var fnc = outer(); // execute outer to get inner
fnc();
Here I have defined a function within a function. The inner function gains access to all the outer function's local variables, including a. The variable a is in scope for the inner function.
Normally when a function exits, all its local variables are blown away. However, if we return the inner function and assign it to a variable fnc so that it persists after outer has exited, all of the variables that were in scope when inner was defined also persist. The variable a has been closed over -- it is within a closure.
Note that the variable a is totally private to fnc. This is a way of creating private variables in a functional programming language such as JavaScript.
As you might be able to guess, when I call fnc() it prints the value of a, which is "1".
In a language without closure, the variable a would have been garbage collected and thrown away when the function outer exited. Calling fnc would have thrown an error because a no longer exists.
In JavaScript, the variable a persists because the variable scope is created when the function is first declared and persists for as long as the function continues to exist.
a belongs to the scope of outer. The scope of inner has a parent pointer to the scope of outer. fnc is a variable which points to inner. a persists as long as fnc persists. a is within the closure.
Further reading (watching)
I made a YouTube video looking at this code with some practical examples of usage.
A: tl;dr
A closure is a function and its scope assigned to (or used as) a variable. Thus, the name closure: the scope and the function is enclosed and used just like any other entity.
In depth Wikipedia style explanation
According to Wikipedia, a closure is:
Techniques for implementing lexically scoped name binding in languages with first-class functions.
What does that mean? Lets look into some definitions.
I will explain closures and other related definitions by using this example:
function startAt(x) {
return function (y) {
return x + y;
}
}
var closure1 = startAt(1);
var closure2 = startAt(5);
console.log(closure1(3)); // 4 (x == 1, y == 3)
console.log(closure2(3)); // 8 (x == 5, y == 3)
First-class functions
Basically that means we can use functions just like any other entity. We can modify them, pass them as arguments, return them from functions or assign them for variables. Technically speaking, they are first-class citizens, hence the name: first-class functions.
In the example above, startAt returns an (anonymous) function which function get assigned to closure1 and closure2. So as you see JavaScript treats functions just like any other entities (first-class citizens).
Name binding
Name binding is about finding out what data a variable (identifier) references. The scope is really important here, as that is the thing that will determine how a binding is resolved.
In the example above:
*
*In the inner anonymous function's scope, y is bound to 3.
*In startAt's scope, x is bound to 1 or 5 (depending on the closure).
Inside the anonymous function's scope, x is not bound to any value, so it needs to be resolved in an upper (startAt's) scope.
Lexical scoping
As Wikipedia says, the scope:
Is the region of a computer program where the binding is valid: where the name can be used to refer to the entity.
There are two techniques:
*
*Lexical (static) scoping: A variable's definition is resolved by searching its containing block or function, then if that fails searching the outer containing block, and so on.
*Dynamic scoping: Calling function is searched, then the function which called that calling function, and so on, progressing up the call stack.
For more explanation, check out this question and take a look at Wikipedia.
In the example above, we can see that JavaScript is lexically scoped, because when x is resolved, the binding is searched in the upper (startAt's) scope, based on the source code (the anonymous function that looks for x is defined inside startAt) and not based on the call stack, the way (the scope where) the function was called.
Wrapping (closuring) up
In our example, when we call startAt, it will return a (first-class) function that will be assigned to closure1 and closure2 thus a closure is created, because the passed variables 1 and 5 will be saved within startAt's scope, that will be enclosed with the returned anonymous function. When we call this anonymous function via closure1 and closure2 with the same argument (3), the value of y will be found immediately (as that is the parameter of that function), but x is not bound in the scope of the anonymous function, so the resolution continues in the (lexically) upper function scope (that was saved in the closure) where x is found to be bound to either 1 or 5. Now we know everything for the summation so the result can be returned, then printed.
Now you should understand closures and how they behave, which is a fundamental part of JavaScript.
Currying
Oh, and you also learned what currying is about: you use functions (closures) to pass each argument of an operation instead of using one functions with multiple parameters.
A: Kyle's answer is pretty good. I think the only additional clarification is that the closure is basically a snapshot of the stack at the point that the lambda function is created. Then when the function is re-executed the stack is restored to that state before executing the function. Thus as Kyle mentions, that hidden value (count) is available when the lambda function executes.
A: Closure is a feature in JavaScript where a function has access to its own scope variables, access to the outer function variables and access to the global variables.
Closure has access to its outer function scope even after the outer function has returned. This means a closure can remember and access variables and arguments of its outer function even after the function has finished.
The inner function can access the variables defined in its own scope, the outer function’s scope, and the global scope. And the outer function can access the variable defined in its own scope and the global scope.
Example of Closure:
var globalValue = 5;
function functOuter() {
var outerFunctionValue = 10;
//Inner function has access to the outer function value
//and the global variables
function functInner() {
var innerFunctionValue = 5;
alert(globalValue + outerFunctionValue + innerFunctionValue);
}
functInner();
}
functOuter();
Output will be 20 which sum of its inner function own variable, outer function variable and global variable value.
A: In a normal situation, variables are bound by scoping rule: Local variables work only within the defined function. Closure is a way of breaking this rule temporarily for convenience.
def n_times(a_thing)
return lambda{|n| a_thing * n}
end
in the above code, lambda(|n| a_thing * n} is the closure because a_thing is referred by the lambda (an anonymous function creator).
Now, if you put the resulting anonymous function in a function variable.
foo = n_times(4)
foo will break the normal scoping rule and start using 4 internally.
foo.call(3)
returns 12.
A: A closure is a function that can reference state in another function. For example, in Python, this uses the closure "inner":
def outer (a):
b = "variable in outer()"
def inner (c):
print a, b, c
return inner
# Now the return value from outer() can be saved for later
func = outer ("test")
func (1) # prints "test variable in outer() 1
A: To help facilitate understanding of closures it might be useful to examine how they might be implemented in a procedural language. This explanation will follow a simplistic implementation of closures in Scheme.
To start, I must introduce the concept of a namespace. When you enter a command into a Scheme interpreter, it must evaluate the various symbols in the expression and obtain their value. Example:
(define x 3)
(define y 4)
(+ x y) returns 7
The define expressions store the value 3 in the spot for x and the value 4 in the spot for y. Then when we call (+ x y), the interpreter looks up the values in the namespace and is able to perform the operation and return 7.
However, in Scheme there are expressions that allow you to temporarily override the value of a symbol. Here's an example:
(define x 3)
(define y 4)
(let ((x 5))
(+ x y)) returns 9
x returns 3
What the let keyword does is introduces a new namespace with x as the value 5. You will notice that it's still able to see that y is 4, making the sum returned to be 9. You can also see that once the expression has ended x is back to being 3. In this sense, x has been temporarily masked by the local value.
Procedural and object-oriented languages have a similar concept. Whenever you declare a variable in a function that has the same name as a global variable you get the same effect.
How would we implement this? A simple way is with a linked list - the head contains the new value and the tail contains the old namespace. When you need to look up a symbol, you start at the head and work your way down the tail.
Now let's skip to the implementation of first-class functions for the moment. More or less, a function is a set of instructions to execute when the function is called culminating in the return value. When we read in a function, we can store these instructions behind the scenes and run them when the function is called.
(define x 3)
(define (plus-x y)
(+ x y))
(let ((x 5))
(plus-x 4)) returns ?
We define x to be 3 and plus-x to be its parameter, y, plus the value of x. Finally we call plus-x in an environment where x has been masked by a new x, this one valued 5. If we merely store the operation, (+ x y), for the function plus-x, since we're in the context of x being 5 the result returned would be 9. This is what's called dynamic scoping.
However, Scheme, Common Lisp, and many other languages have what's called lexical scoping - in addition to storing the operation (+ x y) we also store the namespace at that particular point. That way, when we're looking up the values we can see that x, in this context, is really 3. This is a closure.
(define x 3)
(define (plus-x y)
(+ x y))
(let ((x 5))
(plus-x 4)) returns 7
In summary, we can use a linked list to store the state of the namespace at the time of function definition, allowing us to access variables from enclosing scopes, as well as providing us the ability to locally mask a variable without affecting the rest of the program.
A: In short, function pointer is just a pointer to a location in the program code base (like program counter). Whereas Closure = Function pointer + Stack frame.
.
A: Closures provide JavaScript with state.
State in programming simply means remembering things.
Example
var a = 0;
a = a + 1; // => 1
a = a + 1; // => 2
a = a + 1; // => 3
In the case above, state is stored in the variable "a". We follow by adding 1 to "a" several times. We can only do that because we are able to "remember" the value. The state holder, "a", holds that value in memory.
Often, in programming languages, you want to keep track of things, remember information and access it at a later time.
This, in other languages, is commonly accomplished through the use of classes. A class, just like variables, keeps track of its state. And instances of that class, in turns, also have state within them. State simply means information that you can store and retrieve later.
Example
class Bread {
constructor (weight) {
this.weight = weight;
}
render () {
return `My weight is ${this.weight}!`;
}
}
How can we access "weight" from within the "render" method? Well, thanks to state. Each instance of the class Bread can render its own weight by reading it from the "state", a place in memory where we could store that information.
Now, JavaScript is a very unique language which historically does not have classes (it now does, but under the hood there's only functions and variables) so Closures provide a way for JavaScript to remember things and access them later.
Example
var n = 0;
var count = function () {
n = n + 1;
return n;
};
count(); // # 1
count(); // # 2
count(); // # 3
The example above achieved the goal of "keeping state" with a variable. This is great! However, this has the disadvantage that the variable (the "state" holder) is now exposed. We can do better. We can use Closures.
Example
var countGenerator = function () {
var n = 0;
var count = function () {
n = n + 1;
return n;
};
return count;
};
var count = countGenerator();
count(); // # 1
count(); // # 2
count(); // # 3
This is fantastic.
Now our "count" function can count. It is only able to do so because it can "hold" state. The state in this case is the variable "n". This variable is now closed. Closed in time and space. In time because you won't ever be able to recover it, change it, assign it a value or interact directly with it. In space because it's geographically nested within the "countGenerator" function.
Why is this fantastic? Because without involving any other sophisticated and complicated tool (e.g. classes, methods, instances, etc) we are able to
1. conceal
2. control from a distance
We conceal the state, the variable "n", which makes it a private variable!
We also have created an API that can control this variable in a pre-defined way. In particular, we can call the API like so "count()" and that adds 1 to "n" from a "distance". In no way, shape or form anyone will ever be able to access "n" except through the API.
JavaScript is truly amazing in its simplicity.
Closures are a big part of why this is.
A: Functions containing no free variables are called pure functions.
Functions containing one or more free variables are called closures.
var pure = function pure(x){
return x
// only own environment is used
}
var foo = "bar"
var closure = function closure(){
return foo
// foo is a free variable from the outer environment
}
src: https://leanpub.com/javascriptallongesix/read#leanpub-auto-if-functions-without-free-variables-are-pure-are-closures-impure
A: I'll give an example (in JavaScript):
function makeCounter () {
var count = 0;
return function () {
count += 1;
return count;
}
}
var x = makeCounter();
x(); returns 1
x(); returns 2
...etc...
What this function, makeCounter, does is it returns a function, which we've called x, that will count up by one each time it's called. Since we're not providing any parameters to x, it must somehow remember the count. It knows where to find it based on what's called lexical scoping - it must look to the spot where it's defined to find the value. This "hidden" value is what is called a closure.
Here is my currying example again:
function add (a) {
return function (b) {
return a + b;
}
}
var add3 = add(3);
add3(4); returns 7
What you can see is that when you call add with the parameter a (which is 3), that value is contained in the closure of the returned function that we're defining to be add3. That way, when we call add3, it knows where to find the a value to perform the addition.
A: Here's a real world example of why Closures kick ass... This is straight out of my Javascript code. Let me illustrate.
Function.prototype.delay = function(ms /*[, arg...]*/) {
var fn = this,
args = Array.prototype.slice.call(arguments, 1);
return window.setTimeout(function() {
return fn.apply(fn, args);
}, ms);
};
And here's how you would use it:
var startPlayback = function(track) {
Player.play(track);
};
startPlayback(someTrack);
Now imagine you want the playback to start delayed, like for example 5 seconds later after this code snippet runs. Well that's easy with delay and it's closure:
startPlayback.delay(5000, someTrack);
// Keep going, do other things
When you call delay with 5000ms, the first snippet runs, and stores the passed in arguments in it's closure. Then 5 seconds later, when the setTimeout callback happens, the closure still maintains those variables, so it can call the original function with the original parameters.
This is a type of currying, or function decoration.
Without closures, you would have to somehow maintain those variables state outside the function, thus littering code outside the function with something that logically belongs inside it. Using closures can greatly improve the quality and readability of your code.
A: Here is another real life example, and using a scripting language popular in games - Lua. I needed to slightly change the way a library function worked to avoid a problem with stdin not being available.
local old_dofile = dofile
function dofile( filename )
if filename == nil then
error( 'Can not use default of stdin.' )
end
old_dofile( filename )
end
The value of old_dofile disappears when this block of code finishes it's scope (because it's local), however the value has been enclosed in a closure, so the new redefined dofile function CAN access it, or rather a copy stored along with the function as an 'upvalue'.
A: From Lua.org:
When a function is written enclosed in another function, it has full access to local variables from the enclosing function; this feature is called lexical scoping. Although that may sound obvious, it is not. Lexical scoping, plus first-class functions, is a powerful concept in a programming language, but few languages support that concept.
A: If you are from the Java world, you can compare a closure with a member function of a class. Look at this example
var f=function(){
var a=7;
var g=function(){
return a;
}
return g;
}
The function g is a closure: g closes a in. So g can be compared with a member function, a can be compared with a class field, and the function f with a class.
A: Closures
Whenever we have a function defined inside another function, the inner function has access to the variables declared
in the outer function. Closures are best explained with examples.
In Listing 2-18, you can see that the inner function has access to a variable (variableInOuterFunction) from the
outer scope. The variables in the outer function have been closed by (or bound in) the inner function. Hence the term
closure. The concept in itself is simple enough and fairly intuitive.
Listing 2-18:
function outerFunction(arg) {
var variableInOuterFunction = arg;
function bar() {
console.log(variableInOuterFunction); // Access a variable from the outer scope
}
// Call the local function to demonstrate that it has access to arg
bar();
}
outerFunction('hello closure!'); // logs hello closure!
source: http://index-of.es/Varios/Basarat%20Ali%20Syed%20(auth.)-Beginning%20Node.js-Apress%20(2014).pdf
A: Please have a look below code to understand closure in more deep:
for(var i=0; i< 5; i++){
setTimeout(function(){
console.log(i);
}, 1000);
}
Here what will be output? 0,1,2,3,4 not that will be 5,5,5,5,5 because of closure
So how it will solve? Answer is below:
for(var i=0; i< 5; i++){
(function(j){ //using IIFE
setTimeout(function(){
console.log(j);
},1000);
})(i);
}
Let me simple explain, when a function created nothing happen until it called so for loop in 1st code called 5 times but not called immediately so when it called i.e after 1 second and also this is asynchronous so before this for loop finished and store value 5 in var i and finally execute setTimeout function five time and print 5,5,5,5,5
Here how it solve using IIFE i.e Immediate Invoking Function Expression
(function(j){ //i is passed here
setTimeout(function(){
console.log(j);
},1000);
})(i); //look here it called immediate that is store i=0 for 1st loop, i=1 for 2nd loop, and so on and print 0,1,2,3,4
For more, please understand execution context to understand closure.
*
*There is one more solution to solve this using let (ES6 feature) but under the hood above function is worked
for(let i=0; i< 5; i++){
setTimeout(function(){
console.log(i);
},1000);
}
Output: 0,1,2,3,4
=> More explanation:
In memory, when for loop execute picture make like below:
Loop 1)
setTimeout(function(){
console.log(i);
},1000);
Loop 2)
setTimeout(function(){
console.log(i);
},1000);
Loop 3)
setTimeout(function(){
console.log(i);
},1000);
Loop 4)
setTimeout(function(){
console.log(i);
},1000);
Loop 5)
setTimeout(function(){
console.log(i);
},1000);
Here i is not executed and then after complete loop, var i stored value 5 in memory but it's scope is always visible in it's children function so when function execute inside setTimeout out five time it prints 5,5,5,5,5
so to resolve this use IIFE as explain above.
A: Currying : It allows you to partially evaluate a function by only passing in a subset of its arguments. Consider this:
function multiply (x, y) {
return x * y;
}
const double = multiply.bind(null, 2);
const eight = double(4);
eight == 8;
Closure: A closure is nothing more than accessing a variable outside of a function's scope. It is important to remember that a function inside a function or a nested function isn't a closure. Closures are always used when need to access the variables outside the function scope.
function apple(x){
function google(y,z) {
console.log(x*y);
}
google(7,2);
}
apple(3);
// the answer here will be 21
A: Closure is very easy. We can consider it as follows :
Closure = function + its lexical environment
Consider the following function:
function init() {
var name = “Mozilla”;
}
What will be the closure in the above case ?
Function init() and variables in its lexical environment ie name.
Closure = init() + name
Consider another function :
function init() {
var name = “Mozilla”;
function displayName(){
alert(name);
}
displayName();
}
What will be the closures here ?
Inner function can access variables of outer function. displayName() can access the variable name declared in the parent function, init(). However, the same local variables in displayName() will be used if they exists.
Closure 1 : init function + ( name variable + displayName() function) --> lexical scope
Closure 2 : displayName function + ( name variable ) --> lexical scope
A: A simple example in Groovy for your reference:
def outer() {
def x = 1
return { -> println(x)} // inner
}
def innerObj = outer()
innerObj() // prints 1
A: Here is an example illustrating a closure in the Scheme programming language.
First we define a function defining a local variable, not visible outside the function.
; Function using a local variable
(define (function)
(define a 1)
(display a) ; prints 1, when calling (function)
)
(function) ; prints 1
(display a) ; fails: a undefined
Here is the same example, but now the function uses a global variable, defined outside the function.
; Function using a global variable
(define b 2)
(define (function)
(display b) ; prints 2, when calling (function)
)
(function) ; prints 2
(display 2) ; prints 2
And finally, here is an example of a function carrying its own closure:
; Function with closure
(define (outer)
(define c 3)
(define (inner)
(display c))
inner ; outer function returns the inner function as result
)
(define function (outer))
(function) ; prints 3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "525"
} |
Q: Listing Items and Displaying Data Inline I use asp.net 3.5 and have also begun looking at 3.5 sp1
I like the clean urls that mvc tends to have but use asp.net webforms for my primary development. I normally use a url rewriter in order to accomplish this type stuff. When I say clean urls I mean like /products to get a list of products and /products/Product_One to look at the info about product called Product_One. I've used this on sites where the listing is on one page and when you pick the item it goes to a different page that shows the info about the item selected.
but
I also like the way that the update panel works and changing stuff on screen with out flashing the screen. When I do this I tend to have a list on the left with the different items that are selectable and then have on the left the data about the selected item, then I use an update panel so that when the item on the left is selected it's data shows up on the left without flashing.
I need opinions on what you all think of the two different methods of displaying a list and seeing the item that is selected's data.
1) Which is better in your opinion?
2) What do you all do to display a list and show the data on one of the items?
3) Is there another way of doing this?
4) Is it possible to combine the update panel method and the nice urls? (i.e. change the url to match the url that would get you to the current displayed data even though the update panel was used, and add to the history the new clean url for the current page)
A: What you are referring to is AJAX URL history management but you will not be able to modify the URL besides the "#" anchor.
At least not without reloading the page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Do you use Phing? Does anyone use Phing to deploy PHP applications, and if so how do you use it? We currently have a hand-written "setup" script that we run whenever we deploy a new instance of our project. We just check out from SVN and run it. It sets some basic configuration variables, installs or reloads the database, and generates a v-host for the site instance.
I have often thought that maybe we should be using Phing. I haven't used ant much, so I don't have a real sense of what Phing is supposed to do other than script the copying of files from one place to another much as our setup script does. What are some more advanced uses that you can give examples of to help me understand why we would or would not want to integrate Phing into our process?
A: The compelling answer for me is that phing understands PHP classpaths. Ant doesn't. I don't want to have an ant build.xml full of exec commands. I happen to be primarily a java programmer and still use phing. It's the best tool for the job.
A: I moved from Ant to Phing 'just because' it's PHP. I use it to export from different subversion repositories, copy stuff around, build different installation packages, etc all of that with a 20 line reusable xml file and a config file with project specific stuff. No way I could do it that fast with a custom script. I also plan to integrate api documentation generation and unit tests. Love it!
A: We use phing to deploy SemanticScuttle:
*
*generate zip archive for distribution
*create PEAR package
*upload zip to SourceForge
*update the PEAR channel with the new package file
*render reStructuredText documentation into html files and uploading them. Currently with exec but I'm on the way writing a separate task for it.
Uploading the zip file and the channel is done via rsync, which is unfortunately not supported by phing through a special task - but using exec is always possible and works nicely.
In the end, it saves a lot of time and we're able to test, package and deploy our app with one single command (which gives us another point on the Joel Test). I would not want to live without it.
See the build.xml code.
A: I don't see any compelling reason to go with phing. I mean, should PHP programmers attempt a rewrite of Eclipse "just because" it might somehow be easier to write Eclipse plugins in PHP? I don't think so.
Ant has better documentation, including some nice o'reilly books, and it's well-established in the Java universe, so you avoid the problems of (1) "we haven't copied feature X to phing yet" and (2) the risk of the phing project going dead. Here's an article on configuring PHPUnit to work with ant and cruisecontrol: not that hard. And you get eclipse integration for free.
Good luck!
A: From Federico Cargnelutti's blog post:
Features include file transformations (e.g. token
replacement, XSLT transformation,
Smarty template transformations), file
system operations, interactive build
support, SQL execution, CVS
operations, tools for creating PEAR
packages, and much more.
Of course you could write custom scripts for all of the above. However, using a specialized build tool like Phing gives you a number of benefits. You'll be using a proven framework so instead of having to worry about setting up "infrastructure" you can focus on the code you need to write. Using Phing will also make it easier for when new members join your team, they'll be able to understand what is going on if they've used Phing (or Ant, which is what Phing is based on) before.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: Unit tests in Python Does Python have a unit testing framework compatible with the standard xUnit style of test framework? If so, what is it, where is it, and is it any good?
A: I recommend nose.
It is the most Pythonic of the unit test frameworks. The test runner runs both doctests and unittests, so you are free to use whatever style of test you like.
A: There's testoob which is pretty complete suite of test.Also xUnit-ie, and has a nice reporting option
A: Consider py.test. Not exactly analogous to NUnit, but very good, with nice features including test auto-discovery and a "Watch the tests and code - when something changes rerun the tests that failed last time. As soon as all the tests pass, switch to running all the tests whenever somethings changes." option.
A: Python has several testing frameworks, including unittest, doctest, and nose. The most xUnit-like is unittest, which is documented on Python.org.
*
*unittest documentation
*doctest documentation
A: @Greg: PyUnit is included in the standard library as unittest
A: I recommend Nose.
After the reasonable simple installation, you just have to run "nosetests" in your project folder and Nose will find all your tests and run them. I also like the collection of plugins (coverage, GAE, etc.) and the abilty to call Nose directly from within my Python scripts.
A: There is also PyUnit which might be what you're looking for.
A: Never used xUnit, so I can't tell you if the frameworks are good/bad comparativly, but here is a script I wrote which uses the unittest framework (to check the API works as it should), and the doctest (to check the examples I've given work)
My only problem is checking something raises an exception is slightly convoluted (you have to pass it a function/lambda that raises the exception, rather than just the command itself, like the rest of the framework).. Other than that, it does what it should, reliably, and it has been included in the default python distribution for quite some time.
A: nose seems to be the best combination of flexibility and convenience. It runs unittests, doctests, coverage (with an extension) and py.test-like tests from one framework and does so admirably. It has enough popularity that it has had some IDE integration done as well for Komodo Edit and I wouldn't be surprised to see it elsewhere as well.
I like it for one strong reason: I almost always doctest before writing more extensive tests in another framework. This is because, for basic tests, doctests kill two birds with one stone. You get executable tests (although they are a bit clumsy to write well sometimes) as well as API documentation and interactive documentation at the same time. nose will run these with the bundled doctest extension when you use a command-line option (--with-doctest).
I say this having come from py.test as my former favorite. While it is great, nose tests are similar enough to me that I don't miss it, and I like the integration of the various test methodologies under one roof, so to speak. YMMV, but I recommend taking a good look at nose before choosing another. If you aren't familiar with py.test tests, you should look at them as well. I find them terrific because they are usually written in such a way that they can be easily debugged without the testing framework, which makes one less tricky system involved in the debugging session. I find that alone invaluable, while they are also easier to write than unittest tests in my opinion.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: How do I keep whitespace formatting using PHP/HTML? I'm parsing text from a file and storing it in a string. The problem is that some of the text in the original files contains ASCII art and whatnot that I would like to preserve. When I print out the string on the HTML page, even if it does have the same formatting and everything since it is in HTML, the spacing and line breaks are not preserved. What is the best way to print out the text in HTML exactly as it was in the original text file?
I would like to give an example, but unfortunately, I was not able to get it to display correctly in this markdown editor :P
Basically, I would like suggestions on how to display ASCII art in HTML.
A: use the <pre> tag (pre formatted), that will use a mono spaced font (for your art) and keep all the white space
<pre>
text goes here and here
and here and here Some out here
▄ ▄█▄ █▄ ▄
▄█▀█▓ ▄▓▀▀█▀ ▀▀▀█▓▀▀ ▀▀ ▄█▀█▓▀▀▀▀▀▓▄▀██▀▀
██ ██ ▀██▄▄ ▄█ ▀ ░▒ ░▒ ██ ██ ▄█▄ █▀ ██
█▓▄▀██ ▄ ▀█▌▓█ ▒▓ ▒▓ █▓▄▀██ ▓█ ▀▄ █▓
█▒ █▓ ██▄▓▀ ▀█▄▄█▄▓█ ▓█ █▒ █▓ ▒█ ▓█▄ ▒
▀▒ ▀ ▀ █▀ ▀▒ ▀ █▀ ░
</pre>
You might have to convert any <'s to < 's
A: When you print the data use nl2br() to convert \n and \r\n into <br>
A: For all those searchng for preserving the text fetched from database , this worked for me , setting CSS as following ,
pre {
white-space: pre-line;
text-align : left;
}
in html :
<pre >
<?php echo htmlentities($yourText ) ; ?>
</pre>
A: the <pre> and </pre> might not be ideal in textarea etc..
When wanting to preserve new line - \n and \n\r use nl2br as mentioned by UnkwnTech and Brad Mace.
When wanting to preserve spaces use str_replace:
str_replace(' ', ' ', $stringVariable);
When both use this:
$result = str_replace(' ', ' ', $stringVariable);
$result = nl2br($result);
A: just echo the necessary special characters (\s, \n, or \r ) along with your string in your PHP code.
<?php
echo ("hello world \n")
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: Why do .Net WPF DependencyProperties have to be static members of the class Learning WPF nowadays. Found something new today with .Net dependency properties. What they bring to the table is
*
*Support for Callbacks (Validation, Change, etc)
*Property inheritance
*Attached properties
among others.
But my question here is why do they need to be declared as static in the containing class? The recommmended way is to then add instance 'wrapper' property for them. Why ?
edit:
@Matt, but doesn't that also mandate that the property value is also shared across instances - unless of course it is a derived value ?
A: Dependency properties are static because of a key optimization in WPF: Many of the controls in WPF have tens, if not hundreds of properties. Most of the properties in these classes are set to their default value. If DP's were instance properties, memory would need to be allocated for every property in every object you create. Since DP's are static, WPF is free to manage each property's memory usage more effectively.
The reason why you should supply a default value for any DP you register is because WPF will take care not to allocate extra memory for your property when it's set to its default value, no matter how many objects containing that property you create.
A: I think the reason you need the static instance of a dependency property is really just because that's how they were designed. The static bit holds all the property metadata - its default value, its owner type (handy if it's an attached property) etc, its callback methods for when it changes - that sort of thing. Makes sense to store these things statically across all instances of the class rather than per-instance.
A: I see 2 reasons behind that requirement:
*
*You can't register same DP twice. To comply with this constraint you should use static variable, it will be initialized only one time thus you will register DP one time only.
*DP should be registered before any class (which uses that DB) instance created
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can I render a PNG image (as a memory stream) onto a .NET ReportViewer report surface I have a dynamically created image that I am saving to a stream so that I can display it on a ReportViewer surface.
Setup:
*
*Windows Client application (not WebForms)
*Report datasource is an object datasource, with a dynamically generated stream as a property (CustomImage)
*Report.EnableExternalImages = true
*Image.Source = Database
*Image.MIMEType = image/png
*Image.Value = =Fields!CustomImage.Value
This is not working, but is not reporting any errors, just showing an empty image icon on the report surface. All other fields are displaying correctly.
Does anyone have a working code sample of this scenario?
A: I am doing something similar in order to have a changing logo on reports however I utilise report parameters to pass the value. I don't see any reason why this general method wouldn't work if the images were part of the data.
Essentially the images are passed over two fields. The first field is the MIME Type value and the second field is a Base64 encoded string containing the image content.
Step 1: Convert your image to Base64 encoding. (Our code always passes ImageFormat.Png to this method to make the MIME Type easy)
private static string ConvertImageToBase64(Image image, ImageFormat format)
{
byte[] imageArray;
using (System.IO.MemoryStream imageStream = new System.IO.MemoryStream())
{
image.Save(imageStream, format);
imageArray = new byte[imageStream.Length];
imageStream.Seek(0, System.IO.SeekOrigin.Begin);
imageStream.Read(imageArray, 0, imageStream.Length);
}
return Convert.ToBase64String(imageArray);
}
Step 2: Pass the image and MIME Type to the report.
reportParams[0] = new ReportParameter("ReportLogo", base64Logo);
reportParams[1] = new ReportParameter("ReportLogoMimeType", "image/png");
_reportViewer.LocalReport.SetParameters(reportParams);
Step 3: In the report set the following properties on the image (without the quotes):
*
*MIMEType: "=Parameters!ReportLogoMimeType.Value"
*Value: "=System.Convert.FromBase64String(Parameters!ReportLogo.Value)"
*UPDATE: As Gerardo's says below, the Image Source must be set to 'Database'
Trap for young players:
Often the images will look horrible and like they've been scaled even though you're passing in an image which seems to be the "right size". This is because the reports are rendered for print (300 dpi) and not the screen (usually 72 or 92 dpi). The fix is to send in an image about 3 times too big, set it's correct size in the report and change the "Sizing" property on the image to "FitProportional".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Struct like objects in Java Is it completely against the Java way to create struct like objects?
class SomeData1 {
public int x;
public int y;
}
I can see a class with accessors and mutators being more Java like.
class SomeData2 {
int getX();
void setX(int x);
int getY();
void setY(int y);
private int x;
private int y;
}
The class from the first example is notationally convenient.
// a function in a class
public int f(SomeData1 d) {
return (3 * d.x) / d.y;
}
This is not as convenient.
// a function in a class
public int f(SomeData2 d) {
return (3 * d.getX()) / d.getY();
}
A: By the way, the structure you're giving as an example already exist in the Java base class library as java.awt.Point. It has x and y as public fields, check it out for yourself.
If you know what you're doing, and others in your team know about it, then it is okay to have public fields. But you shouldn't rely on it because they can cause headaches as in bugs related to developers using objects as if they were stack allocated structs (java objects are always sent to methods as references and not as copies).
A: Re: aku, izb, John Topley...
Watch out for mutability issues...
It may seem sensible to omit getters/setters. It actually may be ok in some cases. The real problem with the proposed pattern shown here is mutability.
The problem is once you pass an object reference out containing non-final, public fields. Anything else with that reference is free to modify those fields. You no longer have any control over the state of that object. (Think what would happen if Strings were mutable.)
It gets bad when that object is an important part of the internal state of another, you've just exposed internal implementation. To prevent this, a copy of the object must be returned instead. This works, but can cause massive GC pressure from tons of single-use copies created.
If you have public fields, consider making the class read-only. Add the fields as parameters to the constructor, and mark the fields final. Otherwise make sure you're not exposing internal state, and if you need to construct new instances for a return value, make sure it won't be called excessively.
See: "Effective Java" by Joshua Bloch -- Item #13: Favor Immutability.
PS: Also keep in mind, all JVMs these days will optimize away the getMethod if possible, resulting in just a single field-read instruction.
A: I have tried this in a few projects, on the theory that getters and setters clutter up the code with semantically meaningless cruft, and that other languages seem to do just fine with convention-based data-hiding or partitioning of responsibilities (e.g. python).
As others have noted above, there are 2 problems that you run into, and they're not really fixable:
*
*Just about any automated tool in the java world relies on the getter/setter convention. Ditto for, as noted by others, jsp tags, spring configuration, eclipse tools, etc. etc...
Fighting against what your tools expect to see is a recipe for long sessions trolling through google trying to find that non-standard way of initiating spring beans. Really not worth the trouble.
*Once you have your elegantly coded application with hundreds of public variables you will likely find at least one situation where they're insufficient- where you absolutely need immutability, or you need to trigger some event when the variable gets set, or you want to throw an exception on a variable change because it sets an object state to something unpleasant. You're then stuck with the unenviable choices between cluttering up your code with some special method everywhere the variable is directly referenced, having some special access form for 3 out of the 1000 variables in your application.
And this is in the best case scenario of working entirely in a self-contained private project. Once you export the whole thing to a publicly accessible library these problems will become even larger.
Java is very verbose, and this is a tempting thing to do. Don't do it.
A: This is a commonly discussed topic. The drawback of creating public fields in objects is that you have no control over the values that are set to it. In group projects where there are many programmers using the same code, it's important to avoid side effects. Besides, sometimes it's better to return a copy of field's object or transform it somehow etc. You can mock such methods in your tests. If you create a new class you might not see all possible actions. It's like defensive programming - someday getters and setters may be helpful, and it doesn't cost a lot to create/use them. So they are sometimes useful.
In practice, most fields have simple getters and setters. A possible solution would look like this:
public property String foo;
a->Foo = b->Foo;
Update: It's highly unlikely that property support will be added in Java 7 or perhaps ever. Other JVM languages like Groovy, Scala, etc do support this feature now. - Alex Miller
A: To address mutability concerns you can declare x and y as final. For example:
class Data {
public final int x;
public final int y;
public Data( int x, int y){
this.x = x;
this.y = y;
}
}
Calling code that attempts to write to these fields will get a compile time error of "field x is declared final; cannot be assigned".
The client code can then have the 'short-hand' convenience you described in your post
public class DataTest {
public DataTest() {
Data data1 = new Data(1, 5);
Data data2 = new Data(2, 4);
System.out.println(f(data1));
System.out.println(f(data2));
}
public int f(Data d) {
return (3 * d.x) / d.y;
}
public static void main(String[] args) {
DataTest dataTest = new DataTest();
}
}
A: If the Java way is the OO way, then yes, creating a class with public fields breaks the principles around information hiding which say that an object should manage its own internal state. (So as I'm not just spouting jargon at you, a benefit of information hiding is that the internal workings of a class are hidden behind an interface - say you wanted to change the mechanism by which your struct class saved one of its fields, you'll probably need to go back and change any classes that use the class...)
You also can't take advantage of the support for JavaBean naming compliant classes, which will hurt if you decide to, say, use the class in a JavaServer Page which is written using Expression Language.
The JavaWorld article Why Getter and Setter Methods are Evil article also might be of interest to you in thinking about when not to implement accessor and mutator methods.
If you're writing a small solution and want to minimise the amount of code involved, the Java way may not be the right way - I guess it always depends on you and the problem you're trying to solve.
A: It appears that many Java people are not familiar with the Sun Java Coding Guidelines
which say it is quite appropriate to use public instance variable when the class is
essentially a "Struct", if Java supported "struct" (when there is no behavior).
People tend to think getters and setters are the Java way,
as if they are at the heart of Java. This is not so. If you follow the Sun Java
Coding Guidelines, using public instance variables in appropriate situations,
you are actually writing better code than cluttering it with needless getters and setters.
Java Code Conventions from 1999 and still unchanged.
10.1 Providing Access to Instance and Class Variables
Don't make any instance or class variable public without good reason. Often, instance variables don't need to be explicitly set or gotten-often that happens as a side effect of method calls.
One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. In other words, if you would have used a struct instead of a class (if Java supported struct), then it's appropriate to make the class's instance variables public.
http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-137265.html#177
http://en.wikipedia.org/wiki/Plain_old_data_structure
http://docs.oracle.com/javase/1.3/docs/guide/collections/designfaq.html#28
A: There is nothing wrong with that type of code, provided that the author knows they are structs (or data shuttles) instead of objects. Lots of Java developers can't tell the difference between a well-formed object (not just a subclass of java.lang.Object, but a true object in a specific domain) and a pineapple. Ergo,they end up writing structs when they need objects and viceversa.
A: A very-very old question, but let me make another short contribution. Java 8 introduced lambda expressions and method references. Lambda expressions can be simple method references and not declare a "true" body. But you cannot "convert" a field into a method reference. Thus
stream.mapToInt(SomeData1::x)
isn't legal, but
stream.mapToInt(SomeData2::getX)
is.
A: Use common sense really. If you have something like:
public class ScreenCoord2D{
public int x;
public int y;
}
Then there's little point in wrapping them up in getters and setters. You're never going to store an x, y coordinate in whole pixels any other way. Getters and setters will only slow you down.
On the other hand, with:
public class BankAccount{
public int balance;
}
You might want to change the way a balance is calculated at some point in the future. This should really use getters and setters.
It's always preferable to know why you're applying good practice, so that you know when it's ok to bend the rules.
A: The problem with using public field access is the same problem as using new instead of a factory method - if you change your mind later, all existing callers are broken. So, from an API evolution point of view, it's usually a good idea to bite the bullet and use getters/setters.
One place where I go the other way is when you strongly control access to the class, for example in an inner static class used as an internal data structure. In this case, it might be much clearer to use field access.
By the way, on e-bartek's assertion, it is highly unlikely IMO that property support will be added in Java 7.
A: I frequently use this pattern when building private inner classes to simplify my code, but I would not recommend exposing such objects in a public API. In general, the more frequently you can make objects in your public API immutable the better, and it is not possible to construct your 'struct-like' object in an immutable fashion.
As an aside, even if I were writing this object as a private inner class I would still provide a constructor to simplify the code to initialize the object. Having to have 3 lines of code to get a usable object when one will do is just messy.
A: Do not use public fields
Don't use public fields when you really want to wrap the internal behavior of a class. Take java.io.BufferedReader for example. It has the following field:
private boolean skipLF = false; // If the next character is a line feed, skip it
skipLF is read and written in all read methods. What if an external class running in a separate thread maliciously modified the state of skipLF in the middle of a read? BufferedReader will definitely go haywire.
Do use public fields
Take this Point class for example:
class Point {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return this.x;
}
public double getY() {
return this.y;
}
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
}
This would make calculating the distance between two points very painful to write.
Point a = new Point(5.0, 4.0);
Point b = new Point(4.0, 9.0);
double distance = Math.sqrt(Math.pow(b.getX() - a.getX(), 2) + Math.pow(b.getY() - a.getY(), 2));
The class does not have any behavior other than plain getters and setters. It is acceptable to use public fields when the class represents just a data structure, and does not have, and never will have behavior (thin getters and setters is not considered behavior here). It can be written better this way:
class Point {
public double x;
public double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
}
Point a = new Point(5.0, 4.0);
Point b = new Point(4.0, 9.0);
double distance = Math.sqrt(Math.pow(b.x - a.x, 2) + Math.pow(b.y - a.y, 2));
Clean!
But remember: Not only your class must be absent of behavior, but it should also have no reason to have behavior in the future as well.
(This is exactly what this answer describes. To quote "Code Conventions for the Java Programming Language: 10. Programming Practices":
One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. In other words, if you would have used a struct instead of a class (if Java supported struct), then it's appropriate to make the class's instance variables public.
So the official documentation also accepts this practice.)
Also, if you're extra sure that members of above Point class should be immutable, then you could add final keyword to enforce it:
public final double x;
public final double y;
A: I don't see the harm if you know that it's always going to be a simple struct and that you're never going to want to attach behaviour to it.
A: This is a question on Object Oriented Design, not Java the language. It's generally good practice to hide data types within the class and expose only the methods that are part of the class API. If you expose internal data types, you can never change them in the future. If you hide them, your only obligation to the user is the method's return and argument types.
A: Sometime I use such class, when I need to return multiple values from a method. Of course, such object is short lived and with very limited visibility, so it should be OK.
A: You can make a simple class with public fields and no methods in Java, but it is still a class and is still handled syntactically and in terms of memory allocation just like a class. There is no way to genuinely reproduce structs in Java.
A: As with most things, there's the general rule and then there are specific circumstances.
If you are doing a closed, captured application so that you know how a given object is going to be used, then you can exercise more freedom to favor visibility and/or efficiency.
If you're developing a class which is going to be used publicly by others beyond your control, then lean towards the getter/setter model.
As with all things, just use common sense.
It's often ok to do an initial round with publics and then change them to getter/setters later.
A: Aspect-oriented programming lets you trap assignments or fetches and attach intercepting logic to them, which I propose is the right way to solve the problem. (The issue of whether they should be public or protected or package-protected is orthogonal.)
Thus you start out with unintercepted fields with the right access qualifier. As your program requirements grow you attach logic to perhaps validate, make a copy of the object being returned, etc.
The getter/setter philosophy imposes costs on a large number of simple cases where they are not needed.
Whether aspect-style is cleaner or not is somewhat qualitative. I would find it easy to see just the variables in a class and view the logic separately. In fact, the raison d'etre for Apect-oriented programming is that many concerns are cross-cutting and compartmentalizing them in the class body itself is not ideal (logging being an example -- if you want to log all gets Java wants you to write a whole bunch of getters and keeping them in sync but AspectJ allows you a one-liner).
The issue of IDE is a red-herring. It is not so much the typing as it is the reading and visual pollution that arises from get/sets.
Annotations seem similar to aspect-oriented programming at first sight however they require you to exhaustively enumerate pointcuts by attaching annotations, as opposed to a concise wild-card-like pointcut specification in AspectJ.
I hope awareness of AspectJ prevents people from prematurely settling on dynamic languages.
A: Here I create a program to input Name and Age of 5 different persons and perform a selection sort (age wise). I used an class which act as a structure (like C programming language) and a main class to perform the complete operation. Hereunder I'm furnishing the code...
import java.io.*;
class NameList {
String name;
int age;
}
class StructNameAge {
public static void main(String [] args) throws IOException {
NameList nl[]=new NameList[5]; // Create new radix of the structure NameList into 'nl' object
NameList temp=new NameList(); // Create a temporary object of the structure
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
/* Enter data into each radix of 'nl' object */
for(int i=0; i<5; i++) {
nl[i]=new NameList(); // Assign the structure into each radix
System.out.print("Name: ");
nl[i].name=br.readLine();
System.out.print("Age: ");
nl[i].age=Integer.parseInt(br.readLine());
System.out.println();
}
/* Perform the sort (Selection Sort Method) */
for(int i=0; i<4; i++) {
for(int j=i+1; j<5; j++) {
if(nl[i].age>nl[j].age) {
temp=nl[i];
nl[i]=nl[j];
nl[j]=temp;
}
}
}
/* Print each radix stored in 'nl' object */
for(int i=0; i<5; i++)
System.out.println(nl[i].name+" ("+nl[i].age+")");
}
}
The above code is Error Free and Tested... Just copy and paste it into your IDE and ... You know and what??? :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "198"
} |
Q: How can I improve my programming experience on my Linux Desktop? How can I improve the look and feel of my Linux desktop to suit my programming needs?
I found Compiz and it makes switching between my workspaces (which is something I do all the time to make the most of my 13.3" screen laptop) easy and look great - so what else don't I know about that make my programming environment more productive/pleasing?
@Rob Cooper - thanks for the heads-up, hope this reword addresses the issues
A: I found that the best programming experience comes from having quick access all your tools. This means getting comfortable with basic command line acrobatics and really learning keyboard shortcuts, flags, and little productivity apps.
I find that most of my workflow comes down to just a few apps and commands:
*
*Terminator
*SVN commands - ci, co, status, log, etc.
*Command Line FTP
*Vim
*Basic Command lines operations (cd, rm, mv, cp, touch, grep, and std i/o redirection comprise 80% of my work day)
Not to say that GUI apps aren't necessary. A few I use:
*
*Diffmerge
*RapidSVN
*Filezilla
*VirtualBox
*GnomeDo (this really should be first)
When it comes down to it, the real improvement in programming experience comes from just that - programming experience. Just pick a set of tools and stick with them until you know them inside and out.
A: If you have half decent 3D acceleration on board, CompizFusion adds attractive desktop effects like mapping your workspaces onto a cube using that to switch between them/move windows between them. Looks pretty and improves general usability - great!
http://en.wikipedia.org/wiki/Compiz
A: I've used by Ubuntu desktop for some coding sessions. I haven't settled on an IDE, but if I'm not using gedit, I'll use emacs as my editor. Sometimes I need to ssh to a remote server and edit from there, in which case emacs is preferred. I'm just not the vi(m) type.
Maybe I'll try out Eclipse one day...
I love Compiz, but it does nothing for my coding experience. It's just eye candy. You can do desktop switching and Alt-Tab just fine without it. Aside from that, Jeff Atwood's recommendations for good chair, multi-monitors, and simplistic background still apply for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Should a function have only one return statement? Are there good reasons why it's a better practice to have only one return statement in a function?
Or is it okay to return from a function as soon as it is logically correct to do so, meaning there may be many return statements in the function?
A: You know the adage - beauty is in the eyes of the beholder.
Some people swear by NetBeans and some by IntelliJ IDEA, some by Python and some by PHP.
In some shops you could lose your job if you insist on doing this:
public void hello()
{
if (....)
{
....
}
}
The question is all about visibility and maintainability.
I am addicted to using boolean algebra to reduce and simplify logic and use of state machines. However, there were past colleagues who believed my employ of "mathematical techniques" in coding is unsuitable, because it would not be visible and maintainable. And that would be a bad practice. Sorry people, the techniques I employ is very visible and maintainable to me - because when I return to the code six months later, I would understand the code clearly rather seeing a mess of proverbial spaghetti.
Hey buddy (like a former client used to say) do what you want as long as you know how to fix it when I need you to fix it.
I remember 20 years ago, a colleague of mine was fired for employing what today would be called agile development strategy. He had a meticulous incremental plan. But his manager was yelling at him "You can't incrementally release features to users! You must stick with the waterfall." His response to the manager was that incremental development would be more precise to customer's needs. He believed in developing for the customers needs, but the manager believed in coding to "customer's requirement".
We are frequently guilty for breaking data normalization, MVP and MVC boundaries. We inline instead of constructing a function. We take shortcuts.
Personally, I believe that PHP is bad practice, but what do I know. All the theoretical arguments boils down to trying fulfill one set of rules
quality = precision, maintainability
and profitability.
All other rules fade into the background. And of course this rule never fades:
Laziness is the virtue of a good
programmer.
A: I lean towards using guard clauses to return early and otherwise exit at the end of a method. The single entry and exit rule has historical significance and was particularly helpful when dealing with legacy code that ran to 10 A4 pages for a single C++ method with multiple returns (and many defects). More recently, accepted good practice is to keep methods small which makes multiple exits less of an impedance to understanding. In the following Kronoz example copied from above, the question is what occurs in //Rest of code...?:
void string fooBar(string s, int? i) {
if(string.IsNullOrEmpty(s) || i == null) return null;
var res = someFunction(s, i);
foreach(var r in res) {
if(!r.Passed) return null;
}
// Rest of code...
return ret;
}
I realise the example is somewhat contrived but I would be tempted to refactor the foreach loop into a LINQ statement that could then be considered a guard clause. Again, in a contrived example the intent of the code isn't apparent and someFunction() may have some other side effect or the result may be used in the // Rest of code....
if (string.IsNullOrEmpty(s) || i == null) return null;
if (someFunction(s, i).Any(r => !r.Passed)) return null;
Giving the following refactored function:
void string fooBar(string s, int? i) {
if (string.IsNullOrEmpty(s) || i == null) return null;
if (someFunction(s, i).Any(r => !r.Passed)) return null;
// Rest of code...
return ret;
}
A: I often have several statements at the start of a method to return for "easy" situations. For example, this:
public void DoStuff(Foo foo)
{
if (foo != null)
{
...
}
}
... can be made more readable (IMHO) like this:
public void DoStuff(Foo foo)
{
if (foo == null) return;
...
}
So yes, I think it's fine to have multiple "exit points" from a function/method.
A: Structured programming says you should only ever have one return statement per function. This is to limit the complexity. Many people such as Martin Fowler argue that it is simpler to write functions with multiple return statements. He presents this argument in the classic refactoring book he wrote. This works well if you follow his other advice and write small functions. I agree with this point of view and only strict structured programming purists adhere to single return statements per function.
A: One good reason I can think of is for code maintenance: you have a single point of exit. If you want to change the format of the result,..., it's just much simpler to implement. Also, for debugging, you can just stick a breakpoint there :)
Having said that, I once had to work in a library where the coding standards imposed 'one return statement per function', and I found it pretty tough. I write lots of numerical computations code, and there often are 'special cases', so the code ended up being quite hard to follow...
A: Multiple exit points are fine for small enough functions -- that is, a function that can be viewed on one screen length on its entirety. If a lengthy function likewise includes multiple exit points, it's a sign that the function can be chopped up further.
That said I avoid multiple-exit functions unless absolutely necessary. I have felt pain of bugs that are due to some stray return in some obscure line in more complex functions.
A: As Kent Beck notes when discussing guard clauses in Implementation Patterns making a routine have a single entry and exit point ...
"was to prevent the confusion possible
when jumping into and out of many
locations in the same routine. It made
good sense when applied to FORTRAN or
assembly language programs written
with lots of global data where even
understanding which statements were
executed was hard work ... with small methods and mostly local data, it is needlessly conservative."
I find a function written with guard clauses much easier to follow than one long nested bunch of if then else statements.
A: In a function that has no side-effects, there's no good reason to have more than a single return and you should write them in a functional style. In a method with side-effects, things are more sequential (time-indexed), so you write in an imperative style, using the return statement as a command to stop executing.
In other words, when possible, favor this style
return a > 0 ?
positively(a):
negatively(a);
over this
if (a > 0)
return positively(a);
else
return negatively(a);
If you find yourself writing several layers of nested conditions, there's probably a way you can refactor that, using predicate list for example. If you find that your ifs and elses are far apart syntactically, you might want to break that down into smaller functions. A conditional block that spans more than a screenful of text is hard to read.
There's no hard and fast rule that applies to every language. Something like having a single return statement won't make your code good. But good code will tend to allow you to write your functions that way.
A: I've worked with terrible coding standards that forced a single exit path on you and the result is nearly always unstructured spaghetti if the function is anything but trivial -- you end up with lots of breaks and continues that just get in the way.
A: Single exit point - all other things equal - makes code significantly more readable.
But there's a catch: popular construction
resulttype res;
if if if...
return res;
is a fake, "res=" is not much better than "return". It has single return statement, but multiple points where function actually ends.
If you have function with multiple returns (or "res="s), it's often a good idea to break it into several smaller functions with single exit point.
A: My usual policy is to have only one return statement at the end of a function unless the complexity of the code is greatly reduced by adding more. In fact, I'm rather a fan of Eiffel, which enforces the only one return rule by having no return statement (there's just a auto-created 'result' variable to put your result in).
There certainly are cases where code can be made clearer with multiple returns than the obvious version without them would be. One could argue that more rework is needed if you have a function that is too complex to be understandable without multiple return statements, but sometimes it's good to be pragmatic about such things.
A: If you end up with more than a few returns there may be something wrong with your code. Otherwise I would agree that sometimes it is nice to be able to return from multiple places in a subroutine, especially when it make the code cleaner.
Perl 6: Bad Example
sub Int_to_String( Int i ){
given( i ){
when 0 { return "zero" }
when 1 { return "one" }
when 2 { return "two" }
when 3 { return "three" }
when 4 { return "four" }
...
default { return undef }
}
}
would be better written like this
Perl 6: Good Example
@Int_to_String = qw{
zero
one
two
three
four
...
}
sub Int_to_String( Int i ){
return undef if i < 0;
return undef unless i < @Int_to_String.length;
return @Int_to_String[i]
}
Note this is was just a quick example
A: I vote for Single return at the end as a guideline. This helps a common code clean-up handling ... For example, take a look at the following code ...
void ProcessMyFile (char *szFileName)
{
FILE *fp = NULL;
char *pbyBuffer = NULL:
do {
fp = fopen (szFileName, "r");
if (NULL == fp) {
break;
}
pbyBuffer = malloc (__SOME__SIZE___);
if (NULL == pbyBuffer) {
break;
}
/*** Do some processing with file ***/
} while (0);
if (pbyBuffer) {
free (pbyBuffer);
}
if (fp) {
fclose (fp);
}
}
A: I've seen it in coding standards for C++ that were a hang-over from C, as if you don't have RAII or other automatic memory management then you have to clean up for each return, which either means cut-and-paste of the clean-up or a goto (logically the same as 'finally' in managed languages), both of which are considered bad form. If your practices are to use smart pointers and collections in C++ or another automatic memory system, then there isn't a strong reason for it, and it become all about readability, and more of a judgement call.
A: I lean to the idea that return statements in the middle of the function are bad. You can use returns to build a few guard clauses at the top of the function, and of course tell the compiler what to return at the end of the function without issue, but returns in the middle of the function can be easy to miss and can make the function harder to interpret.
A: The more return statements you have in a function, the higher complexity in that one method. If you find yourself wondering if you have too many return statements, you might want to ask yourself if you have too many lines of code in that function.
But, not, there is nothing wrong with one/many return statements. In some languages, it is a better practice (C++) than in others (C).
A: This is probably an unusual perspective, but I think that anyone who believes that multiple return statements are to be favoured has never had to use a debugger on a microprocessor that supports only 4 hardware breakpoints. ;-)
While the issues of "arrow code" are completely correct, one issue that seems to go away when using multiple return statements is in the situation where you are using a debugger. You have no convenient catch-all position to put a breakpoint to guarantee that you're going to see the exit and hence the return condition.
A: If it's okay to write down just an opinion, that's mine:
I totally and absolutely disagree with the `Single return statement theory' and find it mostly speculative and even destructive regarding the code readability, logic and descriptive aspects.
That habit of having one-single-return is even poor for bare procedural programming not to mention more high-level abstractions (functional, combinatory etc.). And furthermore, I wish all the code written in that style to go through some special rewriting parser to make it have multiple return statements!
A function (if it's really a function/query according to `Query-Command separation' note - see Eiffel programming lang. for example) just MUST define as many return points as the control flow scenarios it has. It is much more clear and mathematically consistent; and it is the way to write functions (i.e. Queries)
But I would not be so militant for the mutation messages that your agent does receive - the procedure calls.
A:
Are there good reasons why it's a better practice to have only one return statement in a function?
Yes, there are:
*
*The single exit point gives an excellent place to assert your post-conditions.
*Being able to put a debugger breakpoint on the one return at the end of the function is often useful.
*Fewer returns means less complexity. Linear code is generally simpler to understand.
*If trying to simplify a function to a single return causes complexity, then that's incentive to refactor to smaller, more general, easier-to-understand functions.
*If you're in a language without destructors or if you don't use RAII, then a single return reduces the number of places you have to clean up.
*Some languages require a single exit point (e.g., Pascal and Eiffel).
The question is often posed as a false dichotomy between multiple returns or deeply nested if statements. There's almost always a third solution which is very linear (no deep nesting) with only a single exit point.
Update: Apparently MISRA guidelines promote single exit, too.
To be clear, I'm not saying it's always wrong to have multiple returns. But given otherwise equivalent solutions, there are lots of good reasons to prefer the one with a single return.
A: Nobody has mentioned or quoted Code Complete so I'll do it.
17.1 return
Minimize the number of returns in each routine. It's harder to understand a routine if, reading it at the bottom, you're unaware of the possibility that it returned somewhere above.
Use a return when it enhances readability. In certain routines, once you know the answer, you want to return it to the calling routine immediately. If the routine is defined in such a way that it doesn't require any cleanup, not returning immediately means that you have to write more code.
A: Having a single exit point does provide an advantage in debugging, because it allows you to set a single breakpoint at the end of a function to see what value is actually going to be returned.
A: It doesn't make sense to always require a single return type. I think it is more of a flag that something may need to be simplified. Sometimes it's necessary to have multiple returns, but often you can keep things simpler by at least trying to have a single exit point.
A: The only important question is "How is the code simpler, better readable, easier to understand?" If it is simpler with multiple returns, then use them.
A: Having multiple exit points is essentially the same thing as using a GOTO. Whether or not that's a bad thing depends on how you feel about raptors.
A: I would say it would be incredibly unwise to decide arbitrarily against multiple exit points as I have found the technique to be useful in practice over and over again, in fact I have often refactored existing code to multiple exit points for clarity. We can compare the two approaches thus:-
string fooBar(string s, int? i) {
string ret = "";
if(!string.IsNullOrEmpty(s) && i != null) {
var res = someFunction(s, i);
bool passed = true;
foreach(var r in res) {
if(!r.Passed) {
passed = false;
break;
}
}
if(passed) {
// Rest of code...
}
}
return ret;
}
Compare this to the code where multiple exit points are permitted:-
string fooBar(string s, int? i) {
var ret = "";
if(string.IsNullOrEmpty(s) || i == null) return null;
var res = someFunction(s, i);
foreach(var r in res) {
if(!r.Passed) return null;
}
// Rest of code...
return ret;
}
I think the latter is considerably clearer. As far as I can tell the criticism of multiple exit points is a rather archaic point of view these days.
A: You already implicitly have multiple implicit return statements, caused by error handling, so deal with it.
As is typical with programming, though, there are examples both for and against the multiple return practice. If it makes the code clearer, do it one way or the other. Use of many control structures can help (the case statement, for example).
A: Well, maybe I'm one of the few people here old enough to remember one of the big reasons why "only one return statement" was pushed so hard. It's so the compiler can emit more efficient code. For each function call, the compiler typically pushes some registers on the stack to preserve their values. This way, the function can use those registers for temporary storage. When the function returns, those saved registers have to be popped off the stack and back into the registers. That's one POP (or MOV -(SP),Rn) instruction per register. If you have a bunch of return statements, then either each one has to pop all the registers (which makes the compiled code bigger) or the compiler has to keep track of which registers might have been modified and only pop those (decreasing code size, but increasing compilation time).
One reason why it still makes sense today to try to stick with one return statement is ease of automated refactoring. If your IDE supports method-extraction refactoring (selecting a range of lines and turning them into a method), it's very difficult to do this if the lines you want to extract have a return statement in them, especially if you're returning a value.
A: I currently am working on a codebase where two of the people working on it blindly subscribe to the "single point of exit" theory and I can tell you that from experience, it's a horrible horrible practice. It makes code extremely difficult to maintain and I'll show you why.
With the "single point of exit" theory, you inevitably wind up with code that looks like this:
function()
{
HRESULT error = S_OK;
if(SUCCEEDED(Operation1()))
{
if(SUCCEEDED(Operation2()))
{
if(SUCCEEDED(Operation3()))
{
if(SUCCEEDED(Operation4()))
{
}
else
{
error = OPERATION4FAILED;
}
}
else
{
error = OPERATION3FAILED;
}
}
else
{
error = OPERATION2FAILED;
}
}
else
{
error = OPERATION1FAILED;
}
return error;
}
Not only does this make the code very hard to follow, but now say later on you need to go back and add an operation in between 1 and 2. You have to indent just about the entire freaking function, and good luck making sure all of your if/else conditions and braces are matched up properly.
This method makes code maintenance extremely difficult and error prone.
A: In general I try to have only a single exit point from a function. There are times, however, that doing so actually ends up creating a more complex function body than is necessary, in which case it's better to have multiple exit points. It really has to be a "judgement call" based on the resulting complexity, but the goal should be as few exit points as possible without sacrificing complexity and understandability.
A: No, because we don't live in the 1970s any more. If your function is long enough that multiple returns are a problem, it's too long.
(Quite apart from the fact that any multi-line function in a language with exceptions will have multiple exit points anyway.)
A: My preference would be for single exit unless it really complicates things. I have found that in some cases, multiple exist points can mask other more significant design problems:
public void DoStuff(Foo foo)
{
if (foo == null) return;
}
On seeing this code, I would immediately ask:
*
*Is 'foo' ever null?
*If so, how many clients of 'DoStuff' ever call the function with a null 'foo'?
Depending on the answers to these questions it might be that
*
*the check is pointless as it never is true (ie. it should be an assertion)
*the check is very rarely true and so it may be better to change those specific caller functions as they should probably take some other action anyway.
In both of the above cases the code can probably be reworked with an assertion to ensure that 'foo' is never null and the relevant callers changed.
There are two other reasons (specific I think to C++ code) where multiple exists can actually have a negative affect. They are code size, and compiler optimizations.
A non-POD C++ object in scope at the exit of a function will have its destructor called. Where there are several return statements, it may be the case that there are different objects in scope and so the list of destructors to call will be different. The compiler therefore needs to generate code for each return statement:
void foo (int i, int j) {
A a;
if (i > 0) {
B b;
return ; // Call dtor for 'b' followed by 'a'
}
if (i == j) {
C c;
B b;
return ; // Call dtor for 'b', 'c' and then 'a'
}
return 'a' // Call dtor for 'a'
}
If code size is an issue - then this may be something worth avoiding.
The other issue relates to "Named Return Value OptimiZation" (aka Copy Elision, ISO C++ '03 12.8/15). C++ allows an implementation to skip calling the copy constructor if it can:
A foo () {
A a1;
// do something
return a1;
}
void bar () {
A a2 ( foo() );
}
Just taking the code as is, the object 'a1' is constructed in 'foo' and then its copy construct will be called to construct 'a2'. However, copy elision allows the compiler to construct 'a1' in the same place on the stack as 'a2'. There is therefore no need to "copy" the object when the function returns.
Multiple exit points complicates the work of the compiler in trying to detect this, and at least for a relatively recent version of VC++ the optimization did not take place where the function body had multiple returns. See Named Return Value Optimization in Visual C++ 2005 for more details.
A: Having a single exit point reduces Cyclomatic Complexity and therefore, in theory, reduces the probability that you will introduce bugs into your code when you change it. Practice however, tends to suggest that a more pragmatic approach is needed. I therefore tend to aim to have a single exit point, but allow my code to have several if that is more readable.
A: I force myself to use only one return statement, as it will in a sense generate code smell. Let me explain:
function isCorrect($param1, $param2, $param3) {
$toret = false;
if ($param1 != $param2) {
if ($param1 == ($param3 * 2)) {
if ($param2 == ($param3 / 3)) {
$toret = true;
} else {
$error = 'Error 3';
}
} else {
$error = 'Error 2';
}
} else {
$error = 'Error 1';
}
return $toret;
}
(The conditions are arbritary...)
The more conditions, the larger the function gets, the more difficult it is to read. So if you're attuned to the code smell, you'll realise it, and want to refactor the code. Two possible solutions are:
*
*Multiple returns
*Refactoring into separate functions
Multiple Returns
function isCorrect($param1, $param2, $param3) {
if ($param1 == $param2) { $error = 'Error 1'; return false; }
if ($param1 != ($param3 * 2)) { $error = 'Error 2'; return false; }
if ($param2 != ($param3 / 3)) { $error = 'Error 3'; return false; }
return true;
}
Separate Functions
function isEqual($param1, $param2) {
return $param1 == $param2;
}
function isDouble($param1, $param2) {
return $param1 == ($param2 * 2);
}
function isThird($param1, $param2) {
return $param1 == ($param2 / 3);
}
function isCorrect($param1, $param2, $param3) {
return !isEqual($param1, $param2)
&& isDouble($param1, $param3)
&& isThird($param2, $param3);
}
Granted, it is longer and a bit messy, but in the process of refactoring the function this way, we've
*
*created a number of reusable functions,
*made the function more human readable, and
*the focus of the functions is on why the values are correct.
A: I would say you should have as many as required, or any that make the code cleaner (such as guard clauses).
I have personally never heard/seen any "best practices" say that you should have only one return statement.
For the most part, I tend to exit a function as soon as possible based on a logic path (guard clauses are an excellent example of this).
A: There are good things to say about having a single exit-point, just as there are bad things to say about the inevitable "arrow" programming that results.
If using multiple exit points during input validation or resource allocation, I try to put all the 'error-exits' very visibly at the top of the function.
Both the Spartan Programming article of the "SSDSLPedia" and the single function exit point article of the "Portland Pattern Repository's Wiki" have some insightful arguments around this. Also, of course, there is this post to consider.
If you really want a single exit-point (in any non-exception-enabled language) for example in order to release resources in one single place, I find the careful application of goto to be good; see for example this rather contrived example (compressed to save screen real-estate):
int f(int y) {
int value = -1;
void *data = NULL;
if (y < 0)
goto clean;
if ((data = malloc(123)) == NULL)
goto clean;
/* More code */
value = 1;
clean:
free(data);
return value;
}
Personally I, in general, dislike arrow programming more than I dislike multiple exit-points, although both are useful when applied correctly. The best, of course, is to structure your program to require neither. Breaking down your function into multiple chunks usually help :)
Although when doing so, I find I end up with multiple exit points anyway as in this example, where some larger function has been broken down into several smaller functions:
int g(int y) {
value = 0;
if ((value = g0(y, value)) == -1)
return -1;
if ((value = g1(y, value)) == -1)
return -1;
return g2(y, value);
}
Depending on the project or coding guidelines, most of the boiler-plate code could be replaced by macros. As a side note, breaking it down this way makes the functions g0, g1 ,g2 very easy to test individually.
Obviously, in an OO and exception-enabled language, I wouldn't use if-statements like that (or at all, if I could get away with it with little enough effort), and the code would be much more plain. And non-arrowy. And most of the non-final returns would probably be exceptions.
In short;
*
*Few returns are better than many returns
*More than one return is better than huge arrows, and guard clauses are generally ok.
*Exceptions could/should probably replace most 'guard clauses' when possible.
A: I believe that multiple returns are usually good (in the code that I write in C#). The single-return style is a holdover from C. But you probably aren't coding in C.
There is no law requiring only one exit point for a method in all programming languages. Some people insist on the superiority of this style, and sometimes they elevate it to a "rule" or "law" but this belief is not backed up by any evidence or research.
More than one return style may be a bad habit in C code, where resources have to be explicitly de-allocated, but languages such as Java, C#, Python or JavaScript that have constructs such as automatic garbage collection and try..finally blocks (and using blocks in C#), and this argument does not apply - in these languages, it is very uncommon to need centralised manual resource deallocation.
There are cases where a single return is more readable, and cases where it isn't. See if it reduces the number of lines of code, makes the logic clearer or reduces the number of braces and indents or temporary variables.
Therefore, use as many returns as suits your artistic sensibilities, because it is a layout and readability issue, not a technical one.
I have talked about this at greater length on my blog.
A: I use multiple exit points for having error-case + handling + return value as close in proximity as possible.
So having to test for conditions a, b, c that have to be true and you need to handle each of them differently:
if (a is false) {
handle this situation (eg. report, log, message, etc.)
return some-err-code
}
if (b is false) {
handle this situation
return other-err-code
}
if (c is false) {
handle this situation
return yet-another-err-code
}
perform any action assured that a, b and c are ok.
The a, b and c might be different things, like a is input parameter check, b is pointer check to newly allocated memory and c is check for a value in 'a' parameter.
A: In the interests of good standards and industry best practises, we must establish the correct number of return statements to appear in all functions. Obviously there is consensus against having one return statement. So I propose we set it at two.
I would appreciate it if everyone would look through their code right now, locate any functions with only one exit point, and add another one. It doesn't matter where.
The result of this change will undoubtedly be fewer bugs, greater readability and unimaginable wealth falling from the sky onto our heads.
A: I prefer a single return statement. One reason which has not yet been pointed out is that some refactoring tools work better for single points of exit, e.g. Eclipse JDT extract/inline method.
A: There are times when it is necessary for performance reasons (I don't want to fetch a different cache line kind of the same need as a continue; sometimes).
If you allocate resources (memory, file descriptors, locks, etc.) without using RAII then muliple returns can be error prone and are certainly duplicative as the releases need to be done manually multiple times and you must keep careful track.
In the example:
function()
{
HRESULT error = S_OK;
if(SUCCEEDED(Operation1()))
{
if(SUCCEEDED(Operation2()))
{
if(SUCCEEDED(Operation3()))
{
if(SUCCEEDED(Operation4()))
{
}
else
{
error = OPERATION4FAILED;
}
}
else
{
error = OPERATION3FAILED;
}
}
else
{
error = OPERATION2FAILED;
}
}
else
{
error = OPERATION1FAILED;
}
return error;
}
I would have written it as:
function() {
HRESULT error = OPERATION1FAILED;//assume failure
if(SUCCEEDED(Operation1())) {
error = OPERATION2FAILED;//assume failure
if(SUCCEEDED(Operation3())) {
error = OPERATION3FAILED;//assume failure
if(SUCCEEDED(Operation3())) {
error = OPERATION4FAILED; //assume failure
if(SUCCEEDED(Operation4())) {
error = S_OK;
}
}
}
}
return error;
}
Which certainly seems better.
This tends to be especially helpful in the manual resource release case as where and which releases are necessary is pretty straightforward. As in the following example:
function() {
HRESULT error = OPERATION1FAILED;//assume failure
if(SUCCEEDED(Operation1())) {
//allocate resource for op2;
char* const p2 = new char[1024];
error = OPERATION2FAILED;//assume failure
if(SUCCEEDED(Operation2(p2))) {
//allocate resource for op3;
char* const p3 = new char[1024];
error = OPERATION3FAILED;//assume failure
if(SUCCEEDED(Operation3(p3))) {
error = OPERATION4FAILED; //assume failure
if(SUCCEEDED(Operation4(p2,p3))) {
error = S_OK;
}
}
//free resource for op3;
delete [] p3;
}
//free resource for op2;
delete [] p2;
}
return error;
}
If you write this code without RAII (forgetting the issue of exceptions!) with multiple exits then the deletes have to be written multiple times. If you write it with }else{ then
it gets a little ugly.
But RAII makes the multiple exit resource issue moot.
A: I always avoid multiple return statements. Even in small functions. Small functions can become larger, and tracking the multiple return paths makes it harder (to my small mind) to keep track of what is going on. A single return also makes debugging easier. I've seen people post that the only alternative to multiple return statements is a messy arrow of nested IF statements 10 levels deep. While I certain agree that such coding does occur, it isn't the only option. I wouldn't make the choice between a multiple return statements and a nest of IFs, I'd refactor it so you'd eliminate both. And that is how I code. The following code eliminates both issues and, in my mind, is very easy to read:
public string GetResult()
{
string rv = null;
bool okay = false;
okay = PerformTest(1);
if (okay)
{
okay = PerformTest(2);
}
if (okay)
{
okay = PerformTest(3);
}
if (okay)
{
okay = PerformTest(4);
};
if (okay)
{
okay = PerformTest(5);
}
if (okay)
{
rv = "All Tests Passed";
}
return rv;
}
A: As an alternative to the nested IFs, there's a way to use do/while(false) to break out anywhere:
function()
{
HRESULT error = S_OK;
do
{
if(!SUCCEEDED(Operation1()))
{
error = OPERATION1FAILED;
break;
}
if(!SUCCEEDED(Operation2()))
{
error = OPERATION2FAILED;
break;
}
if(!SUCCEEDED(Operation3()))
{
error = OPERATION3FAILED;
break;
}
if(!SUCCEEDED(Operation4()))
{
error = OPERATION4FAILED;
break;
}
} while (false);
return error;
}
That gets you one exit point, lets you have other nesting of operations, but still not a real deep structure. If you don't like the !SUCCEEDED you could always do FAILED whatever. This kind of thing also lets you add other code between any two other checks without having to re-indent anything.
If you were really crazy, that whole if block could be macroized too. :D
#define BREAKIFFAILED(x,y) if (!SUCCEEDED((x))) { error = (Y); break; }
do
{
BREAKIFFAILED(Operation1(), OPERATION1FAILED)
BREAKIFFAILED(Operation2(), OPERATION2FAILED)
BREAKIFFAILED(Operation3(), OPERATION3FAILED)
BREAKIFFAILED(Operation4(), OPERATION4FAILED)
} while (false);
A: I think in different situations different method is better. For example, if you should process the return value before return, you should have one point of exit. But in other situations, it is more comfortable to use several returns.
One note. If you should process the return value before return in several situations, but not in all, the best solutions (IMHO) to define a method like ProcessVal and call it before return:
var retVal = new RetVal();
if(!someCondition)
return ProcessVal(retVal);
if(!anotherCondition)
return retVal;
A: I'm probably going to be hated for this, but ideally there should be no return statement at all I think, a function should just return its last expression, and should in the completely ideal case contain only one.
So not
function name(arg) {
if (arg.failure?)
return;
//code for non failure
}
But rather
function name(arg) {
if (arg.failure?)
voidConstant
else {
//code for non failure
}
If-statements that aren't expressions and return statements are a very dubious practise to me.
A: One might argue... if you have multiple conditions that must be satisfied before the tasks of the function are to be performed, then don't invoke the function until those conditions are met:
Instead of:
function doStuff(foo) {
if (foo != null) return;
}
Or
function doStuff(foo) {
if (foo !== null) {
...
}
}
Don't invoke doStuff until foo != null
if(foo != null) doStuff(foo);
Which, requires that every call site ensures that the conditions for the invocation are satisfied before the call. If there are multiple call sites, this logic is perhaps best placed in a separate function, in a method of the to-be-invoked function (assuming they are first-class citizens), or in a proxy.
On the topic of whether or not the function is mathematically provable, consider the logic over the syntax. If a function has multiple return points, this doesn't mean (by default) that it is not mathematically provable.
A: This is mainly a hang over from Fortran, where it was possible to pass multiple statement labels to a function so it could return to any one of them.
So this sort of code was perfectly valid
CALL SOMESUB(ARG1, 101, 102, 103)
C Some code
101 CONTINUE
C Some more code
102 CONTINUE
C Yet more code
103 CONTINUE
C You get the general idea
But the function being called made the decision as to where your code path went. Efficient? Probably. Maintainable? No.
That is where that rule comes from (incidentally along with no multiple entry points to a function, which is possible in fortran and assembler, but not in C).
However, the wording of that looks like it can be applied to other languages (the one about multiple entry points can't be applied to other languages, so it's not really a program). So the rule got carried over, even though it refers to a completely different problem, and isn't applicable.
For more structured languages, that rule needs to be dropped or at least thought through more. Certainly a function spattered with returns is difficult to understand, but returning at the beginning isn't an issue. And in some C++ compilers a single return point may generate better code if you're returning a value from only one place.
But the original rule is misunderstood, misapplied. and no longer relevant.
A: You can do this for achieving only one return statement - declare it at start and output it at the end - problem solved:
$content = "";
$return = false;
if($content != "")
{
$return = true;
}
else
{
$return = false;
}
return $return;
A: Multiple exit is good if you manage it well
The first step is to specify the reasons of exit. Mine is usually something like this:
1. No need to execute the function
2. Error is found
3. Early completion
4. Normal completion
I suppose you can group "1. No need to execute the function" into "3. Early completion" (a very early completion if you will).
The second step is to let the world outside the function know the reason of exit. The pseudo-code looks something like this:
function foo (input, output, exit_status)
exit_status == UNDEFINED
if (check_the_need_to_execute == false) then
exit_status = NO_NEED_TO_EXECUTE // reason #1
exit
useful_work
if (error_is_found == true) then
exit_status = ERROR // reason #2
exit
if (need_to_go_further == false) then
exit_status = EARLY_COMPLETION // reason #3
exit
more_work
if (error_is_found == true) then
exit_status = ERROR
else
exit_status = NORMAL_COMPLETION // reason #4
end function
Obviously, if it's beneficial to move a lump of work in the illustration above into a separate function, you should do so.
If you want to, you can be more specific with the exit status, say, with several error codes and early completion codes to pinpoint the reason (or even the location) of exit.
Even if you force this function into one that has only a single exit, I think you still need to specify exit status anyway. The caller needs to know whether it's OK to use the output, and it helps maintenance.
A: You should never use a return statement in a method.
I know I will be jumped on for this, but I am serious.
Return statements are basically a hangover from the procedural programming days. They are a form of goto, along with break, continue, if, switch/case, while, for, yield and some other statements and the equivalents in most modern programming languages.
Return statements effectively 'GOTO' the point where the function was called, assigning a variable in that scope.
Return statements are what I call a 'Convenient Nightmare'. They seem to get things done quickly, but cause massive maintenance headaches down the line.
Return statements are diametrically opposed to Encapsulation
This is the most important and fundamental concept of object oriented programming. It is the raison d'etre of OOP.
Whenever you return anything from a method, you are basically 'leaking' state information from the object. It doesn't matter if your state has changed or not, nor whether this information comes from other objects - it makes no difference to the caller. What this does is allow an object's behaviour to be outside of the object - breaking encapsulation. It allows the caller to start manipulating the object in ways that lead to fragile designs.
LoD is your friend
I recommend any developer to read about the Law of Demeter (LoD) on c2.com or Wikipedia. LoD is a design philosophy that has been used at places that have real 'mission-critical' software constraints in the literal sense, like the JPL. It has been shown to reduce the amount of bugs in code and improve flexibility.
There has an excellent analogy based on walking a dog. When you walk a dog, you do not physically grab hold of its legs and move them such that the dog walks. You command the dog to walk and it takes care of it's own legs. A return statement in this analogy is equivalent to the dog letting you grab hold of its legs.
Only talk to your immediate friends:
*
*arguments of the function you are in,
*your own attributes,
*any objects you created within the function
You will notice that none of these require a return statement. You might think the constructor is a return, and you are on to something. Actually the return is from the memory allocator. The constructor just sets what is in the memory. This is OK so long as the encapsulation of that new object is OK, because, as you made it, you have full control over it - no-one else can break it.
Accessing attributes of other objects is right out. Getters are out (but you knew they were bad already, right?). Setters are OK, but it is better to use constructors. Inheritance is bad - when you inherit from another class, any changes in that class can and probably will break you. Type sniffing is bad (Yes - LoD implies that Java/C++ style type based dispatch is incorrect - asking about type, even implicitly, is breaking encapsulation. Type is an implicit attribute of an object. Interfaces are The Right Thing).
So why is this all a problem? Well, unless your universe is very different from mine, you spend a lot of time debugging code. You aren't writing code that you plan never to reuse. Your software requirements are changing, and that causes internal API/interface changes. Every time you have used a return statement you have introduced a very tricky dependency - methods returning anything are required to know about how whatever they return is going to be used - that is each and every case! As soon as the interface changes, on one end or the other, everything can break, and you are faced with a lengthy and tedious bug hunt.
They really are an malignant cancer in your code, because once you start using them, they promote further use elsewhere (which is why you can often find returning method-chains amongst object systems).
So what is the alternative?
Tell, don't ask.
With OOP - the goal is to tell other objects what to do, and let them take care of it. So you have to forget the procedural ways of doing things. It's easy really - just never write return statements. There are much better ways of doing the same things:
There is nothing wrong with the return concept, but return statements are deeply flawed.
If you really need an answer back - use a call back. Pass in a data structure to be filled in, even. That way you keep the interfaces clean and open to change, and your whole system is less fragile and more adaptable. It does not slow your system down, in fact it can speed it up, in the same way as tail call optimisation does - except in this case, there is no tail call so you don't even have to waste time manipulating the stack with return values.
If you follow these arguments, you will find there really is never a need for a return statement.
If you follow these practices, I guarantee that pretty soon you will find that you are spending a lot less time hunting bugs, are adapting to requirement changes much more quickly, and having less problems understanding your own code.
A: I'm usually in favor of multiple return statements. They are easiest to read.
There are situations where it isn't good. Sometimes returning from a function can be very complicated. I recall one case where all functions had to link into multiple different libraries. One library expected return values to be error/status codes and others didn't. Having a single return statement can save time there.
I'm surprised that no one mentioned goto. Goto is not the bane of programming that everyone would have you believe. If you must have just a single return in each function, put it at the end and use gotos to jump to that return statement as needed. Definitely avoid flags and arrow programming which are both ugly and run slowly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "780"
} |
Q: Is there a good yacc/bison type LALR parser generator for .NET? Is there a good yacc/bison type LALR parser generator for .NET ?
A: SableCC can generate c# code. It's pretty good but you need a few days to figure out how it all works, because the documentation ist not that great
A: Antlr supports C# code generation, though it is LL(k) not technically LALR. Its tree rewriting rules are an interesting feature though.
A: The Gardens Point Parser Generator looks good, however I've not had a chance to try it myself.
A: Check out Gold. It is LALR compliant and supports lots of languages, if not the most. Gold can convert YACC and Bison type grammars.
If it does not suit your needs then check out this page.
Spirit is another LALR parser.
Also note that Mono created a variant of the Jay parser for their c# and .NET framework. Their c# compiler is, from what I can tell, production quality.
A: Coco It's LL(k) but does a good job
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How can I access a website configured with host headers in IIS on the local machine? When using host headers to host multiple websites on the same IP address in IIS, is there any way of accessing that website from a browser running on the local machine?
This is normally required when a given web component only allows configuration from the local machine. It's also useful when things like ASP.Net's built in error handling isn't working and you can only view the error in the browser but don't want to allow remote users to see it.
This has baffled me for a while and everytime I come across it I end up giving up in frustration and reconfigure stuff so I can accomplish such tasks remotely.
Added: @Ishmaeel - modifying hosts doesn't seem to help - you either get a 400 error (if all websites have host headers) or whichever site is configured without a host header.
A: Just an idea: Mapping the hostname to 127.0.0.1 in the hosts ($WINDOWS$\system32\drivers\etc) file may help. This way you should be able to pull up the local IIS site by typing the hostname as if it's a remote server
A: Maybe I am not understanding the question, but what's wrong with just typing in the URL for the website? If it's the matter of domain name resolution, you can point to the right DNS or put it in hosts file.
A: eed3si9n -- if you are trying to access a url locally and you use host headers you cant just type in the url: for example you have 2 websites (website1.com website2.com) on 1 server using host headers. the local ip of the web server is 192.168.1.50 --> if you type in 192.168.1.50 you will get a 'page cannot found'. if you put in the url website1.com or website2.com you will be accessing the sites from the outside (not locally).
so the problem is how to access the sites locally not from the outside -- for example i need this ability so that i can access locally as the test sites are only available locally. not from the outside...
A: You can try telnetting to the server.
$ telnet localhost 80
(type these lines manually)
GET / HTTP/1.1
Host: www.example.com
(exchange www.example.com for the host name your server is mapped to)
A: I would assume the only way you can do this is assigning a custom port to the specific website you want to monitor and just access it as "localhost:CustomPort".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Redirecting users from edit page back to calling page I am working on a project management web application. The user has a variety of ways to display a list of tasks. When viewing a list page, they click on task and are redirected to the task edit page.
Since they are coming from a variety of ways, I am just curious as to the best way to redirect the user back to the calling page. I have some ideas, but would like to get other developers input.
Would you store the calling url in session? as a cookie? I like the concept of using an object handle the redirection.
A: I would store the referring URL using the ViewState. Storing this outside the scope of the page (i.e. in the Session state or cookie) may cause problems if more than one browser window is open.
The example below validates that the page was called internally (i.e. not requested directly) and bounces back to the referring page after the user submits their response.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.UrlReferrer == null)
{
//Handle the case where the page is requested directly
throw new Exception("This page has been called without a referring page");
}
if (!IsPostBack)
{
ReturnUrl = Request.UrlReferrer.PathAndQuery;
}
}
public string ReturnUrl
{
get { return ViewState["returnUrl"].ToString(); }
set { ViewState["returnUrl"] = value; }
}
protected void btn_Click(object sender, EventArgs e)
{
//Do what you need to do to save the page
//...
//Go back to calling page
Response.Redirect(ReturnUrl, true);
}
}
A: I personally would store the required redirection info in an object and handle globally. I would avoid using a QueryString param or the like since they could try bouncing themselves back to a page they are not supposed to (possible security issue?). You could then create a static method to handle the redirection object, which could read the information and act accordingly. This encapsulates your redirection process within one page.
Using an object also means you can later extend it if required (such as adding return messages and other info).
For example (this is a 2 minute rough guideline BTW!):
public partial class _Default : System.Web.UI.Page
{
void Redirect(string url, string messsage)
{
RedirectionParams paras = new RedirectionParams(url, messsage);
RedirectionHandler(paras); // pass to some global method (or this could BE the global method)
}
protected void Button1_Click(object sender, EventArgs e)
{
Redirect("mypage.aspx", "you have been redirected");
}
}
public class RedirectionParams
{
private string _url;
public string URL
{
get { return _url; }
set { _url = value; }
}
private string _message;
public string Message
{
get { return _message; }
set { _message = value; }
}
public RedirectionParams(string url, string message)
{
this.URL = url;
this.Message = message;
}
}
A: This message my be tagged asp.net but I think it is a platform independent issue that pains all new web developers as they seek a 'clean' way to do this.
I think the two options in achieving this are:
*
*A param in the url
*A url stored in the session
I don't like the url method, it is a bit messy, and you have to remember to include the param in every relevent URL.
I'd just use an object with static methods for this. The object would wrap around the session item you use to store redirect URLS.
The methods would probably be as follows (all public static):
*
*setRedirectUrl(string URL)
*doRedirect(string defaultURL)
setRedirectUrl would be called in any action that produces links / forms which need to redirect to a given url. So say you had a projects view action that generates a list of projects, each with tasks that can be performed on them (e.g. delete, edit) you would call RedirectClass.setRedirectUrl("/project/view-all") in the code for this action.
Then lets say the user clicks delete, they need to be redirected to the view page after a delete action, so in the delete action you would call RedirectClass.setRedirectUrl("/project/view-all"). This method would look to see if the redirect variable was set in the session. If so redirect to that URL. If not, redirect to the default url (the string passed to the setRedirectUrl method).
A: I agree with "rmbarnes.myopenid.com" regarding this issue as being platform independent.
I would store the calling page URL in the QueryString or in a hidden field (for example in ViewState for ASP.NET). If you will store it outside of the page scope (such as Session, global variable - Application State and so on) then it will not be just overkill as Tom said but it will bring you trouble.
What kind of trouble? Trouble if the user has more than one tab (window) of that browser open. The tabs (or windows) of the same browser will probably share the same session and the redirection will not be the one expected and all the user will feel is that it is a bug.
My 2 eurocents..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How do I find broken NMEA log sentences with grep? My GPS logger occassionally leaves "unfinished" lines at the end of the log files. I think they're only at the end, but I want to check all lines just in case.
A sample complete sentence looks like:
$GPRMC,005727.000,A,3751.9418,S,14502.2569,E,0.00,339.17,210808,,,A*76
The line should start with a $ sign, and end with an * and a two character hex checksum. I don't care if the checksum is correct, just that it's present. It also needs to ignore "ADVER" sentences which don't have the checksum and are at the start of every file.
The following Python code might work:
import re
from path import path
nmea = re.compile("^\$.+\*[0-9A-F]{2}$")
for log in path("gpslogs").files("*.log"):
for line in log.lines():
if not nmea.match(line) and not "ADVER" in line:
print "%s\n\t%s\n" % (log, line)
Is there a way to do that with grep or awk or something simple? I haven't really figured out how to get grep to do what I want.
Update: Thanks @Motti and @Paul, I was able to get the following to do almost what I wanted, but had to use single quotes and remove the trailing $ before it would work:
grep -nvE '^\$.*\*[0-9A-F]{2}' *.log | grep -v ADVER | grep -v ADPMB
Two further questions arise, how can I make it ignore blank lines? And can I combine the last two greps?
A: The minimum of testing shows that this should do it:
grep -Ev "^\$.*\*[0-9A-Fa-f]{2}$" a.txt | grep -v ADVER
*
*-E use extended regexp
*-v Show lines that do not match
*^ starts with
*.* anything
*\* an asterisk
*[0-9A-Fa-f] hexadecimal digit
*{2} exactly two of the previous
*$ end of line
*| grep -v ADVER weed out the ADVER lines
HTH, Motti.
A: @Motti's answer doesn't ignore ADVER lines, but you easily pipe the results of that grep to another:
grep -Ev "^\$.*\*[0-9A-Fa-f]{2}$" a.txt |grep -v ADVER
A:
@Tom (rephrased) I had to remove the trailing $ for it to work
Removing the $ means that the line may end with something else (e.g. the following will be accepted)
$GPRMC,005727.000,A,3751.9418,S,14502.2569,E,0.00,339.17,210808,,,A*76xxx
@Tom And can I combine the last two greps?
grep -Ev "ADVER|ADPMB"
A: @Motti: Combining the greps isn't working, it's having no effect.
I understand that without the trailing $ something else may folow the checksum & still match, but it didn't work at all with it so I had no choice...
GNU grep 2.5.3 and GNU bash 3.2.39(1) if that makes any difference.
And it looks like the log files are using DOS line-breaks (CR+LF). Does grep need a switch to handle that properly?
A: @Tom
GNU grep 2.5.3 and GNU bash 3.2.39(1) if that makes any difference.
And it looks like the log files are using DOS line-breaks (CR+LF). Does grep need a switch to handle that properly?
I'm using grep (GNU grep) 2.4.2 on Windows (for shame!) and it works for me (and DOS line-breaks are naturally accepted) , I don't really have access to other OSs at the moment so I'm sorry but I won't be able to help you any further :o(
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Asynchronously Loading a BitmapImage in C# using WPF What's the best way to asynchronously load an BitmapImage in C# using WPF?
A: I was just looking into this and had to throw in my two cents, though a few years after the original post (just in case any one else comes looking for this same thing I was looking into).
I have an Image control that needs to have it's image loaded in the background using a Stream, and then displayed.
The problem that I kept running into is that the BitmapSource, it's Stream source and the Image control all had to be on the same thread.
In this case, using a Binding and setting it's IsAsynch = true will throw a cross thread exception.
A BackgroundWorker is great for WinForms, and you can use this in WPF, but I prefer to avoid using the WinForm assemblies in WPF (bloating of a project is not recommended, and it's a good rule of thumb too). This should throw an invalid cross reference exception in this case too, but I didn't test it.
Turns out that one line of code will make any of these work:
//Create the image control
Image img = new Image {HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Stretch};
//Create a seperate thread to load the image
ThreadStart thread = delegate
{
//Load the image in a seperate thread
BitmapImage bmpImage = new BitmapImage();
MemoryStream ms = new MemoryStream();
//A custom class that reads the bytes of off the HD and shoves them into the MemoryStream. You could just replace the MemoryStream with something like this: FileStream fs = File.Open(@"C:\ImageFileName.jpg", FileMode.Open);
MediaCoder.MediaDecoder.DecodeMediaWithStream(ImageItem, true, ms);
bmpImage.BeginInit();
bmpImage.StreamSource = ms;
bmpImage.EndInit();
//**THIS LINE locks the BitmapImage so that it can be transported across threads!!
bmpImage.Freeze();
//Call the UI thread using the Dispatcher to update the Image control
Dispatcher.BeginInvoke(new ThreadStart(delegate
{
img.Source = bmpImage;
img.Unloaded += delegate
{
ms.Close();
ms.Dispose();
};
grdImageContainer.Children.Add(img);
}));
};
//Start previously mentioned thread...
new Thread(thread).Start();
A: Assuming you're using data binding, setting Binding.IsAsync property to True seems to be a standard way to achieve this.
If you're loading the bitmap in the code-behind file using background thread + Dispatcher object is a common way to update UI asynchronous
A: This will allow you to create the BitmapImage on the UI thread by using the HttpClient to do the async downloading:
private async Task<BitmapImage> LoadImage(string url)
{
HttpClient client = new HttpClient();
try
{
BitmapImage img = new BitmapImage();
img.CacheOption = BitmapCacheOption.OnLoad;
img.BeginInit();
img.StreamSource = await client.GetStreamAsync(url);
img.EndInit();
return img;
}
catch (HttpRequestException)
{
// the download failed, log error
return null;
}
}
A: To elaborate onto aku's answer, here is a small example as to where to set the IsAsync:
ItemsSource="{Binding IsAsync=True,Source={StaticResource ACollection},Path=AnObjectInCollection}"
That's what you would do in XAML.
A: BitmapCacheOption.OnLoad
var bmp = await System.Threading.Tasks.Task.Run(() =>
{
BitmapImage img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.UriSource = new Uri(path);
img.EndInit();
ImageBrush brush = new ImageBrush(img);
}
A: Use or extend System.ComponentModel.BackgroundWorker:
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
Personally, I find this to be the easiest way to perform asynchronous operations in client apps. (I've used this in WinForms, but not WPF. I'm assuming this will work in WPF as well.)
I usually extend Backgroundworker, but you dont' have to.
public class ResizeFolderBackgroundWorker : BackgroundWorker
{
public ResizeFolderBackgroundWorker(string sourceFolder, int resizeTo)
{
this.sourceFolder = sourceFolder;
this.destinationFolder = destinationFolder;
this.resizeTo = resizeTo;
this.WorkerReportsProgress = true;
this.DoWork += new DoWorkEventHandler(ResizeFolderBackgroundWorker_DoWork);
}
void ResizeFolderBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
DirectoryInfo dirInfo = new DirectoryInfo(sourceFolder);
FileInfo[] files = dirInfo.GetFiles("*.jpg");
foreach (FileInfo fileInfo in files)
{
/* iterate over each file and resizing it */
}
}
}
This is how you would use it in your form:
//handle a button click to start lengthy operation
private void resizeImageButtonClick(object sender, EventArgs e)
{
string sourceFolder = getSourceFolderSomehow();
resizer = new ResizeFolderBackgroundWorker(sourceFolder,290);
resizer.ProgressChanged += new progressChangedEventHandler(genericProgressChanged);
resizer.RunWorkerCompleted += new RunWorkerCompletedEventHandler(genericRunWorkerCompleted);
progressBar1.Value = 0;
progressBar1.Visible = true;
resizer.RunWorkerAsync();
}
void genericRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.Visible = false;
//signal to user that operation has completed
}
void genericProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
//I just update a progress bar
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: SQL Query, Count with 0 count I have three tables: page, attachment, page-attachment
I have data like this:
page
ID NAME
1 first page
2 second page
3 third page
4 fourth page
attachment
ID NAME
1 foo.word
2 test.xsl
3 mm.ppt
page-attachment
ID PAGE-ID ATTACHMENT-ID
1 2 1
2 2 2
3 3 3
I would like to get the number of attachments per page also when that number is 0. I have tried with:
select page.name, count(page-attachment.id) as attachmentsnumber
from page
inner join page-attachment on page.id=page-id
group by page.id
I am getting this output:
NAME ATTACHMENTSNUMBER
second page 2
third page 1
I would like to get this output:
NAME ATTACHMENTSNUMBER
first page 0
second page 2
third page 1
fourth page 0
How do I get the 0 part?
A: Change your "inner join" to a "left outer join", which means "get me all the rows on the left of the join, even if there isn't a matching row on the right."
select page.name, count(page-attachment.id) as attachmentsnumber
from page
left outer join page-attachment on page.id=page-id
group by page.name
A: Depending on the database, for speed, you could use the UNION command.
The SQL is longer, but, depending on the database, it speeds things up by seperating "count things that are there" and "count things that are not there".
(
select page.name, count(page-attachment.id) as attachmentsnumber
from page
inner join page-attachment on page.id=page-id
group by page.id
)
UNION
(
select page.name, 0 as attachmentsnumber
from page
where page.id not in (
select page-id from page-attachment)
)
The database I need this solution for has 20 pages in more than a million attachments. The UNION made it run in 13 seconds rather than so long I got bored and tried another way (somewhere above 60 seconds before I killed the outer join and subquery methods).
A: Here's another solution using sub-querying.
SELECT
p.name,
(
SELECT COUNT(*) FROM [page-attachment] pa
WHERE pa.[PAGE-ID] = p.id
) as attachmentsnumber
FROM page p
A: You want a left join, instead of an inner join, as that allows records to not exist.
A: LEFT join is your friend.
To learn more about different join types refer to http://en.wikipedia.org/wiki/Join_(SQL)
A: Use this:
SELECT p.name,(
SELECT COUNT(*) FROM [page-attachment] pa WHERE pa.[PAGE-ID] = p.id) as attachmentsnumber
FROM page p
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Firefox vs. IE: innerHTML handling After hours of debugging, it appears to me that in FireFox, the innerHTML of a DOM reflects what is actually in the markup, but in IE, the innerHTML reflects what's in the markup PLUS any changes made by the user or dynamically (i.e. via Javascript).
Has anyone else found this to be true? Any interesting work-arounds to ensure both behave the same way?
A: I agree with Pat. At this point in the game, writing your own code to deal with cross-browser compatibility given the available Javascript frameworks doesn't make a lot of sense. There's a framework for nearly any taste (some really quite tiny) and they've focused on really abstracting out all of the differences between the browsers. They're doing WAY more testing of it than you're likely to.
Something like jQuery or Yahoo's YUI (think how many people hit the Yahoo Javascript in a day and the variety of browsers) is just way more road-tested than any snippet you or I come up with.
A: using a good library is a great way to get around browser inconsistencies, and jquery is the one that I typically recommend - and if you're running into issues altering the elements in a form in particular, jquery boasts a few really useful plugins focused specifically on form manipulation and evaluation.
A: I use jQuery's .html() to get a consistent result across browsers.
A: Using prototype and the $("thisid") syntax instead of document.getElementById("thisid") might do the trick for you. It worked for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Setup django with WSGI and apache I have been sold on mod_wsgi and apache rather than mod_python.
I have all the parts installed (django, apache, mod_wsgi) but have run into a problem deploying.
I am on osx 10.5 with apache 2.2 and django 1.0b2, mod_wsgi-2.3
My application is called tred.
Here are the relevant files:
httpd-vhosts (included in httpd-conf)
NameVirtualHost tred:80
ServerName tred
Alias /admin_media /usr/lib/python2.5/site-packages/django/contrib/admin/media
Order allow,deny
Allow from all
Alias /media /Users/dmg/Sites/tred/media
Order allow,deny
Allow from all
Alias / /Users/dmg/Sites/tred/
Order allow,deny
Allow from all
WSGIScriptAlias / /Users/dmg/Sites/tred/mod_wsgi-handler.wsgi
WSGIDaemonProcess tred user=dmg group=staff processes=1 threads=10
WSGIProcessGroup tred
mod_wsgi-handle.wsgi
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
os.environ['DJANGO_SETTINGS_MODULE'] = 'tred.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
When I go to http://tred I get a directory listing rather than the rendered website. I think I have followed the tutorials correctly but it is obviously not right. What can I do to make this work?
A: What happens if you remove the Alias / directive?
A: Note that Alias and WSGIScriptAlias directives do not have the same precedence. Thus, they will not be processed in file order as written. Instead, all Alias directives get precedence over WSGIScriptAlias directives. Thus, it wouldn't have mattered if the Alias for '/' appeared after WSGIScriptAlias, it would still have taken precedence.
A:
It works. I have no idea why, but it does.
For future reference:
It works because Apache processes alias directives in order, and uses the first match. It was always hitting Alias /, which will match anything, before WSGIScriptAlias.
From the mod_alias documentation:
First, all Redirects are processed before Aliases are processed, and therefore a request that matches a Redirect or RedirectMatch will never have Aliases applied. Second, the Aliases and Redirects are processed in the order they appear in the configuration files, with the first match taking precedence.
A: try following this tutorial - http://singlas.in/5-step-tutorial-for-using-django-with-apache-and-mod_wsgi/
you are trying to host apache /var/www/ folder and the Django app both at root (/). Since Alias directive takes precedence over WSGIScriptAlias, it is rendering apache directory.
you can try to host the django app at /app. Alternatively host the /var/www/ folder at a different location like /public
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: How do I add data to an existing model in Django? Currently, I am writing up a bit of a product-based CMS as my first project.
Here is my question. How can I add additional data (products) to my Product model?
I have added '/admin/products/add' to my urls.py, but I don't really know where to go from there. How would i build both my view and my template? Please keep in mind that I don't really know all that much Python, and i am very new to Django
How can I do this all without using this existing django admin interface.
A: You will want to wire your URL to the Django create_object generic view, and pass it either "model" (the model you want to create) or "form_class" (a customized ModelForm class). There are a number of other arguments you can also pass to override default behaviors.
Sample URLconf for the simplest case:
from django.conf.urls.defaults import *
from django.views.generic.create_update import create_object
from my_products_app.models import Product
urlpatterns = patterns('',
url(r'^admin/products/add/$', create_object, {'model': Product}))
Your template will get the context variable "form", which you just need to wrap in a <form> tag and add a submit button. The simplest working template (by default should go in "my_products_app/product_form.html"):
<form action="." method="POST">
{{ form }}
<input type="submit" name="submit" value="add">
</form>
Note that your Product model must have a get_absolute_url method, or else you must pass in the post_save_redirect parameter to the view. Otherwise it won't know where to redirect to after save.
A: Follow the Django tutorial for setting up the "admin" part of an application. This will allow you to modify your database.
Django Admin Setup
Alternatively, you can just connect directly to the database using the standard tools for whatever database type you are using.
A: This topic is covered in Django tutorials.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Table Stats gathering for Oracle When and how should table stats gathering be performed for Oracle, version 9 and up? How would you go about gathering stats for a large database, where stats gathering would collide with "business hours".
A: I don't agree that you should always rebuild your statistics after there have been lots of deletes or inserts. As ever, it depends. In a data warehouse situation, when re-building your materialized views you will be doing lots of deletes and inserts but the base structure of the data will not change.
You only need to re-calculate statistics on a table if there has been a significant change in its content. This does not necessarily mean after lots of deletes or inserts, but rather when deletes, inserts, or updates materially change the content with respect to possible execution plans.
If you are truncating tables and rebuilding (which will reset your statistics), instead of an expensive statistics calculation, you're often better off storing the statistics before truncating and restoring them once you've rebuilt the table.
For saving the current views of statistics you use:
dbms_stats.export_table_stats
and to restore them afterwards you use:
dbms_stats.import_table_stats
(There are corresponding procedures for schema and database.)
A: Gathering stats should be done whenever there has been large changes to the data content, for example a large number of deletes or inserts. If the table structure has changed you should gather stats also. It is advisable to use the 'ESTIMATE' option.
Do this as an automated process out of business hours if possible, or if you have to do it during business hours then choose a time when there is minimum access to the tables you wish to gather stats for.
A: Make sure when using the estimate (sample_percent) that you gather at least 10 percent. Below that can yield very questionable results.
A: Consider backing up current stats when gathering -- that way you can compare them (if you're interested) and possibly restore them if your new stats cause problems. Keep in mind that stats are used to determine execution plans -- you may only want to gather them if you want execution plans to change.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Integrating Perl and Oracle Advanced Queuing Is there any way to listen to an Oracle AQ using a Perl process as the listener.
A: This Introduction to Oracle Advanced Queuing states that you can interface to it through "Internet access using HTTP, HTTPS, and SMTP" so it should be straightforward to do that using a Perl script.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do you parse an IP address string to a uint value in C#? I'm writing C# code that uses the windows IP Helper API. One of the functions I'm trying to call is "GetBestInterface" that takes a 'uint' representation of an IP. What I need is to parse a textual representation of the IP to create the 'uint' representation.
I've found some examples via Google, like this one or this one, but I'm pretty sure there should be a standard way to achieve this with .NET. Only problem is, I can't find this standard way. IPAddress.Parse seems to be in the right direction, but it doesn't supply any way of getting a 'uint' representation...
There is also a way of doing this using IP Helper, using the ParseNetworkString, but again, I'd rather use .NET - I believe the less I rely on pInvoke the better.
So, anyone knows of a standard way to do this in .NET?
A: Also you should remember that IPv4 and IPv6 are different lengths.
A: Correct solution that observes Endianness:
var ipBytes = ip.GetAddressBytes();
ulong ip = 0;
if (BitConverter.IsLittleEndian)
{
ip = (uint) ipBytes[0] << 24;
ip += (uint) ipBytes[1] << 16;
ip += (uint) ipBytes[2] << 8;
ip += (uint) ipBytes[3];
}
else
{
ip = (uint)ipBytes [3] << 24;
ip += (uint)ipBytes [2] << 16;
ip += (uint)ipBytes [1] <<8;
ip += (uint)ipBytes [0];
}
A: Shouldn't it be:
var ipAddress = IPAddress.Parse("some.ip.address");
var ipBytes = ipAddress.GetAddressBytes();
var ip = (uint)ipBytes [0] << 24;
ip += (uint)ipBytes [1] << 16;
ip += (uint)ipBytes [2] <<8;
ip += (uint)ipBytes [3];
?
A: MSDN says that IPAddress.Address property (which returns numeric representation of IP address) is obsolete and you should use GetAddressBytes method.
You can convert IP address to numeric value using following code:
var ipAddress = IPAddress.Parse("some.ip.address");
var ipBytes = ipAddress.GetAddressBytes();
var ip = (uint)ipBytes [3] << 24;
ip += (uint)ipBytes [2] << 16;
ip += (uint)ipBytes [1] <<8;
ip += (uint)ipBytes [0];
EDIT:
As other commenters noticed above-mentioned code is for IPv4 addresses only.
IPv6 address is 128 bits long so it's impossible to convert it to 'uint' as question's author wanted.
A: var ipuint32 = BitConverter.ToUInt32(IPAddress.Parse("some.ip.address.ipv4").GetAddressBytes(), 0);`
This solution is easier to read than manual bit shifting.
See How to convert an IPv4 address into a integer in C#?
A: Byte arithmetic is discouraged, as it relies on all IPs being 4-octet ones.
A: System.Net.IPAddress ipAddress = System.Net.IPAddress.Parse("192.168.1.1");
byte[] bytes = ipAddress.GetAddressBytes();
for (int i = 0; i < bytes.Length ; i++)
Console.WriteLine(bytes[i]);
Output will be
192
168
1
1
A: Complete solution:
public static uint IpStringToUint(string ipString)
{
var ipAddress = IPAddress.Parse(ipString);
var ipBytes = ipAddress.GetAddressBytes();
var ip = (uint)ipBytes [0] << 24;
ip += (uint)ipBytes [1] << 16;
ip += (uint)ipBytes [2] <<8;
ip += (uint)ipBytes [3];
return ip;
}
public static string IpUintToString(uint ipUint)
{
var ipBytes = BitConverter.GetBytes(ipUint);
var ipBytesRevert = new byte[4];
ipBytesRevert[0] = ipBytes[3];
ipBytesRevert[1] = ipBytes[2];
ipBytesRevert[2] = ipBytes[1];
ipBytesRevert[3] = ipBytes[0];
return new IPAddress(ipBytesRevert).ToString();
}
Reverse order of bytes:
public static uint IpStringToUint(string ipString)
{
return BitConverter.ToUInt32(IPAddress.Parse(ipString).GetAddressBytes(), 0);
}
public static string IpUintToString(uint ipUint)
{
return new IPAddress(BitConverter.GetBytes(ipUint)).ToString();
}
You can test here:
https://www.browserling.com/tools/dec-to-ip
http://www.smartconversion.com/unit_conversion/IP_Address_Converter.aspx
http://www.silisoftware.com/tools/ipconverter.php
A: I have never found a clean solution (i.e.: a class / method in the .NET Framework) for this problem. I guess it just isn't available except the solutions / examples you provided or Aku's example. :(
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Virtual functions in constructors, why do languages differ? In C++ when a virtual function is called from within a constructor it doesn't behave like a virtual function.
I think everyone who encountered this behavior for the first time was surprised but on second thought it made sense:
As long as the derived constructor has not been executed the object is not yet a derived instance.
So how can a derived function be called? The preconditions haven't had the chance to be set up. Example:
class base {
public:
base()
{
std::cout << "foo is " << foo() << std::endl;
}
virtual int foo() { return 42; }
};
class derived : public base {
int* ptr_;
public:
derived(int i) : ptr_(new int(i*i)) { }
// The following cannot be called before derived::derived due to how C++ behaves,
// if it was possible... Kaboom!
virtual int foo() { return *ptr_; }
};
It's exactly the same for Java and .NET yet they chose to go the other way, and is possibly the only reason for the principle of least surprise?
Which do you think is the correct choice?
A: Both ways can lead to unexpected results. Your best bet is to not call a virtual function in your constructor at all.
The C++ way I think makes more sense, but leads to expectation problems when someone reviews your code. If you are aware of this situation, you should purposely not put your code in this situation for later debugging's sake.
A:
Virtual functions in constructors, why do languages differ?
Because there's no one good behaviour. I find the C++ behaviour makes more sense (since base class c-tors are called first, it stands to reason that they should call base class virtual functions--after all, the derived class c-tor hasn't run yet, so it may not have set up the right preconditions for the derived class virtual function).
But sometimes, where I want to use the virtual functions to initialize state (so it doesn't matter that they're being called with the state uninitialized) the C#/Java behaviour is nicer.
A: There's a fundamental difference in how the languages define an object's life time. In Java and .Net the object members are zero/null initialized before any constructor is run and is at this point that the object life time begins. So when you enter the constructor you've already got an initialized object.
In C++ the object life time only begins when the constructor finishes (although member variables and base classes are fully constructed before it starts). This explains the behaviour when virtual functions are called and also why the destructor isn't run if there's an exception in the constructor's body.
The problem with the Java/.Net definition of object lifetime is that it's harder to make sure the object always meets its invariant without having to put in special cases for when the object is initialized but the constructor hasn't run. The problem with the C++ definition is that you have this odd period where the object is in limbo and not fully constructed.
A: I think C++ offers the best semantics in terms of having the 'most correct' behavior ... however it is more work for the compiler and the code is definitiely non-intuitive to someone reading it later.
With the .NET approach the function must be very limited not to rely on any derived object state.
A: Delphi makes good use of virtual constructors in the VCL GUI framework:
type
TComponent = class
public
constructor Create(AOwner: TComponent); virtual; // virtual constructor
end;
TMyEdit = class(TComponent)
public
constructor Create(AOwner: TComponent); override; // override virtual constructor
end;
TMyButton = class(TComponent)
public
constructor Create(AOwner: TComponent); override; // override virtual constructor
end;
TComponentClass = class of TComponent;
function CreateAComponent(ComponentClass: TComponentClass; AOwner: TComponent): TComponent;
begin
Result := ComponentClass.Create(AOwner);
end;
var
MyEdit: TMyEdit;
MyButton: TMyButton;
begin
MyEdit := CreateAComponent(TMyEdit, Form) as TMyEdit;
MyButton := CreateAComponent(TMyButton, Form) as TMyButton;
end;
A: I have found the C++ behavior very annoying. You cannot write virtual functions to, for instance, return the desired size of the object, and have the default constructor initialize each item. For instance it would be nice to do:
BaseClass() {
for (int i=0; i<virtualSize(); i++)
initialize_stuff_for_index(i);
}
Then again the advantage of C++ behavior is that it discourages constuctors like the above from being written.
I don't think the problem of calling methods that assume the constructor has been finished is a good excuse for C++. If this really was a problem then the constructor would not be allowed to call any methods, since the same problem can apply to methods for the base class.
Another point against C++ is that the behavior is much less efficient. Although the constructor knows directly what it calls, the vtab pointer has to be changed for every single class from base to final, because the constructor might call other methods that will call virtual functions. From my experience this wastes far more time than is saved by making virtual functions calls in the constructor more efficient.
Far more annoying is that this is also true of destructors. If you write a virtual cleanup() function, and the base class destructor does cleanup(), it certainly does not do what you expect.
This and the fact that C++ calls destructors on static objects on exit have really pissed me off for a long time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Strange boo language syntax I've run into a strange syntax in Boo Language Guide :
setter = { value | a = value }
What does the | operator mean?
A: The documentation of Boo seems to be lacking in this area -- it seems that
setter = { value | a = value }
is shorthand for
setter = def(value):
a = value
A: Well, having never used Boo, my (educated) guess is that it's for passing parameter to the closure lambda-style functions. In this case, { p | C } refers to an anonymous function taking a single parameter bound to p within the code C.
A: Adam is correct. The point of the example is to show that lambdas in boo have read and write access to enclosing scope.
A: That syntax for specifying code blocks (anonymous functions) has been borrowed from Ruby and Smalltalk
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do you organise multiple git repositories, so that all of them are backed up together? With SVN, I had a single big repository I kept on a server, and checked-out on a few machines. This was a pretty good backup system, and allowed me easily work on any of the machines. I could checkout a specific project, commit and it updated the 'master' project, or I could checkout the entire thing.
Now, I have a bunch of git repositories, for various projects, several of which are on github. I also have the SVN repository I mentioned, imported via the git-svn command..
Basically, I like having all my code (not just projects, but random snippets and scripts, some things like my CV, articles I've written, websites I've made and so on) in one big repository I can easily clone onto remote machines, or memory-sticks/harddrives as backup.
The problem is, since it's a private repository, and git doesn't allow checking out of a specific folder (that I could push to github as a separate project, but have the changes appear in both the master-repo, and the sub-repos)
I could use the git submodule system, but it doesn't act how I want it too (submodules are pointers to other repositories, and don't really contain the actual code, so it's useless for backup)
Currently I have a folder of git-repos (for example, ~/code_projects/proj1/.git/ ~/code_projects/proj2/.git/), and after doing changes to proj1 I do git push github, then I copy the files into ~/Documents/code/python/projects/proj1/ and do a single commit (instead of the numerous ones in the individual repos). Then do git push backupdrive1, git push mymemorystick etc
So, the question: How do your personal code and projects with git repositories, and keep them synced and backed-up?
A: I would strongly advise against putting unrelated data in a given
Git repository. The overhead of creating new repositories is quite
low, and that is a feature that makes it possible to keep
different lineages completely separate.
Fighting that idea means ending up with unnecessarily tangled history,
which renders administration more difficult and--more
importantly--"archeology" tools less useful because of the resulting
dilution. Also, as you mentioned, Git assumes that the "unit of
cloning" is the repository, and practically has to do so because of
its distributed nature.
One solution is to keep every project/package/etc. as its own bare
repository (i.e., without working tree) under a blessed hierarchy,
like:
/repos/a.git
/repos/b.git
/repos/c.git
Once a few conventions have been established, it becomes trivial to
apply administrative operations (backup, packing, web publishing) to
the complete hierarchy, which serves a role not entirely dissimilar to
"monolithic" SVN repositories. Working with these repositories also
becomes somewhat similar to SVN workflows, with the addition that one
can use local commits and branches:
svn checkout --> git clone
svn update --> git pull
svn commit --> git push
You can have multiple remotes in each working clone, for the ease of
synchronizing between the multiple parties:
$ cd ~/dev
$ git clone /repos/foo.git # or the one from github, ...
$ cd foo
$ git remote add github ...
$ git remote add memorystick ...
You can then fetch/pull from each of the "sources", work and commit
locally, and then push ("backup") to each of these remotes when you
are ready with something like (note how that pushes the same commits
and history to each of the remotes!):
$ for remote in origin github memorystick; do git push $remote; done
The easiest way to turn an existing working repository ~/dev/foo
into such a bare repository is probably:
$ cd ~/dev
$ git clone --bare foo /repos/foo.git
$ mv foo foo.old
$ git clone /repos/foo.git
which is mostly equivalent to a svn import--but does not throw the
existing, "local" history away.
Note: submodules are a mechanism to include shared related
lineages, so I indeed wouldn't consider them an appropriate tool for
the problem you are trying to solve.
A: ,I haven't tried nesting git repositories yet because I haven't run into a situation where I need to. As I've read on the #git channel git seems to get confused by nesting the repositories, i.e. you're trying to git-init inside a git repository. The only way to manage a nested git structure is to either use git-submodule or Android's repo utility.
As for that backup responsibility you're describing I say delegate it... For me I usually put the "origin" repository for each project at a network drive at work that is backed up regularly by the IT-techs by their backup strategy of choice. It is simple and I don't have to worry about it. ;)
A: I also am curious about suggested ways to handle this and will describe the current setup that I use (with SVN). I have basically created a repository that contains a mini-filesystem hierarchy including its own bin and lib dirs. There is script in the root of this tree that will setup your environment to add these bin, lib, etc... other dirs to the proper environment variables. So the root directory essentially looks like:
./bin/ # prepended to $PATH
./lib/ # prepended to $LD_LIBRARY_PATH
./lib/python/ # prepended to $PYTHONPATH
./setup_env.bash # sets up the environment
Now inside /bin and /lib there are the multiple projects and and their corresponding libraries. I know this isn't a standard project, but it is very easy for someone else in my group to checkout the repo, run the 'setup_env.bash' script and have the most up to date versions of all of the projects locally in their checkout. They don't have to worry about installing/updating /usr/bin or /usr/lib and it keeps it simple to have multiple checkouts and a very localized environment per checkout. Someone can also just rm the entire repository and not worry about uninstalling any programs.
This is working fine for us, and I'm not sure if we'll change it. The problem with this is that there are many projects in this one big repository. Is there a git/Hg/bzr standard way of creating an environment like this and breaking out the projects into their own repositories?
A: I want to add to Damien's answer where he recommends:
$ for remote in origin github memorystick; do git push $remote; done
You can set up a special remote to push to all the individual real remotes with 1 command; I found it at http://marc.info/?l=git&m=116231242118202&w=2:
So for "git push" (where it makes
sense to push the same branches
multiple times), you can actually do
what I do:
*
*.git/config contains:
[remote "all"]
url = master.kernel.org:/pub/scm/linux/kernel/git/torvalds/linux-2.6
url = login.osdl.org:linux-2.6.git
*and now git push all master will push the "master" branch to both
of those remote repositories.
You can also save yourself typing the URLs twice by using the contruction:
[url "<actual url base>"]
insteadOf = <other url base>
A: What about using mr for managing your multiple Git repos at once:
The mr(1) command can checkout, update, or perform other actions on a
set of repositories as if they were one combined respository. It
supports any combination of subversion, git, cvs, mercurial, bzr,
darcs, cvs, vcsh, fossil and veracity repositories, and support for
other revision control systems can easily be added. [...]
It is extremely configurable via simple shell scripting. Some examples
of things it can do include:
[...]
*
*When updating a git repository, pull from two different upstreams and merge the two together.
*Run several repository updates in parallel, greatly speeding up the update process.
*Remember actions that failed due to a laptop being offline, so they can be retried when it comes back online.
A: There is another method for having nested git repos, but it doesn't solve the problem you're after. Still, for others who are looking for the solution I was:
In the top level git repo just hide the folder in .gitignore containing the nested git repo. This makes it easy to have two separate (but nested!) git repos.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "99"
} |
Q: Conditional Redirect on Login I am using forms authentication. My users are redirected to a page (written in web.config) when they login, but some of them may not have the privilages to access this default page. In this case, I want them to redirect to another page but RedirectFromLoginPage method always redirects to the default page in web.config. How do I make the users login, and then redirect to a page which depends on some criteria?
A: The SetAuthCookie allows you to issue the auth cookie but retain control over the navigation. After that method is called you can run your logic to do a typical ASP.NET redirect to wherever you want.
A: if(mc.GetfaalUsers(mm.UserName.ToString())=="True")
{
this.Page.ClientScript.
RegisterClientScriptBlock(this.GetType(), "key",
"alert('این نام کاربری فعال نشده است');", false);
FormsAuthentication.SignOut();
Response.Redirect("default.aspx");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do you set up use HttpOnly cookies in PHP How can I set the cookies in my PHP apps as HttpOnly cookies?
A: <?php
//None HttpOnly cookie:
setcookie("abc", "test", NULL, NULL, NULL, NULL, FALSE);
//HttpOnly cookie:
setcookie("abc", "test", NULL, NULL, NULL, NULL, TRUE);
?>
Source
A: You can specify it in the set cookie function see the php manual
setcookie('Foo','Bar',0,'/', 'www.sample.com' , FALSE, TRUE);
A: Explanation here from Ilia... 5.2 only though
httpOnly cookie flag support in PHP 5.2
As stated in that article, you can set the header yourself in previous versions of PHP
header("Set-Cookie: hidden=value; httpOnly");
A: You can use this in a header file.
// setup session enviroment
ini_set('session.cookie_httponly',1);
ini_set('session.use_only_cookies',1);
This way all future session cookies will use httponly.
*
*Updated.
A: The right syntax of the php_flag command is
php_flag session.cookie_httponly On
And be aware, just first answer from server set the cookie and here (for example You can see the "HttpOnly" directive. So for testing delete cookies from browser after every testing request.
A: Note that PHP session cookies don't use httponly by default.
To do that:
$sess_name = session_name();
if (session_start()) {
setcookie($sess_name, session_id(), null, '/', null, null, true);
}
A couple of items of note here:
*
*You have to call session_name()
before session_start()
*This also
sets the default path to '/', which
is necessary for Opera but which PHP
session cookies don't do by default
either.
A: For PHP's own session cookies on Apache:
add this to your Apache configuration or .htaccess
<IfModule php5_module>
php_flag session.cookie_httponly on
</IfModule>
This can also be set within a script, as long as it is called before session_start().
ini_set( 'session.cookie_httponly', 1 );
A: Be aware that HttpOnly doesn't stop cross-site scripting; instead, it neutralizes one possible attack, and currently does that only on IE (FireFox exposes HttpOnly cookies in XmlHttpRequest, and Safari doesn't honor it at all). By all means, turn HttpOnly on, but don't drop even an hour of output filtering and fuzz testing in trade for it.
A: *
*For your cookies, see this answer.
*For PHP's own session cookie (PHPSESSID, by default), see @richie's answer
The setcookie() and setrawcookie() functions, introduced the boolean httponly parameter, back in the dark ages of PHP 5.2.0, making this nice and easy. Simply set the 7th parameter to true, as per the syntax
Function syntax simplified for brevity
setcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )
setrawcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )
In PHP < 8, specify NULL for parameters you wish to remain as default.
In PHP >= 8 you can benefit from using named parameters. See this question about named params.
setcookie( $name, $value, httponly:true )
It is also possible using the older, lower-level header() function:
header( "Set-Cookie: name=value; HttpOnly" );
You may also want to consider if you should be setting the Secure parameter.
A: A more elegant solution since PHP >=7.0
session_start(['cookie_lifetime' => 43200,'cookie_secure' => true,'cookie_httponly' => true]);
session_start
session_start options
A: Solução session_start(['cookie_lifetime' => 43200,'cookie_secure' => true,'cookie_httponly' => true]);
Dessa forma funcionou para mim na última versão do chromedriver.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "104"
} |
Q: Updating Android Tab Icons I have an activity that has a TabHost containing a set of TabSpecs each with a listview containing the items to be displayed by the tab. When each TabSpec is created, I set an icon to be displayed in the tab header.
The TabSpecs are created in this way within a setupTabs() method which loops to create the appropriate number of tabs:
TabSpec ts = mTabs.newTabSpec("tab");
ts.setIndicator("TabTitle", iconResource);
ts.setContent(new TabHost.TabContentFactory(
{
public View createTabContent(String tag)
{
...
}
});
mTabs.addTab(ts);
There are a couple of instances where I want to be able to change the icon which is displayed in each tab during the execution of my program. Currently, I am deleting all the tabs, and calling the above code again to re-create them.
mTabs.getTabWidget().removeAllViews();
mTabs.clearAllTabs(true);
setupTabs();
Is there a way to replace the icon that is being displayed without deleting and re-creating all of the tabs?
A: See my post with code example regarding Customized Android Tabs.
Thanks
Spct
A: This is what I did and it works for me. I created this function in the activity that extends from TabBarActivity
public void updateTab(int stringID) {
ViewGroup identifyView = (ViewGroup)getTabWidget().getChildAt(0);
TextView v = (TextView)identifyView.getChildAt(identifyView.getChildCount() - 1);
v.setText(stringID);
}
You can modify this function to change the image instead of text or you can change both, also you can modify this to get any tab child. I was particularly interested in modifying the text of the first tab at runtime.
I called this function from the relevant activity using this call
getParent().updateTab(R.string.tab_bar_analyze);
A: Try This:
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
public void onTabChanged(String tabId) {
if (TAB_MAP.equals(tabId)) {
ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon);
iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_black));
iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon);
iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_white));
} else if (TAB_LIST.equals(tabId)) {
ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon);
iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_white));
iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon);
iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_black));
}
}
});
A: The short answer is, you're not missing anything. The Android SDK doesn't provide a direct method to change the indicator of a TabHost after it's been created. The TabSpec is only used to build the tab, so changing the TabSpec after the fact will have no effect.
I think there's a workaround, though. Call mTabs.getTabWidget() to get a TabWidget object. This is just a subclass of ViewGroup, so you can call getChildCount() and getChildAt() to access individual tabs within the TabWidget. Each of these tabs is also a View, and in the case of a tab with a graphical indicator and a text label, it's almost certainly some other ViewGroup (maybe a LinearLayout, but it doesn't matter) that contains an ImageView and a TextView. So with a little fiddling with the debugger or Log.i, you should be able to figure out a recipe to get the ImageView and change it directly.
The downside is that if you're not careful, the exact layout of the controls within a tab could change and your app could break. Your initial solution is perhaps more robust, but then again it might lead to other unwanted side effects like flicker or focus problems.
A: Just to confirm dominics answer, here's his solution in code (that actually works):
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
public void onTabChanged(String tabId) {
if (TAB_MAP.equals(tabId)) {
ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon);
iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_black));
iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon);
iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_white));
} else if (TAB_LIST.equals(tabId)) {
ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon);
iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_white));
iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon);
iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_black));
}
}
});
Of course it's not polished at all and using those direct indices in getChildAt() is not nice at all...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
} |
Q: Memcache control panel? We've been running eAccelerator on each of 3 webservers and are looking to move to a memcache pool across all 3, hopefully reducing by about 2/3 our db lookups.
One of the handy things about eAccelerator is the web-based control interface (control.php), which has proved very useful when we've had to flush the cache unexpectedly, quickly monitor which scripts are in cache, etc.
We've been looking but haven't found anything that offers the same type of functionality for memcache - does anyone know if such a thing exists?
Obviously flushing cache etc is easy enough with memcache on the console, but our particular set-up means we may have guys monitoring our front-end and needing to flush the cache who will not necessarily have shell access on the servers.
A: I know this is a late addition to an old question but none of the answers were a simple plain solution, so i created one and put it up on github for you to enjoy:
Screenshoots
A: memcache.php may be what you're looking for.
memcache.php that you can get stats and dump from multiple memcache servers.
Can delete keys and flush servers.
A: PHPMemcacheAdmin - http://code.google.com/p/phpmemcacheadmin/
A:
If all you need to do is to be able to flush the cache from a web-application, you could create a simple php-page and then use the system() call...
Cache flushing is part of what we're looking for, but also a way to monitor what scripts are currently in there, how much data is in there, etc - basically the same stuff available on the EA control panel page.
We've played around with munin plugins for showing data usage, and were thinking we'd have to go down the line suggested above (system calls, etc), but were hoping that someone, somewhere would have rolled something similar already!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Changing a CORBA interface without recompiling I'd like to add a method to my existing server's CORBA interface. Will that require recompiling all clients?
I'm using TAO.
A: Recompilation of clients is not required (and should not be, regardless of the ORB that you use). As Adam indicated, lookups are done by operation name (a straight text comparison).
I've done what you're describing with our ACE/TAO-based system, and encountered no issues (servers were in ACE/TAO C++, clients were ACE/TAO C++, C# using Borland's Janeva, and OmniORBPy).
A: Assuming that the clients and servers are communicating via IIOP, no recompilation is required. An IIOP message contains the name of the interface, the name of the method, and the parameters. If none of those things have changed, then everything should remain compatible. Adding another method to the interface won't change any of those existing things.
On the other hand, if your objects are using a different protocol, or if the clients are in-process with the server and thus bypassing IIOP, you may need to make sure everything gets recompiled.
A: Operations (methods) are looked-up by name, so you only need to recompile the clients that use the new operation.
A: Clients using colocation (i.e. running within the same process with colocation enabled in ORB) must be recompiled. Remote clients may remain the same - as said previously, methods are matched by symbolic name.
A: It depends on usage of new idl method.
If Corba invocation is static(SII), meaning your client is linked with stub, you have to recompile a stub if you want to use your new added method interface.
If corba invocation is dynamic(DII), there is no stub required for client. None of recompilation is required. In this case, your client code should be like:
remoteObjRef->invoke("methodname", args); // send("methodname", args)
I did CORBA DII invocation four years ago and it works with TAO client&TAO/Jacorb/IONA corba service.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: What does ** (double star/asterisk) and * (star/asterisk) do for parameters? What do *args and **kwargs mean in these function definitions?
def foo(x, y, *args):
pass
def bar(x, y, **kwargs):
pass
See What do ** (double star/asterisk) and * (star/asterisk) mean in a function call? for the complementary question about arguments.
A: Building on nickd's answer...
def foo(param1, *param2):
print(param1)
print(param2)
def bar(param1, **param2):
print(param1)
print(param2)
def three_params(param1, *param2, **param3):
print(param1)
print(param2)
print(param3)
foo(1, 2, 3, 4, 5)
print("\n")
bar(1, a=2, b=3)
print("\n")
three_params(1, 2, 3, 4, s=5)
Output:
1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}
1
(2, 3, 4)
{'s': 5}
Basically, any number of positional arguments can use *args and any named arguments (or kwargs aka keyword arguments) can use **kwargs.
A: In addition to function calls, *args and **kwargs are useful in class hierarchies and also avoid having to write __init__ method in Python. Similar usage can seen in frameworks like Django code.
For example,
def __init__(self, *args, **kwargs):
for attribute_name, value in zip(self._expected_attributes, args):
setattr(self, attribute_name, value)
if kwargs.has_key(attribute_name):
kwargs.pop(attribute_name)
for attribute_name in kwargs.viewkeys():
setattr(self, attribute_name, kwargs[attribute_name])
A subclass can then be
class RetailItem(Item):
_expected_attributes = Item._expected_attributes + ['name', 'price', 'category', 'country_of_origin']
class FoodItem(RetailItem):
_expected_attributes = RetailItem._expected_attributes + ['expiry_date']
The subclass then be instantiated as
food_item = FoodItem(name = 'Jam',
price = 12.0,
category = 'Foods',
country_of_origin = 'US',
expiry_date = datetime.datetime.now())
Also, a subclass with a new attribute which makes sense only to that subclass instance can call the Base class __init__ to offload the attributes setting.
This is done through *args and **kwargs. kwargs mainly used so that code is readable using named arguments. For example,
class ElectronicAccessories(RetailItem):
_expected_attributes = RetailItem._expected_attributes + ['specifications']
# Depend on args and kwargs to populate the data as needed.
def __init__(self, specifications = None, *args, **kwargs):
self.specifications = specifications # Rest of attributes will make sense to parent class.
super(ElectronicAccessories, self).__init__(*args, **kwargs)
which can be instatiated as
usb_key = ElectronicAccessories(name = 'Sandisk',
price = '$6.00',
category = 'Electronics',
country_of_origin = 'CN',
specifications = '4GB USB 2.0/USB 3.0')
The complete code is here
A: It's also worth noting that you can use * and ** when calling functions as well. This is a shortcut that allows you to pass multiple arguments to a function directly using either a list/tuple or a dictionary. For example, if you have the following function:
def foo(x,y,z):
print("x=" + str(x))
print("y=" + str(y))
print("z=" + str(z))
You can do things like:
>>> mylist = [1,2,3]
>>> foo(*mylist)
x=1
y=2
z=3
>>> mydict = {'x':1,'y':2,'z':3}
>>> foo(**mydict)
x=1
y=2
z=3
>>> mytuple = (1, 2, 3)
>>> foo(*mytuple)
x=1
y=2
z=3
Note: The keys in mydict have to be named exactly like the parameters of function foo. Otherwise it will throw a TypeError:
>>> mydict = {'x':1,'y':2,'z':3,'badnews':9}
>>> foo(**mydict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() got an unexpected keyword argument 'badnews'
A: Let us first understand what are positional arguments and keyword arguments.
Below is an example of function definition with Positional arguments.
def test(a,b,c):
print(a)
print(b)
print(c)
test(1,2,3)
#output:
1
2
3
So this is a function definition with positional arguments.
You can call it with keyword/named arguments as well:
def test(a,b,c):
print(a)
print(b)
print(c)
test(a=1,b=2,c=3)
#output:
1
2
3
Now let us study an example of function definition with keyword arguments:
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(a=1,b=2,c=3)
#output :
1
2
3
-------------------------
You can call this function with positional arguments as well:
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(1,2,3)
# output :
1
2
3
---------------------------------
So we now know function definitions with positional as well as keyword arguments.
Now let us study the '*' operator and '**' operator.
Please note these operators can be used in 2 areas:
a) function call
b) function definition
The use of '*' operator and '**' operator in function call.
Let us get straight to an example and then discuss it.
def sum(a,b): #receive args from function calls as sum(1,2) or sum(a=1,b=2)
print(a+b)
my_tuple = (1,2)
my_list = [1,2]
my_dict = {'a':1,'b':2}
# Let us unpack data structure of list or tuple or dict into arguments with help of '*' operator
sum(*my_tuple) # becomes same as sum(1,2) after unpacking my_tuple with '*'
sum(*my_list) # becomes same as sum(1,2) after unpacking my_list with '*'
sum(**my_dict) # becomes same as sum(a=1,b=2) after unpacking by '**'
# output is 3 in all three calls to sum function.
So remember
when the '*' or '**' operator is used in a function call -
'*' operator unpacks data structure such as a list or tuple into arguments needed by function definition.
'**' operator unpacks a dictionary into arguments needed by function definition.
Now let us study the '*' operator use in function definition.
Example:
def sum(*args): #pack the received positional args into data structure of tuple. after applying '*' - def sum((1,2,3,4))
sum = 0
for a in args:
sum+=a
print(sum)
sum(1,2,3,4) #positional args sent to function sum
#output:
10
In function definition the '*' operator packs the received arguments into a tuple.
Now let us see an example of '**' used in function definition:
def sum(**args): #pack keyword args into datastructure of dict after applying '**' - def sum({a:1,b:2,c:3,d:4})
sum=0
for k,v in args.items():
sum+=v
print(sum)
sum(a=1,b=2,c=3,d=4) #positional args sent to function sum
In function definition The '**' operator packs the received arguments into a dictionary.
So remember:
In a function call the '*' unpacks data structure of tuple or list into positional or keyword arguments to be received by function definition.
In a function call the '**' unpacks data structure of dictionary into positional or keyword arguments to be received by function definition.
In a function definition the '*' packs positional arguments into a tuple.
In a function definition the '**' packs keyword arguments into a dictionary.
A: Given a function that has 3 items as argument
sum = lambda x, y, z: x + y + z
sum(1,2,3) # sum 3 items
sum([1,2,3]) # error, needs 3 items, not 1 list
x = [1,2,3][0]
y = [1,2,3][1]
z = [1,2,3][2]
sum(x,y,z) # ok
sum(*[1,2,3]) # ok, 1 list becomes 3 items
Imagine this toy with a bag of a triangle, a circle and a rectangle item. That bag does not directly fit. You need to unpack the bag to take those 3 items and now they fit. The Python * operator does this unpack process.
A: This table is handy for using * and ** in function construction and function call:
In function construction In function call
=======================================================================
| def f(*args): | def f(a, b):
*args | for arg in args: | return a + b
| print(arg) | args = (1, 2)
| f(1, 2) | f(*args)
----------|--------------------------------|---------------------------
| def f(a, b): | def f(a, b):
**kwargs | return a + b | return a + b
| def g(**kwargs): | kwargs = dict(a=1, b=2)
| return f(**kwargs) | f(**kwargs)
| g(a=1, b=2) |
-----------------------------------------------------------------------
This really just serves to summarize Lorin Hochstein's answer but I find it helpful.
Relatedly: uses for the star/splat operators have been expanded in Python 3
A: *args and **kwargs: allow you to pass a variable number of arguments to a function.
*args: is used to send a non-keyworded variable length argument list to the function:
def args(normal_arg, *argv):
print("normal argument:", normal_arg)
for arg in argv:
print("Argument in list of arguments from *argv:", arg)
args('animals', 'fish', 'duck', 'bird')
Will produce:
normal argument: animals
Argument in list of arguments from *argv: fish
Argument in list of arguments from *argv: duck
Argument in list of arguments from *argv: bird
**kwargs*
**kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function.
def who(**kwargs):
if kwargs is not None:
for key, value in kwargs.items():
print("Your %s is %s." % (key, value))
who(name="Nikola", last_name="Tesla", birthday="7.10.1856", birthplace="Croatia")
Will produce:
Your name is Nikola.
Your last_name is Tesla.
Your birthday is 7.10.1856.
Your birthplace is Croatia.
A: TL;DR
Below are 6 different use cases for * and ** in python programming:
*
*To accept any number of positional arguments using *args: def foo(*args): pass, here foo accepts any number of positional arguments, i. e., the following calls are valid foo(1), foo(1, 'bar')
*To accept any number of keyword arguments using **kwargs: def foo(**kwargs): pass, here 'foo' accepts any number of keyword arguments, i. e., the following calls are valid foo(name='Tom'), foo(name='Tom', age=33)
*To accept any number of positional and keyword arguments using *args, **kwargs: def foo(*args, **kwargs): pass, here foo accepts any number of positional and keyword arguments, i. e., the following calls are valid foo(1,name='Tom'), foo(1, 'bar', name='Tom', age=33)
*To enforce keyword only arguments using *: def foo(pos1, pos2, *, kwarg1): pass, here * means that foo only accept keyword arguments after pos2, hence foo(1, 2, 3) raises TypeError but foo(1, 2, kwarg1=3) is ok.
*To express no further interest in more positional arguments using *_ (Note: this is a convention only): def foo(bar, baz, *_): pass means (by convention) foo only uses bar and baz arguments in its working and will ignore others.
*To express no further interest in more keyword arguments using **_ (Note: this is a convention only): def foo(bar, baz, **_): pass means (by convention) foo only uses bar and baz arguments in its working and will ignore others.
BONUS: From python 3.8 onward, one can use / in function definition to enforce positional only parameters. In the following example, parameters a and b are positional-only, while c or d can be positional or keyword, and e or f are required to be keywords:
def f(a, b, /, c, d, *, e, f):
pass
BONUS 2: THIS ANSWER to the same question also brings a new perspective, where it shares what does * and ** means in a function call, functions signature, for loops, etc.
A: * and ** have special usage in the function argument list. *
implies that the argument is a list and ** implies that the argument
is a dictionary. This allows functions to take arbitrary number of
arguments
A: The *args and **kwargs is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation.
The *args will give you all function parameters as a tuple:
def foo(*args):
for a in args:
print(a)
foo(1)
# 1
foo(1,2,3)
# 1
# 2
# 3
The **kwargs will give you all
keyword arguments except for those corresponding to a formal parameter as a dictionary.
def bar(**kwargs):
for a in kwargs:
print(a, kwargs[a])
bar(name='one', age=27)
# name one
# age 27
Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:
def foo(kind, *args, **kwargs):
pass
It is also possible to use this the other way around:
def foo(a, b, c):
print(a, b, c)
obj = {'b':10, 'c':'lee'}
foo(100,**obj)
# 100 10 lee
Another usage of the *l idiom is to unpack argument lists when calling a function.
def foo(bar, lee):
print(bar, lee)
l = [1,2]
foo(*l)
# 1 2
In Python 3 it is possible to use *l on the left side of an assignment (Extended Iterable Unpacking), though it gives a list instead of a tuple in this context:
first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]
Also Python 3 adds new semantic (refer PEP 3102):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass
For example the following works in python 3 but not python 2:
>>> x = [1, 2]
>>> [*x]
[1, 2]
>>> [*x, 3, 4]
[1, 2, 3, 4]
>>> x = {1:1, 2:2}
>>> x
{1: 1, 2: 2}
>>> {**x, 3:3, 4:4}
{1: 1, 2: 2, 3: 3, 4: 4}
Such function accepts only 3 positional arguments, and everything after * can only be passed as keyword arguments.
Note:
*
*A Python dict, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order.
*"The order of elements in **kwargs now corresponds to the order in which keyword arguments were passed to the function." - What’s New In Python 3.6
*In fact, all dicts in CPython 3.6 will remember insertion order as an implementation detail, this becomes standard in Python 3.7.
A: A good example of using both in a function is:
>>> def foo(*arg,**kwargs):
... print arg
... print kwargs
>>>
>>> a = (1, 2, 3)
>>> b = {'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(*a,**b)
(1, 2, 3)
{'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(a,**b)
((1, 2, 3),)
{'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(a,b)
((1, 2, 3), {'aa': 11, 'bb': 22})
{}
>>>
>>>
>>> foo(a,*b)
((1, 2, 3), 'aa', 'bb')
{}
A: This example would help you remember *args, **kwargs and even super and inheritance in Python at once.
class base(object):
def __init__(self, base_param):
self.base_param = base_param
class child1(base): # inherited from base class
def __init__(self, child_param, *args) # *args for non-keyword args
self.child_param = child_param
super(child1, self).__init__(*args) # call __init__ of the base class and initialize it with a NON-KEYWORD arg
class child2(base):
def __init__(self, child_param, **kwargs):
self.child_param = child_param
super(child2, self).__init__(**kwargs) # call __init__ of the base class and initialize it with a KEYWORD arg
c1 = child1(1,0)
c2 = child2(1,base_param=0)
print c1.base_param # 0
print c1.child_param # 1
print c2.base_param # 0
print c2.child_param # 1
A: For those of you who learn by examples!
*
*The purpose of * is to give you the ability to define a function that can take an arbitrary number of arguments provided as a list (e.g. f(*myList) ).
*The purpose of ** is to give you the ability to feed a function's arguments by providing a dictionary (e.g. f(**{'x' : 1, 'y' : 2}) ).
Let us show this by defining a function that takes two normal variables x, y, and can accept more arguments as myArgs, and can accept even more arguments as myKW. Later, we will show how to feed y using myArgDict.
def f(x, y, *myArgs, **myKW):
print("# x = {}".format(x))
print("# y = {}".format(y))
print("# myArgs = {}".format(myArgs))
print("# myKW = {}".format(myKW))
print("# ----------------------------------------------------------------------")
# Define a list for demonstration purposes
myList = ["Left", "Right", "Up", "Down"]
# Define a dictionary for demonstration purposes
myDict = {"Wubba": "lubba", "Dub": "dub"}
# Define a dictionary to feed y
myArgDict = {'y': "Why?", 'y0': "Why not?", "q": "Here is a cue!"}
# The 1st elem of myList feeds y
f("myEx", *myList, **myDict)
# x = myEx
# y = Left
# myArgs = ('Right', 'Up', 'Down')
# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}
# ----------------------------------------------------------------------
# y is matched and fed first
# The rest of myArgDict becomes additional arguments feeding myKW
f("myEx", **myArgDict)
# x = myEx
# y = Why?
# myArgs = ()
# myKW = {'y0': 'Why not?', 'q': 'Here is a cue!'}
# ----------------------------------------------------------------------
# The rest of myArgDict becomes additional arguments feeding myArgs
f("myEx", *myArgDict)
# x = myEx
# y = y
# myArgs = ('y0', 'q')
# myKW = {}
# ----------------------------------------------------------------------
# Feed extra arguments manually and append even more from my list
f("myEx", 4, 42, 420, *myList, *myDict, **myDict)
# x = myEx
# y = 4
# myArgs = (42, 420, 'Left', 'Right', 'Up', 'Down', 'Wubba', 'Dub')
# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}
# ----------------------------------------------------------------------
# Without the stars, the entire provided list and dict become x, and y:
f(myList, myDict)
# x = ['Left', 'Right', 'Up', 'Down']
# y = {'Wubba': 'lubba', 'Dub': 'dub'}
# myArgs = ()
# myKW = {}
# ----------------------------------------------------------------------
Caveats
*
*** is exclusively reserved for dictionaries.
*Non-optional argument assignment happens first.
*You cannot use a non-optional argument twice.
*If applicable, ** must come after *, always.
A: The single * means that there can be any number of extra positional arguments. foo() can be invoked like foo(1,2,3,4,5). In the body of foo() param2 is a sequence containing 2-5.
The double ** means there can be any number of extra named parameters. bar() can be invoked like bar(1, a=2, b=3). In the body of bar() param2 is a dictionary containing {'a':2, 'b':3 }
With the following code:
def foo(param1, *param2):
print(param1)
print(param2)
def bar(param1, **param2):
print(param1)
print(param2)
foo(1,2,3,4,5)
bar(1,a=2,b=3)
the output is
1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}
A: From the Python documentation:
If there are more positional arguments than there are formal parameter slots, a TypeError exception is raised, unless a formal parameter using the syntax "*identifier" is present; in this case, that formal parameter receives a tuple containing the excess positional arguments (or an empty tuple if there were no excess positional arguments).
If any keyword argument does not correspond to a formal parameter name, a TypeError exception is raised, unless a formal parameter using the syntax "**identifier" is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments.
A:
What does ** (double star) and * (star) do for parameters?
They allow for functions to be defined to accept and for users to pass any number of arguments, positional (*) and keyword (**).
Defining Functions
*args allows for any number of optional positional arguments (parameters), which will be assigned to a tuple named args.
**kwargs allows for any number of optional keyword arguments (parameters), which will be in a dict named kwargs.
You can (and should) choose any appropriate name, but if the intention is for the arguments to be of non-specific semantics, args and kwargs are standard names.
Expansion, Passing any number of arguments
You can also use *args and **kwargs to pass in parameters from lists (or any iterable) and dicts (or any mapping), respectively.
The function recieving the parameters does not have to know that they are being expanded.
For example, Python 2's xrange does not explicitly expect *args, but since it takes 3 integers as arguments:
>>> x = xrange(3) # create our *args - an iterable of 3 integers
>>> xrange(*x) # expand here
xrange(0, 2, 2)
As another example, we can use dict expansion in str.format:
>>> foo = 'FOO'
>>> bar = 'BAR'
>>> 'this is foo, {foo} and bar, {bar}'.format(**locals())
'this is foo, FOO and bar, BAR'
New in Python 3: Defining functions with keyword only arguments
You can have keyword only arguments after the *args - for example, here, kwarg2 must be given as a keyword argument - not positionally:
def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs):
return arg, kwarg, args, kwarg2, kwargs
Usage:
>>> foo(1,2,3,4,5,kwarg2='kwarg2', bar='bar', baz='baz')
(1, 2, (3, 4, 5), 'kwarg2', {'bar': 'bar', 'baz': 'baz'})
Also, * can be used by itself to indicate that keyword only arguments follow, without allowing for unlimited positional arguments.
def foo(arg, kwarg=None, *, kwarg2=None, **kwargs):
return arg, kwarg, kwarg2, kwargs
Here, kwarg2 again must be an explicitly named, keyword argument:
>>> foo(1,2,kwarg2='kwarg2', foo='foo', bar='bar')
(1, 2, 'kwarg2', {'foo': 'foo', 'bar': 'bar'})
And we can no longer accept unlimited positional arguments because we don't have *args*:
>>> foo(1,2,3,4,5, kwarg2='kwarg2', foo='foo', bar='bar')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() takes from 1 to 2 positional arguments
but 5 positional arguments (and 1 keyword-only argument) were given
Again, more simply, here we require kwarg to be given by name, not positionally:
def bar(*, kwarg=None):
return kwarg
In this example, we see that if we try to pass kwarg positionally, we get an error:
>>> bar('kwarg')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() takes 0 positional arguments but 1 was given
We must explicitly pass the kwarg parameter as a keyword argument.
>>> bar(kwarg='kwarg')
'kwarg'
Python 2 compatible demos
*args (typically said "star-args") and **kwargs (stars can be implied by saying "kwargs", but be explicit with "double-star kwargs") are common idioms of Python for using the * and ** notation. These specific variable names aren't required (e.g. you could use *foos and **bars), but a departure from convention is likely to enrage your fellow Python coders.
We typically use these when we don't know what our function is going to receive or how many arguments we may be passing, and sometimes even when naming every variable separately would get very messy and redundant (but this is a case where usually explicit is better than implicit).
Example 1
The following function describes how they can be used, and demonstrates behavior. Note the named b argument will be consumed by the second positional argument before :
def foo(a, b=10, *args, **kwargs):
'''
this function takes required argument a, not required keyword argument b
and any number of unknown positional arguments and keyword arguments after
'''
print('a is a required argument, and its value is {0}'.format(a))
print('b not required, its default value is 10, actual value: {0}'.format(b))
# we can inspect the unknown arguments we were passed:
# - args:
print('args is of type {0} and length {1}'.format(type(args), len(args)))
for arg in args:
print('unknown arg: {0}'.format(arg))
# - kwargs:
print('kwargs is of type {0} and length {1}'.format(type(kwargs),
len(kwargs)))
for kw, arg in kwargs.items():
print('unknown kwarg - kw: {0}, arg: {1}'.format(kw, arg))
# But we don't have to know anything about them
# to pass them to other functions.
print('Args or kwargs can be passed without knowing what they are.')
# max can take two or more positional args: max(a, b, c...)
print('e.g. max(a, b, *args) \n{0}'.format(
max(a, b, *args)))
kweg = 'dict({0})'.format( # named args same as unknown kwargs
', '.join('{k}={v}'.format(k=k, v=v)
for k, v in sorted(kwargs.items())))
print('e.g. dict(**kwargs) (same as {kweg}) returns: \n{0}'.format(
dict(**kwargs), kweg=kweg))
We can check the online help for the function's signature, with help(foo), which tells us
foo(a, b=10, *args, **kwargs)
Let's call this function with foo(1, 2, 3, 4, e=5, f=6, g=7)
which prints:
a is a required argument, and its value is 1
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 2
unknown arg: 3
unknown arg: 4
kwargs is of type <type 'dict'> and length 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: g, arg: 7
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
4
e.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns:
{'e': 5, 'g': 7, 'f': 6}
Example 2
We can also call it using another function, into which we just provide a:
def bar(a):
b, c, d, e, f = 2, 3, 4, 5, 6
# dumping every local variable into foo as a keyword argument
# by expanding the locals dict:
foo(**locals())
bar(100) prints:
a is a required argument, and its value is 100
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 0
kwargs is of type <type 'dict'> and length 4
unknown kwarg - kw: c, arg: 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: d, arg: 4
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
100
e.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns:
{'c': 3, 'e': 5, 'd': 4, 'f': 6}
Example 3: practical usage in decorators
OK, so maybe we're not seeing the utility yet. So imagine you have several functions with redundant code before and/or after the differentiating code. The following named functions are just pseudo-code for illustrative purposes.
def foo(a, b, c, d=0, e=100):
# imagine this is much more code than a simple function call
preprocess()
differentiating_process_foo(a,b,c,d,e)
# imagine this is much more code than a simple function call
postprocess()
def bar(a, b, c=None, d=0, e=100, f=None):
preprocess()
differentiating_process_bar(a,b,c,d,e,f)
postprocess()
def baz(a, b, c, d, e, f):
... and so on
We might be able to handle this differently, but we can certainly extract the redundancy with a decorator, and so our below example demonstrates how *args and **kwargs can be very useful:
def decorator(function):
'''function to wrap other functions with a pre- and postprocess'''
@functools.wraps(function) # applies module, name, and docstring to wrapper
def wrapper(*args, **kwargs):
# again, imagine this is complicated, but we only write it once!
preprocess()
function(*args, **kwargs)
postprocess()
return wrapper
And now every wrapped function can be written much more succinctly, as we've factored out the redundancy:
@decorator
def foo(a, b, c, d=0, e=100):
differentiating_process_foo(a,b,c,d,e)
@decorator
def bar(a, b, c=None, d=0, e=100, f=None):
differentiating_process_bar(a,b,c,d,e,f)
@decorator
def baz(a, b, c=None, d=0, e=100, f=None, g=None):
differentiating_process_baz(a,b,c,d,e,f, g)
@decorator
def quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None):
differentiating_process_quux(a,b,c,d,e,f,g,h)
And by factoring out our code, which *args and **kwargs allows us to do, we reduce lines of code, improve readability and maintainability, and have sole canonical locations for the logic in our program. If we need to change any part of this structure, we have one place in which to make each change.
A: Context
*
*python 3.x
*unpacking with **
*use with string formatting
Use with string formatting
In addition to the answers in this thread, here is another detail that was not mentioned elsewhere. This expands on the answer by Brad Solomon
Unpacking with ** is also useful when using python str.format.
This is somewhat similar to what you can do with python f-strings f-string but with the added overhead of declaring a dict to hold the variables (f-string does not require a dict).
Quick Example
## init vars
ddvars = dict()
ddcalc = dict()
pass
ddvars['fname'] = 'Huomer'
ddvars['lname'] = 'Huimpson'
ddvars['motto'] = 'I love donuts!'
ddvars['age'] = 33
pass
ddcalc['ydiff'] = 5
ddcalc['ycalc'] = ddvars['age'] + ddcalc['ydiff']
pass
vdemo = []
## ********************
## single unpack supported in py 2.7
vdemo.append('''
Hello {fname} {lname}!
Today you are {age} years old!
We love your motto "{motto}" and we agree with you!
'''.format(**ddvars))
pass
## ********************
## multiple unpack supported in py 3.x
vdemo.append('''
Hello {fname} {lname}!
In {ydiff} years you will be {ycalc} years old!
'''.format(**ddvars,**ddcalc))
pass
## ********************
print(vdemo[-1])
A: *args ( or *any ) means every parameters
def any_param(*param):
pass
any_param(1)
any_param(1,1)
any_param(1,1,1)
any_param(1,...)
NOTICE : you can don't pass parameters to *args
def any_param(*param):
pass
any_param() # will work correct
The *args is in type tuple
def any_param(*param):
return type(param)
any_param(1) #tuple
any_param() # tuple
for access to elements don't use of *
def any(*param):
param[0] # correct
def any(*param):
*param[0] # incorrect
The **kwd
**kwd or **any
This is a dict type
def func(**any):
return type(any) # dict
def func(**any):
return any
func(width="10",height="20") # {width="10",height="20")
A: * means receive variable arguments as tuple
** means receive variable arguments as dictionary
Used like the following:
1) single *
def foo(*args):
for arg in args:
print(arg)
foo("two", 3)
Output:
two
3
2) Now **
def bar(**kwargs):
for key in kwargs:
print(key, kwargs[key])
bar(dic1="two", dic2=3)
Output:
dic1 two
dic2 3
A: In Python 3.5, you can also use this syntax in list, dict, tuple, and set displays (also sometimes called literals). See PEP 488: Additional Unpacking Generalizations.
>>> (0, *range(1, 4), 5, *range(6, 8))
(0, 1, 2, 3, 5, 6, 7)
>>> [0, *range(1, 4), 5, *range(6, 8)]
[0, 1, 2, 3, 5, 6, 7]
>>> {0, *range(1, 4), 5, *range(6, 8)}
{0, 1, 2, 3, 5, 6, 7}
>>> d = {'one': 1, 'two': 2, 'three': 3}
>>> e = {'six': 6, 'seven': 7}
>>> {'zero': 0, **d, 'five': 5, **e}
{'five': 5, 'seven': 7, 'two': 2, 'one': 1, 'three': 3, 'six': 6, 'zero': 0}
It also allows multiple iterables to be unpacked in a single function call.
>>> range(*[1, 10], *[2])
range(1, 10, 2)
(Thanks to mgilson for the PEP link.)
A: I want to give an example which others haven't mentioned
* can also unpack a generator
An example from Python3 Document
x = [1, 2, 3]
y = [4, 5, 6]
unzip_x, unzip_y = zip(*zip(x, y))
unzip_x will be (1, 2, 3), unzip_y will be (4, 5, 6)
The zip() receives multiple iretable args, and return a generator.
zip(*zip(x,y)) -> zip((1, 4), (2, 5), (3, 6))
A: TL;DR
It packs arguments passed to the function into list and dict respectively inside the function body. When you define a function signature like this:
def func(*args, **kwds):
# do stuff
it can be called with any number of arguments and keyword arguments. The non-keyword arguments get packed into a list called args inside the function body and the keyword arguments get packed into a dict called kwds inside the function body.
func("this", "is a list of", "non-keyowrd", "arguments", keyword="ligma", options=[1,2,3])
now inside the function body, when the function is called, there are two local variables, args which is a list having value ["this", "is a list of", "non-keyword", "arguments"] and kwds which is a dict having value {"keyword" : "ligma", "options" : [1,2,3]}
This also works in reverse, i.e. from the caller side. for example if you have a function defined as:
def f(a, b, c, d=1, e=10):
# do stuff
you can call it with by unpacking iterables or mappings you have in the calling scope:
iterable = [1, 20, 500]
mapping = {"d" : 100, "e": 3}
f(*iterable, **mapping)
# That call is equivalent to
f(1, 20, 500, d=100, e=3)
A: *
**args is the special parameter which can take 0 or more (positional) arguments as a tuple.
***kwargs is the special parameter which can take 0 or more (keyword) arguments as a dictionary.
*In Python, there are 2 kinds of arguments positional argument and keyword argument:
*args:
For example, *args can take 0 or more arguments as a tuple as shown below:
↓
def test(*args):
print(args)
test() # Here
test(1, 2, 3, 4) # Here
test((1, 2, 3, 4)) # Here
test(*(1, 2, 3, 4)) # Here
Output:
()
(1, 2, 3, 4)
((1, 2, 3, 4),)
(1, 2, 3, 4)
And, when printing *args, 4 numbers are printed without parentheses and commas:
def test(*args):
print(*args) # Here
test(1, 2, 3, 4)
Output:
1 2 3 4
And, args has tuple type:
def test(*args):
print(type(args)) # Here
test(1, 2, 3, 4)
Output:
<class 'tuple'>
But, *args has no type:
def test(*args):
print(type(*args)) # Here
test(1, 2, 3, 4)
Output(Error):
TypeError: type() takes 1 or 3 arguments
And, normal parameters can be put before *args as shown below:
↓ ↓
def test(num1, num2, *args):
print(num1, num2, args)
test(1, 2, 3, 4)
Output:
1 2 (3, 4)
But, **kwargs cannot be put before *args as shown below:
↓
def test(**kwargs, *args):
print(kwargs, args)
test(num1=1, num2=2, 3, 4)
Output(Error):
SyntaxError: invalid syntax
And, normal parameters cannot be put after *args as shown below:
↓ ↓
def test(*args, num1, num2):
print(args, num1, num2)
test(1, 2, 3, 4)
Output(Error):
TypeError: test() missing 2 required keyword-only arguments: 'num1' and 'num2'
But, if normal parameters have default values, they can be put after *args as shown below:
↓ ↓
def test(*args, num1=100, num2=None):
print(args, num1, num2)
test(1, 2, num1=3, num2=4)
Output:
(1, 2) 3 4
And also, **kwargs can be put after *args as shown below:
↓
def test(*args, **kwargs):
print(args, kwargs)
test(1, 2, num1=3, num2=4)
Output:
(1, 2) {'num1': 3, 'num2': 4}
**kwargs:
For example, **kwargs can take 0 or more arguments as a dictionary as shown below:
↓
def test(**kwargs):
print(kwargs)
test() # Here
test(name="John", age=27) # Here
test(**{"name": "John", "age": 27}) # Here
Output:
{}
{'name': 'John', 'age': 27}
{'name': 'John', 'age': 27}
And, when printing *kwargs, 2 keys are printed:
def test(**kwargs):
print(*kwargs) # Here
test(name="John", age=27)
Output:
name age
And, kwargs has dict type:
def test(**kwargs):
print(type(kwargs)) # Here
test(name="John", age=27)
Output:
<class 'dict'>
But, *kwargs and **kwargs have no type:
def test(**kwargs):
print(type(*kwargs)) # Here
test(name="John", age=27)
def test(**kwargs):
print(type(**kwargs)) # Here
test(name="John", age=27)
Output(Error):
TypeError: type() takes 1 or 3 arguments
And, normal parameters can be put before **kwargs as shown below:
↓ ↓
def test(num1, num2, **kwargs):
print(num1, num2, kwargs)
test(1, 2, name="John", age=27)
Output:
1 2 {'name': 'John', 'age': 27}
And also, *args can be put before **kwargs as shown below:
↓
def test(*args, **kwargs):
print(args, kwargs)
test(1, 2, name="John", age=27)
Output:
(1, 2) {'name': 'John', 'age': 27}
And, normal parameters and *args cannot be put after **kwargs as shown below:
↓ ↓
def test(**kwargs, num1, num2):
print(kwargs, num1, num2)
test(name="John", age=27, 1, 2)
↓
def test(**kwargs, *args):
print(kwargs, args)
test(name="John", age=27, 1, 2)
Output(Error):
SyntaxError: invalid syntax
For both *args and **kwargs:
Actually, you can use other names for *args and **kwargs as shown below. *args and **kwargs are used conventionally:
↓ ↓
def test(*banana, **orange):
print(banana, orange)
test(1, 2, num1=3, num2=4)
Output:
(1, 2) {'num1': 3, 'num2': 4}
A: *
*def foo(param1, *param2): is a method can accept arbitrary number of values for *param2,
*def bar(param1, **param2): is a method can accept arbitrary number of values with keys for *param2
*param1 is a simple parameter.
For example, the syntax for implementing varargs in Java as follows:
accessModifier methodName(datatype… arg) {
// method body
}
A: "Infinite" Args with *args and **kwargs
*args and **kwargs are just some way to input unlimited characters to functions, like:
def print_all(*args, **kwargs):
print(args) # print any number of arguments like: "print_all("foo", "bar")"
print(kwargs.get("to_print")) # print the value of the keyworded argument "to_print"
# example:
print_all("Hello", "World", to_print="!")
# will print:
"""
('Hello', 'World')
!
"""
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3238"
} |
Q: What is the fastest way to swap values in C? I want to swap two integers, and I want to know which of these two implementations will be faster:
The obvious way with a temp variable:
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
Or the xor version that I'm sure most people have seen:
void swap(int* a, int* b)
{
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
It seems like the first uses an extra register, but the second one is doing three loads and stores while the first only does two of each. Can someone tell me which is faster and why? The why being more important.
A: The XOR method fails if a and b point to the same address. The first XOR will clear all of the bits at the memory address pointed to by both variables, so once the function returns (*a == *b == 0), regardless of the initial value.
More info on the Wiki page:
XOR swap algorithm
Although it's not likely that this issue would come up, I'd always prefer to use the method that's guaranteed to work, not the clever method that fails at unexpected moments.
A: For those to stumble upon this question and decide to use the XOR method. You should consider inlining your function or using a macro to avoid the overhead of a function call:
#define swap(a, b) \
do { \
int temp = a; \
a = b; \
b = temp; \
} while(0)
A: Never understood the hate for macros. When used properly they can make code more compact and readable. I believe most programmers know macros should be used with care, what is important is making it clear that a particular call is a macro and not a function call (all caps). If SWAP(a++, b++); is a consistent source of problems, perhaps programming is not for you.
Admittedly, the xor trick is neat the first 5000 times you see it, but all it really does is save one temporary at the expense of reliability. Looking at the assembly generated above it saves a register but creates dependencies. Also I would not recommend xchg since it has an implied lock prefix.
Eventually we all come to the same place, after countless hours wasted on unproductive optimization and debugging caused by our most clever code - Keep it simple.
#define SWAP(type, a, b) \
do { type t=(a);(a)=(b);(b)=t; } while (0)
void swap(size_t esize, void* a, void* b)
{
char* x = (char*) a;
char* y = (char*) b;
char* z = x + esize;
for ( ; x < z; x++, y++ )
SWAP(char, *x, *y);
}
A: You are optimizing the wrong thing, both of those should be so fast that you'll have to run them billions of times just to get any measurable difference.
And just about anything will have much greater effect on your performance, for example, if the values you are swapping are close in memory to the last value you touched they are lily to be in the processor cache, otherwise you'll have to access the memory - and that is several orders of magnitude slower then any operation you do inside the processor.
Anyway, your bottleneck is much more likely to be an inefficient algorithm or inappropriate data structure (or communication overhead) then how you swap numbers.
A: The only way to really know is to test it, and the answer may even vary depending on what compiler and platform you are on. Modern compilers are really good at optimizing code these days, and you should never try to outsmart the compiler unless you can prove that your way is really faster.
With that said, you'd better have a damn good reason to choose #2 over #1. The code in #1 is far more readable and because of that should always be chosen first. Only switch to #2 if you can prove that you need to make that change, and if you do - comment it to explain what's happening and why you did it the non-obvious way.
As an anecdote, I work with a couple of people that love to optimize prematurely and it makes for really hideous, unmaintainable code. I'm also willing to bet that more often than not they're shooting themselves in the foot because they've hamstrung the ability of the compiler to optimize the code by writing it in a non-straightforward way.
A: For modern CPU architectures, method 1 will be faster, also with higher readability than method 2.
On modern CPU architectures, the XOR technique is considerably slower than using a temporary variable to do swapping. One reason is that modern CPUs strive to execute instructions in parallel via instruction pipelines. In the XOR technique, the inputs to each operation depend on the results of the previous operation, so they must be executed in strictly sequential order. If efficiency is of tremendous concern, it is advised to test the speeds of both the XOR technique and temporary variable swapping on the target architecture. Check out here for more info.
Edit: Method 2 is a way of in-place swapping (i.e. without using extra variables). To make this question complete, I will add another in-place swapping by using +/-.
void swap(int* a, int* b)
{
if (a != b) // important to handle a/b share the same reference
{
*a = *a+*b;
*b = *a-*b;
*a = *a-*b;
}
}
A: On a modern processor, you could use the following when sorting large arrays and see no difference in speed:
void swap (int *a, int *b)
{
for (int i = 1 ; i ; i <<= 1)
{
if ((*a & i) != (*b & i))
{
*a ^= i;
*b ^= i;
}
}
}
The really important part of your question is the 'why?' part. Now, going back 20 years to the 8086 days, the above would have been a real performance killer, but on the latest Pentium it would be a match speed wise to the two you posted.
The reason is purely down to memory and has nothing to do with the CPU.
CPU speeds compared to memory speeds have risen astronomically. Accessing memory has become the major bottleneck in application performance. All the swap algorithms will be spending most of their time waiting for data to be fetched from memory. Modern OS's can have up to 5 levels of memory:
*
*Cache Level 1 - runs at the same speed as the CPU, has negligible access time, but is small
*Cache Level 2 - runs a bit slower than L1 but is larger and has a bigger overhead to access (usually, data needs to be moved to L1 first)
*Cache Level 3 - (not always present) Often external to the CPU, slower and bigger than L2
*RAM - the main system memory, usually implements a pipeline so there's latency in read requests (CPU requests data, message sent to RAM, RAM gets data, RAM sends data to CPU)
*Hard Disk - when there's not enough RAM, data is paged to HD which is really slow, not really under CPU control as such.
Sorting algorithms will make memory access worse since they usually access the memory in a very unordered way, thus incurring the inefficient overhead of fetching data from L2, RAM or HD.
So, optimising the swap method is really pointless - if it's only called a few times then any inefficiency is hidden due to the small number of calls, if it's called a lot then any inefficiency is hidden due to the number of cache misses (where the CPU needs to get data from L2 (1's of cycles), L3 (10's of cycles), RAM (100's of cycles), HD (!)).
What you really need to do is look at the algorithm that calls the swap method. This is not a trivial exercise. Although the Big-O notation is useful, an O(n) can be significantly faster than a O(log n) for small n. (I'm sure there's a CodingHorror article about this.) Also, many algorithms have degenerate cases where the code does more than is necessary (using qsort on nearly ordered data could be slower than a bubble sort with an early-out check). So, you need to analyse your algorithm and the data it's using.
Which leads to how to analyse the code. Profilers are useful but you do need to know how to interpret the results. Never use a single run to gather results, always average results over many executions - because your test application could have been paged to hard disk by the OS halfway through. Always profile release, optimised builds, profiling debug code is pointless.
As to the original question - which is faster? - it's like trying to figure out if a Ferrari is faster than a Lambourgini by looking at the size and shape of the wing mirror.
A: I would not do it with pointers unless you have to. The compiler cannot optimize them very well because of the possibility of pointer aliasing (although if you can GUARANTEE that the pointers point to non-overlapping locations, GCC at least has extensions to optimize this).
And I would not do it with functions at all, since it's a very simple operation and the function call overhead is significant.
The best way to do it is with macros if raw speed and the possibility of optimization is what you require. In GCC you can use the typeof() builtin to make a flexible version that works on any built-in type.
Something like this:
#define swap(a,b) \
do { \
typeof(a) temp; \
temp = a; \
a = b; \
b = temp; \
} while (0)
...
{
int a, b;
swap(a, b);
unsigned char x, y;
swap(x, y); /* works with any type */
}
With other compilers, or if you require strict compliance with standard C89/99, you would have to make a separate macro for each type.
A good compiler will optimize this as aggressively as possible, given the context, if called with local/global variables as arguments.
A: All the top rated answers are not actually definitive "facts"... they are people who are speculating!
You can definitively know for a fact which code takes less assembly instructions to execute because you can look at the output assembly generated by the compiler and see which executes in less assembly instructions!
Here is the c code I compiled with flags "gcc -std=c99 -S -O3 lookingAtAsmOutput.c":
#include <stdio.h>
#include <stdlib.h>
void swap_traditional(int * restrict a, int * restrict b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void swap_xor(int * restrict a, int * restrict b)
{
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
int main() {
int a = 5;
int b = 6;
swap_traditional(&a,&b);
swap_xor(&a,&b);
}
ASM output for swap_traditional() takes >>> 11 <<< instructions ( not including "leave", "ret", "size"):
.globl swap_traditional
.type swap_traditional, @function
swap_traditional:
pushl %ebp
movl %esp, %ebp
movl 8(%ebp), %edx
movl 12(%ebp), %ecx
pushl %ebx
movl (%edx), %ebx
movl (%ecx), %eax
movl %ebx, (%ecx)
movl %eax, (%edx)
popl %ebx
popl %ebp
ret
.size swap_traditional, .-swap_traditional
.p2align 4,,15
ASM output for swap_xor() takes >>> 11 <<< instructions not including "leave" and "ret":
.globl swap_xor
.type swap_xor, @function
swap_xor:
pushl %ebp
movl %esp, %ebp
movl 8(%ebp), %ecx
movl 12(%ebp), %edx
movl (%ecx), %eax
xorl (%edx), %eax
movl %eax, (%ecx)
xorl (%edx), %eax
xorl %eax, (%ecx)
movl %eax, (%edx)
popl %ebp
ret
.size swap_xor, .-swap_xor
.p2align 4,,15
Summary of assembly output:
swap_traditional() takes 11 instructions
swap_xor() takes 11 instructions
Conclusion:
Both methods use the same amount of instructions to execute and therefore are approximately the same speed on this hardware platform.
Lesson learned:
When you have small code snippets, looking at the asm output is helpful to rapidly iterate your code and come up with the fastest ( i.e. least instructions ) code. And you can save time even because you don't have to run the program for each code change. You only need to run the code change at the end with a profiler to show that your code changes are faster.
I use this method a lot for heavy DSP code that needs speed.
A: To answer your question as stated would require digging into the instruction timings of the particular CPU that this code will be running on which therefore require me to make a bunch of assumptions around the state of the caches in the system and the assembly code emitted by the compiler. It would be an interesting and useful exercise from the perspective of understanding how your processor of choice actually works but in the real world the difference will be negligible.
A: x=x+y-(y=x);
float x; cout << "X:"; cin >> x;
float y; cout << "Y:" ; cin >> y;
cout << "---------------------" << endl;
cout << "X=" << x << ", Y=" << y << endl;
x=x+y-(y=x);
cout << "X=" << x << ", Y=" << y << endl;
A: The first is faster because bitwise operations such as xor are usually very hard to visualize for the reader.
Faster to understand of course, which is the most important part ;)
A: Number 2 is often quoted as being the "clever" way of doing it. It is in fact most likely slower as it obscures the explicit aim of the programmer - swapping two variables. This means that a compiler can't optimize it to use the actual assembler ops to swap. It also assumes the ability to do a bitwise xor on the objects.
Stick to number 1, it's the most generic and most understandable swap and can be easily templated/genericized.
This wikipedia section explains the issues quite well:
http://en.wikipedia.org/wiki/XOR_swap_algorithm#Reasons_for_avoidance_in_practice
A: Regarding @Harry:
Never implement functions as macros for the following reasons:
*
*Type safety. There is none. The following only generates a warning when compiling but fails at run time:
float a=1.5f,b=4.2f;
swap (a,b);
A templated function will always be of the correct type (and why aren't you treating warnings as errors?).
EDIT: As there's no templates in C, you need to write a separate swap for each type or use some hacky memory access.
*It's a text substitution. The following fails at run time (this time, without compiler warnings):
int a=1,temp=3;
swap (a,temp);
*It's not a function. So, it can't be used as an argument to something like qsort.
*Compilers are clever. I mean really clever. Made by really clever people. They can do inlining of functions. Even at link time (which is even more clever). Don't forget that inlining increases code size. Big code means more chance of cache miss when fetching instructions, which means slower code.
*Side effects. Macros have side effects! Consider:
int &f1 ();
int &f2 ();
void func ()
{
swap (f1 (), f2 ());
}
Here, f1 and f2 will be called twice.
EDIT: A C version with nasty side effects:
int a[10], b[10], i=0, j=0;
swap (a[i++], b[j++]);
Macros: Just say no!
EDIT: This is why I prefer to define macro names in UPPERCASE so that they stand out in the code as a warning to use with care.
EDIT2: To answer Leahn Novash's comment:
Suppose we have a non-inlined function, f, that is converted by the compiler into a sequence of bytes then we can define the number of bytes thus:
bytes = C(p) + C(f)
where C() gives the number of bytes produced, C(f) is the bytes for the function and C(p) is the bytes for the 'housekeeping' code, the preamble and post-amble the compiler adds to the function (creating and destroying the function's stack frame and so on). Now, to call function f requires C(c) bytes. If the function is called n times then the total code size is:
size = C(p) + C(f) + n.C(c)
Now let's inline the function. C(p), the function's 'housekeeping', becomes zero since the function can use the stack frame of the caller. C(c) is also zero since there is now no call opcode. But, f is replicated wherever there was a call. So, the total code size is now:
size = n.C(f)
Now, if C(f) is less than C(c) then the overall executable size will be reduced. But, if C(f) is greater than C(c) then the code size is going to increase. If C(f) and C(c) are similar then you need to consider C(p) as well.
So, how many bytes do C(f) and C(c) produce. Well, the simplest C++ function would be a getter:
void GetValue () { return m_value; }
which would probably generate the four byte instruction:
mov eax,[ecx + offsetof (m_value)]
which is four bytes. A call instuction is five bytes. So, there is an overall size saving. If the function is more complex, say an indexer ("return m_value [index];") or a calculation ("return m_value_a + m_value_b;") then the code will be bigger.
A: In my opinion local optimizations like this should only be considered tightly related to the platform. It makes a huge difference if you are compiling this on a 16 bit uC compiler or on gcc with x64 as target.
If you have a specific target in mind then just try both of them and look at the generated asm code or profile your applciation with both methods and see which is actually faster on your platform.
A: If you can use some inline assembler and do the following (psuedo assembler):
PUSH A
A=B
POP B
You will save a lot of parameter passing and stack fix up code etc.
A: Another beautiful way.
#define Swap( a, b ) (a)^=(b)^=(a)^=(b)
Advantage
No need of function call and handy.
Drawback:
This fails when both inputs are same variable. It can be used only on integer variables.
A: void swap(int* a, int* b)
{
*a = (*b - *a) + (*b = *a);
}
// My C is a little rusty, so I hope I got the * right :)
A: Below piece of code will do the same. This snippet is optimized way of programming as it doesn't use any 3rd variable.
x = x ^ y;
y = x ^ y;
x = x ^ y;
A: I just placed both swaps (as macros) in hand written quicksort I've been playing with. The XOR version was much faster (0.1sec) then the one with the temporary variable (0.6sec). The XOR did however corrupt the data in the array (probably the same address thing Ant mentioned).
As it was a fat pivot quicksort, the XOR version's speed is probably from making large portions of the array the same. I tried a third version of swap which was the easiest to understand and it had the same time as the single temporary version.
acopy=a;
bcopy=b;
a=bcopy;
b=acopy;
[I just put an if statements around each swap, so it won't try to swap with itself, and the XOR now takes the same time as the others (0.6 sec)]
A: If your compiler supports inline assembler and your target is 32-bit x86 then the XCHG instruction is probably the best way to do this... if you really do care that much about performance.
Here is a method which works with MSVC++:
#include <stdio.h>
#define exchange(a,b) __asm mov eax, a \
__asm xchg eax, b \
__asm mov a, eax
int main(int arg, char** argv)
{
int a = 1, b = 2;
printf("%d %d --> ", a, b);
exchange(a,b)
printf("%d %d\r\n", a, b);
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "74"
} |
Q: Is there any way to "sticky" a file in subversion? We have been working with CVS for years, and frequently find it useful to "sticky" a single file here and there.
Is there any way to do this in subversion, specifically from TortoiseSVN?
A: Short answer: no.
Long answer:
Working copies are sticky to a branch by definition, as changing to a different branch means changing the base-Subversion-URL used to access the repository.
However sticky-revision files... that's not a concept that Subversion has.
See:
*
*Subversion update command reference
*Appendix A of the subversion book: Subversion for CVS Users
One workaround might be to manually return the file to a specific revision after doing an update. Perhaps putting something like the following into a script.
svn update
svn update -r1234 that/particular/file.txt
Another workaround, as tweakt suggests, is to have a partial branch with just one file in it. This needs very careful management though and things can get a bit.. er... sticky :-)
, if you're not vigilant.
A: You can technically "branch" as little as a single file if you'd like... you can use 'svn switch' on any level directory or file. SVN tracks resources on a per-file basis just as CVS does, so it can do 'sticky' to the same effect. Committing a working copy containing mixed paths has very different effects though.
See:
*
*http://svnbook.red-bean.com/en/1.0/re27.html
*http://svn.haxx.se/dev/archive-2002-11/0336.shtml
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Communication between pages I want to enable an user to be able to communicate with other users through a site. I know that ASP.net is stateless, but what can I use for this synced communication? Java servlets?
A: I don't think you need to set up Java just to use a servlet for this. I would use AJAX and the database. I don't know ASP.NET but I PHP is similar in this case, being also basically "stateless". If you want to display some kind of asynchronous communication between two different users, say, from two different sessions, without a lot of refreshing (like chat), you can have the AJAX page constantly poll the database for new messages, and display them when they come in. You can also use AJAX to insert the new messages, giving the user read/write access to this messages data structure. Since the "other" user is doing the same thing, user A should see new messages pop up when user B types them in.
Is that what you mean?
A: You probably don't want to use sessions for things like chat messages but you probably could use some type of implementation of queueing using MSMQ.
The approach to chat could be done in many different ways, this is just a suggesting off the top of my head.
A: ASP.NET is "stateless" but it maintains state using Sessions. You can use them by default just using the Session[] keyword.
Look at ASP.NET Session State for some details from Microsoft.
A: Could do a messaging solution in Java Servlets using the application context. Objects stored as attributes in the application context are visible from anywhere in your webapp.
Update: Chat like functionality... I guess that would be AJAX polling your message structure stored in the app context unless you want to use something like applets.
A: Don't know if it's any good, but there's a chat servlet here that might be useful to use or learn from if you decide to go the Java route...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I represent an 'Enum' in Python? I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python?
A: Before PEP 435, Python didn't have an equivalent but you could implement your own.
Myself, I like keeping it simple (I've seen some horribly complex examples on the net), something like this ...
class Animal:
DOG = 1
CAT = 2
x = Animal.DOG
In Python 3.4 (PEP 435), you can make Enum the base class. This gets you a little bit of extra functionality, described in the PEP. For example, enum members are distinct from integers, and they are composed of a name and a value.
from enum import Enum
class Animal(Enum):
DOG = 1
CAT = 2
print(Animal.DOG)
# <Animal.DOG: 1>
print(Animal.DOG.value)
# 1
print(Animal.DOG.name)
# "DOG"
If you don't want to type the values, use the following shortcut:
class Animal(Enum):
DOG, CAT = range(2)
Enum implementations can be converted to lists and are iterable. The order of its members is the declaration order and has nothing to do with their values. For example:
class Animal(Enum):
DOG = 1
CAT = 2
COW = 0
list(Animal)
# [<Animal.DOG: 1>, <Animal.CAT: 2>, <Animal.COW: 0>]
[animal.value for animal in Animal]
# [1, 2, 0]
Animal.CAT in Animal
# True
A: The typesafe enum pattern which was used in Java pre-JDK 5 has a
number of advantages. Much like in Alexandru's answer, you create a
class and class level fields are the enum values; however, the enum
values are instances of the class rather than small integers. This has
the advantage that your enum values don't inadvertently compare equal
to small integers, you can control how they're printed, add arbitrary
methods if that's useful and make assertions using isinstance:
class Animal:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __repr__(self):
return "<Animal: %s>" % self
Animal.DOG = Animal("dog")
Animal.CAT = Animal("cat")
>>> x = Animal.DOG
>>> x
<Animal: dog>
>>> x == 1
False
A recent thread on python-dev pointed out there are a couple of enum libraries in the wild, including:
*
*flufl.enum
*lazr.enum
*... and the imaginatively named enum
A: The enum package from PyPI provides a robust implementation of enums. An earlier answer mentioned PEP 354; this was rejected but the proposal was implemented
http://pypi.python.org/pypi/enum.
Usage is easy and elegant:
>>> from enum import Enum
>>> Colors = Enum('red', 'blue', 'green')
>>> shirt_color = Colors.green
>>> shirt_color = Colors[2]
>>> shirt_color > Colors.red
True
>>> shirt_color.index
2
>>> str(shirt_color)
'green'
A: Here's an approach with some different characteristics I find valuable:
*
*allows > and < comparison based on order in enum, not lexical order
*can address item by name, property or index: x.a, x['a'] or x[0]
*supports slicing operations like [:] or [-1]
and most importantly prevents comparisons between enums of different types!
Based closely on http://code.activestate.com/recipes/413486-first-class-enums-in-python.
Many doctests included here to illustrate what's different about this approach.
def enum(*names):
"""
SYNOPSIS
Well-behaved enumerated type, easier than creating custom classes
DESCRIPTION
Create a custom type that implements an enumeration. Similar in concept
to a C enum but with some additional capabilities and protections. See
http://code.activestate.com/recipes/413486-first-class-enums-in-python/.
PARAMETERS
names Ordered list of names. The order in which names are given
will be the sort order in the enum type. Duplicate names
are not allowed. Unicode names are mapped to ASCII.
RETURNS
Object of type enum, with the input names and the enumerated values.
EXAMPLES
>>> letters = enum('a','e','i','o','u','b','c','y','z')
>>> letters.a < letters.e
True
## index by property
>>> letters.a
a
## index by position
>>> letters[0]
a
## index by name, helpful for bridging string inputs to enum
>>> letters['a']
a
## sorting by order in the enum() create, not character value
>>> letters.u < letters.b
True
## normal slicing operations available
>>> letters[-1]
z
## error since there are not 100 items in enum
>>> letters[99]
Traceback (most recent call last):
...
IndexError: tuple index out of range
## error since name does not exist in enum
>>> letters['ggg']
Traceback (most recent call last):
...
ValueError: tuple.index(x): x not in tuple
## enums must be named using valid Python identifiers
>>> numbers = enum(1,2,3,4)
Traceback (most recent call last):
...
AssertionError: Enum values must be string or unicode
>>> a = enum('-a','-b')
Traceback (most recent call last):
...
TypeError: Error when calling the metaclass bases
__slots__ must be identifiers
## create another enum
>>> tags = enum('a','b','c')
>>> tags.a
a
>>> letters.a
a
## can't compare values from different enums
>>> letters.a == tags.a
Traceback (most recent call last):
...
AssertionError: Only values from the same enum are comparable
>>> letters.a < tags.a
Traceback (most recent call last):
...
AssertionError: Only values from the same enum are comparable
## can't update enum after create
>>> letters.a = 'x'
Traceback (most recent call last):
...
AttributeError: 'EnumClass' object attribute 'a' is read-only
## can't update enum after create
>>> del letters.u
Traceback (most recent call last):
...
AttributeError: 'EnumClass' object attribute 'u' is read-only
## can't have non-unique enum values
>>> x = enum('a','b','c','a')
Traceback (most recent call last):
...
AssertionError: Enums must not repeat values
## can't have zero enum values
>>> x = enum()
Traceback (most recent call last):
...
AssertionError: Empty enums are not supported
## can't have enum values that look like special function names
## since these could collide and lead to non-obvious errors
>>> x = enum('a','b','c','__cmp__')
Traceback (most recent call last):
...
AssertionError: Enum values beginning with __ are not supported
LIMITATIONS
Enum values of unicode type are not preserved, mapped to ASCII instead.
"""
## must have at least one enum value
assert names, 'Empty enums are not supported'
## enum values must be strings
assert len([i for i in names if not isinstance(i, types.StringTypes) and not \
isinstance(i, unicode)]) == 0, 'Enum values must be string or unicode'
## enum values must not collide with special function names
assert len([i for i in names if i.startswith("__")]) == 0,\
'Enum values beginning with __ are not supported'
## each enum value must be unique from all others
assert names == uniquify(names), 'Enums must not repeat values'
class EnumClass(object):
""" See parent function for explanation """
__slots__ = names
def __iter__(self):
return iter(constants)
def __len__(self):
return len(constants)
def __getitem__(self, i):
## this makes xx['name'] possible
if isinstance(i, types.StringTypes):
i = names.index(i)
## handles the more normal xx[0]
return constants[i]
def __repr__(self):
return 'enum' + str(names)
def __str__(self):
return 'enum ' + str(constants)
def index(self, i):
return names.index(i)
class EnumValue(object):
""" See parent function for explanation """
__slots__ = ('__value')
def __init__(self, value):
self.__value = value
value = property(lambda self: self.__value)
enumtype = property(lambda self: enumtype)
def __hash__(self):
return hash(self.__value)
def __cmp__(self, other):
assert self.enumtype is other.enumtype, 'Only values from the same enum are comparable'
return cmp(self.value, other.value)
def __invert__(self):
return constants[maximum - self.value]
def __nonzero__(self):
## return bool(self.value)
## Original code led to bool(x[0])==False, not correct
return True
def __repr__(self):
return str(names[self.value])
maximum = len(names) - 1
constants = [None] * len(names)
for i, each in enumerate(names):
val = EnumValue(i)
setattr(EnumClass, each, val)
constants[i] = val
constants = tuple(constants)
enumtype = EnumClass()
return enumtype
A: An Enum class can be a one-liner.
class Enum(tuple): __getattr__ = tuple.index
How to use it (forward and reverse lookup, keys, values, items, etc.)
>>> State = Enum(['Unclaimed', 'Claimed'])
>>> State.Claimed
1
>>> State[1]
'Claimed'
>>> State
('Unclaimed', 'Claimed')
>>> range(len(State))
[0, 1]
>>> [(k, State[k]) for k in range(len(State))]
[(0, 'Unclaimed'), (1, 'Claimed')]
>>> [(k, getattr(State, k)) for k in State]
[('Unclaimed', 0), ('Claimed', 1)]
A: Alexandru's suggestion of using class constants for enums works quite well.
I also like to add a dictionary for each set of constants to lookup a human-readable string representation.
This serves two purposes: a) it provides a simple way to pretty-print your enum and b) the dictionary logically groups the constants so that you can test for membership.
class Animal:
TYPE_DOG = 1
TYPE_CAT = 2
type2str = {
TYPE_DOG: "dog",
TYPE_CAT: "cat"
}
def __init__(self, type_):
assert type_ in self.type2str.keys()
self._type = type_
def __repr__(self):
return "<%s type=%s>" % (
self.__class__.__name__, self.type2str[self._type].upper())
A: So, I agree. Let's not enforce type safety in Python, but I would like to protect myself from silly mistakes. So what do we think about this?
class Animal(object):
values = ['Horse','Dog','Cat']
class __metaclass__(type):
def __getattr__(self, name):
return self.values.index(name)
It keeps me from value-collision in defining my enums.
>>> Animal.Cat
2
There's another handy advantage: really fast reverse lookups:
def name_of(self, i):
return self.values[i]
A: Python doesn't have a built-in equivalent to enum, and other answers have ideas for implementing your own (you may also be interested in the over the top version in the Python cookbook).
However, in situations where an enum would be called for in C, I usually end up just using simple strings: because of the way objects/attributes are implemented, (C)Python is optimized to work very fast with short strings anyway, so there wouldn't really be any performance benefit to using integers. To guard against typos / invalid values you can insert checks in selected places.
ANIMALS = ['cat', 'dog', 'python']
def take_for_a_walk(animal):
assert animal in ANIMALS
...
(One disadvantage compared to using a class is that you lose the benefit of autocomplete)
A: While the original enum proposal, PEP 354, was rejected years ago, it keeps coming back up. Some kind of enum was intended to be added to 3.2, but it got pushed back to 3.3 and then forgotten. And now there's a PEP 435 intended for inclusion in Python 3.4. The reference implementation of PEP 435 is flufl.enum.
As of April 2013, there seems to be a general consensus that something should be added to the standard library in 3.4—as long as people can agree on what that "something" should be. That's the hard part. See the threads starting here and here, and a half dozen other threads in the early months of 2013.
Meanwhile, every time this comes up, a slew of new designs and implementations appear on PyPI, ActiveState, etc., so if you don't like the FLUFL design, try a PyPI search.
A: Here is a nice Python recipe that I found here: http://code.activestate.com/recipes/577024-yet-another-enum-for-python/
def enum(typename, field_names):
"Create a new enumeration type"
if isinstance(field_names, str):
field_names = field_names.replace(',', ' ').split()
d = dict((reversed(nv) for nv in enumerate(field_names)), __slots__ = ())
return type(typename, (object,), d)()
Example Usage:
STATE = enum('STATE', 'GET_QUIZ, GET_VERSE, TEACH')
More details can be found on the recipe page.
A: On 2013-05-10, Guido agreed to accept PEP 435 into the Python 3.4 standard library. This means that Python finally has builtin support for enumerations!
There is a backport available for Python 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4. It's on Pypi as enum34.
Declaration:
>>> from enum import Enum
>>> class Color(Enum):
... red = 1
... green = 2
... blue = 3
Representation:
>>> print(Color.red)
Color.red
>>> print(repr(Color.red))
<Color.red: 1>
Iteration:
>>> for color in Color:
... print(color)
...
Color.red
Color.green
Color.blue
Programmatic access:
>>> Color(1)
Color.red
>>> Color['blue']
Color.blue
For more information, refer to the proposal. Official documentation will probably follow soon.
A: I prefer to define enums in Python like so:
class Animal:
class Dog: pass
class Cat: pass
x = Animal.Dog
It's more bug-proof than using integers since you don't have to worry about ensuring that the integers are unique (e.g. if you said Dog = 1 and Cat = 1 you'd be screwed).
It's more bug-proof than using strings since you don't have to worry about typos (e.g.
x == "catt" fails silently, but x == Animal.Catt is a runtime exception).
ADDENDUM :
You can even enhance this solution by having Dog and Cat inherit from a symbol class with the right metaclass :
class SymbolClass(type):
def __repr__(self): return self.__qualname__
def __str__(self): return self.__name__
class Symbol(metaclass=SymbolClass): pass
class Animal:
class Dog(Symbol): pass
class Cat(Symbol): pass
Then, if you use those values to e.g. index a dictionary, Requesting it's representation will make them appear nicely:
>>> mydict = {Animal.Dog: 'Wan Wan', Animal.Cat: 'Nyaa'}
>>> mydict
{Animal.Dog: 'Wan Wan', Animal.Cat: 'Nyaa'}
A: It's funny, I just had a need for this the other day and I couldnt find an implementation worth using... so I wrote my own:
import functools
class EnumValue(object):
def __init__(self,name,value,type):
self.__value=value
self.__name=name
self.Type=type
def __str__(self):
return self.__name
def __repr__(self):#2.6 only... so change to what ever you need...
return '{cls}({0!r},{1!r},{2})'.format(self.__name,self.__value,self.Type.__name__,cls=type(self).__name__)
def __hash__(self):
return hash(self.__value)
def __nonzero__(self):
return bool(self.__value)
def __cmp__(self,other):
if isinstance(other,EnumValue):
return cmp(self.__value,other.__value)
else:
return cmp(self.__value,other)#hopefully their the same type... but who cares?
def __or__(self,other):
if other is None:
return self
elif type(self) is not type(other):
raise TypeError()
return EnumValue('{0.Name} | {1.Name}'.format(self,other),self.Value|other.Value,self.Type)
def __and__(self,other):
if other is None:
return self
elif type(self) is not type(other):
raise TypeError()
return EnumValue('{0.Name} & {1.Name}'.format(self,other),self.Value&other.Value,self.Type)
def __contains__(self,other):
if self.Value==other.Value:
return True
return bool(self&other)
def __invert__(self):
enumerables=self.Type.__enumerables__
return functools.reduce(EnumValue.__or__,(enum for enum in enumerables.itervalues() if enum not in self))
@property
def Name(self):
return self.__name
@property
def Value(self):
return self.__value
class EnumMeta(type):
@staticmethod
def __addToReverseLookup(rev,value,newKeys,nextIter,force=True):
if value in rev:
forced,items=rev.get(value,(force,()) )
if forced and force: #value was forced, so just append
rev[value]=(True,items+newKeys)
elif not forced:#move it to a new spot
next=nextIter.next()
EnumMeta.__addToReverseLookup(rev,next,items,nextIter,False)
rev[value]=(force,newKeys)
else: #not forcing this value
next = nextIter.next()
EnumMeta.__addToReverseLookup(rev,next,newKeys,nextIter,False)
rev[value]=(force,newKeys)
else:#set it and forget it
rev[value]=(force,newKeys)
return value
def __init__(cls,name,bases,atts):
classVars=vars(cls)
enums = classVars.get('__enumerables__',None)
nextIter = getattr(cls,'__nextitr__',itertools.count)()
reverseLookup={}
values={}
if enums is not None:
#build reverse lookup
for item in enums:
if isinstance(item,(tuple,list)):
items=list(item)
value=items.pop()
EnumMeta.__addToReverseLookup(reverseLookup,value,tuple(map(str,items)),nextIter)
else:
value=nextIter.next()
value=EnumMeta.__addToReverseLookup(reverseLookup,value,(str(item),),nextIter,False)#add it to the reverse lookup, but don't force it to that value
#build values and clean up reverse lookup
for value,fkeys in reverseLookup.iteritems():
f,keys=fkeys
for key in keys:
enum=EnumValue(key,value,cls)
setattr(cls,key,enum)
values[key]=enum
reverseLookup[value]=tuple(val for val in values.itervalues() if val.Value == value)
setattr(cls,'__reverseLookup__',reverseLookup)
setattr(cls,'__enumerables__',values)
setattr(cls,'_Max',max([key for key in reverseLookup] or [0]))
return super(EnumMeta,cls).__init__(name,bases,atts)
def __iter__(cls):
for enum in cls.__enumerables__.itervalues():
yield enum
def GetEnumByName(cls,name):
return cls.__enumerables__.get(name,None)
def GetEnumByValue(cls,value):
return cls.__reverseLookup__.get(value,(None,))[0]
class Enum(object):
__metaclass__=EnumMeta
__enumerables__=None
class FlagEnum(Enum):
@staticmethod
def __nextitr__():
yield 0
for val in itertools.count():
yield 2**val
def enum(name,*args):
return EnumMeta(name,(Enum,),dict(__enumerables__=args))
Take it or leave it, it did what I needed it to do :)
Use it like:
class Air(FlagEnum):
__enumerables__=('None','Oxygen','Nitrogen','Hydrogen')
class Mammals(Enum):
__enumerables__=('Bat','Whale',('Dog','Puppy',1),'Cat')
Bool = enum('Bool','Yes',('No',0))
A: Use the following.
TYPE = {'EAN13': u'EAN-13',
'CODE39': u'Code 39',
'CODE128': u'Code 128',
'i25': u'Interleaved 2 of 5',}
>>> TYPE.items()
[('EAN13', u'EAN-13'), ('i25', u'Interleaved 2 of 5'), ('CODE39', u'Code 39'), ('CODE128', u'Code 128')]
>>> TYPE.keys()
['EAN13', 'i25', 'CODE39', 'CODE128']
>>> TYPE.values()
[u'EAN-13', u'Interleaved 2 of 5', u'Code 39', u'Code 128']
I used that for Django model choices, and it looks very pythonic. It is not really an Enum, but it does the job.
A: Here is a variant on Alec Thomas's solution:
def enum(*args, **kwargs):
return type('Enum', (), dict((y, x) for x, y in enumerate(args), **kwargs))
x = enum('POOH', 'TIGGER', 'EEYORE', 'ROO', 'PIGLET', 'RABBIT', 'OWL')
assert x.POOH == 0
assert x.TIGGER == 1
A: This solution is a simple way of getting a class for the enumeration defined as a list (no more annoying integer assignments):
enumeration.py:
import new
def create(class_name, names):
return new.classobj(
class_name, (object,), dict((y, x) for x, y in enumerate(names))
)
example.py:
import enumeration
Colors = enumeration.create('Colors', (
'red',
'orange',
'yellow',
'green',
'blue',
'violet',
))
A: Didn't see this one in the list of answers, here is the one I whipped up. It allows the use of 'in' keyword and len() method:
class EnumTypeError(TypeError):
pass
class Enum(object):
"""
Minics enum type from different languages
Usage:
Letters = Enum(list('abc'))
a = Letters.a
print(a in Letters) # True
print(54 in Letters) # False
"""
def __init__(self, enums):
if isinstance(enums, dict):
self.__dict__.update(enums)
elif isinstance(enums, list) or isinstance(enums, tuple):
self.__dict__.update(**dict((v,k) for k,v in enumerate(enums)))
else:
raise EnumTypeError
def __contains__(self, key):
return key in self.__dict__.values()
def __len__(self):
return len(self.__dict__.values())
if __name__ == '__main__':
print('Using a dictionary to create Enum:')
Letters = Enum(dict((v,k) for k,v in enumerate(list('abcde'))))
a = Letters.a
print('\tIs a in e?', a in Letters)
print('\tIs 54 in e?', 54 in Letters)
print('\tLength of Letters enum:', len(Letters))
print('\nUsing a list to create Enum:')
Letters = Enum(list('abcde'))
a = Letters.a
print('\tIs a in e?', a in Letters)
print('\tIs 54 in e?', 54 in Letters)
print('\tLength of Letters enum:', len(Letters))
try:
# make sure we raise an exception if we pass an invalid arg
Failure = Enum('This is a Failure')
print('Failure')
except EnumTypeError:
print('Success!')
Output:
Using a dictionary to create Enum:
Is a in e? True
Is 54 in e? False
Length of Letters enum: 5
Using a list to create Enum:
Is a in e? True
Is 54 in e? False
Length of Letters enum: 5
Success!
A: def M_add_class_attribs(attribs):
def foo(name, bases, dict_):
for v, k in attribs:
dict_[k] = v
return type(name, bases, dict_)
return foo
def enum(*names):
class Foo(object):
__metaclass__ = M_add_class_attribs(enumerate(names))
def __setattr__(self, name, value): # this makes it read-only
raise NotImplementedError
return Foo()
Use it like this:
Animal = enum('DOG', 'CAT')
Animal.DOG # returns 0
Animal.CAT # returns 1
Animal.DOG = 2 # raises NotImplementedError
if you just want unique symbols and don't care about the values, replace this line:
__metaclass__ = M_add_class_attribs(enumerate(names))
with this:
__metaclass__ = M_add_class_attribs((object(), name) for name in names)
A: Here is one implementation:
class Enum(set):
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
Here is its usage:
Animals = Enum(["DOG", "CAT", "HORSE"])
print(Animals.DOG)
A: Another, very simple, implementation of an enum in Python, using namedtuple:
from collections import namedtuple
def enum(*keys):
return namedtuple('Enum', keys)(*keys)
MyEnum = enum('FOO', 'BAR', 'BAZ')
or, alternatively,
# With sequential number values
def enum(*keys):
return namedtuple('Enum', keys)(*range(len(keys)))
# From a dict / keyword args
def enum(**kwargs):
return namedtuple('Enum', kwargs.keys())(*kwargs.values())
# Example for dictionary param:
values = {"Salad": 20, "Carrot": 99, "Tomato": "No i'm not"}
Vegetables= enum(**values)
# >>> print(Vegetables.Tomato) 'No i'm not'
# Example for keyworded params:
Fruits = enum(Apple="Steve Jobs", Peach=1, Banana=2)
# >>> print(Fruits.Apple) 'Steve Jobs'
Like the method above that subclasses set, this allows:
'FOO' in MyEnum
other = MyEnum.FOO
assert other == MyEnum.FOO
But has more flexibility as it can have different keys and values. This allows
MyEnum.FOO < MyEnum.BAR
to act as is expected if you use the version that fills in sequential number values.
A: From Python 3.4 there is official support for enums. You can find documentation and examples here on Python 3.4 documentation page.
Enumerations are created using the class syntax, which makes them easy
to read and write. An alternative creation method is described in
Functional API. To define an enumeration, subclass Enum as follows:
from enum import Enum
class Color(Enum):
red = 1
green = 2
blue = 3
A: Keep it simple, using old Python 2.x (see below for Python 3!):
class Enum(object):
def __init__(self, tupleList):
self.tupleList = tupleList
def __getattr__(self, name):
return self.tupleList.index(name)
Then:
DIRECTION = Enum(('UP', 'DOWN', 'LEFT', 'RIGHT'))
DIRECTION.DOWN
1
Keep it simple when using Python 3:
from enum import Enum
class MyEnum(Enum):
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
Then:
MyEnum.DOWN
See: https://docs.python.org/3/library/enum.html
A: I had need of some symbolic constants in pyparsing to represent left and right associativity of binary operators. I used class constants like this:
# an internal class, not intended to be seen by client code
class _Constants(object):
pass
# an enumeration of constants for operator associativity
opAssoc = _Constants()
opAssoc.LEFT = object()
opAssoc.RIGHT = object()
Now when client code wants to use these constants, they can import the entire enum using:
import opAssoc from pyparsing
The enumerations are unique, they can be tested with 'is' instead of '==', they don't take up a big footprint in my code for a minor concept, and they are easily imported into the client code. They don't support any fancy str() behavior, but so far that is in the YAGNI category.
A: Why must enumerations be ints? Unfortunately, I can't think of any good looking construct to produce this without changing the Python language, so I'll use strings:
class Enumerator(object):
def __init__(self, name):
self.name = name
def __eq__(self, other):
if self.name == other:
return True
return self is other
def __ne__(self, other):
if self.name != other:
return False
return self is other
def __repr__(self):
return 'Enumerator({0})'.format(self.name)
def __str__(self):
return self.name
class Enum(object):
def __init__(self, *enumerators):
for e in enumerators:
setattr(self, e, Enumerator(e))
def __getitem__(self, key):
return getattr(self, key)
Then again maybe it's even better now that we can naturally test against strings, for the sake of configuration files or other remote input.
Example:
class Cow(object):
State = Enum(
'standing',
'walking',
'eating',
'mooing',
'sleeping',
'dead',
'dying'
)
state = State.standing
In [1]: from enum import Enum
In [2]: c = Cow()
In [3]: c2 = Cow()
In [4]: c.state, c2.state
Out[4]: (Enumerator(standing), Enumerator(standing))
In [5]: c.state == c2.state
Out[5]: True
In [6]: c.State.mooing
Out[6]: Enumerator(mooing)
In [7]: c.State['mooing']
Out[7]: Enumerator(mooing)
In [8]: c.state = Cow.State.dead
In [9]: c.state == c2.state
Out[9]: False
In [10]: c.state == Cow.State.dead
Out[10]: True
In [11]: c.state == 'dead'
Out[11]: True
In [12]: c.state == Cow.State['dead']
Out[11]: True
A: A variant (with support to get an enum value's name) to Alec Thomas's neat answer:
class EnumBase(type):
def __init__(self, name, base, fields):
super(EnumBase, self).__init__(name, base, fields)
self.__mapping = dict((v, k) for k, v in fields.iteritems())
def __getitem__(self, val):
return self.__mapping[val]
def enum(*seq, **named):
enums = dict(zip(seq, range(len(seq))), **named)
return EnumBase('Enum', (), enums)
Numbers = enum(ONE=1, TWO=2, THREE='three')
print Numbers.TWO
print Numbers[Numbers.ONE]
print Numbers[2]
print Numbers['three']
A: I like to use lists or sets as enumerations. For example:
>>> packet_types = ['INIT', 'FINI', 'RECV', 'SEND']
>>> packet_types.index('INIT')
0
>>> packet_types.index('FINI')
1
>>>
A: Enums have been added to Python 3.4 as described in PEP 435. It has also been backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4 on pypi.
For more advanced Enum techniques try the aenum library (2.7, 3.3+, same author as enum34. Code is not perfectly compatible between py2 and py3, e.g. you'll need __order__ in python 2).
*
*To use enum34, do $ pip install enum34
*To use aenum, do $ pip install aenum
Installing enum (no numbers) will install a completely different and incompatible version.
from enum import Enum # for enum34, or the stdlib version
# from aenum import Enum # for the aenum version
Animal = Enum('Animal', 'ant bee cat dog')
Animal.ant # returns <Animal.ant: 1>
Animal['ant'] # returns <Animal.ant: 1> (string lookup)
Animal.ant.name # returns 'ant' (inverse lookup)
or equivalently:
class Animal(Enum):
ant = 1
bee = 2
cat = 3
dog = 4
In earlier versions, one way of accomplishing enums is:
def enum(**enums):
return type('Enum', (), enums)
which is used like so:
>>> Numbers = enum(ONE=1, TWO=2, THREE='three')
>>> Numbers.ONE
1
>>> Numbers.TWO
2
>>> Numbers.THREE
'three'
You can also easily support automatic enumeration with something like this:
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
and used like so:
>>> Numbers = enum('ZERO', 'ONE', 'TWO')
>>> Numbers.ZERO
0
>>> Numbers.ONE
1
Support for converting the values back to names can be added this way:
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
reverse = dict((value, key) for key, value in enums.iteritems())
enums['reverse_mapping'] = reverse
return type('Enum', (), enums)
This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw a KeyError if the reverse mapping doesn't exist. With the first example:
>>> Numbers.reverse_mapping['three']
'THREE'
If you are using MyPy another way to express "enums" is with typing.Literal.
For example:
from typing import Literal #python >=3.8
from typing_extensions import Literal #python 2.7, 3.4-3.7
Animal = Literal['ant', 'bee', 'cat', 'dog']
def hello_animal(animal: Animal):
print(f"hello {animal}")
hello_animal('rock') # error
hello_animal('bee') # passes
A: Hmmm... I suppose the closest thing to an enum would be a dictionary, defined either like this:
months = {
'January': 1,
'February': 2,
...
}
or
months = dict(
January=1,
February=2,
...
)
Then, you can use the symbolic name for the constants like this:
mymonth = months['January']
There are other options, like a list of tuples, or a tuple of tuples, but the dictionary is the only one that provides you with a "symbolic" (constant string) way to access the
value.
Edit: I like Alexandru's answer too!
A: If you need the numeric values, here's the quickest way:
dog, cat, rabbit = range(3)
In Python 3.x you can also add a starred placeholder at the end, which will soak up all the remaining values of the range in case you don't mind wasting memory and cannot count:
dog, cat, rabbit, horse, *_ = range(100)
A: What I use:
class Enum(object):
def __init__(self, names, separator=None):
self.names = names.split(separator)
for value, name in enumerate(self.names):
setattr(self, name.upper(), value)
def tuples(self):
return tuple(enumerate(self.names))
How to use:
>>> state = Enum('draft published retracted')
>>> state.DRAFT
0
>>> state.RETRACTED
2
>>> state.FOO
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Enum' object has no attribute 'FOO'
>>> state.tuples()
((0, 'draft'), (1, 'published'), (2, 'retracted'))
So this gives you integer constants like state.PUBLISHED and the two-tuples to use as choices in Django models.
A: The standard in Python is PEP 435, so an Enum class is available in Python 3.4+:
>>> from enum import Enum
>>> class Colors(Enum):
... red = 1
... green = 2
... blue = 3
>>> for color in Colors: print color
Colors.red
Colors.green
Colors.blue
A: Following the Java like enum implementation proposed by Aaron Maenpaa, I came out with the following. The idea was to make it generic and parseable.
class Enum:
#'''
#Java like implementation for enums.
#
#Usage:
#class Tool(Enum): name = 'Tool'
#Tool.DRILL = Tool.register('drill')
#Tool.HAMMER = Tool.register('hammer')
#Tool.WRENCH = Tool.register('wrench')
#'''
name = 'Enum' # Enum name
_reg = dict([]) # Enum registered values
@classmethod
def register(cls, value):
#'''
#Registers a new value in this enum.
#
#@param value: New enum value.
#
#@return: New value wrapper instance.
#'''
inst = cls(value)
cls._reg[value] = inst
return inst
@classmethod
def parse(cls, value):
#'''
#Parses a value, returning the enum instance.
#
#@param value: Enum value.
#
#@return: Value corresp instance.
#'''
return cls._reg.get(value)
def __init__(self, value):
#'''
#Constructor (only for internal use).
#'''
self.value = value
def __str__(self):
#'''
#str() overload.
#'''
return self.value
def __repr__(self):
#'''
#repr() overload.
#'''
return "<" + self.name + ": " + self.value + ">"
A: I like the Java enum, that's how I do it in Python:
def enum(clsdef):
class Enum(object):
__slots__=tuple([var for var in clsdef.__dict__ if isinstance((getattr(clsdef, var)), tuple) and not var.startswith('__')])
def __new__(cls, *args, **kwargs):
if not '_the_instance' in cls.__dict__:
cls._the_instance = object.__new__(cls, *args, **kwargs)
return cls._the_instance
def __init__(self):
clsdef.values=lambda cls, e=Enum: e.values()
clsdef.valueOf=lambda cls, n, e=self: e.valueOf(n)
for ordinal, key in enumerate(self.__class__.__slots__):
args=getattr(clsdef, key)
instance=clsdef(*args)
instance._name=key
instance._ordinal=ordinal
setattr(self, key, instance)
@classmethod
def values(cls):
if not hasattr(cls, '_values'):
cls._values=[getattr(cls, name) for name in cls.__slots__]
return cls._values
def valueOf(self, name):
return getattr(self, name)
def __repr__(self):
return ''.join(['<class Enum (', clsdef.__name__, ') at ', str(hex(id(self))), '>'])
return Enum()
Sample use:
i=2
@enum
class Test(object):
A=("a",1)
B=("b",)
C=("c",2)
D=tuple()
E=("e",3)
while True:
try:
F, G, H, I, J, K, L, M, N, O=[tuple() for _ in range(i)]
break;
except ValueError:
i+=1
def __init__(self, name="default", aparam=0):
self.name=name
self.avalue=aparam
All class variables are defined as a tuple, just like the constructor. So far, you can't use named arguments.
A: I use a metaclass to implement an enumeration (in my thought, it is a const). Here is the code:
class ConstMeta(type):
'''
Metaclass for some class that store constants
'''
def __init__(cls, name, bases, dct):
'''
init class instance
'''
def static_attrs():
'''
@rtype: (static_attrs, static_val_set)
@return: Static attributes in dict format and static value set
'''
import types
attrs = {}
val_set = set()
#Maybe more
filter_names = set(['__doc__', '__init__', '__metaclass__', '__module__', '__main__'])
for key, value in dct.iteritems():
if type(value) != types.FunctionType and key not in filter_names:
if len(value) != 2:
raise NotImplementedError('not support for values that is not 2 elements!')
#Check value[0] duplication.
if value[0] not in val_set:
val_set.add(value[0])
else:
raise KeyError("%s 's key: %s is duplicated!" % (dict([(key, value)]), value[0]))
attrs[key] = value
return attrs, val_set
attrs, val_set = static_attrs()
#Set STATIC_ATTRS to class instance so that can reuse
setattr(cls, 'STATIC_ATTRS', attrs)
setattr(cls, 'static_val_set', val_set)
super(ConstMeta, cls).__init__(name, bases, dct)
def __getattribute__(cls, name):
'''
Rewrite the special function so as to get correct attribute value
'''
static_attrs = object.__getattribute__(cls, 'STATIC_ATTRS')
if name in static_attrs:
return static_attrs[name][0]
return object.__getattribute__(cls, name)
def static_values(cls):
'''
Put values in static attribute into a list, use the function to validate value.
@return: Set of values
'''
return cls.static_val_set
def __getitem__(cls, key):
'''
Rewrite to make syntax SomeConstClass[key] works, and return desc string of related static value.
@return: Desc string of related static value
'''
for k, v in cls.STATIC_ATTRS.iteritems():
if v[0] == key:
return v[1]
raise KeyError('Key: %s does not exists in %s !' % (str(key), repr(cls)))
class Const(object):
'''
Base class for constant class.
@usage:
Definition: (must inherit from Const class!
>>> class SomeConst(Const):
>>> STATUS_NAME_1 = (1, 'desc for the status1')
>>> STATUS_NAME_2 = (2, 'desc for the status2')
Invoke(base upper SomeConst class):
1) SomeConst.STATUS_NAME_1 returns 1
2) SomeConst[1] returns 'desc for the status1'
3) SomeConst.STATIC_ATTRS returns {'STATUS_NAME_1': (1, 'desc for the status1'), 'STATUS_NAME_2': (2, 'desc for the status2')}
4) SomeConst.static_values() returns set([1, 2])
Attention:
SomeCosnt's value 1, 2 can not be duplicated!
If WrongConst is like this, it will raise KeyError:
class WrongConst(Const):
STATUS_NAME_1 = (1, 'desc for the status1')
STATUS_NAME_2 = (1, 'desc for the status2')
'''
__metaclass__ = ConstMeta
##################################################################
#Const Base Class ends
##################################################################
def main():
class STATUS(Const):
ERROR = (-3, '??')
OK = (0, '??')
print STATUS.ERROR
print STATUS.static_values()
print STATUS.STATIC_ATTRS
#Usage sample:
user_input = 1
#Validate input:
print user_input in STATUS.static_values()
#Template render like:
print '<select>'
for key, value in STATUS.STATIC_ATTRS.items():
print '<option value="%s">%s</option>' % (value[0], value[1])
print '</select>'
if __name__ == '__main__':
main()
A: The solution that I usually use is this simple function to get an instance of a dynamically created class.
def enum(names):
"Create a simple enumeration having similarities to C."
return type('enum', (), dict(map(reversed, enumerate(
names.replace(',', ' ').split())), __slots__=()))()
Using it is as simple as calling the function with a string having the names that you want to reference.
grade = enum('A B C D F')
state = enum('awake, sleeping, dead')
The values are just integers, so you can take advantage of that if desired (just like in the C language).
>>> grade.A
0
>>> grade.B
1
>>> grade.F == 4
True
>>> state.dead == 2
True
A: Python 2.7 and find_name()
Here is an easy-to-read implementation of the chosen idea with some helper methods, which perhaps are more Pythonic and cleaner to use than "reverse_mapping". Requires Python >= 2.7.
To address some comments below, Enums are quite useful to prevent spelling mistakes in code, e.g. for state machines, error classifiers, etc.
def Enum(*sequential, **named):
"""Generate a new enum type. Usage example:
ErrorClass = Enum('STOP','GO')
print ErrorClass.find_name(ErrorClass.STOP)
= "STOP"
print ErrorClass.find_val("STOP")
= 0
ErrorClass.FOO # Raises AttributeError
"""
enums = { v:k for k,v in enumerate(sequential) } if not named else named
@classmethod
def find_name(cls, val):
result = [ k for k,v in cls.__dict__.iteritems() if v == val ]
if not len(result):
raise ValueError("Value %s not found in Enum" % val)
return result[0]
@classmethod
def find_val(cls, n):
return getattr(cls, n)
enums['find_val'] = find_val
enums['find_name'] = find_name
return type('Enum', (), enums)
A: davidg recommends using dicts. I'd go one step further and use sets:
months = set('January', 'February', ..., 'December')
Now you can test whether a value matches one of the values in the set like this:
if m in months:
like dF, though, I usually just use string constants in place of enums.
A: This is the best one I have seen: "First Class Enums in Python"
http://code.activestate.com/recipes/413486/
It gives you a class, and the class contains all the enums. The enums can be compared to each other, but don't have any particular value; you can't use them as an integer value. (I resisted this at first because I am used to C enums, which are integer values. But if you can't use it as an integer, you can't use it as an integer by mistake so overall I think it is a win.) Each enum is a unique value. You can print enums, you can iterate over them, you can test that an enum value is "in" the enum. It's pretty complete and slick.
Edit (cfi): The above link is not Python 3 compatible. Here's my port of enum.py to Python 3:
def cmp(a,b):
if a < b: return -1
if b < a: return 1
return 0
def Enum(*names):
##assert names, "Empty enums are not supported" # <- Don't like empty enums? Uncomment!
class EnumClass(object):
__slots__ = names
def __iter__(self): return iter(constants)
def __len__(self): return len(constants)
def __getitem__(self, i): return constants[i]
def __repr__(self): return 'Enum' + str(names)
def __str__(self): return 'enum ' + str(constants)
class EnumValue(object):
__slots__ = ('__value')
def __init__(self, value): self.__value = value
Value = property(lambda self: self.__value)
EnumType = property(lambda self: EnumType)
def __hash__(self): return hash(self.__value)
def __cmp__(self, other):
# C fans might want to remove the following assertion
# to make all enums comparable by ordinal value {;))
assert self.EnumType is other.EnumType, "Only values from the same enum are comparable"
return cmp(self.__value, other.__value)
def __lt__(self, other): return self.__cmp__(other) < 0
def __eq__(self, other): return self.__cmp__(other) == 0
def __invert__(self): return constants[maximum - self.__value]
def __nonzero__(self): return bool(self.__value)
def __repr__(self): return str(names[self.__value])
maximum = len(names) - 1
constants = [None] * len(names)
for i, each in enumerate(names):
val = EnumValue(i)
setattr(EnumClass, each, val)
constants[i] = val
constants = tuple(constants)
EnumType = EnumClass()
return EnumType
if __name__ == '__main__':
print( '\n*** Enum Demo ***')
print( '--- Days of week ---')
Days = Enum('Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su')
print( Days)
print( Days.Mo)
print( Days.Fr)
print( Days.Mo < Days.Fr)
print( list(Days))
for each in Days:
print( 'Day:', each)
print( '--- Yes/No ---')
Confirmation = Enum('No', 'Yes')
answer = Confirmation.No
print( 'Your answer is not', ~answer)
A: I have had occasion to need of an Enum class, for the purpose of decoding a binary file format. The features I happened to want is concise enum definition, the ability to freely create instances of the enum by either integer value or string, and a useful representation. Here's what I ended up with:
>>> class Enum(int):
... def __new__(cls, value):
... if isinstance(value, str):
... return getattr(cls, value)
... elif isinstance(value, int):
... return cls.__index[value]
... def __str__(self): return self.__name
... def __repr__(self): return "%s.%s" % (type(self).__name__, self.__name)
... class __metaclass__(type):
... def __new__(mcls, name, bases, attrs):
... attrs['__slots__'] = ['_Enum__name']
... cls = type.__new__(mcls, name, bases, attrs)
... cls._Enum__index = _index = {}
... for base in reversed(bases):
... if hasattr(base, '_Enum__index'):
... _index.update(base._Enum__index)
... # create all of the instances of the new class
... for attr in attrs.keys():
... value = attrs[attr]
... if isinstance(value, int):
... evalue = int.__new__(cls, value)
... evalue._Enum__name = attr
... _index[value] = evalue
... setattr(cls, attr, evalue)
... return cls
...
A whimsical example of using it:
>>> class Citrus(Enum):
... Lemon = 1
... Lime = 2
...
>>> Citrus.Lemon
Citrus.Lemon
>>>
>>> Citrus(1)
Citrus.Lemon
>>> Citrus(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in __new__
KeyError: 5
>>> class Fruit(Citrus):
... Apple = 3
... Banana = 4
...
>>> Fruit.Apple
Fruit.Apple
>>> Fruit.Lemon
Citrus.Lemon
>>> Fruit(1)
Citrus.Lemon
>>> Fruit(3)
Fruit.Apple
>>> "%d %s %r" % ((Fruit.Apple,)*3)
'3 Apple Fruit.Apple'
>>> Fruit(1) is Citrus.Lemon
True
Key features:
*
*str(), int() and repr() all produce the most useful output possible, respectively the name of the enumartion, its integer value, and a Python expression that evaluates back to the enumeration.
*Enumerated values returned by the constructor are limited strictly to the predefined values, no accidental enum values.
*Enumerated values are singletons; they can be strictly compared with is
A: The best solution for you would depend on what you require from your fake enum.
Simple enum:
If you need the enum as only a list of names identifying different items, the solution by Mark Harrison (above) is great:
Pen, Pencil, Eraser = range(0, 3)
Using a range also allows you to set any starting value:
Pen, Pencil, Eraser = range(9, 12)
In addition to the above, if you also require that the items belong to a container of some sort, then embed them in a class:
class Stationery:
Pen, Pencil, Eraser = range(0, 3)
To use the enum item, you would now need to use the container name and the item name:
stype = Stationery.Pen
Complex enum:
For long lists of enum or more complicated uses of enum, these solutions will not suffice. You could look to the recipe by Will Ware for Simulating Enumerations in Python published in the Python Cookbook. An online version of that is available here.
More info:
PEP 354: Enumerations in Python has the interesting details of a proposal for enum in Python and why it was rejected.
A: For old Python 2.x
def enum(*sequential, **named):
enums = dict(zip(sequential, [object() for _ in range(len(sequential))]), **named)
return type('Enum', (), enums)
If you name it, is your problem, but if not creating objects instead of values allows you to do this:
>>> DOG = enum('BARK', 'WALK', 'SIT')
>>> CAT = enum('MEOW', 'WALK', 'SIT')
>>> DOG.WALK == CAT.WALK
False
When using other implementations sited here (also when using named instances in my example) you must be sure you never try to compare objects from different enums. For here's a possible pitfall:
>>> DOG = enum('BARK'=1, 'WALK'=2, 'SIT'=3)
>>> CAT = enum('WALK'=1, 'SIT'=2)
>>> pet1_state = DOG.BARK
>>> pet2_state = CAT.WALK
>>> pet1_state == pet2_state
True
Yikes!
A: I really like Alec Thomas' solution (http://stackoverflow.com/a/1695250):
def enum(**enums):
'''simple constant "enums"'''
return type('Enum', (object,), enums)
It's elegant and clean looking, but it's just a function that creates a class with the specified attributes.
With a little modification to the function, we can get it to act a little more 'enumy':
NOTE: I created the following examples by trying to reproduce the
behavior of pygtk's new style 'enums' (like Gtk.MessageType.WARNING)
def enum_base(t, **enums):
'''enums with a base class'''
T = type('Enum', (t,), {})
for key,val in enums.items():
setattr(T, key, T(val))
return T
This creates an enum based off a specified type. In addition to giving attribute access like the previous function, it behaves as you would expect an Enum to with respect to types. It also inherits the base class.
For example, integer enums:
>>> Numbers = enum_base(int, ONE=1, TWO=2, THREE=3)
>>> Numbers.ONE
1
>>> x = Numbers.TWO
>>> 10 + x
12
>>> type(Numbers)
<type 'type'>
>>> type(Numbers.ONE)
<class 'Enum'>
>>> isinstance(x, Numbers)
True
Another interesting thing that can be done with this method is customize specific behavior by overriding built-in methods:
def enum_repr(t, **enums):
'''enums with a base class and repr() output'''
class Enum(t):
def __repr__(self):
return '<enum {0} of type Enum({1})>'.format(self._name, t.__name__)
for key,val in enums.items():
i = Enum(val)
i._name = key
setattr(Enum, key, i)
return Enum
>>> Numbers = enum_repr(int, ONE=1, TWO=2, THREE=3)
>>> repr(Numbers.ONE)
'<enum ONE of type Enum(int)>'
>>> str(Numbers.ONE)
'1'
A: def enum( *names ):
'''
Makes enum.
Usage:
E = enum( 'YOUR', 'KEYS', 'HERE' )
print( E.HERE )
'''
class Enum():
pass
for index, name in enumerate( names ):
setattr( Enum, name, index )
return Enum
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1141"
} |
Q: How do I use ADAM to run unit tests? I writing a web site that uses Active Directory to validate users. I don't have access to an Active Directory instance that I can edit in any way.
I've heard that some people are using Active Directory Application Mode (ADAM) to create AD data to be used in Unit and Integration Testing.
Has anyone else done this? Are the any good site/blog that tells how to do this? What are the issues? Is this even a good idea?
A: I don't think this is a good idea just like reading files or accessing the database in unit tests isn't a good idea. Your tests will become dependent on the state of an external piece of software. Or you will have a lot of setup and teardown code. If you write tests this way you can expect you'll spend a lot of extra time maintaining your test-code. Setting up and maintaining a build server will become harder too and setting up the development environment for new programmers will take more time.
The way to go in cases like this is to set up an adapter class around the infrastructure for calling into AD and to use something like rhino-mocks or another mocking framework to setup a mock-active-directory in your tests. If you're not familiar with mocking it sounds like a lot of work. But in practice it's usually only a couple of lines of code per test.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Resources for lexing, tokenising and parsing in python Can people point me to resources on lexing, parsing and tokenising with Python?
I'm doing a little hacking on an open source project (hotwire) and wanted to do a few changes to the code that lexes, parses and tokenises the commands entered into it. As it is real working code it is fairly complex and a bit hard to work out.
I haven't worked on code to lex/parse/tokenise before, so I was thinking one approach would be to work through a tutorial or two on this aspect. I would hope to learn enough to navigate around the code I actually want to alter. Is there anything suitable out there? (Ideally it could be done in an afternoon without having to buy and read the dragon book first ...)
Edit: (7 Oct 2008) None of the below answers quite give what I want. With them I could generate parsers from scratch, but I want to learn how to write my own basic parser from scratch, not using lex and yacc or similar tools. Having done that I can then understand the existing code better.
So could someone point me to a tutorial where I can build a basic parser from scratch, using just python?
A: pygments is a source code syntax highlighter written in python. It has lexers and formatters, and may be interesting to peek at the source.
A: Here's a few things to get you started (roughly from simplest-to-most-complex, least-to-most-powerful):
http://en.wikipedia.org/wiki/Recursive_descent_parser
http://en.wikipedia.org/wiki/Top-down_parsing
http://en.wikipedia.org/wiki/LL_parser
http://effbot.org/zone/simple-top-down-parsing.htm
http://en.wikipedia.org/wiki/Bottom-up_parsing
http://en.wikipedia.org/wiki/LR_parser
http://en.wikipedia.org/wiki/GLR_parser
When I learned this stuff, it was in a semester-long 400-level university course. We did a number of assignments where we did parsing by hand; if you want to really understand what's going on under the hood, I'd recommend the same approach.
This isn't the book I used, but it's pretty good: Principles of Compiler Design.
Hopefully that's enough to get you started :)
A: Have a look at the standard module shlex and modify one copy of it to match the syntax you use for your shell, it is a good starting point
If you want all the power of a complete solution for lexing/parsing, ANTLR can generate python too.
A: Frederico Tomassetti had a good (but short) concise write-up to all things related from BNF to binary deciphering on:
*
*lexical,
*parser,
*abstract-syntax tree (AST), and
*Construct/code-generator.
He even mentioned the new Parsing Expression Grammar (PEG).
https://tomassetti.me/parsing-in-python/
A: I'm a happy user of PLY. It is a pure-Python implementation of Lex & Yacc, with lots of small niceties that make it quite Pythonic and easy to use. Since Lex & Yacc are the most popular lexing & parsing tools and are used for the most projects, PLY has the advantage of standing on giants' shoulders. A lot of knowledge exists online on Lex & Yacc, and you can freely apply it to PLY.
PLY also has a good documentation page with some simple examples to get you started.
For a listing of lots of Python parsing tools, see this.
A: This question is pretty old, but maybe my answer would help someone who wants to learn the basics. I find this resource to be very good. It is a simple interpreter written in python without the use of any external libraries. So this will help anyone who would like to understand the internal working of parsing, lexing, and tokenising:
"A Simple Intepreter from Scratch in Python:" Part 1, Part 2,
Part 3, and Part 4.
A: I suggest http://www.canonware.com/Parsing/, since it is pure python and you don't need to learn a grammar, but it isn't widely used, and has comparatively little documentation. The heavyweight is ANTLR and PyParsing. ANTLR can generate java and C++ parsers too, and AST walkers but you will have to learn what amounts to a new language.
A: For medium-complex grammars, PyParsing is brilliant. You can define grammars directly within Python code, no need for code generation:
>>> from pyparsing import Word, alphas
>>> greet = Word( alphas ) + "," + Word( alphas ) + "!" # <-- grammar defined here
>>> hello = "Hello, World!"
>>>> print hello, "->", greet.parseString( hello )
Hello, World! -> ['Hello', ',', 'World', '!']
(Example taken from the PyParsing home page).
With parse actions (functions that are invoked when a certain grammar rule is triggered), you can convert parses directly into abstract syntax trees, or any other representation.
There are many helper functions that encapsulate recurring patterns, like operator hierarchies, quoted strings, nesting or C-style comments.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "65"
} |
Q: Simulating queries of large views for benchmarking purposes A Windows Forms application of ours pulls records from a view on SQL Server through ADO.NET and a SOAP web service, displaying them in a data grid. We have had several cases with ~25,000 rows, which works relatively smoothly, but a potential customer needs to have many times that much in a single list.
To figure out how well we scale right now, and how (and how far) we can realistically improve, I'd like to implement a simulation: instead of displaying actual data, have the SQL Server send fictional, random data. The client and transport side would be mostly the same; the view (or at least the underlying table) would of course work differently. The user specifies the amount of fictional rows (e.g. 100,000).
For the time being, I just want to know how long it takes for the client to retrieve and process the data and is just about ready to display it.
What I'm trying to figure out is this: how do I make the SQL Server send such data?
Do I:
*
*Create a stored procedure that has to be run beforehand to fill an actual table?
*Create a function that I point the view to, thus having the server generate the data 'live'?
*Somehow replicate and/or randomize existing data?
The first option sounds to me like it would yield the results closest to the real world. Because the data is actually 'physically there', the SELECT query would be quite similar performance-wise to one on real data. However, it taxes the server with an otherwise meaningless operation. The fake data would also be backed up, as it would live in one and the same database — unless, of course, I delete the data after each benchmark run.
The second and third option tax the server while running the actual simulation, thus potentially giving unrealistically slow results.
In addition, I'm unsure how to create those rows, short of using a loop or cursor. I can use SELECT top <n> random1(), random2(), […] FROM foo if foo actually happens to have <n> entries, but otherwise I'll (obviously) only get as many rows as foo happens to have. A GROUP BY newid() or similar doesn't appear to do the trick.
A: For data for testing CRM type tables, I highly recommend fakenamegenerator.com, you can get 40,000 fake names for free.
A: You didn't mention if you're using SQL Server 2008. If you use 2008 and you use Data Compression, be aware that random data will act very differently (slower) than real data. Random data is much harder to compress.
Quest Toad for SQL Server and Microsoft Visual Studio Data Dude both have test data generators that will put fake "real" data into records for you.
A: If you want results you can rely on you need to make the testing scenario as realistic as possible, which makes option 1 by far your best bet. As you point out if you get results that aren't good enough with the other options you won't be sure that it wasn't due to the different database behaviour.
How you generate the data will depend to a large degree on the problem domain. Can you take data sets from multiple customers and merge them into a single mega-dataset? If the data is time series then maybe it can be duplicated over a different range.
A: The data is typically CRM-like, i.e. contacts, projects, etc. It would be fine to simply duplicate the data (e.g., if I only have 20,000 rows, I'll copy them five times to get my desired 100,000 rows). Merging, on the other hand, would only work if we never deploy the benchmarking tool publicly, for obvious privacy reasons (unless, of course, I apply a function to each column that renders the original data unintelligible beyond repair? Similar to a hashing function, only without modifying the value's size too much).
To populate the rows, perhaps something like this would do:
WHILE (SELECT count(1) FROM benchmark) < 100000
INSERT INTO benchmark
SELECT TOP 100000 * FROM actualData
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do you use script variables in psql? In MS SQL Server, I create my scripts to use customizable variables:
DECLARE @somevariable int
SELECT @somevariable = -1
INSERT INTO foo VALUES ( @somevariable )
I'll then change the value of @somevariable at runtime, depending on the value that I want in the particular situation. Since it's at the top of the script it's easy to see and remember.
How do I do the same with the PostgreSQL client psql?
A: One final word on PSQL variables:
*
*They don't expand if you enclose them in single quotes in the SQL statement.
Thus this doesn't work:
SELECT * FROM foo WHERE bar = ':myvariable'
*To expand to a string literal in a SQL statement, you have to include the quotes in the variable set. However, the variable value already has to be enclosed in quotes, which means that you need a second set of quotes, and the inner set has to be escaped. Thus you need:
\set myvariable '\'somestring\''
SELECT * FROM foo WHERE bar = :myvariable
EDIT: starting with PostgreSQL 9.1, you may write instead:
\set myvariable somestring
SELECT * FROM foo WHERE bar = :'myvariable'
A: You can try to use a WITH clause.
WITH vars AS (SELECT 42 AS answer, 3.14 AS appr_pi)
SELECT t.*, vars.answer, t.radius*vars.appr_pi
FROM table AS t, vars;
A: I solved it with a temp table.
CREATE TEMP TABLE temp_session_variables (
"sessionSalt" TEXT
);
INSERT INTO temp_session_variables ("sessionSalt") VALUES (current_timestamp || RANDOM()::TEXT);
This way, I had a "variable" I could use over multiple queries, that is unique for the session. I needed it to generate unique "usernames" while still not having collisions if importing users with the same user name.
A: Another approach is to (ab)use the PostgreSQL GUC mechanism to create variables. See this prior answer for details and examples.
You declare the GUC in postgresql.conf, then change its value at runtime with SET commands and get its value with current_setting(...).
I don't recommend this for general use, but it could be useful in narrow cases like the one mentioned in the linked question, where the poster wanted a way to provide the application-level username to triggers and functions.
A: Specifically for psql, you can pass psql variables from the command line too; you can pass them with -v. Here's a usage example:
$ psql -v filepath=/path/to/my/directory/mydatafile.data regress
regress=> SELECT :'filepath';
?column?
---------------------------------------
/path/to/my/directory/mydatafile.data
(1 row)
Note that the colon is unquoted, then the variable name its self is quoted. Odd syntax, I know. This only works in psql; it won't work in (say) PgAdmin-III.
This substitution happens during input processing in psql, so you can't (say) define a function that uses :'filepath' and expect the value of :'filepath' to change from session to session. It'll be substituted once, when the function is defined, and then will be a constant after that. It's useful for scripting but not runtime use.
A: I've found this question and the answers extremely useful, but also confusing. I had lots of trouble getting quoted variables to work, so here is the way I got it working:
\set deployment_user username -- username
\set deployment_pass '\'string_password\''
ALTER USER :deployment_user WITH PASSWORD :deployment_pass;
This way you can define the variable in one statement. When you use it, single quotes will be embedded into the variable.
NOTE! When I put a comment after the quoted variable it got sucked in as part of the variable when I tried some of the methods in other answers. That was really screwing me up for a while. With this method comments appear to be treated as you'd expect.
A: I really miss that feature. Only way to achieve something similar is to use functions.
I have used it in two ways:
*
*perl functions that use $_SHARED variable
*store your variables in table
Perl version:
CREATE FUNCTION var(name text, val text) RETURNS void AS $$
$_SHARED{$_[0]} = $_[1];
$$ LANGUAGE plperl;
CREATE FUNCTION var(name text) RETURNS text AS $$
return $_SHARED{$_[0]};
$$ LANGUAGE plperl;
Table version:
CREATE TABLE var (
sess bigint NOT NULL,
key varchar NOT NULL,
val varchar,
CONSTRAINT var_pkey PRIMARY KEY (sess, key)
);
CREATE FUNCTION var(key varchar, val anyelement) RETURNS void AS $$
DELETE FROM var WHERE sess = pg_backend_pid() AND key = $1;
INSERT INTO var (sess, key, val) VALUES (sessid(), $1, $2::varchar);
$$ LANGUAGE 'sql';
CREATE FUNCTION var(varname varchar) RETURNS varchar AS $$
SELECT val FROM var WHERE sess = pg_backend_pid() AND key = $1;
$$ LANGUAGE 'sql';
Notes:
*
*plperlu is faster than perl
*pg_backend_pid is not best session identification, consider using pid combined with backend_start from pg_stat_activity
*this table version is also bad because you have to clear this is up occasionally (and not delete currently working session variables)
A: Postgres variables are created through the \set command, for example ...
\set myvariable value
... and can then be substituted, for example, as ...
SELECT * FROM :myvariable.table1;
... or ...
SELECT * FROM table1 WHERE :myvariable IS NULL;
edit: As of psql 9.1, variables can be expanded in quotes as in:
\set myvariable value
SELECT * FROM table1 WHERE column1 = :'myvariable';
In older versions of the psql client:
... If you want to use the variable as the value in a conditional string query, such as ...
SELECT * FROM table1 WHERE column1 = ':myvariable';
... then you need to include the quotes in the variable itself as the above will not work. Instead define your variable as such ...
\set myvariable 'value'
However, if, like me, you ran into a situation in which you wanted to make a string from an existing variable, I found the trick to be this ...
\set quoted_myvariable '\'' :myvariable '\''
Now you have both a quoted and unquoted variable of the same string! And you can do something like this ....
INSERT INTO :myvariable.table1 SELECT * FROM table2 WHERE column1 = :quoted_myvariable;
A: Variables in psql suck. If you want to declare an integer, you have to enter the integer, then do a carriage return, then end the statement in a semicolon. Observe:
Let's say I want to declare an integer variable my_var and insert it into a table test:
Example table test:
thedatabase=# \d test;
Table "public.test"
Column | Type | Modifiers
--------+---------+---------------------------------------------------
id | integer | not null default nextval('test_id_seq'::regclass)
Indexes:
"test_pkey" PRIMARY KEY, btree (id)
Clearly, nothing in this table yet:
thedatabase=# select * from test;
id
----
(0 rows)
We declare a variable. Notice how the semicolon is on the next line!
thedatabase=# \set my_var 999
thedatabase=# ;
Now we can insert. We have to use this weird ":''" looking syntax:
thedatabase=# insert into test(id) values (:'my_var');
INSERT 0 1
It worked!
thedatabase=# select * from test;
id
-----
999
(1 row)
Explanation:
So... what happens if we don't have the semicolon on the next line? The variable? Have a look:
We declare my_var without the new line.
thedatabase=# \set my_var 999;
Let's select my_var.
thedatabase=# select :'my_var';
?column?
----------
999;
(1 row)
WTF is that? It's not an integer, it's a string 999;!
thedatabase=# select 999;
?column?
----------
999
(1 row)
A: I've posted a new solution for this on another thread.
It uses a table to store variables, and can be updated at any time. A static immutable getter function is dynamically created (by another function), triggered by update to your table. You get nice table storage, plus the blazing fast speeds of an immutable getter.
A: FWIW, the real problem was that I had included a semicolon at the end of my \set command:
\set owner_password 'thepassword';
The semicolon was interpreted as an actual character in the variable:
\echo :owner_password
thepassword;
So when I tried to use it:
CREATE ROLE myrole LOGIN UNENCRYPTED PASSWORD :owner_password NOINHERIT CREATEDB CREATEROLE VALID UNTIL 'infinity';
...I got this:
CREATE ROLE myrole LOGIN UNENCRYPTED PASSWORD thepassword; NOINHERIT CREATEDB CREATEROLE VALID UNTIL 'infinity';
That not only failed to set the quotes around the literal, but split the command into 2 parts (the second of which was invalid as it started with "NOINHERIT").
The moral of this story: PostgreSQL "variables" are really macros used in text expansion, not true values. I'm sure that comes in handy, but it's tricky at first.
A: postgres (since version 9.0) allows anonymous blocks in any of the supported server-side scripting languages
DO '
DECLARE somevariable int = -1;
BEGIN
INSERT INTO foo VALUES ( somevariable );
END
' ;
http://www.postgresql.org/docs/current/static/sql-do.html
As everything is inside a string, external string variables being substituted in will need to be escaped and quoted twice. Using dollar quoting instead will not give full protection against SQL injection.
A: You need to use one of the procedural languages such as PL/pgSQL not the SQL proc language.
In PL/pgSQL you can use vars right in SQL statements.
For single quotes you can use the quote literal function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "181"
} |
Q: Designing Panels without a parent Form in VS? Are there any tools or plugins to design a Panel independently of a Form (Windows, not Web Form) within Visual Studio?
I've been using the designer and manually extracting the bits I want from the source, but surely there is a nicer way.
A: You could just write the code by hand!
A: You could do all the design work inside of a UserControl.
If you go that route, instead of just copying the bits out of the user control, simply use the user control itself.
A: As Chris Karcher said, you should probably use a user control. This will allow easy, VS-supported/-integrated reuse without having to manually fiddle with designer code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a standard way to return values from custom dialogs in Windows Forms? So right now my project has a few custom dialogs that do things like prompt the user for his birthday, or whatever. Right now they're just doing things like setting a this.Birthday property once they get an answer (which is of type DateTime?, with the null indicating a "Cancel"). Then the caller inspects the Birthday property of the dialog it created to figure out what the user answered.
My question is, is there a more standard pattern for doing stuff like this? I know we can set this.DialogResult for basic OK/Cancel stuff, but is there a more general way in Windows Forms for a form to indicate "here's the data I collected"?
A: I would say exposing properties on your custom dialog is the idiomatic way to go because that is how standard dialogs (like the Select/OpenFileDialog) do it. Someone could argue it is more explicit and intention revealing to have a ShowBirthdayDialog() method that returns the result you're looking for, but following the framework's pattern is probably the wise way to go.
A:
is there a more standard pattern for doing stuff like this?
No, it sounds like you're using the right approach.
If the dialog returns DialogResult.OK, assume that all the necessary properties in the dialog are valid.
A: For me sticking with the Dialog returning the standard dialog responses and then accessing the results via properties is the way to go.
Two good reasons from where I sit:
*
*Consistency - you're always doing the same thing with a dialog and the very nature of the question suggests that patterns are good (-: Although equally the question is whether this is a good pattern?
*It allows for return of multiple values from the dialog - ok there's whole new discussion here too but applied pragmatism means that this is what one wants in some circumstances its not always appropriate or desirable to package values up just so that you can pass them back in all in one go.
The flow of logic is nice too:
if (Dialog == Ok)
{
// Do Stuff with the entered values
}
else
{
// Respond appropriately to the user cancelling the dialog
}
Its a good question - we're supposed to question stuff like this - but for me the current pattern is a decent one.
Murph
A: For modal input dialogs, I typically overload ShowDialog and pass out params for the data I need.
DialogResult ShowDialog(out datetime birthday)
I generally find that it's easier to discover and understand vs mixing my properties with the 100+ that the Form class exposes.
For forms, I normally have a Controller and a IView interface that uses readonly properties to pass data.
A: I've always done it exactly the way you're describing. I'm curious to see if there's a more accepted approach.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Do you have to register a Dialog Box? So, I am a total beginner in any kind of Windows related programming. I have been playing around with the Windows API and came across a couple of examples on how to initialize create windows and such.
One example creates a regular window (I abbreviated some of the code):
int WINAPI WinMain( [...] )
{
[...]
// Windows Class setup
wndClass.cbSize = sizeof( wndClass );
wndClass.style = CS_HREDRAW | CS_VREDRAW;
[...]
// Register class
RegisterClassEx( &wndClass );
// Create window
hWnd = CreateWindow( szAppName, "Win32 App",
WS_OVERLAPPEDWINDOW,
0, 0, 512, 384,
NULL, NULL, hInstance, NULL );
[...]
}
The second example creates a dialog box (no abbreviations except the WinMain arguments):
int WINAPI WinMain( [...] )
{
// Create dialog box
DialogBox(hInstance,
MAKEINTRESOURCE(IDD_MAIN_DLG),
NULL,
(DLGPROC)DialogProc);
}
The second example does not contain any call to the register function. It just creates the DialogBox with its DialogProc process attached.
This works fine, but I am wondering if there is a benefit of registering the window class and then creating the dialog box (if this is at all possible).
A: You do not have to register a dialog box.
Dialog boxes are predefined so (as you noted) there is no reference to a window class when you create a dialog. If you want more control of a dialog (like you get when you create your own window class) you would subclass the dialog which is a method by which you replace the dialogs window procedure with your own. When your procedure is called you modify the behavior of the dialog window; you then might or might not call the original window procedure depending upon what you're trying to do.
A: It's been a while since I've done this, but IIRC, the first case is for creating a dialog dynamically, from an in-memory template. The second example is for the far more common case of creating a dialog using a resource. The dynamic dialog stuff in Win32 was fairly complex, but it allowed you to create a true data-driven interface, and avoid issues with bundling resources with DLLs.
As for why use Win32 - if you need a windows app and you don't want to depend on MFC or the .NET runtime, then that's what you use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Best practices for versioning your services with WCF? I'm starting to work with my model almost exclusively in WCF and wanted to get some practical approaches to versioning these services over time. Can anyone point me in the right direction?
A: While not an instant answer for you, I found the book Learning WCF very useful; in it there's a small section on versioning (which is similar to Craig McMurtry's advice posted by Espo). If you're looking for a general intro book, it's very good. Her website has lots of good stuff too: Das Blonde
Edit:
No sure why her site isn't responding; it's been a while since I've visited, so maybe she shut it down. No sure.
A: There is a good writeup on Craig McMurtry's WebLog. Its from 2006, but most of it is still relevant.
As well as a decision tree to walk through the choices, he shows how to implement those changes using Windows Communication Foundation
A: See "Versioning WCF Services: Part I" and "Versioning WCF Services: Part II".
See also:
*
*WCF Backwards Compatibility and Versioning Strategies – Part 1
*WCF Backward Compatibility and Versioning Strategies – Part 2
*WCF Backward Compatibility and Versioning Strategies – Part 3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: Should you ever use protected member variables? Should you ever use protected member variables? What are the the advantages and what issues can this cause?
A: In general, I would keep your protected member variables to the rare case where you have total control over the code that uses them as well. If you are creating a public API, I'd say never. Below, we'll refer to the member variable as a "property" of the object.
Here's what your superclass cannot do after making a member variable protected rather than private-with-accessors:
*
*lazily create a value on the fly when the property is being read. If you add a protected getter method, you can lazily create the value and pass it back.
*know when the property been modified or deleted. This can introduce bugs when the superclass makes assumptions about the state of that variable. Making a protected setter method for the variable keeps that control.
*Set a breakpoint or add debug output when the variable is read or written to.
*Rename that member variable without searching through all the code that might use it.
In general, I think it'd be the rare case that I'd recommend making a protected member variable. You are better off spending a few minutes exposing the property through getters/setters than hours later tracking down a bug in some other code that modified the protected variable. Not only that, but you are insured against adding future functionality (such as lazy loading) without breaking dependent code. It's harder to do it later than to do it now.
A:
Should you ever use protected member variables?
Depends on how picky you are about hiding state.
*
*If you don't want any leaking of internal state, then declaring all your member variables private is the way to go.
*If you don't really care that subclasses can access internal state, then protected is good enough.
If a developer comes along and subclasses your class they may mess it up because they don't understand it fully. With private members, other than the public interface, they can't see the implementation specific details of how things are being done which gives you the flexibility of changing it later.
A: At the design level it might be appropriate to use a protected property, but for implementation I see no advantage in mapping this to a protected member variable rather than accessor/mutator methods.
Protected member variables have significant disadvantages because they effectively allow client code (the sub-class) access to the internal state of the base class class. This prevents the base class from effectively maintaining its invariants.
For the same reason, protected member variables also make writing safe multi-threaded code significantly more difficult unless guaranteed constant or confined to a single thread.
Accessor/mutator methods offer considerably more API stability and implementation flexibility under maintenance.
Also, if you're an OO purist, objects collaborate/communicate by sending messages, not reading/setting state.
In return they offer very few advantages. I wouldn't necessarily remove them from somebody else's code, but I don't use them myself.
A: Just for the record, under Item 24 of "Exceptional C++", in one of the footnotes, Sutter goes
"you would never write a class that has a public or protected member variable. right? (Regardless of the poor example set by some libraries.)"
A: Most of the time, it is dangerous to use protected because you break somewhat the encapsulation of your class, which could well be broken down by a poorly designed derived class.
But I have one good example: Let's say you can some kind of generic container. It has an internal implementation, and internal accessors. But you need to offer at least 3 public access to its data: map, hash_map, vector-like. Then you have something like:
template <typename T, typename TContainer>
class Base
{
// etc.
protected
TContainer container ;
}
template <typename Key, typename T>
class DerivedMap : public Base<T, std::map<Key, T> > { /* etc. */ }
template <typename Key, typename T>
class DerivedHashMap : public Base<T, std::hash_map<Key, T> > { /* etc. */ }
template <typename T>
class DerivedVector : public Base<T, std::vector<T> > { /* etc. */ }
I used this kind of code less than a month ago (so the code is from memory). After some thinking, I believe that while the generic Base container should be an abstract class, even if it can live quite well, because using directly Base would be such a pain it should be forbidden.
Summary Thus, you have protected data used by the derived class. Still, we must take int o account the fact the Base class should be abstract.
A: Generally, if something is not deliberately conceived as public, I make it private.
If a situation arises where I need access to that private variable or method from a derived class, I change it from private to protected.
This hardly ever happens - I'm really not a fan at all of inheritance, as it isn't a particularly good way to model most situations. At any rate, carry on, no worries.
I'd say this is fine (and probably the best way to go about it) for the majority of developers.
The simple fact of the matter is, if some other developer comes along a year later and decides they need access to your private member variable, they are simply going to edit the code, change it to protected, and carry on with their business.
The only real exceptions to this are if you're in the business of shipping binary dll's in black-box form to third parties. This consists basically of Microsoft, those 'Custom DataGrid Control' vendors, and maybe a few other large apps that ship with extensibility libraries. Unless you're in that category, it's not worth expending the time/effort to worry about this kind of thing.
A: The general feeling nowadays is that they cause undue coupling between derived classes and their bases.
They have no particular advantage over protected methods/properties (once upon a time they might have a slight performance advantage), and they were also used more in an era when very deep inheritance was in fashion, which it isn't at the moment.
A: In short, yes.
Protected member variables allow access to the variable from any sub-classes as well as any classes in the same package. This can be highly useful, especially for read-only data. I don't believe that they are ever necessary however, because any use of a protected member variable can be replicated using a private member variable and a couple of getters and setters.
A: For detailed info on .Net access modifiers go here
There are no real advantages or disadvantages to protected member variables, it's a question of what you need in your specific situation. In general it is accepted practice to declare member variables as private and enable outside access through properties. Also, some tools (e.g. some O/R mappers) expect object data to be represented by properties and do not recognize public or protected member variables. But if you know that you want your subclasses (and ONLY your subclasses) to access a certain variable there is no reason not to declare it as protected.
A: The key issue for me is that once you make a variable protected, you then cannot allow any method in your class to rely on its value being within a range, because a subclass can always place it out of range.
For example, if I have a class that defines width and height of a renderable object, and I make those variables protected, I then can make no assumptions over (for example), aspect ratio.
Critically, I can never make those assumptions at any point from the moment that code's released as a library, since even if I update my setters to maintain aspect ratio, I have no guarantee that the variables are being set via the setters or accessed via the getters in existing code.
Nor can any subclass of my class choose to make that guarantee, as they can't enforce the variables values either, even if that's the entire point of their subclass.
As an example:
*
*I have a rectangle class with width and height being stored as protected variables.
*An obvious sub-class (within my context) is a "DisplayedRectangle" class, where the only difference is that I restrict the widths and heights to valid values for a graphical display.
*But that's impossible now, since my DisplayedRectangle class cannot truly constrain those values, as any subclass of it could override the values directly, while still being treated as a DisplayedRectangle.
By constraining the variables to be private, I can then enforce the behaviour I want through setters or getters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "105"
} |
Q: Java: notify() vs. notifyAll() all over again If one Googles for "difference between notify() and notifyAll()" then a lot of explanations will pop up (leaving apart the javadoc paragraphs). It all boils down to the number of waiting threads being waken up: one in notify() and all in notifyAll().
However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition; in the first case the one selected by the VM, in the second case the one selected by the system thread scheduler. The exact selection procedures for both of them (in the general case) are not known to the programmer.
What's the useful difference between notify() and notifyAll() then? Am I missing something?
A: From Joshua Bloch, the Java Guru himself in Effective Java 2nd edition:
"Item 69: Prefer concurrency utilities to wait and notify".
A: There are three states for a thread.
*
*WAIT - The thread is not using any CPU cycle
*BLOCKED - The thread is blocked trying to acquire a monitor. It might still be using the CPU cycles
*RUNNING - The thread is running.
Now, when a notify() is called, JVM picks one thread and move them to the BLOCKED state and hence to the RUNNING state as there is no competition for the monitor object.
When a notifyAll() is called, JVM picks all the threads and move all of them to BLOCKED state. All these threads will get the lock of the object on a priority basis. Thread which is able to acquire the monitor first will be able to go to the RUNNING state first and so on.
A: This answer is a graphical rewriting and simplification of the excellent answer by xagyg, including comments by eran.
Why use notifyAll, even when each product is intended for a single consumer?
Consider producers and consumers, simplified as follows.
Producer:
while (!empty) {
wait() // on full
}
put()
notify()
Consumer:
while (empty) {
wait() // on empty
}
take()
notify()
Assume 2 producers and 2 consumers, sharing a buffer of size 1. The following picture depicts a scenario leading to a deadlock, which would be avoided if all threads used notifyAll.
Each notify is labeled with the thread being woken up.
A: Useful differences:
*
*Use notify() if all your waiting threads are interchangeable (the order they wake up doesn't matter), or if you only ever have one waiting thread. A common example is a thread pool used to execute jobs from a queue--when a job is added, one of threads is notified to wake up, execute the next job and go back to sleep.
*Use notifyAll() for other cases where the waiting threads may have different purposes and should be able to run concurrently. An example is a maintenance operation on a shared resource, where multiple threads are waiting for the operation to complete before accessing the resource.
A: I am very surprised that no one mentioned the infamous "lost wakeup" problem (google it).
Basically:
*
*if you have multiple threads waiting on a same condition and,
*multiple threads that can make you transition from state A to state B and,
*multiple threads that can make you transition from state B to state A (usually the same threads as in 1.) and,
*transitioning from state A to B should notify threads in 1.
THEN you should use notifyAll unless you have provable guarantees that lost wakeups are impossible.
A common example is a concurrent FIFO queue where:
multiple enqueuers (1. and 3. above) can transition your queue from empty to non-empty
multiple dequeuers (2. above) can wait for the condition "the queue is not empty"
empty -> non-empty should notify dequeuers
You can easily write an interleaving of operations in which, starting from an empty queue, 2 enqueuers and 2 dequeuers interact and 1 enqueuer will remain sleeping.
This is a problem arguably comparable with the deadlock problem.
A: Here's a simpler explanation:
You're correct that whether you use notify() or notifyAll(), the immediate result is that exactly one other thread will acquire the monitor and begin executing. (Assuming some threads were in fact blocked on wait() for this object, other unrelated threads aren't soaking up all available cores, etc.) The impact comes later.
Suppose thread A, B, and C were waiting on this object, and thread A gets the monitor. The difference lies in what happens once A releases the monitor. If you used notify(), then B and C are still blocked in wait(): they are not waiting on the monitor, they are waiting to be notified. When A releases the monitor, B and C will still be sitting there, waiting for a notify().
If you used notifyAll(), then B and C have both advanced past the "wait for notification" state and are both waiting to acquire the monitor. When A releases the monitor, either B or C will acquire it (assuming no other threads are competing for that monitor) and begin executing.
A: notify() will wake up one thread while notifyAll() will wake up all. As far as I know there is no middle ground. But if you are not sure what notify() will do to your threads, use notifyAll(). Works like a charm everytime.
A: All the above answers are correct, as far as I can tell, so I'm going to tell you something else. For production code you really should use the classes in java.util.concurrent. There is very little they cannot do for you, in the area of concurrency in java.
A: notify() lets you write more efficient code than notifyAll().
Consider the following piece of code that's executed from multiple parallel threads:
synchronized(this) {
while(busy) // a loop is necessary here
wait();
busy = true;
}
...
synchronized(this) {
busy = false;
notifyAll();
}
It can be made more efficient by using notify():
synchronized(this) {
if(busy) // replaced the loop with a condition which is evaluated only once
wait();
busy = true;
}
...
synchronized(this) {
busy = false;
notify();
}
In the case if you have a large number of threads, or if the wait loop condition is costly to evaluate, notify() will be significantly faster than notifyAll(). For example, if you have 1000 threads then 999 threads will be awakened and evaluated after the first notifyAll(), then 998, then 997, and so on. On the contrary, with the notify() solution, only one thread will be awakened.
Use notifyAll() when you need to choose which thread will do the work next:
synchronized(this) {
while(idx != last+1) // wait until it's my turn
wait();
}
...
synchronized(this) {
last = idx;
notifyAll();
}
Finally, it's important to understand that in case of notifyAll(), the code inside synchronized blocks that have been awakened will be executed sequentially, not all at once. Let's say there are three threads waiting in the above example, and the fourth thread calls notifyAll(). All three threads will be awakened but only one will start execution and check the condition of the while loop. If the condition is true, it will call wait() again, and only then the second thread will start executing and will check its while loop condition, and so on.
A: notify() - Selects a random thread from the wait set of the object and puts it in the BLOCKED state. The rest of the threads in the wait set of the object are still in the WAITING state.
notifyAll() - Moves all the threads from the wait set of the object to BLOCKED state. After you use notifyAll(), there are no threads remaining in the wait set of the shared object because all of them are now in BLOCKED state and not in WAITING state.
BLOCKED - blocked for lock acquisition.
WAITING - waiting for notify ( or blocked for join completion ).
A: Clearly, notify wakes (any) one thread in the wait set, notifyAll wakes all threads in the waiting set. The following discussion should clear up any doubts. notifyAll should be used most of the time. If you are not sure which to use, then use notifyAll.Please see explanation that follows.
Read very carefully and understand. Please send me an email if you have any questions.
Look at producer/consumer (assumption is a ProducerConsumer class with two methods). IT IS BROKEN (because it uses notify) - yes it MAY work - even most of the time, but it may also cause deadlock - we will see why:
public synchronized void put(Object o) {
while (buf.size()==MAX_SIZE) {
wait(); // called if the buffer is full (try/catch removed for brevity)
}
buf.add(o);
notify(); // called in case there are any getters or putters waiting
}
public synchronized Object get() {
// Y: this is where C2 tries to acquire the lock (i.e. at the beginning of the method)
while (buf.size()==0) {
wait(); // called if the buffer is empty (try/catch removed for brevity)
// X: this is where C1 tries to re-acquire the lock (see below)
}
Object o = buf.remove(0);
notify(); // called if there are any getters or putters waiting
return o;
}
FIRSTLY,
Why do we need a while loop surrounding the wait?
We need a while loop in case we get this situation:
Consumer 1 (C1) enter the synchronized block and the buffer is empty, so C1 is put in the wait set (via the wait call). Consumer 2 (C2) is about to enter the synchronized method (at point Y above), but Producer P1 puts an object in the buffer, and subsequently calls notify. The only waiting thread is C1, so it is woken and now attempts to re-acquire the object lock at point X (above).
Now C1 and C2 are attempting to acquire the synchronization lock. One of them (nondeterministically) is chosen and enters the method, the other is blocked (not waiting - but blocked, trying to acquire the lock on the method). Let's say C2 gets the lock first. C1 is still blocking (trying to acquire the lock at X). C2 completes the method and releases the lock. Now, C1 acquires the lock. Guess what, lucky we have a while loop, because, C1 performs the loop check (guard) and is prevented from removing a non-existent element from the buffer (C2 already got it!). If we didn't have a while, we would get an IndexArrayOutOfBoundsException as C1 tries to remove the first element from the buffer!
NOW,
Ok, now why do we need notifyAll?
In the producer/consumer example above it looks like we can get away with notify. It seems this way, because we can prove that the guards on the wait loops for producer and consumer are mutually exclusive. That is, it looks like we cannot have a thread waiting in the put method as well as the get method, because, for that to be true, then the following would have to be true:
buf.size() == 0 AND buf.size() == MAX_SIZE (assume MAX_SIZE is not 0)
HOWEVER, this is not good enough, we NEED to use notifyAll. Let's see why ...
Assume we have a buffer of size 1 (to make the example easy to follow). The following steps lead us to deadlock. Note that ANYTIME a thread is woken with notify, it can be non-deterministically selected by the JVM - that is any waiting thread can be woken. Also note that when multiple threads are blocking on entry to a method (i.e. trying to acquire a lock), the order of acquisition can be non-deterministic. Remember also that a thread can only be in one of the methods at any one time - the synchronized methods allow only one thread to be executing (i.e. holding the lock of) any (synchronized) methods in the class. If the following sequence of events occurs - deadlock results:
STEP 1:
- P1 puts 1 char into the buffer
STEP 2:
- P2 attempts put - checks wait loop - already a char - waits
STEP 3:
- P3 attempts put - checks wait loop - already a char - waits
STEP 4:
- C1 attempts to get 1 char
- C2 attempts to get 1 char - blocks on entry to the get method
- C3 attempts to get 1 char - blocks on entry to the get method
STEP 5:
- C1 is executing the get method - gets the char, calls notify, exits method
- The notify wakes up P2
- BUT, C2 enters method before P2 can (P2 must reacquire the lock), so P2 blocks on entry to the put method
- C2 checks wait loop, no more chars in buffer, so waits
- C3 enters method after C2, but before P2, checks wait loop, no more chars in buffer, so waits
STEP 6:
- NOW: there is P3, C2, and C3 waiting!
- Finally P2 acquires the lock, puts a char in the buffer, calls notify, exits method
STEP 7:
- P2's notification wakes P3 (remember any thread can be woken)
- P3 checks the wait loop condition, there is already a char in the buffer, so waits.
- NO MORE THREADS TO CALL NOTIFY and THREE THREADS PERMANENTLY SUSPENDED!
SOLUTION: Replace notify with notifyAll in the producer/consumer code (above).
A: I would like to mention what is explained in Java Concurrency in Practice:
First point, whether Notify or NotifyAll?
It will be NotifyAll, and reason is that it will save from signall hijacking.
If two threads A and B are waiting on different condition predicates
of same condition queue and notify is called, then it is upto JVM to
which thread JVM will notify.
Now if notify was meant for thread A and JVM notified thread B, then
thread B will wake up and see that this notification is not useful so
it will wait again. And Thread A will never come to know about this
missed signal and someone hijacked it's notification.
So, calling notifyAll will resolve this issue, but again it will have
performance impact as it will notify all threads and all threads will
compete for same lock and it will involve context switch and hence
load on CPU. But we should care about performance only if it is
behaving correctly, if it's behavior itself is not correct then
performance is of no use.
This problem can be solved with using Condition object of explicit locking Lock, provided in jdk 5, as it provides different wait for each condition predicate. Here it will behave correctly and there will not be performance issue as it will call signal and make sure that only one thread is waiting for that condition
A: Taken from blog on Effective Java:
The notifyAll method should generally be used in preference to notify.
If notify is used, great care must be taken to ensure liveness.
So, what i understand is (from aforementioned blog, comment by "Yann TM" on accepted answer and Java docs):
*
*notify() : JVM awakens one of the waiting threads on this object. Thread selection is made arbitrarily without fairness. So same thread can be awakened again and again. So system's state changes but no real progress is made. Thus creating a livelock.
*notifyAll() : JVM awakens all threads and then all threads race for the lock on this object. Now, CPU scheduler selects a thread which acquires lock on this object. This selection process would be much better than selection by JVM. Thus, ensuring liveness.
A:
However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition.
That is not correct. o.notifyAll() wakes all of the threads that are blocked in o.wait() calls. The threads are only allowed to return from o.wait() one-by-one, but they each will get their turn.
Simply put, it depends on why your threads are waiting to be notified. Do you want to tell one of the waiting threads that something happened, or do you want to tell all of them at the same time?
In some cases, all waiting threads can take useful action once the wait finishes. An example would be a set of threads waiting for a certain task to finish; once the task has finished, all waiting threads can continue with their business. In such a case you would use notifyAll() to wake up all waiting threads at the same time.
Another case, for example mutually exclusive locking, only one of the waiting threads can do something useful after being notified (in this case acquire the lock). In such a case, you would rather use notify(). Properly implemented, you could use notifyAll() in this situation as well, but you would unnecessarily wake threads that can't do anything anyway.
In many cases, the code to await a condition will be written as a loop:
synchronized(o) {
while (! IsConditionTrue()) {
o.wait();
}
DoSomethingThatOnlyMakesSenseWhenConditionIsTrue_and_MaybeMakeConditionFalseAgain();
}
That way, if an o.notifyAll() call wakes more than one waiting thread, and the first one to return from the o.wait() makes leaves the condition in the false state, then the other threads that were awakened will go back to waiting.
A: Take a look at the code posted by @xagyg.
Suppose two different threads are waiting for two different conditions:
The first thread is waiting for buf.size() != MAX_SIZE, and the second thread is waiting for buf.size() != 0.
Suppose at some point buf.size() is not equal to 0. JVM calls notify() instead of notifyAll(), and the first thread is notified (not the second one).
The first thread is woken up, checks for buf.size() which might return MAX_SIZE, and goes back to waiting. The second thread is not woken up, continues to wait and does not call get().
A: I think it depends on how resources are produced and consumed. If 5 work objects are available at once and you have 5 consumer objects, it would make sense to wake up all threads using notifyAll() so each one can process 1 work object.
If you have just one work object available, what is the point in waking up all consumer objects to race for that one object? The first one checking for available work will get it and all other threads will check and find they have nothing to do.
I found a great explanation here. In short:
The notify() method is generally used
for resource pools, where there
are an arbitrary number of "consumers"
or "workers" that take resources, but
when a resource is added to the pool,
only one of the waiting consumers or
workers can deal with it. The
notifyAll() method is actually used in
most other cases. Strictly, it is
required to notify waiters of a
condition that could allow multiple
waiters to proceed. But this is often
difficult to know. So as a general
rule, if you have no particular
logic for using notify(), then you
should probably use notifyAll(),
because it is often difficult to know
exactly what threads will be waiting
on a particular object and why.
A: Note that with concurrency utilities you also have the choice between signal() and signalAll() as these methods are called there. So the question remains valid even with java.util.concurrent.
Doug Lea brings up an interesting point in his famous book: if a notify() and Thread.interrupt() happen at the same time, the notify might actually get lost. If this can happen and has dramatic implications notifyAll() is a safer choice even though you pay the price of overhead (waking too many threads most of the time).
A: Here is an example. Run it. Then change one of the notifyAll() to notify() and see what happens.
ProducerConsumerExample class
public class ProducerConsumerExample {
private static boolean Even = true;
private static boolean Odd = false;
public static void main(String[] args) {
Dropbox dropbox = new Dropbox();
(new Thread(new Consumer(Even, dropbox))).start();
(new Thread(new Consumer(Odd, dropbox))).start();
(new Thread(new Producer(dropbox))).start();
}
}
Dropbox class
public class Dropbox {
private int number;
private boolean empty = true;
private boolean evenNumber = false;
public synchronized int take(final boolean even) {
while (empty || evenNumber != even) {
try {
System.out.format("%s is waiting ... %n", even ? "Even" : "Odd");
wait();
} catch (InterruptedException e) { }
}
System.out.format("%s took %d.%n", even ? "Even" : "Odd", number);
empty = true;
notifyAll();
return number;
}
public synchronized void put(int number) {
while (!empty) {
try {
System.out.println("Producer is waiting ...");
wait();
} catch (InterruptedException e) { }
}
this.number = number;
evenNumber = number % 2 == 0;
System.out.format("Producer put %d.%n", number);
empty = false;
notifyAll();
}
}
Consumer class
import java.util.Random;
public class Consumer implements Runnable {
private final Dropbox dropbox;
private final boolean even;
public Consumer(boolean even, Dropbox dropbox) {
this.even = even;
this.dropbox = dropbox;
}
public void run() {
Random random = new Random();
while (true) {
dropbox.take(even);
try {
Thread.sleep(random.nextInt(100));
} catch (InterruptedException e) { }
}
}
}
Producer class
import java.util.Random;
public class Producer implements Runnable {
private Dropbox dropbox;
public Producer(Dropbox dropbox) {
this.dropbox = dropbox;
}
public void run() {
Random random = new Random();
while (true) {
int number = random.nextInt(10);
try {
Thread.sleep(random.nextInt(100));
dropbox.put(number);
} catch (InterruptedException e) { }
}
}
}
A: Short summary:
Always prefer notifyAll() over notify() unless you have a massively parallel application where a large number of threads all do the same thing.
Explanation:
notify() [...] wakes up a single
thread. Because notify() doesn't allow you to specify the thread that is
woken up, it is useful only in massively parallel applications — that
is, programs with a large number of threads, all doing similar chores.
In such an application, you don't care which thread gets woken up.
source: https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
Compare notify() with notifyAll() in the above described situation: a massively parallel application where threads are doing the same thing. If you call notifyAll() in that case, notifyAll() will induce the waking up (i.e. scheduling) of a huge number of threads, many of them unnecessarily (since only one thread can actually proceed, namely the thread which will be granted the monitor for the object wait(), notify(), or notifyAll() was called on), therefore wasting computing resources.
Thus, if you don't have an application where a huge number of threads do the same thing concurrently, prefer notifyAll() over notify(). Why? Because, as other users have already answered in this forum, notify()
wakes up a single thread that is waiting on this object's monitor. [...] The
choice is arbitrary and occurs at the discretion of the
implementation.
source: Java SE8 API (https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#notify--)
Imagine you have a producer consumer application where consumers are ready (i.e. wait() ing) to consume, producers are ready (i.e. wait() ing) to produce and the queue of items (to be produced / consumed) is empty. In that case, notify() might wake up only consumers and never producers because the choice who is waken up is arbitrary. The producer consumer cycle wouldn't make any progress although producers and consumers are ready to produce and consume, respectively. Instead, a consumer is woken up (i.e. leaving the wait() status), doesn't take an item out of the queue because it's empty, and notify() s another consumer to proceed.
In contrast, notifyAll() awakens both producers and consumers. The choice who is scheduled depends on the scheduler. Of course, depending on the scheduler's implementation, the scheduler might also only schedule consumers (e.g. if you assign consumer threads a very high priority). However, the assumption here is that the danger of the scheduler scheduling only consumers is lower than the danger of the JVM only waking up consumers because any reasonably implemented scheduler doesn't make just arbitrary decisions. Rather, most scheduler implementations make at least some effort to prevent starvation.
A: notify will notify only one thread which are in waiting state, while notify all will notify all the threads in the waiting state now all the notified threads and all the blocked threads are eligible for the lock, out of which only one will get the lock and all others (including those who are in waiting state earlier) will be in blocked state.
A: To summarize the excellent detailed explanations above, and in the simplest way I can think of, this is due to the limitations of the JVM built-in monitor, which 1) is acquired on the entire synchronization unit (block or object) and 2) does not discriminate about the specific condition being waited/notified on/about.
This means that if multiple threads are waiting on different conditions and notify() is used, the selected thread may not be the one which would make progress on the newly fulfilled condition - causing that thread (and other currently still waiting threads which would be able to fulfill the condition, etc..) not to be able to make progress, and eventually starvation or program hangup.
In contrast, notifyAll() enables all waiting threads to eventually re-acquire the lock and check for their respective condition, thereby eventually allowing progress to be made.
So notify() can be used safely only if any waiting thread is guaranteed to allow progress to be made should it be selected, which in general is satisfied when all threads within the same monitor check for only one and the same condition - a fairly rare case in real world applications.
A: notify() wakes up the first thread that called wait() on the same object.
notifyAll() wakes up all the threads that called wait() on the same object.
The highest priority thread will run first.
A: When you call the wait() of the "object"(expecting the object lock is acquired),intern this will release the lock on that object and help's the other threads to have lock on this "object", in this scenario there will be more than 1 thread waiting for the "resource/object"(considering the other threads also issued the wait on the same above object and down the way there will be a thread that fill the resource/object and invokes notify/notifyAll).
Here when you issue the notify of the same object(from the same/other side of the process/code),this will release a blocked and waiting single thread (not all the waiting threads -- this released thread will be picked by JVM Thread Scheduler and all the lock obtaining process on the object is same as regular).
If you have Only one thread that will be sharing/working on this object , it is ok to use the notify() method alone in your wait-notify implementation.
if you are in situation where more than one thread read's and writes on resources/object based on your business logic,then you should go for notifyAll()
now i am looking how exactly the jvm is identifying and breaking the waiting thread when we issue notify() on a object ...
A: While there are some solid answers above, I am surprised by the number of confusions and misunderstandings I have read. This probably proves the idea that one should use java.util.concurrent as much as possible instead of trying to write their own broken concurrent code.
Back to the question: to summarize, the best practice today is to AVOID notify() in ALL situations due to the lost wakeup problem. Anyone who doesn't understand this should not be allowed to write mission critical concurrency code. If you are worried about the herding problem, one safe way to achieve waking one thread up at a time is to:
*
*Build an explicit waiting queue for the waiting threads;
*Have each of the thread in the queue wait for its predecessor;
*Have each thread call notifyAll() when done.
Or you can use Java.util.concurrent.*, which have already implemented this.
A: Waiting queue and blocked queue
You can assume there are two kinds of queues associated with each lock object. One is blocked queue containing thread waiting for the monitor lock, other is waiting queue containing thread waiting to be notified. (Thread will be put into waiting queue when they call Object.wait).
Each time the lock is available, the scheduler choose one thread from blocked queue to execute.
When notify is called, there will only be one thread in waiting queue are put into blocked queue to contend for the lock, while notifyAll will put all thread in waiting queue into blocked queue.
Now can you see the difference?
Although in both case there will only be one thread get executed, but with notifyAll, other threads still get a change to be executed(Because they are in the blocked queue) even if they failed to contend the lock.
some guidline
I basically recommend use notifyAll all the time althrough there may be a little performance penalty.
And use notify only if :
*
*Any waked thread can make the programe proceed.
*performance is important.
For example:
@xagyg 's answer gives a example which notify will cause deadlock. In his example, both producer and consumer are related with the same lock object. So when a producer calls notify, either a producer or a consumer can be notified. But if a producer is woken up it can not make the programe proceed because the buffer is already full.So a deadlock happens.
There are two ways to solve it :
*
*use notifyALl as @xagyg suggests.
*Make procuder and consumer related with different lock object and procuder can only wake up consumer, consumer can only wake up producer. In that case, no matter which consumer is waked, it can consumer the buffer and make the programe proceed.
A: Waking up all does not make much significance here.
wait notify and notifyall, all these are put after owning the object's monitor. If a thread is in the waiting stage and notify is called, this thread will take up the lock and no other thread at that point can take up that lock. So concurrent access can not take place at all. As far as i know any call to wait notify and notifyall can be made only after taking the lock on the object. Correct me if i am wrong.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "421"
} |
Q: SQL Server Fast Forward Cursors It is generally accepted that the use of cursors in stored procedures should be avoided where possible (replaced with set based logic etc). If you take the cases where you need to iterate over some data, and can do in a read only manner, are fast forward (read only forward) cursor more or less inefficient than say while loops? From my investigations it looks as though the cursor option is generally faster and uses less reads and cpu time. I haven't done any extensive testing, but is this what others find? Do cursors of this type (fast forward) carry additional overhead or resource that could be expensive that I don't know about.
Is all the talk about not using cursors really about avoiding the use of cursors when set-based approaches are available, and the use of updatable cursors etc.
A: While a fast forward cursor does have some optimizations in Sql Server 2005, it is not true that they are anywhere close to a set based query in terms of performance. There are very few situations where cursor logic cannot be replaced by a set-based query. Cursors will always be inherently slower, due in part to the fact that you have to keep interrupting the execution in order to fill your local variables.
Here are few references, which would only be the tip of the iceberg if you research this issue:
http://www.code-magazine.com/Article.aspx?quickid=060113
http://dataeducation.com/re-inventing-the-recursive-cte/
A: This answer hopes to consolidate the replies given to date.
1) If at all possible, used set based logic for your queries i.e. try and use just SELECT, INSERT, UPDATE or DELETE with the appropriate FROM clauses or nested queries - these will almost always be faster.
2) If the above is not possible, then in SQL Server 2005+ FAST FORWARD cursors are efficient and perform well and should be used in preference to while loops.
A: "If You want a even faster cursor than FAST FORWARD then use a STATIC cursor. They are faster than FAST FORWARD. Not extremely faster but can make a difference."
Not so fast! According to Microsoft:
"Typically, when these conversions occurred, the cursor type degraded to a ‘more expensive’ cursor type. Generally, a (FAST) FORWARD-ONLY cursor is the most performant, followed by DYNAMIC, KEYSET, and finally STATIC which is generally the least performant."
from: Link
A: You can avoid cursors most of the time, but sometimes it's necessary.
Just keep in mind that FAST_FORWARD is DYNAMIC ... FORWARD_ONLY you can use with a STATIC cursor.
Try using it on the Halloween problem to see what happens !!!
IF OBJECT_ID('Funcionarios') IS NOT NULL
DROP TABLE Funcionarios
GO
CREATE TABLE Funcionarios(ID Int IDENTITY(1,1) PRIMARY KEY,
ContactName Char(7000),
Salario Numeric(18,2));
GO
INSERT INTO Funcionarios(ContactName, Salario) VALUES('Fabiano', 1900)
INSERT INTO Funcionarios(ContactName, Salario) VALUES('Luciano',2050)
INSERT INTO Funcionarios(ContactName, Salario) VALUES('Gilberto', 2070)
INSERT INTO Funcionarios(ContactName, Salario) VALUES('Ivan', 2090)
GO
CREATE NONCLUSTERED INDEX ix_Salario ON Funcionarios(Salario)
GO
-- Halloween problem, will update all rows until then reach 3000 !!!
UPDATE Funcionarios SET Salario = Salario * 1.1
FROM Funcionarios WITH(index=ix_Salario)
WHERE Salario < 3000
GO
-- Simulate here with all different CURSOR declarations
-- DYNAMIC update the rows until all of then reach 3000
-- FAST_FORWARD update the rows until all of then reach 3000
-- STATIC update the rows only one time.
BEGIN TRAN
DECLARE @ID INT
DECLARE TMP_Cursor CURSOR DYNAMIC
--DECLARE TMP_Cursor CURSOR FAST_FORWARD
--DECLARE TMP_Cursor CURSOR STATIC READ_ONLY FORWARD_ONLY
FOR SELECT ID
FROM Funcionarios WITH(index=ix_Salario)
WHERE Salario < 3000
OPEN TMP_Cursor
FETCH NEXT FROM TMP_Cursor INTO @ID
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT * FROM Funcionarios WITH(index=ix_Salario)
UPDATE Funcionarios SET Salario = Salario * 1.1
WHERE ID = @ID
FETCH NEXT FROM TMP_Cursor INTO @ID
END
CLOSE TMP_Cursor
DEALLOCATE TMP_Cursor
SELECT * FROM Funcionarios
ROLLBACK TRAN
GO
A: Some alternatives to using cursor:
WHILE loops
Temp tablolar
Derived tables
Associated subqueries
CASE statements
Multiple interrogations
Often, cursor operations can also be achieved with non-cursor techniques.
If you are sure that the cursor needs to be used, the number of records to be processed should be reduced as much as possible. One way of doing this is to get the records to be processed first into a temp table, not the original table, but a cursor that will use the records in the temp table. When this path is used, it is assumed that the number of records in the temp table has been greatly reduced compared to the original table. With fewer records, the cursor completes faster.
Some cursor properties that affect performance include:
FORWARD_ONLY: Supports forwarding only the cursor from the first row to the end with FETCH NEXT. Unless set as KEYSET or STATIC, the SELECT clause is re-evaluated when each fetch is called.
STATIC: Creates a temp copy of the created data and is used by the cursor. This prevents the cursor from being recalculated each time it is called, which improves performance. This does not allow cursor type modification, and changes to the table are not reflected when the fetch is called.
KEYSET: Cursored rows are placed in a table under tempdb, and changes to nonkey columns are reflected when the fetch is called. However, new records added to the table are not reflected. With the keyset cursor, the SELECT statement is not evaluated again.
DYNAMIC: All changes to the table are reflected in the cursore. The cursor is re-evaluated when each fetch is called. It uses a lot of resources and adversely affects performance.
FAST_FORWARD: The cursor is one-way, such as FORWARD_ONLY, but specifies the cursor as read-only. FORWARD_ONLY is a performance increase and the cursor is not reevaluated every fetch. It gives the best performance if it is suitable for programming.
OPTIMISTIC: This option can be used to update rows in the cursor. If a row is fetched and updated, and another row is updated between fetch and update operations, the cursor update operation fails. If an OPTIMISTIC cursor is used that can perform line update, it should not be updated by another process.
NOTE: If cursore is not specified, the default is FORWARD_ONLY.
A: People avoid cursor because they generally are more difficult to write than a simple while loops, however, a while loop can be expensive because your constantly selecting data from a table, temporary or otherwise.
With a cursor, which is readonly fast forward, the data is kept in memory and has been specifically designed for looping.
This article highlights that an average cursor runs 50 times faster than a while loop.
A: To answer Mile's original questions...
Fast Forward, Read Only, Static cursors (affectionately known as a "Fire Hose Cursor") are typically as fast or faster than a equivalent Temp Table and a While loop because such a cursor is nothing more than a Temp Table and a While loop that has been optimized a bit behind the scenes.
To add to what Eric Z. Beard posted on this thread and to further answer the question of...
"Is all the talk about not using cursors really about avoiding the use
of cursors when set-based approaches are available, and the use of
updatable cursors etc."
Yes. With very few exceptions, it takes less time and less code to write proper set-based code to do the same thing as most cursors and has the added benefit of using much fewer resources and usually runs MUCH faster than a cursor or While loop. Generally speaking and with the exception of certain administrative tasks, they really should be avoided in favor of properly written set-based code. There are, of course, exceptions to every "rule" but, in the case of Cursors, While loops, and other forms of RBAR, most people can count the exceptions on one hand without using all of the fingers. ;-)
There's also the notion of "Hidden RBAR". This is code that looks set-based but actually isn't. This type of "set-based" code is the reason why certain people have embraced RBAR methods and say they're "OK". For example, solving the running total problem using an aggregated (SUM) correlated sub-query with an inequality in it to build the running total isn't really set-based in my book. Instead, it's RBAR on steroids because ,for each row calculated, it has to repeatedly "touch" many other rows at a rate of N*(N+1)/2. That's known as a "Triangular Join" and is at least half as bad as a full Cartesian Join (Cross Join or "Square Join").
Although MS has made some improvements in how Cursors work since SQL Server 2005, the term "Fast Cursor" is still an oxymoron compared to properly written set-based code. That also holds true even in Oracle. I worked with Oracle for a short 3 years in the past but my job was to make performance improvements in existing code. Most of the really substantial improvements were realized when I converted Cursors to set-based code. Many jobs that previously took 4 to 8 hours to execute were reduced to minutes and, sometimes, seconds.
A: If You want a even faster cursor than FAST FORWARD then use a STATIC cursor. They are faster than FAST FORWARD. Not extremely faster but can make a difference.
A: The 'Best Practice' of avoiding cursors in SQL Server dates back to SQL Server 2000 and earlier versions. The rewrite of the engine in SQL 2005 addressed most of the issues related to the problems of cursors, particularly with the introduction of the fast forward option. Cursors are not neccessarily worse than set-based and are used extensively and successfully in Oracle PL/SQL (LOOP).
The 'generally accepted' that you refer to was valid, but is now outdated and incorrect - go on the assumption that fast forward cursors behave as advertised and perform. Do some tests and research, basing your findings on SQL2005 and later
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to best implement software updates on windows? I want to implement an "automatic update" system for a windows application.
Right now I'm semi-manually creating an "appcast" which my program checks, and notifies the user that a new version is available. (I'm using
NSIS for my installers).
Is there software that I can use that will handle the "automatic" part of the updates, perhaps similar to Sparkle on the mac? Any issues/pitfalls that I should be aware of?
A: There is no solution quite as smooth as Sparkle (that I know of).
If you need an easy means of deployment and updating applications, ClickOnce is an option. Unfortunately, it's inflexible (e.g., no per-machine installation instead of per-user), opaque (you have very little influence and clarity and control over how its deployment actually works) and non-standard (the paths it stores the installed app in are unlike anything else on Windows).
Much closer to what you're asking would be ClickThrough, a side project of WiX, but I'm not sure it's still in development (if it is, they should be clearer about that…) — and it would use MSI in any case, not NSIS.
You're likely best off rolling something on your own. I'd love to see a Sparkle-like project for Windows, but nobody seems to have given it a shot thus far.
A: Google Chrome auto-update is based on Omaha:
http://code.google.com/p/omaha/
Their overview has a great section on why it was needed:
The browser typically prompted the user with a long series of techy, confusing and scary dialogs all trying to convince the user not to install. Then the user was prompted with a wizard filled with choices that they did not need to or know how to decide amongst. These factors combined to form a bad user experience and large drop-off during the app installation process
A: It's a good idea to use a third-party solution, cause autoupdates can be a pain, especially with Windows Vista/7 (UAC). For what it's worth, the product my company uses is AutoUpdate+ and it seems to work fairly well.
A: For .NET, a while back Microsoft Patterns + Practices published the Application Updater Block. This was (to my mind) rather overblown and over-engineered, but did the job quite well.
In essence it used a "stub loader" to check a manifest and a Web service to see if a later version of the program than the one installed was available, then used the BITS background downloader technology to download a new version if one was available on the server.
Once the new version was downloaded and installed (with .NET this is as simple as an xcopy to the relevant folder), the application would update the manifest. The next time the program was loaded the new version would be launched.
While the Patterns + Practices code is .NET specific, there's nothing there that couldn't be copied for a non-.NET application, especially if you have the ability to silently run the install process in the background.
A: If your application is written in .Net, you could try ClickOnce. However, it's difficult to perform administrative or custom actions during install using this approach.
A: wyUpdate looks really nice. See video here:
http://wyday.com/wybuild/help/automatic-updates/
A: There's now a Windows port of Sparkle, see http://winsparkle.org.
A: For .NET applications you might want to have a look at NetSparkle, a Sparkle variant for .NET programs. It is pretty new (from 2011) and developed actively.
A: Just came here from an answer to my own question on the same subject - I mention one other updating solution in my question. It uses a stub loader, and an xml file to point to the latest executable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: Exposing a remote interface or object model I have a question on the best way of exposing an asynchronous remote interface.
The conditions are as follows:
*
*The protocol is asynchronous
*A third party can modify the data at any time
*The command round-trip can be significant
*The model should be well suited for UI interaction
*The protocol supports queries over certain objects, and so must the model
As a means of improving my lacking skills in this area (and brush up my Java in general), I have started a project to create an Eclipse-based front-end for xmms2 (described below).
So, the question is; how should I expose the remote interface as a neat data model (In this case, track management and event handling)?
I welcome anything from generic discussions to pattern name-dropping or concrete examples and patches :)
My primary goal here is learning about this class of problems in general. If my project can gain from it, fine, but I present it strictly to have something to start a discussion around.
I've implemented a protocol abstraction which I call 'client' (for legacy reasons) which allows me to access most exposed features using method calls which I am happy with even if it's far from perfect.
The features provided by the xmms2 daemon are things like track searching, meta-data retrieval and manipulation, change playback state, load playlists and so on and so forth.
I'm in the middle of updating to the latest stable release of xmms2, and I figured I might as well fix some of the glaring weaknesses of my current implementation.
My plan is to build a better abstraction on top of the protocol interface, one that allows a more natural interaction with the daemon. The current 'model' implementation is hard to use and is frankly quite ugly (not to mention the UI-code which is truly horrible atm).
Today I have the Tracks interface which I can use to get instances of Track classes based on their id. Searching is performed through the Collections interface (unfortunate namespace clash) which I'd rather move to Tracks, I think.
Any data can be modified by a third party at any time, and this should be properly reflected in the model and change-notifications distributed
These interfaces are exposed when connecting, by returning an object hierarchy that looks like this:
*
*Connection
*
*Playback getPlayback()
*
*Play, pause, jump, current track etc
*Expose playback state changes
*Tracks getTracks()
*
*Track getTrack(id) etc
*Expose track updates
*Collections getCollection()
*
*Load and manipulate playlists or named collections
*Query media library
*Expose collection updates
A: For the asynchronous bit, I would suggest checking into java.util.concurrent, and especially the Future<T> interface. The future interface is used to represent objects which are not ready yet, but are being created in a separate thread. You say that objects can be modified at any time by a third party, but I would still suggest you use immutable return objects here, and instead have a separate thread/event log you can subscribe to to get noticed when objects expire. I have little programming with UIs, but I believe using Futures for asynchronous calls would let you have a responsive GUI, rather than one that was waiting for a server reply.
For the queries I would suggest using method chaining to build the query object, and each object returned by method chaining should be Iterable. Similar to how Djangos model is. Say you have QuerySet which implements Iterable<Song>. You can then call allSongs() which would return a result iterating over all Songs. Or allSongs().artist("Beatles"), and you would have an iterable over all Betles songs. Or even allSongs().artist("Beatles").years(1965,1967) and so on.
Hope this helps as a starting place.
A: @Staale: Thanks a bunch!
Using Future for the async operations is interesting. The only drawback being that it is doesn't provide callbacks. But then again, I tried that approach, and look where that got me :)
I'm currently solving a similar problem using a worker thread and a blocking queue for dispatching the incoming command replies, but that approach doesn't translate very well.
The remote objects can be modified, but since I do use threads, I try to keep the objects immutable. My current hypothesis is that I will send notification events on track updates on the form
somehandlername(int changes, Track old_track, Track new_track)
or similar, but then I might end up with several versions of the same track.
I'll definitely look into Djangos method chaining. I've been looking at some similar constructs but haven't been able to come up with a good variant. Returning something iterable is interesting, but the query could take some time to complete, and I wouldn't want to actually execute the query before it's completely constructed.
Perhaps something like
Tracks.allSongs().artist("Beatles").years(1965,1967).execute()
returning a Future might work...
A: Iterable only has the method Iterator get() or somesuch. So no need to build any query or execute any code until you actually start iterating. It does make the execute in your example redundant. However, the thread will be locked until the first result is available, so you might consider using an Executor to run the code for the query in a separate thread.
A: @Staale
It is certainly possibly, but as you note, that would make it blocking (at home for something like 10 seconds due to sleeping disks), meaning I can't use it to update the UI directly.
I could use the iterator to create a copy of the result in a separate thread and then send that to the UI, but while the iterator solution by itself is rather elegant, it won't fit in very well. In the end, something implementing IStructuredContentProvider needs to return an array of all the objects in order to display it in a TableViewer, so if I can get away with getting something like that out of a callback... :)
I'll give it some more thought. I might just be able to work out something. It does give the code a nice look.
A: My conclusions so far;
I am torn on whether to use getters for the Track objects or just expose the members since the object is immutable.
class Track {
public final String album;
public final String artist;
public final String title;
public final String genre;
public final String comment;
public final String cover_id;
public final long duration;
public final long bitrate;
public final long samplerate;
public final long id;
public final Date date;
/* Some more stuff here */
}
Anybody who wants to know when something happened to a track in the library would implement this...
interface TrackUpdateListener {
void trackUpdate(Track oldTrack, Track newTrack);
}
This is how querys are built. Chain calls to your hearts content. the jury is still out on the get() though. There are some details missing, such as how I should handle wildcards and more advanced queries with disjunctions. I might just need some completion callback functionality, perhaps similar to the Asynchronous Completion Token, but we'll see about that. Perhaps that will happen in an additional layer.
interface TrackQuery extends Iterable<Track> {
TrackQuery years(int from, int to);
TrackQuery artist(String name);
TrackQuery album(String name);
TrackQuery id(long id);
TrackQuery ids(long id[]);
Future<Track[]> get();
}
Some examples:
tracks.allTracks();
tracks.allTracks().artist("Front 242").album("Tyranny (For You)");
The tracks interface is mostly just the glue between the connection and the individual tracks. It will be the one implementing or managing meta-data caching, if any (as today, but I think I'll just remove it during the refactoring and see if I actually need it). Also, this provides medialib track updates as it would just be too much work to implement it by track.
interface Tracks {
TrackQuery allTracks();
void addUpdateListener(TrackUpdateListener listener);
void removeUpdateListener(TrackUpdateListener listener);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Flex MVC Frameworks I'm currently using and enjoying using the Flex MVC framework PureMVC. I have heard some good things about Cairngorm, which is supported by Adobe and has first-to-market momentum. And there is a new player called Mate, which has a good deal of buzz.
Has anyone tried two or three of these frameworks and formed an opinion?
Thanks!
A: Check out Robotlegs.
"It provides the glue that your application needs to easily function in a decoupled way. Through the use of automated metadata based dependency injection Robotlegs removes boilerplate code in an application. By promoting loose coupling and avoiding the use of Singletons and statics in the framework Robotlegs can help you write code that is highly testable."
A: I've seen these kinds of discussions many many times. They usually start with WHICH Flex framework do you use. Not many people ask the question WHY do you even need to use any framework on top of Flex framework.
I'm not in favor of using any MVC framework (Cairngorm, PureMVC) in Flex code. Mate is a better candidate. At least it's simple to understand and is non intrusive. I prefer using enhanced components à la carte. We've created and open sourced a bunch of them (see clear.swc in the Clear Toolkit at http://sourceforge.net/projects/cleartoolkit/.
The first chapter of our upcoming O'Reilly book "Enterprise Development with Flex" has a detailed comparison of several Flex frameworks: http://my.safaribooksonline.com/9780596801465 .
A: Mate is my pick. The first and foremost reason is that it is completely unobtrusive. My application code has no dependencies on the framework, it is highly decoupled, reusable and testable.
One of the nicest features of Mate is the declarative configuration, essentially you wire up your application in using tags in what is called an event map -- basically a list of events that your application generates, and what actions to take when they occur. The event map gives a good overview of what your application does. Mate uses Flex' own event mechanism, it does not invent its own like most other frameworks. You can dispatch an event from anywhere in the view hierarchy and have it bubble up to the framework automatically, instead of having to have a direct line, like Cairngorms CairngormEventDispatcher or PureMVC's notification system.
Mate also uses a form of dependency injection (leveraging bindings) that makes it possible to connect your models to your views without either one knowing about the other. This is probably the most powerful feature of the framework.
In my view none of the other Flex application frameworks come anywhere near Mate. However, these are the contenders and why I consider them to be less useful:
PureMVC actively denies you many of the benefits of Flex (for example bindings and event bubbling) in order for the framework to be portable -- a doubious goal in my view. It is also over-engineered, and as invasive as they come. Every single part of your application depends on the framework. However, PureMVC isn't terrible, just not a very good fit for Flex. An alternative is FlexMVCS, an effort to make PureMVC more suitable for Flex (unfortunately there's no documentation yet, just source).
Cairngorm is a bundle of anti-patterns that lead to applications that are tightly coupled to global variables. Nuff said (but if you're interested, here are some more of my thoughts, and here too).
Swiz is a framework inspired by the Spring framework for Java and Cairngorm (trying to make up for the worst parts of the latter). It provides a dependency injection container and uses metadata to enable auto-wiring of dependencies. It is interesting, but a little bizzare in that goes to such lengths to avoid the global variables of Cairngorm by using dependency injection but then uses a global variable for central event dispatching.
Those are the ones I've tried or researched. There are a few others that I've heard about, but none that I think are widely used. Mate and Swiz were both presented at the recent 360|Flex conference, and there are videos available (the Mate folks have instructions on how to watch them)
A: We are currently working on a MVCS implementation in the Spring ActionScript framework. It uses the full power of the Inversion of Control container so you have centralized dependency management and are able to swap things easily. It is not very prescriptive in how you do things but provides you with a very flexible infrastructure.
If you are new to Spring ActionScript and MVCS, I have an introductory post at my blog: http://www.herrodius.com/blog/158
A: I am using (and recommend) Swiz framework. It's not as complex and PureMVC, but it gets the job done. Moreover, it's a IoC container, and I like IoC.
I never used Mate, so I can't comment on that. But I do recommend against Cairngorm. Cairngorm is said to be open source, but it's really not supported well by the community. It's release cycle is also slow. I've been waiting FOREVER for Navigation Library to come out of beta.
A: Bear in mind that Cairngorm is THE adobe sponsored framework, and now hosted on opensource.adobe.com. Also note that it's by far the most prolific amongst developers at the moment.
If you know Cairngorm and are looking for a job, you won't go far wrong.
A: Cairngorm is easy to use and well documented:
http://www.cairngormdocs.org/
I recommend the Cairngorm Diagram Explorer and the classic article about Cairngorm.
I was new to Flex when I learned Cairngorm but found it useful and easy to learn with the above.
A: MATE is the way to go.A framework which does what a framework should do.
De-coupled architecture
Simple
Small foot print
Efficiency
A: I kinda have my doubts on these MVC frameworks (Mate, Cairgnorm, etc...) with the way they implement event maps and event controllers, it reminds me too much of wxWidgets and other GUI toolkits of that sort.
However, would be really nice is if Flex or one of these MVC frameworks uses the Signal/Slots paradigm that Qt offers.
A: I recommend to use MATE for developing greats and complicated projects,like other frameworks, Mate addresses the common architectural concerns in Flex such as event handling, data binding, and asynchronous processing, but the most important goal is that it's only tag-based so it's very easy to use it in our Flex Applications.
A: Yes Mate is the best framework for flex. I have used in one application which had several revisions both in terms of GUI and back-end data service. I only needed to change my event-map every time there was any change.
Mate also has MockService implementation which makes testing easy not a mate's advantage but nice to have one.
A: You should design you own MVC "framework" based on your own needs. If you know a bit of design patterns, Flex has a lot to offer natively.
Best thing of designing your own MVC is that it can be a light weighted or complex as you need.
My experience with frameworks is that you basically have to write twice as much code than you would without using a framework. The good thing about frameworks is, that it forces you to work in a consistent way, but if you can work in a consistent way by making use of Design Patterns, best practices and common sense, I would suggest to stay away from frameworks.
A: Its very difficult to come to a conclusion about which framework is better than others. Depending on the nature and complexity of project and team members expertise & preference one may be more suitable than other in a given situation
I have compiled a list of Flex Frameworks with there brief descriptions and pointers to more information about them in this URL.
http://practicalflex.blogspot.com/2011/08/list-of-adobe-flex-tools-frameworks.html
the url may be helpful for anyone looking for evaluating a Flex framework for his/her project.
After evaluating many most of the Flex frameworks I found the Swiz framework most simpler and easy to get started with for a new developer. Hence it ensures easy maintainability & extensiblity of your application.
A: I have worked on cairngorm and mate frameworks. I started with cairngorm framework. It is good to work but difficult to understand in the beginning. It handles event dispatching cleverly. You can dispatch events from classes itself and it will be taken care of by the framework wired command classes. There is single repository for storing the data, so easy to handle the data. It is a singleton class. Once you get a hold of the framework, work is easier.
Mate on other hand is tag based framework. It is an event driven framework, so all events are handled in the eventmap file. It does event listening, property injection, and many other things from this class itself. You can dispatch events from the classes by passing it the instance of framework event dispatcher. You don't have to use singleton class like cairngorm in this. You can bind property in a class to views using directly using property injection so no need to use any singleton class. In mate all the classes and view are free from framework code, so it is decoupled framework. It is easy to move components from one place to other.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: Image cropping C# without .net library Can anyone advise on how to crop an image, let's say jpeg, without using any .NET framework constructs, just raw bytes? Since this is the only* way in Silverlight...
Or point to a library?
I'm not concerned with rendering i'm wanting to manipulate a jpg before uploading.
*There are no GDI+(System.Drawing) or WPF(System.Windows.Media.Imaging) libraries available in Silverlight.
Lockbits requires GDI+, clarified question
Using fjcore: http://code.google.com/p/fjcore/ to resize but no way to crop :(
A: You could easily write crop yourself in fjcore. Start with the code for Resizer
http://web.archive.org/web/20140304090029/http://code.google.com:80/p/fjcore/source/browse/trunk/FJCore/Resize/ImageResizer.cs?
and FilterNNResize -- you can see how the image data is stored -- it's just simple arrays of pixels.
The important part is:
for (int y = 0; y < _newHeight; y++)
{
i_sY = (int)sY; sX = 0;
UpdateProgress((double)y / _newHeight);
for (int x = 0; x < _newWidth; x++)
{
i_sX = (int)sX;
_destinationData[0][x, y] = _sourceData[0][i_sX, i_sY];
if (_color) {
_destinationData[1][x, y] = _sourceData[1][i_sX, i_sY];
_destinationData[2][x, y] = _sourceData[2][i_sX, i_sY];
}
sX += xStep;
}
sY += yStep;
}
shows you that the data is stored in an array of color planes (1 element for 8bpp gray, 3 elements for color) and each element has a 2-D array of bytes (x, y) for the image.
You just need to loop through the destination pixels, copying then from the appropriate place in the source.
edit: don't forget to provide the patch to the author of fjcore
A: ImageMagick does a pretty good job. If you're ok with handing off editing tasks to your server...
(Seriously? The recommended way of manipulating images in Silverlight is to work with raw bytes? That's... incredibly lame.)
A: I'm taking a look at : http://code.google.com/p/fjcore/source/checkout
A dependency free image processing library.
A: where is silverlight executed?
Is there any reason at all to send an complete picture to the client to make the client crop it?
Do it on the server... (if you are not creating an image editor that is..)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How can I get the localized name of a 'special' windows folder (Recycle bin etc.)? I'm trying to find out the 'correct' windows API for finding out the localized name of 'special' folders, specifically the Recycle Bin. I want to be able to prompt the user with a suitably localized dialog box asking them if they want to send files to the recycle bin or delete them directly.
I've found lots on the internet (and on Stackoverflow) about how to do the actual deletion, and it seems simple enough, I just really want to be able to have the text localized.
A: Read this article for code samples and usage:
http://www.codeproject.com/KB/winsdk/SpecialFolders.aspx
Also there is an article on MSDN that helps you Identify the Location of Special Folders with API Calls
A: I actually didn't find the CodeProject article terribly helpful, so I thought I'd answer this question with the actual code that I used to retrieve the localized name of the recycle bin.
This sample also tries to behave correctly with regard to freeing resources. Any comments are welcome, especially if you spot an error with my resource management!
public static string GetLocalizedRecycleBinName()
{
IntPtr relative_pidl, parent_ptr, absolute_pidl;
PInvoke.SHGetFolderLocation(IntPtr.Zero, PInvoke.CSIDL.BitBucket,
IntPtr.Zero, 0, out absolute_pidl);
try
{
PInvoke.SHBindToParent(absolute_pidl,
ref PInvoke.Guids.IID_IShellFolder,
out parent_ptr, out relative_pidl);
PInvoke.IShellFolder shell_folder =
Marshal.GetObjectForIUnknown(parent_ptr)
as PInvoke.IShellFolder;
// Release() for this object is called at finalization
if (shell_folder == null)
return Strings.RecycleBin;
PInvoke.STRRET strret = new PInvoke.STRRET();
StringBuilder sb = new StringBuilder(260);
shell_folder.GetDisplayNameOf(relative_pidl, PInvoke.SHGNO.Normal,
out strret);
PInvoke.StrRetToBuf(ref strret, relative_pidl, sb, 260);
string name = sb.ToString();
return String.IsNullOrEmpty(name) ? Strings.RecycleBin : name;
}
finally { PInvoke.ILFree(absolute_pidl); }
}
static class PInvoke
{
[DllImport("shell32.dll")]
public static extern int SHGetFolderLocation(IntPtr hwndOwner,
CSIDL nFolder, IntPtr hToken, uint dwReserved, out IntPtr ppidl);
[DllImport("shell32.dll")]
public static extern int SHBindToParent(IntPtr lpifq, [In] ref Guid riid,
out IntPtr ppv, out IntPtr pidlLast);
[DllImport("shlwapi.dll")]
public static extern Int32 StrRetToBuf(ref STRRET pstr, IntPtr pidl,
StringBuilder pszBuf, uint cchBuf);
[DllImport("shell32.dll")]
public static extern void ILFree([In] IntPtr pidl);
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("000214E6-0000-0000-C000-000000000046")]
public interface IShellFolder
{
[PreserveSig]
Int32 CompareIDs(Int32 lParam, IntPtr pidl1, IntPtr pidl2);
void ParseDisplayName(IntPtr hwnd, IntPtr pbc, String pszDisplayName,
UInt32 pchEaten, out IntPtr ppidl, UInt32 pdwAttributes);
void EnumObjects(IntPtr hwnd, int grfFlags,
out IntPtr ppenumIDList);
void BindToObject(IntPtr pidl, IntPtr pbc, [In] ref Guid riid,
out IntPtr ppv);
void BindToStorage(IntPtr pidl, IntPtr pbc, [In] ref Guid riid,
out IntPtr ppv);
void CreateViewObject(IntPtr hwndOwner, [In] ref Guid riid,
out IntPtr ppv);
void GetAttributesOf(UInt32 cidl,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]
IntPtr[] apidl, ref uint rgfInOut);
void GetUIObjectOf(IntPtr hwndOwner, UInt32 cidl,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]
IntPtr[] apidl, [In] ref Guid riid, UInt32 rgfReserved,
out IntPtr ppv);
void GetDisplayNameOf(IntPtr pidl, SHGNO uFlags, out STRRET pName);
void SetNameOf(IntPtr hwnd, IntPtr pidl, string pszName,
int uFlags, out IntPtr ppidlOut);
}
public enum CSIDL
{
BitBucket = 0x000a,
}
public enum SHGNO
{
Normal = 0x0000, ForParsing = 0x8000,
}
[StructLayout(LayoutKind.Explicit, Size = 520)]
public struct STRRETinternal
{
[FieldOffset(0)] public IntPtr pOleStr;
[FieldOffset(0)] public IntPtr pStr;
[FieldOffset(0)] public uint uOffset;
}
[StructLayout(LayoutKind.Sequential)]
public struct STRRET
{
public uint uType;
public STRRETinternal data;
}
public class Guids
{
public static Guid IID_IShellFolder =
new Guid("{000214E6-0000-0000-C000-000000000046}");
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: PostgreSQL performance monitoring tool I'm setting up a web application with a FreeBSD PostgreSQL back-end. I'm looking for some database performance optimization tool/technique.
A: Database optimization is usually a combination of two things
*
*Reduce the number of queries to the database
*Reduce the amount of data that needs to be looked at to answer queries
Reducing the amount of queries is usually done by caching non-volatile/less important data (e.g. "Which users are online" or "What are the latest posts by this user?") inside the application (if possible) or in an external - more efficient - datastore (memcached, redis, etc.). If you've got information which is very write-heavy (e.g. hit-counters) and doesn't need ACID-semantics you can also think about moving it out of the Postgres database to more efficient data stores.
Optimizing the query runtime is more tricky - this can amount to creating special indexes (or indexes in the first place), changing (possibly denormalizing) the data model or changing the fundamental approach the application takes when it comes to working with the database. See for example the Pagination done the Postgres way talk by Markus Winand on how to rethink the concept of pagination to make it more database efficient
Measuring queries the slow way
But to understand which queries should be looked at first you need to know how often they are executed and how long they run on average.
One approach to this is logging all (or "slow") queries including their runtime and then parsing the query log. A good tool for this is pgfouine which has already been mentioned earlier in this discussion, it has since been replaced by pgbadger which is written in a more friendly language, is much faster and more actively maintained.
Both pgfouine and pgbadger suffer from the fact that they need query-logging enabled, which can cause a noticeable performance hit on the database or bring you into disk space troubles on top of the fact that parsing the log with the tool can take quite some time and won't give you up-to-date insights on what is going in the database.
Speeding it up with extensions
To address these shortcomings there are now two extensions which track query performance directly in the database - pg_stat_statements (which is only helpful in version 9.2 or newer) and pg_stat_plans. Both extensions offer the same basic functionality - tracking how often a given "normalized query" (Query string minus all expression literals) has been run and how long it took in total. Due to the fact that this is done while the query is actually run this is done in a very efficient manner, the measurable overhead was less than 5% in synthetic benchmarks.
Making sense of the data
The list of queries itself is very "dry" from an information perspective. There's been work on a third extension trying to address this fact and offer nicer representation of the data called pg_statsinfo (along with pg_stats_reporter), but it's a bit of an undertaking to get it up and running.
To offer a more convenient solution to this problem I started working on a commercial project which is focussed around pg_stat_statements and pg_stat_plans and augments the information collected by lots of other data pulled out of the database. It's called pganalyze and you can find it at https://pganalyze.com/.
To offer a concise overview of interesting tools and projects in the Postgres Monitoring area i also started compiling a list at the Postgres Wiki which is updated regularly.
A: pgfouine works fairly well for me. And it looks like there's a FreeBSD port for it.
A: I've used pgtop a little. It is quite crude, but at least I can see which query is running for each process ID.
I tried pgfouine, but if I remember, it's an offline tool.
I also tail the psql.log file and set the logging criteria down to a level where I can see the problem queries.
#log_min_duration_statement = -1 # -1 is disabled, 0 logs all statements
# and their durations, > 0 logs only
# statements running at least this time.
I also use EMS Postgres Manager to do general admin work. It doesn't do anything for you, but it does make most tasks easier and makes reviewing and setting up your schema more simple. I find that when using a GUI, it is much easier for me to spot inconsistencies (like a missing index, field criteria, etc.). It's only one of two programs I'm willing to use VMWare on my Mac to use.
A: Munin is quite simple yet effective to get trends of how the database is evolving and performing over time. In the standard kit of Munin you can among other thing monitor the size of the database, number of locks, number of connections, sequential scans, size of transaction log and long running queries.
Easy to setup and to get started with and if needed you can write your own plugin quite easily.
Check out the latest postgresql plugins that are shipped with Munin here:
http://munin-monitoring.org/browser/branches/1.4-stable/plugins/node.d/
A: Well, the first thing to do is try all your queries from psql using "explain" and see if there are sequential scans that can be converted to index scans by adding indexes or rewriting the query.
Other than that, I'm as interested in the answers to this question as you are.
A: Check out Lightning Admin, it has a GUI for capturing log statements, not perfect but works great for most needs. http://www.amsoftwaredesign.com
A: DBTuna http://www.dbtuna.com/postgresql_monitor.php has recently started supporting PostgreSQL monitoring. We use it extensively for MySQL monitoring, so if it provides the same for Postgres then it should be a good fit for you too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Configure Lucene.Net with SQL Server Has anyone used Lucene.NET rather than using the full text search that comes with sql server?
If so I would be interested on how you implemented it.
Did you for example write a windows service that queried the database every hour then saved the results to the lucene.net index?
A: Yes, I've used it for exactly what you are describing. We had two services - one for read, and one for write, but only because we had multiple readers. I'm sure we could have done it with just one service (the writer) and embedded the reader in the web app and services.
I've used lucene.net as a general database indexer, so what I got back was basically DB id's (to indexed email messages), and I've also use it to get back enough info to populate search results or such without touching the database. It's worked great in both cases, tho the SQL can get a little slow, as you pretty much have to get an ID, select an ID etc. We got around this by making a temp table (with just the ID row in it) and bulk-inserting from a file (which was the output from lucene) then joining to the message table. Was a lot quicker.
Lucene isn't perfect, and you do have to think a little outside the relational database box, because it TOTALLY isn't one, but it's very very good at what it does. Worth a look, and, I'm told, doesn't have the "oops, sorry, you need to rebuild your index again" problems that MS SQL's FTI does.
BTW, we were dealing with 20-50million emails (and around 1 million unique attachments), totaling about 20GB of lucene index I think, and 250+GB of SQL database + attachments.
Performance was fantastic, to say the least - just make sure you think about, and tweak, your merge factors (when it merges index segments). There is no issue in having more than one segment, but there can be a BIG problem if you try to merge two segments which have 1mil items in each, and you have a watcher thread which kills the process if it takes too long..... (yes, that kicked our arse for a while). So keep the max number of documents per thinggie LOW (ie, dont set it to maxint like we did!)
EDIT Corey Trager documented how to use Lucene.NET in BugTracker.NET here.
A: I have not done it against database yet, your question is kinda open.
If you want to search an db, and can choose to use Lucene, I also guess that you can control when data is inserted to the database.
If so, there is little reason to poll the db to find out if you need to reindex, just index as you insert, or create an queue table which can be used to tell lucene what to index.
I think we don't need another indexer that is ignorant about what it is doing, and reindexing everytime, or uses resources wasteful.
A: I have used lucene.net also as storage engine, because it's easier to distribute and setup alternate machines with an index than a database, it's just a filesystem copy, you can index on one machine, and just copy the new files to the other machines to distribute the index. All the searches and details are shown from the lucene index, and the database is just used for editing. This setup has been proven as a very scalable solution for our needs.
Regarding the differences between sql server and lucene, the principal problem with sql server 2005 full text search is that the service is decoupled from the relational engine, so joins, orders, aggregates and filter between the full text results and the relational columns are very expensive in performance terms, Microsoft claims that this issues have been addressed in sql server 2008, integrating the full text search inside the relational engine, but I don't have tested it. They also made the whole full text search much more transparent, in previous versions the stemmers, stopwords, and several other parts of the indexing where like a black box and difficult to understand, and in the new version are easier to see how they works.
With my experience, if sql server meet your requirements, it will be the easiest way, if you expect a lot of growth, complex queries or need a big control of the full text search, you might consider working with lucene from the start because it will be easier to scale and personalise.
A: I used Lucene.NET along with MySQL. My approach was to store primary key of db record in Lucene document along with indexed text. In pseudo code it looks like:
*
*Store record:
insert text, other data to the table
get latest inserted ID
create lucene document
put (ID, text) into lucene document
update lucene index
*Querying
search lucene index
for each lucene doc in result set load data from DB by stored record's ID
Just to note, I switched from Lucene to Sphinx due to it superb performance
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "60"
} |
Q: Task oriented thread pooling I've created a model for executing worker tasks in a server application using a thread pool associated with an IO completion port such as shown in the posts below:
http://weblogs.asp.net/kennykerr/archive/2008/01/03/parallel-programming-with-c-part-4-i-o-completion-ports.aspx
http://blogs.msdn.com/larryosterman/archive/2004/03/29/101329.aspx
Are there any classes in boost that can help with this programming model?
A: Not really, at least, not last time I looked. I mean, boost::thread_group might make things marginally tidier in places, but not so as would make much of a difference, I don't think.
Boost's thread support seems marginally useful when writing something that's cross-platform, but given that what you're writing is going to be Win32-specific anyway (due to the use of IOCPs) there doesn't really seem to be much benefit from that.
A: You might want to check out the threadpool project, which looks like a nice threadpool implementation on top of boost. I haven't tried it myself, but it looks fairly nice.
A: I haven't seen anything in boost that helps with the structure that you tend to end up with when using IO Completion Ports, but then I haven't looked that recently... However, slightly off-topic, you might like to take a look at the IOCP based thread pool that is part of my free IOCP server framework. It might give you some ideas if nothing else. You can find the code here. The thread pool supports expansion and contraction based on demand and has been in use in production systems for over 6 years.
A: ACE has some reactors that you can use to model things around your IOCPs. Some of these could have been added to boost, but boost makes building them pretty easy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Apache - how do I build individual and/or all modules as shared modules On Mac OS X 10.5 I downloaded the latest version of Apache 2.2.9. After the usual configure, make, make install dance I had a build of apache without mod_rewrite. This wasn't statically linked and the module was not built in the /modules folder either.
I had to do the following to build Apache and mod_rewrite:
./configure --prefix=/usr/local/apache2 --enable-rewrite=shared
*
*Is there a way to tell Apache to build all modules as Shared Modules (DSOs) so I can control loading from the Apache config?
*Now that I have built Apache and the mod_rewrite DSO, how can I build another shared module without building all of Apache?
(The last time I built Apache (2.2.8) on Solaris, by default it built everything as a shared module.)
A: Try the ./configure option --enable-mods-shared="all", or --enable-mods-shared="<list of modules>" to compile modules as shared objects. See further details in Apache 2.2 docs
To just compile Apache with the ability to load shared objects (and add modules later), use --enable-so, then consult the documentation on compiling modules seperately in the Apache 2.2. DSO docs.
A: ./configure --prefix=/usr/local/apache2 --enable-mods-shared="all" --enable-proxy=shared
To get rewrite, proxy and bunch of other modules, I used the above command. In my previous installation, using --enable-mods-shared="all" compiled/installed the proxy module as well. But in v2.2.22 "all" did not include the proxy module.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: What is the meaning of "non temporal" memory accesses in x86 This is a somewhat low-level question. In x86 assembly there are two SSE instructions:
MOVDQA xmmi, m128
and
MOVNTDQA xmmi, m128
The IA-32 Software Developer's Manual says that the NT in MOVNTDQA stands for Non-Temporal, and that otherwise it's the same as MOVDQA.
My question is, what does Non-Temporal mean?
A: Espo is pretty much bang on target. Just wanted to add my two cents:
The "non temporal" phrase means lacking temporal locality. Caches exploit two kinds of locality - spatial and temporal, and by using a non-temporal instruction you're signaling to the processor that you don't expect the data item be used in the near future.
I am a little skeptical about the hand-coded assembly that uses the cache control instructions. In my experience these things lead to more evil bugs than any effective performance increases.
A: Non-Temporal SSE instructions (MOVNTI, MOVNTQ, etc.), don't follow the normal cache-coherency rules. Therefore non-temporal stores must be followed by an SFENCE instruction in order for their results to be seen by other processors in a timely fashion.
When data is produced and not (immediately) consumed again, the fact that memory store operations read a full cache line first and then modify the cached data is detrimental to performance. This operation pushes data out of the caches which might be needed again in favor of data which will not be used soon. This is especially true for large data structures, like matrices, which are filled and then used later. Before the last element of the matrix is filled the sheer size evicts the first elements, making caching of the writes ineffective.
For this and similar situations, processors provide support for non-temporal write operations. Non-temporal in this context means the data will not be reused soon, so there is no reason to cache it. These non-temporal write operations do not read a cache line and then modify it; instead, the new content is directly written to memory.
Source: http://lwn.net/Articles/255364/
A: According to the Intel® 64 and IA-32 Architectures Software Developer’s Manual, Volume 1: Basic Architecture,
"Programming with Intel Streaming SIMD Extensions (Intel SSE)" chapter:
Caching of Temporal vs. Non-Temporal Data
Data referenced by a program can be temporal (data will be used again) or non-temporal (data will be referenced once and not reused in the immediate future). For example, program code is generally temporal, whereas, multimedia data, such as the display list in a 3-D graphics application, is often non-temporal. To make efficient use of the processor’s caches, it is generally desirable to cache temporal data and not cache non-temporal data. Overloading the processor’s caches with non-temporal data is sometimes referred to as "polluting the caches". The SSE and SSE2 cacheability control instructions enable a program to write non-temporal data to memory in a manner that minimizes pollution of caches.
Description of non-temporal load and store instructions.
Source: Intel 64 and IA-32 Architectures Software Developer’s Manual, Volume 2: Instruction Set Reference
LOAD (MOVNTDQA—Load Double Quadword Non-Temporal Aligned Hint)
Loads a double quadword from the source operand (second operand) to the destination operand (first operand) using a non-temporal hint if the memory source is WC (write combining) memory type [...]
[...] the processor does not read the data into the cache hierarchy, nor does it fetch the corresponding cache line from memory into the cache hierarchy.
Note that, as Peter Cordes comments, it's not useful on normal WB (write-back) memory on current processors because the NT hint is ignored (probably because there are no NT-aware HW prefetchers) and the full strongly-ordered load semantics apply. prefetchnta can be used as a pollution-reducing load from WB memory
STORE (MOVNTDQ—Store Packed Integers Using Non-Temporal Hint)
Moves the packed integers in the source operand (second operand) to the destination operand (first operand) using a non-temporal hint to prevent caching of the data during the write to memory.
[...] the processor does not write the data into the cache hierarchy, nor does it fetch the corresponding cache line from memory into the cache hierarchy.
Using the terminology defined in Cache Write Policies and Performance, they can be considered as write-around (no-write-allocate, no-fetch-on-write-miss).
Finally, it may be interesting to review John McAlpin notes about non-temporal stores.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "154"
} |
Q: What is currently the best way to get a favicon to display in all browsers that support Favicons? What is currently the best way to get a favicon to display in all browsers that currently support it?
Please include:
*
*Which image formats are supported by which browsers.
*Which lines are needed in what places for the various browsers.
A: To also support touch icons for tablets and smartphones I prefer the approach of HTML5Boilerplate
More information on touch icons can be found in this article.
With the current status of browser-support you don't even have to add the HTML tag for the favicon in your document. The browsers will search automaticly a list of files, see this example for iOS:
If no icons are specified in the HTML, iOS Safari will search the
website’s root directory for icons with the apple-touch-icon or
apple-touch-icon-precomposed prefix. For example, if the appropriate
icon size for the device is 57 × 57 pixels, iOS searches for filenames
in the following order:
*
*apple-touch-icon-57x57-precomposed.png
*apple-touch-icon-57x57.png
*apple-touch-icon-precomposed.png
*apple-touch-icon.png
My advise is to not include a favicon in your document, but have a list of files ready in the root website:
*
*apple-touch-icon-114x114-precomposed.png
*apple-touch-icon-144x144-precomposed.png
*apple-touch-icon-57x57-precomposed.png
*apple-touch-icon-72x72-precomposed.png
*apple-touch-icon-precomposed.png
*apple-touch-icon.png (57px*57px)
*favicon.ico HiDPI (32x32px)
When you download a template from html5boilerplate.com these are all included, you just have to replace them with your own icons.
A: Wikipedia to the rescue
A: IE6 cannot handle PNGs correctly, be warned.
A: Favicon must be an .ico file to work properly on all browsers.
Modern browsers also support PNG and GIF images.
I've found that in general the easiest way to create one is to use a freely available web service such as favicon.cc.
A: There is also a site where you can check how the favicon of any page is made
getfavicon.org
There you can see a tutorial about making favicons, image types and resolutions, it's nice!
A: Having a favicon.* in your root directory is automatically detected by most browsers. You can ensure it's detected by using:
<link rel="icon" type="image/png" href="/path/image.png" />
Personally I use .png images but most formats should work.
A: I go for a belt and braces approach here.
I create a 32x32 icon in both the .ico and .png formats called favicon.ico and favicon.png. The icon name doesn't really matter unless you are dealing with older browsers.
*
*Place favicon.ico at your site root to support the older browsers (optional and only relevant for older browsers.
*Place favicon.png in my images sub-directory (just to keep things tidy).
*Add the following HTML inside the <head> element.
<link rel="icon" href="/images/favicon.png" type="image/png" />
<link rel="shortcut icon" href="/favicon.ico" />
Please note that:
*
*The MIME type for .ico files was registered as image/vnd.microsoft.icon by the IANA.
*Internet Explorer will ignore the type attribute for the shortcut icon relationship and this is the only browser to support this relationship, it doesn't need to be supplied.
Reference
A: I use .ico format and put the following two lines within the <head> element:
<link rel="icon" href="/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
A: The answer to this question has become complicated enough that the best way is to just use a tool like RealFaviconGenerator, which lets you upload a png/jpg and then generates favicons and code to cover all the platforms for you: https://realfavicongenerator.net/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "83"
} |
Q: How can an application use multiple cores or CPUs in .NET or Java? When launching a thread or a process in .NET or Java, is there a way to choose which processor or core it is launched on? How does the shared memory model work in such cases?
A: If you're using multiple threads, the operating system will automatically take care of using multiple cores.
A:
is there a way to choose which processor or core it is launched on?
You can use the task manager to tell windows what CPU(s) your program should be allowed to run on. Normally this is only useful for troubleshooting legacy programs which have broken implementations of multi-threading. To do this,
*
*Run task manager
*Find your process in the Processes window.
*Right click and choose Set Affinity...
*Tick the checkboxes next to the CPU's you want to allow your application to run on. Windows will then only schedule threads from that process onto those particular CPU's
If I recall correctly, windows will 'remember' these settings for subsequent times your process is run, but please don't quote me on that - run some tests yourself :-)
You can also do this programatically in .NET after your program has launched using using the System.Diagnostics.Process.ProcessorAffinity property, but I don't think it will 'remember' the settings, so there will always be a short period in which your app is run on whichever CPU windows sees fit. I don't know how to do this in java sorry.
Note:
This applies at the entire process level. If you set affinity for CPU0 only, and then launch 50 threads, all 50 of those threads will run on CPU0, and CPU1, 2, 3, etc will sit around doing nothing.
Just to reiterate the point, this is primarily useful for troubleshooting broken legacy software. If your software is not broken, you really shouldn't mess with any of these settings, and let windows decide the best CPU(s) to run your program on, so it can take the rest of the system's performance into account.
As for the 'shared memory' model, it works the same, but there are more things that can go subtly wrong when your app is running on multiple CPU's as opposed to just timeslices on a single one.
For an eye-opening example, read this ridiculousfish article about CPU's and Memory Barriers.
It's aimed at OSX development on PowerPC, but general enough that it should apply everywhere. IMHO it's one of the top ten 'all developers should read this' articles I've read.
A: The operating system takes care of multi-threading when the virtual machine is using native threads (as opposed to green-threads), and you can't specify low level details, like choosing a processor for a certain thread. It is better that way because you usually have many more threads than you have processors available, so the operating system needs to do time-slicing to give all threads a chance to run.
That being said, you can set threads priorities if you have a critical task, and a threading API usually provides this possibility. See the Java API for example: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#setPriority(int)
PS: there's something broken in the parsing engine ... I had to add the above link as plain text
A: I have used this in a couple of programs because my core 0 was kind of messed up.
// Programmatically set process affinity
var process = System.Diagnostics.Process.GetCurrentProcess();
// Set Core 0
process.ProcessorAffinity = new IntPtr(0x0001);
or
// Set Core 1
process.ProcessorAffinity = new IntPtr(0x0002);
More on this in "Process.ProcessorAffinity Property".
A: I would have a look at the Parallel extensions to the .NET framework. It is still in CTP, however it supposed to make the best use of multi core processors. The easiest place to get started for .NET is on the parallel teams blog.
As for Java I have no idea.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How do I avoid read locks in my database? How do I avoid read locks in my database?
Answers for multiple databases welcome!
A: In SQL Server you can use the with(nolock) keyword in your select statements. For example:
Select table1.columna, table2.columna
from table1 with(nolock), table2 with(nolock)
Make sure to specify with(nolock) for each table/view in the query.
A: In Oracle the default mode of operation is the Read committed isolation level where a select statement is not blocked by another transaction modifying the data it's reading.
From Data Concurrency and Consistency:
Each query executed by a transaction sees only data that was committed before the query (not the transaction) began. An Oracle query never reads dirty (uncommitted) data.
A: PostgreSQL also uses MVCC (Multi-Version Concurrency Control), so using the default transaction isolation level (read-committed), you should never block, unless somebody is doing maintainace on th DB (dropping / adding columns / tables / indexes / etc).
A: In Firebird writers never block readers and there are no dirty-reads. Only read-commited and snapshot isolation levels.
It uses a multi-generational engine (like oracle i believe) instead of simple page or record locking.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to Clear OutputCache for Website without Restarting App Is there a way clear or reset the outputcache for an entire website without a restart?
I'm just starting to use outputcache on a site and when I make a mistake in setting it up I need a page I can browse to that will reset it.
A: This should do the trick:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim path As String
path="/AbosoluteVirtualPath/OutputCached.aspx"
HttpResponse.RemoveOutputCacheItem(path)
End Sub
A: Add the following code to controller or to page code:
HttpContext.Cache.Insert("Page", 1);
Response.AddCacheItemDependency("Page");
To clear output cachne use the following command in controller:
HttpContext.Cache.Remove("Page");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: CSS - Make divs align horizontally I have a container div with a fixed width and height, with overflow: hidden.
I want a horizontal row of float: left divs within this container. Divs which are floated left will naturally push onto the 'line' below after they read the right bound of their parent. This will happen even if the height of the parent should not allow this. This is how this looks:
How I would like it to look:
![Right][2] - removed image shack image that had been replaced by an advert
Note: the effect I want can be achieved by using inline elements & white-space: no-wrap (that is how I did it in the image shown). This, however, is no good to me (for reasons too lengthy to explain here), as the child divs need to be floated block level elements.
A: You can now use css flexbox to align divs horizontally and vertically if you need to. general formula goes like this
parent-div {
display: flex;
flex-wrap: wrap;
/* for horizontal aligning of child divs */
justify-content: center;
/* for vertical aligning */
align-items: center;
}
child-div {
width: /* yoursize for each div */
;
}
A: This seems close to what you want:
#foo {
background: red;
max-height: 100px;
overflow-y: hidden;
}
.bar {
background: blue;
width: 100px;
height: 100px;
float: left;
margin: 1em;
}
<div id="foo">
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
</div>
A: you can use the clip property:
#container {
position: absolute;
clip: rect(0px,200px,100px,0px);
overflow: hidden;
background: red;
}
note the position: absolute and overflow: hidden needed in order to get clip to work.
A: style="overflow:hidden" for parent div and style="float: left" for all the child divs are important to make the divs align horizontally for old browsers like IE7 and below.
For modern browsers, you can use style="display: table-cell" for all the child divs and it would render horizontally properly.
A: Float: left, display: inline-block will both fail to align the elements horizontally if they exceed the width of the container.
It's important to note that the container should not wrap if the elements MUST display horizontally:
white-space: nowrap
A: You may put an inner div in the container that is enough wide to hold all the floated divs.
#container {
background-color: red;
overflow: hidden;
width: 200px;
}
#inner {
overflow: hidden;
width: 2000px;
}
.child {
float: left;
background-color: blue;
width: 50px;
height: 50px;
}
<div id="container">
<div id="inner">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
</div>
A: Float them left. In Chrome, at least, you don't need to have a wrapper, id="container", in LucaM's example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "88"
} |
Q: Best Practices for versioning web site? What's are the best practices for versioning web sites?
*
*Which revision control systems are well suited for such a job?
*What special-purpose tools exist?
*What other questions should I be asking?
A: Firstly you can - and should - use a revision control system, most will handle binary files although unlike text files you can't merge two different set of changes so you may want to set the system up to lock these files whilst they are being changed (assuming that that's not the default mode of operation for you rcs in the first place).
Where things get a bit more interesting for Websites is managing those files that are required for the site but don't actually form part of the site - the most obvious example being something like .psd files from which web graphics are produced but which don't get deployed.
We therefore have a tree for each site which has two folders: assets and site. Assets are things that aren't in the site, and site is - well the site.
What you have to watch with this is that designers tend to have their own "systems" for "versioning" graphic files (count the layers in the PSD). You don't need necessarily to stop them doing this but you do need to ensure that they commit each change too.
Other questions?
Deployment. We're still working on this one (-: But we're getting better (I'm happier now with what we do!)
Murph
A: In response to Christian Lescuyer's post, you also need to enable the "svn:keywords" property on the file with that line in it. Subversion won't bother looking in your files for keywords like $Revision$ unless that property is set.
Also, if using PHP like in his example, you may want to put $Revision$ inside a single-quoted string instead of a double quoted string to prevent PHP from trying to parse $Revision as a PHP variable and throwing a warning. :)
A: I use Subversion.
As an easy way to reference the website version (production, testing, development), I use a very simple trick. I add the revision number somewhere on the site (eg in the admin footer). Something like this:
<?php print("$Revision: 1 $"); ?>
Each time you checkout (development versions) or export (for production), the "1" will be replaced by the revision number in your repository, thus making it easy to setup the customer version on your test server, for example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Make browser window blink in task Bar How do I make a user's browser blink/flash/highlight in the task bar using JavaScript? For example, if I make an AJAX request every 10 seconds to see if the user has any new messages on the server, I want the user to know it right away, even if he is using another application at the time.
Edit: These users do want to be distracted when a new message arrives.
A: this won't make the taskbar button flash in changing colours, but the title will blink on and off until they move the mouse. This should work cross platform, and even if they just have it in a different tab.
newExcitingAlerts = (function () {
var oldTitle = document.title;
var msg = "New!";
var timeoutId;
var blink = function() { document.title = document.title == msg ? ' ' : msg; };
var clear = function() {
clearInterval(timeoutId);
document.title = oldTitle;
window.onmousemove = null;
timeoutId = null;
};
return function () {
if (!timeoutId) {
timeoutId = setInterval(blink, 1000);
window.onmousemove = clear;
}
};
}());
Update: You may want to look at using HTML5 notifications.
A: var oldTitle = document.title;
var msg = "New Popup!";
var timeoutId = false;
var blink = function() {
document.title = document.title == msg ? oldTitle : msg;//Modify Title in case a popup
if(document.hasFocus())//Stop blinking and restore the Application Title
{
document.title = oldTitle;
clearInterval(timeoutId);
}
};
if (!timeoutId) {
timeoutId = setInterval(blink, 500);//Initiate the Blink Call
};//Blink logic
A: I've made a jQuery plugin for the purpose of blinking notification messages in the browser title bar. You can specify different options like blinking interval, duration, if the blinking should stop when the window/tab gets focused, etc. The plugin works in Firefox, Chrome, Safari, IE6, IE7 and IE8.
Here is an example on how to use it:
$.titleAlert("New mail!", {
requireBlur:true,
stopOnFocus:true,
interval:600
});
If you're not using jQuery, you might still want to look at the source code (there are a few quirky bugs and edge cases that you need to work around when doing title blinking if you want to fully support all major browsers).
A: Supposedly you can do this on windows with the growl for windows javascript API:
http://ajaxian.com/archives/growls-for-windows-and-a-web-notification-api
Your users will have to install growl though.
Eventually this is going to be part of google gears, in the form of the NotificationAPI:
http://code.google.com/p/gears/wiki/NotificationAPI
So I would recommend using the growl approach for now, falling back to window title updates if possible, and already engineering in attempts to use the Gears Notification API, for when it eventually becomes available.
A: My "user interface" response is: Are you sure your users want their browsers flashing, or do you think that's what they want? If I were the one using your software, I know I'd be annoyed if these alerts happened very often and got in my way.
If you're sure you want to do it this way, use a javascript alert box. That's what Google Calendar does for event reminders, and they probably put some thought into it.
A web page really isn't the best medium for need-to-know alerts. If you're designing something along the lines of "ZOMG, the servers are down!" alerts, automated e-mails or SMS messages to the right people might do the trick.
A: The only way I can think of doing this is by doing something like alert('you have a new message') when the message is received. This will flash the taskbar if the window is minimized, but it will also open a dialog box, which you may not want.
A: Why not take the approach that GMail uses and show the number of messages in the page title?
Sometimes users don't want to be distracted when a new message arrives.
A: you could change the title of the web page with each new message to alert the user. I did this for a browser chat client and most users thought it worked well enough.
document.title = "[user] hello world";
A: You may want to try window.focus() - but it may be annoying if the screen switches around
A: AFAIK, there is no good way to do this with consistency. I was writing an IE only web-based IM client. We ended up using window.focus(), which works most of the time. Sometimes it will actually cause the window to steal focus from the foreground app, which can be really annoying.
A: function blinkTab() {
const browserTitle = document.title;
let timeoutId;
let message = 'My New Title';
const stopBlinking = () => {
document.title = browserTitle;
clearInterval(timeoutId);
};
const startBlinking = () => {
document.title = document.title === message ? browserTitle : message;
};
function registerEvents() {
window.addEventListener("focus", function(event) {
stopBlinking();
});
window.addEventListener("blur", function(event) {
const timeoutId = setInterval(startBlinking, 500);
});
};
registerEvents();
};
blinkTab();
A:
These users do want to be distracted when a new message arrives.
It sounds like you're writing an app for an internal company project.
You might want to investigate writing a small windows app in .net which adds a notify icon and can then do fancy popups or balloon popups or whatever, when they get new messages.
This isn't overly hard and I'm sure if you ask SO 'how do I show a tray icon' and 'how do I do pop up notifications' you'll get some great answers :-)
For the record, I'm pretty sure that (other than using an alert/prompt dialog box) you can't flash the taskbar in JS, as this is heavily windows specific, and JS really doesn't work like that. You may be able to use some IE-specific windows activex controls, but then you inflict IE upon your poor users. Don't do that :-(
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "106"
} |
Q: Event handling in Dojo Taking Jeff Atwood's advice, I decided to use a JavaScript library for the very basic to-do list application I'm writing. I picked the Dojo toolkit, version 1.1.1. At first, all was fine: the drag-and-drop code I wrote worked first time, you can drag tasks on-screen to change their order of precedence, and each drag-and-drop operation calls an event handler that sends an AJAX call to the server to let it know that order has been changed.
Then I went to add in the email tracking functionality. Standard stuff: new incoming emails have a unique ID number attached to their subject line, all subsequent emails about that problem can be tracked by simply leaving that ID number in the subject when you reply. So, we have a list of open tasks, each with their own ID number, and each of those tasks has a time-ordered list of associated emails. I wanted the text of those emails to be available to the user as they were looking at their list of tasks, so I made each task box a Dijit "Tree" control - top level contains the task description, branches contain email dates, and a single "leaf" off of each of those branches contains the email text.
First problem: I wanted the tree view to be fully-collapsed by default. After searching Google quite extensively, I found a number of solutions, all of which seemed to be valid for previous versions of Dojo but not the one I was using. I eventually figured out that the best solution would seem to be to have a event handler called when the Tree control had loaded that simply collapsed each branch/leaf. Unfortunately, even though the Tree control had been instantiated and its "startup" event handler called, the branches and leaves still hadn't loaded (the data was still being loaded via an AJAX call). So, I modified the system so that all email text and Tree structure is added server-side. This means the whole fully-populated Tree control is available when its startup event handler is called.
So, the startup event handler fully collapses the tree. Next, I couldn't find a "proper" way to have nice formatted text for the email leaves. I can put the email text in the leaf just fine, but any HTML gets escaped out and shows up in the web page. Cue more rummaging around Dojo's documentation (tends to be out of date, with code and examples for pre-1.0 versions) and Google. I eventually came up with the solution of getting JavaScript to go and read the SPAN element that's inside each leaf node and un-escape the escaped HTML code in it's innerHTML. I figured I'd put code to do this in with the fully-collapse-the-tree code, in the Tree control's startup event handler.
However... it turns out that the SPAN element isn't actually created until the user clicks on the expando (the little "+" symbol in a tree view you click to expand a node). Okay, fair enough - I'll add the re-formatting code to the onExpand() event handler, or whatever it's called. Which doesn't seem to exist. I've searched to documentation, I've searched Google... I'm quite possibly mis-understanding Dojo's "publish/subscribe" event handling system, but I think that mainly because there doesn't seem to be any comprehensive documentation for it anywhere (like, where do I find out what events I can subscribe to?).
So, in the end, the best solution I can come up with is to add an onClick event handler (not a "Dojo" event, but a plain JavaScript event that Dojo knows nothing about) to the expando node of each Tree branch that re-formats the HTML inside the SPAN element of each leaf. Except... when that is called, the SPAN element still doesn't exist (sometimes - other times it's been cached, just to further confuse you). Therefore, I have the event handler set up a timer that periodically calls a function that checks to see if the relevant SPAN element has turned up yet before then re-formatting it.
// An event handler called whenever a "email title" tree node is expanded.
function formatTreeNode(nodeID) {
if (dijit.byId(nodeID).getChildren().length != 0) {
clearInterval(nodeUpdateIntervalID);
messageBody = dijit.byId(nodeID).getChildren()[0].labelNode.innerHTML
if (messageBody.indexOf("<b>Message text:</b>") == -1) {
messageBody = messageBody.replace(/>/g, ">");
messageBody = messageBody.replace(/</g, "<");
messageBody = messageBody.replace(/&/g, "&");
dijit.byId(nodeID).getChildren()[0].labelNode.innerHTML = "<b>Message text:</b><div style=\"font-family:courier\">"+messageBody+"</div>";
}
}
}
// An event handler called when a tree node has been set up - we changed the default fully-expanded to fully-collapsed.
function setupTree(theTree) {
dijit.byId("tree-"+theTree).rootNode.collapse();
messageNode = dijit.byId("tree-"+theTree).rootNode.getChildren();
for (pl = 0; pl < messageNode.length; pl++) {
messageNode[pl].collapse();
messageNode[pl].expandoNode.onclick = eval("nodeUpdateIntervalID = setInterval(\"formatTreeNode('"+messageNode[pl].id+"')\",200); formatTreeNode('"+messageNode[pl].id+"');");
}
}
The above has the feel of a truly horrible hack, and I feel sure I must have taken a wrong turn somewhere early on in my thought process. Can someone please tell me:
*
*The correct way to go about putting nicely-formatted text inside a Dojo/Dijit Tree control.
*The correct way to handle Dojo events, like where I can figure out what events are available for me to subscribe to.
*A better JavaScript library to use (can I do what I want to with JQuery and avoid the all-around-the-houses approach seen above?).
PS: If you're naming a software project, give thought to its name's uniqueness in Google - I'm sure searching for "Dojo" documentation in Google would be easier without all the martial arts results getting in the way.
PPS: Firefox spellchecker knows how to spell "Atwood", correcting me when I put two 'T's instead of one. Is Jeff just that famous now?
A: I assume that you followed the dijit.Tree and dojo.data in Dojo 1.1 tutorial which directed you to pass the data to the tree control using a data store. That had me banging my head of a brick wall for a while.
Its not really a great approach and the alternative is not really well documented. You need to create a use model instead. I have included an example below of a tree model that I created for displaying the structure of an LDAP directory.
You will find the default implementation of the model in your dojo distribution at ./dijit/_tree/model.js. The comments should help you understand the functions supported by the model.
The IDirectoryService class the code below are stubs for server-side Java POJOs generated by Direct Web Remoting (DWR). I highly recommend DWR if you going to be doing a lot of client-server interaction.
dojo.declare("LDAPDirectoryTreeModel", [ dijit.tree.model ], {
getRoot : function(onItem) {
IDirectoryService.getRoots( function(roots) {
onItem(roots[0])
});
},
mayHaveChildren : function(item) {
return true;
},
getChildren : function(parentItem, onComplete) {
IDirectoryService.getChildrenImpl(parentItem, onComplete);
},
getIdentity : function(item) {
return item.dn;
},
getLabel : function(item) {
return item.rdn;
}
});
And here is an extract from the my JSP page where I created the model and used it to populate the tree control.
<div
dojoType="LDAPDirectoryTreeModel"
jsid="treeModel"
id="treeModel">
</div>
<div
jsid="tree"
id="tree"
dojoType="dijit.Tree" model="treeModel"
labelAttr="name"
label="${directory.host}:${directory.port}">
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to make Ruby or Python web sites to use multiple cores? Even though Python and Ruby have one kernel thread per interpreter thread, they have a global interpreter lock (GIL) that is used to protect potentially shared data structures, so this inhibits multi-processor execution. Even though the portions in those languajes that are written in C or C++ can be free-threaded, that's not possible with pure interpreted code unless you use multiple processes. What's the best way to achieve this? Using FastCGI? Creating a cluster or a farm of virtualized servers? Using their Java equivalents, JRuby and Jython?
A: I'm not totally sure which problem you want so solve, but if you deploy your python/django application via an apache prefork MPM using mod_python apache will start several worker processes for handling different requests.
If one request needs so much resources, that you want to use multiple cores have a look at pyprocessing. But I don't think that would be wise.
A: The 'standard' way to do this with rails is to run a "pack" of Mongrel instances (ie: 4 copies of the rails application) and then use apache or nginx or some other piece of software to sit in front of them and act as a load balancer.
This is probably how it's done with other ruby frameworks such as merb etc, but I haven't used those personally.
The OS will take care of running each mongrel on it's own CPU.
If you install mod_rails aka phusion passenger it will start and stop multiple copies of the rails process for you as well, so it will end up spreading the load across multiple CPUs/cores in a similar way.
A: Use an interface that runs each response in a separate interpreter, such as mod_wsgi for Python. This lets multi-threading be used without encountering the GIL.
EDIT: Apparently, mod_wsgi no longer supports multiple interpreters per process because idiots couldn't figure out how to properly implement extension modules. It still supports running requests in separate processes FastCGI-style, though, so that's apparently the current accepted solution.
A: In Python and Ruby it is only possible to use multiple cores, is to spawn new (heavyweight) processes.
The Java counterparts inherit the possibilities of the Java platform. You could imply use Java threads. That is for example a reason why sometimes (often) Java Application Server like Glassfish are used for Ruby on Rails applications.
A: For Python, the PyProcessing project allows you to program with processes much like you would use threads. It is included in the standard library of the recently released 2.6 version as multiprocessing. The module has many features for establishing and controlling access to shared data structures (queues, pipes, etc.) and support for common idioms (i.e. managers and worker pools).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Caching MySQL queries Is there a simple way to cache MySQL queries in PHP or failing that, is there a small class set that someone has written and made available that will do it? I can cache a whole page but that won't work as some data changes but some do not, I want to cache the part that does not.
A: You can use Zend Cache to cache results of your queries among other things.
A: This is a great overview of how to cache queries in MySQL:
*
*The MySQL Query Cache
A: I think the query cache size is 0 by default, which is off.
Edit your my.cnf file to give it at least a few megabytes.
No PHP changes necessary :)
A: It may be complete overkill for what you're attempting, but have a look at eAccelerator or memcache. If you have queries that will change regularly and queries that won't, you may not want all of your db queries cached for the same length of time by mysql.
Caching engines like the above allow you to decide, on a query-by-query basis, how long the data should be cached for. So say you've data in your header that will change infrequently, you can check if it's currently in the cache - if so, return it, otherwise do the query, and put it into cache with a lifetime of N, so for the next N seconds every page load will pull the data from cache without going near MySQL.
You're then free to pull your other data "live" from the db as and when required, by-passing the cache.
A: I would recommend the whole page caching route. If some of the data changes, simply place tokens/placeholders in place of the dynamic data. Cache the entire page with those tokens in place, then post process the tokens for the cached data for the tokens. Thus you now have a cached page that contains dynamic content.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How do I make an HTML page print in landscape when the user selects 'print'? We generate web pages that should always be printed in landscape mode. Web browser print dialogs default to portrait, so for every print job the user has to manually select landscape. It's minor, but would be nice for the user if we can remove this unnecessary step.
Thanks in advance to all respondents.
A: A quick Google indicates that it's not really supported. There's more than a few folks out there trying to hack their way to it - but I'd strongly suggest just rendering a server side PDF instead.
A: Possible in CSS2 (@page, looks like Opera only) and in CSS3 which will work nowhere. Sorry.
A: The @page rule is supposed to allow this, but is only implemented in Opera.
A: I was looking to do this same thing and found this article. It looks particularly "hacky" and as the author points out, may invoke an active x warning in IE. Seems like a losing proposition to confuse the user with an active x warning when they just wanted to print a web page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: What's the idiomatic way to do async socket programming in Delphi? What is the normal way people writing network code in Delphi use Windows-style overlapped asynchronous socket I/O?
Here's my prior research into this question:
The Indy components seem entirely synchronous. On the other hand, while ScktComp unit does use WSAAsyncSelect, it basically only asynchronizes a BSD-style multiplexed socket app. You get dumped in a single event callback, as if you had just returned from select() in a loop, and have to do all the state machine navigation yourself.
The .NET situation is considerably nicer, with Socket.BeginRead / Socket.EndRead, where the continuation is passed directly to Socket.BeginRead, and that's where you pick back up. A continuation coded as a closure obviously has all the context you need, and more.
A: I have found that Indy, while a simpler concept in the beginning, is awkward to manage due to the need to kill sockets to free threads at application termination. In addition, I had the Indy library stop working after an OS patch upgrade. ScktComp works well for my application.
A: @Roddy - Synchronous sockets are not what I'm after. Burning a whole thread for the sake of a possibly long-lived connection means you limit the amount of concurrent connections to the number of threads that your process can contain. Since threads use a lot of resources - reserved stack address space, committed stack memory, and kernel transitions for context switches - they do not scale when you need to support hundreds of connections, much less thousands or more.
A:
What is the normal way people writing
network code in Delphi use
Windows-style overlapped asynchronous
socket I/O?
Well, Indy has been the 'standard' library for socket I/O for a long while now - and it's based on blocking sockets. This means if you want asynchronous behaviour, you use additional thread(s) to connect/read/write data. To my mind this is actually a major advantage, as there's no need to manage any kind of state machine navigation, or worry about callback procs or similar stuff. I find the logic of my 'reading' thread is less cluttered and much more portable than non-blocking sockets would allow.
Indy 9 has been mostly bombproof, fast and reliable for us. However the move to Indy 10 for Tiburon is causing me a little concern.
@Mike: "...the need to kill sockets to free threads...".
This made go "huh?" until I remembered our threading library uses an exception-based technique to kill 'waiting' threads safely. We call QueueUserAPC to queue a function which raises a C++ exception (NOT derived from class Exception) which should only be caught by our thread wrapper procedure. All destructors get called so the threads all terminate cleanly and tidy up on the way out.
A:
"Synchronous sockets are not what I'm after."
Understood - but I think in that case the answer to your original question is that there just isn't a Delphi idiom for async socket IO because it's actually a highly specialized and uncommon requirement.
As a side issue, you might find these links interesting. They're both a little old, and more *nxy than Windows. The second one implies that - in the right environment - threads might not be as bad as you think.
The C10K problem
Why Events Are A Bad Idea (for High-concurrency Servers)
A: @Chris Miller - What you've stated in your answer is factually inaccurate.
Windows message-style async, as available through WSAAsyncSelect, is indeed largely a workaround for lack of a proper threading model in Win 3.x days.
.NET Begin/End, however, is not using extra threads. Instead, it is using overlapped I/O, using the extra argument on WSASend / WSARecv, specifically the overlapped completion routine, to specify the continuation.
This means that the .NET style harnesses the Windows OS's async I/O support to avoid burning a thread by blocking on a socket.
Since threads are generally speaking expensive (unless you specify a very small stack size to CreateThread), having threads blocking on sockets will stop you from scaling to 10,000s of concurrent connections.
This is why it's important that async I/O be used if you want to scale, and also why .NET is not, I repeat, is not, simply "using threads, [...] just managed by the Framework".
A: @Roddy - I've already read the links you point to, they are both referenced from Paul Tyma's presentation "Thousands of Threads and Blocking I/O - The old way to write Java Servers is New again".
Some of the things that don't necessarily jump out from Paul's presentation, however, are that he specified -Xss:48k to the JVM on startup, and that he's assuming that the JVM's NIO implementation is efficient in order for it to be a valid comparison.
Indy does not specify a similarly shrunken and tightly constrained stack size. There are no calls to BeginThread (the Delphi RTL thread creation routine, which you should use for such situations) or CreateThread (the raw WinAPI call) in the Indy codebase.
The default stack size is stored in the PE, and for the Delphi compiler it defaults to 1MB of reserved address space (space is committed page by page by the OS in 4K chunks; in fact, the compiler needs to generate code to touch pages if there are >4K of locals in a function, because the extension is controlled by page faults, but only for the lowest (guard) page in the stack). That means you're going to run out of address space after max 2,000 concurrent threads handling connections.
Now, you can change the default stack size in the PE using the {$M minStackSize [,maxStackSize]} directive, but that will affect all threads, including the main thread. I hope you don't do much recursion, because 48K or (similar) isn't a lot of space.
Now, whether Paul is right about non-performance of async I/O for Windows in particular, I'm not 100% sure - I'd have to measure it to be certain. What I do know, however, is that arguments about threaded programming being easier than async event-based programming, are presenting a false dichotomy.
Async code doesn't need to be event-based; it can be continuation-based, like it is in .NET, and if you specify a closure as your continuation, you get state maintained for you for free. Moreover, conversion from linear thread-style code to continuation-passing-style async code can be made mechanical by a compiler (CPS transform is mechanical), so there need be no cost in code clarity either.
A: There is a free IOCP (completion ports) socket components : http://www.torry.net/authorsmore.php?id=7131 (source code included)
"By Naberegnyh Sergey N.. High
performance socket server based on
Windows Completion Port and with using
Windows Socket Extensions. IPv6
supported. "
i've found it while looking better components/library to rearchitecture my little instant messaging server. I haven't tried it yet but it looks good coded as a first impression.
A: Indy uses synchronous sockets because it's a simpler way of programming. The asynchronous socket blocking was something added to the winsock stack back in the Windows 3.x days. Windows 3.x did not support threads and there you couldn't do socket I/O without threads. For some additional information about why Indy uses the blocking model, please see this article.
The .NET Socket.BeginRead/EndRead calls are using threads, it's just managed by the Framework instead of by you.
@Roddy, Indy 10 has been bundled with Delphi since at Delphi 2006. I found that migrating from Indy 9 to Indy 10 to be a straight forward task.
A: For async stuff try ICS
http://www.overbyte.be/frame_index.html?redirTo=/products/ics.html
A: With the ScktComp classes, you need to use a ThreadBlocking server rather than an a NonBlocking server type. Use the OnGetThread event to hand off the ClientSocket param to a new thread of your devising. Once you've instantiated an inherited instance of TServerClientThread you'll create a instance of TWinSocketStream (inside the thread) which you can use to read and write to the socket. This method gets you away from trying to process data in the event handler. These threads could exist for just the short period need to read or write, or hang on for the duration for the purpose of being reused.
The subject of writing a socket server is fairly vast. There are many techniques and practices you could choose to implement. The method of reading and writing to the same socket with in the TServerClientThread is straight forward and fine for simple applications. If you need a model for high availability and high concurrency then you need to look into patterns like the Proactor pattern.
Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: C# console program can't send fax when run as a scheduled task I have a console program written in C# that I am using to send faxes. When I step through the program in Visual Studio it works fine. When I double click on the program in Windows Explorer it works fine. When I setup a Windows scheduled task to run the program it fails with this in the event log.
EventType clr20r3, P1 consolefaxtest.exe, P2 1.0.0.0,
P3 48bb146b, P4 consolefaxtest, P5 1.0.0.0, P6 48bb146b,
P7 1, P8 80, P9 system.io.filenotfoundexception,
P10 NIL.
I wrote a batch file to run the fax program and it fails with this message.
Unhandled Exception: System.IO.FileNotFoundException: Operation failed.
at FAXCOMEXLib.FaxDocumentClass.ConnectedSubmit(FaxServer pFaxServer)
Can anyone explain this behavior to me?
A: I can't explain it - but I have a few ideas.
Most of the times, when a program works fine testing it, and doesn't when scheduling it - security is the case. In the context of which user is your program scheduled? Maybe that user isn't granted enough access.
Is the resource your programm is trying to access a network drive, that the user running the scheduled task simply haven't got?
A: Check that you set correct working directory for your task
A: Is the scheduled task running on the same computer you're developing on, or is it on a dedicated olp server? It's quite common for paths to change when you change environments, so is the path to the document you're trying to send the same?
A: I agree with MartinNH.
Many of these problems root from the fact that you develop while logged in as an administrator in Visual Studio (so the program has all the permissions for execution set properly) but you deploy as a user with lesser privileges.
Try setting the priveleges of the task scheduler user higher.
A: If you are running in Vista, you may find that the elevation is getting in the way. You may need to ensure your task runs as a proper administrator, not as a restricted user.
A: When you run a schedule task you can have it run under a user. Verify the user that is running the schedule task has the same rights for the fax resource as you. Which is why you can run it when you double click in Windows explore.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the best way to get OS specific information in Java?
*
*Specifically getting on Windows the "..\Documents & Settings\All Users, basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on. (Now I need the answer to this)
*the current users My Documents dirctory (okay this has been answered)
and basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on.
A: My docs would probably best be handled by accessing:
System.getProperty("user.home");
Look up the docs on System.getProperty.
A: Any information you can get about the user's environment can be fetched from
System.getProperty("...");
For a list of what you can get, take a look here.
I don't think you'll be able to get the path you require (the All Users path) in an OS dependent way. After all - do other operating systems have an equivalent? Your best bet is to probably inspect:
System.getProperty("os.name");
to see if you are running Windows and then if so use "C:\Documents & Settings\All Users\".
But you'll be better off just constantly using
System.getProperty("user.home");
(as mentioned by other people) throughout the application. Or alternatively, allow the user to specify the directory to store whatever it is you want to store.
A:
Specifically getting on Windows the "..\Documents & Settings\All Users, basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on. (Now I need the answer to this)
The folders below the All Users dir are variable directories in windows. Details can be found in the document about KNOWNFOLDERIDs (CSIDL in older versions).
Because this values are system dependent Java does not provide a way to access the values.
I think there is in general no equivalent on other operating systems to this windows specific folder. In addition the folder Documents & Settings\All Users is only present in latest windows versions and things are handled differently for e.g Windows 2000 or XP I think.
If you really need this information you should read the microsoft docs and impement a native library or some script invoked by Runtime.exec to provide the information to your java application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do you remove a specific revision in the git history? Suppose your git history looks like this:
1
2
3
4
5
1–5 are separate revisions. You need to remove 3 while still keeping 1, 2, 4 and 5. How can this be done?
Is there an efficient method when there are hundreds of revisions after the one to be deleted?
A: As noted before git-rebase(1) is your friend. Assuming the commits are in your master branch, you would do:
git rebase --onto master~3 master~2 master
Before:
1---2---3---4---5 master
After:
1---2---4'---5' master
From git-rebase(1):
A range of commits could also be
removed with rebase. If we have the
following situation:
E---F---G---H---I---J topicA
then the command
git rebase --onto topicA~5 topicA~3 topicA
would result in the removal of
commits F and G:
E---H'---I'---J' topicA
This is useful if F and G were flawed in some
way, or should not be part of topicA.
Note that the argument to --onto and
the parameter can be any
valid commit-ish.
A: To combine revision 3 and 4 into a single revision, you can use git rebase. If you want to remove the changes in revision 3, you need to use the edit command in the interactive rebase mode. If you want to combine the changes into a single revision, use squash.
I have successfully used this squash technique, but have never needed to remove a revision before. The git-rebase documentation under "Splitting commits" should hopefully give you enough of an idea to figure it out. (Or someone else might know).
From the git documentation:
Start it with the oldest commit you want to retain as-is:
git rebase -i <after-this-commit>
An editor will be fired up with all the commits in your current branch (ignoring merge commits), which come after the given commit. You can reorder the commits in this list to your heart's content, and you can remove them. The list looks more or less like this:
pick deadbee The oneline of this commit
pick fa1afe1 The oneline of the next commit
...
The oneline descriptions are purely for your pleasure; git-rebase will not look at them but at the commit names ("deadbee" and "fa1afe1" in this example), so do not delete or edit the names.
By replacing the command "pick" with the command "edit", you can tell git-rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.
If you want to fold two or more commits into one, replace the command "pick" with "squash" for the second and subsequent commit. If the commits had different authors, it will attribute the squashed commit to the author of the first commit.
A: I also landed in a similar situation. Use interactive rebase using the command below and while selecting, drop 3rd commit.
git rebase -i remote/branch
A: If all you want to do is remove the changes made in revision 3, you might want to use git revert.
Git revert simply creates a new revision with changes that undo all of the changes in the revision you are reverting.
What this means, is that you retain information about both the unwanted commit, and the commit that removes those changes.
This is probably a lot more friendly if it's at all possible the someone has pulled from your repository in the mean time, since the revert is basically just a standard commit.
A: So here is the scenario that I faced, and how I solved it.
[branch-a]
[Hundreds of commits] -> [R] -> [I]
here R is the commit that I needed to be removed, and I is a single commit that comes after R
I made a revert commit and squashed them together
git revert [commit id of R]
git rebase -i HEAD~3
During the interactive rebase squash the last 2 commits.
A: All the answers so far don't address the trailing concern:
Is there an efficient method when there are hundreds of revisions
after the one to be deleted?
The steps follow, but for reference, let's assume the following history:
[master] -> [hundreds-of-commits-including-merges] -> [C] -> [R] -> [B]
C:
commit just following the commit to be removed (clean)
R:
The commit to be removed
B:
commit just preceding the commit to be removed (base)
Because of the "hundreds of revisions" constraint, I'm assuming the following pre-conditions:
*
*there is some embarrassing commit that you wish never existed
*there are ZERO subsequent commits that actually depend on that embarassing commit (zero conflicts on revert)
*you don't care that you will be listed as the 'Committer' of the hundreds of intervening commits ('Author' will be preserved)
*you have never shared the repository
*
*or you actually have enough influence over all the people who have ever cloned history with that commit in it to convince them to use your new history
*and you don't care about rewriting history
This is a pretty restrictive set of constraints, but there is an interesting answer that actually works in this corner case.
Here are the steps:
*
*git branch base B
*git branch remove-me R
*git branch save
*git rebase --preserve-merges --onto base remove-me
If there are truly no conflicts, then this should proceed with no further interruptions. If there are conflicts, you can resolve them and rebase --continue or decide to just live with the embarrassment and rebase --abort.
Now you should be on master that no longer has commit R in it. The save branch points to where you were before, in case you want to reconcile.
How you want to arrange everyone else's transfer over to your new history is up to you. You will need to be acquainted with stash, reset --hard, and cherry-pick. And you can delete the base, remove-me, and save branches
A: Per this comment (and I checked that this is true), rado's answer is very close but leaves git in a detached head state. Instead, remove HEAD and use this to remove <commit-id> from the branch you're on:
git rebase --onto <commit-id>^ <commit-id>
A: Here is a way to remove non-interactively a specific <commit-id>, knowing only the <commit-id> you would like to remove:
git rebase --onto <commit-id>^ <commit-id> HEAD
A: Answers of rado and kareem do nothing for me (only message "Current branch is up to date." appears). Possibly this happens because '^' symbol doesn't work in Windows console. However, according to this comment, replacing '^' by '~1' solves the problem.
git rebase --onto <commit-id>^ <commit-id>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "244"
} |
Q: C# Preprocessor While the C# spec does include a pre-processor and basic directives (#define, #if, etc), the language does not have the same flexible pre-processor found in languages such as C/C++. I believe the lack of such a flexible pre-processor was a design decision made by Anders Hejlsberg (although, unfortunately, I can't find reference to this now). From experience, this is certainly a good decision, as there were some really terrible un-maintainable macros created back when I was doing a lot of C/C++.
That said, there are a number of scenarios where I could find a slightly more flexible pre-processor to be useful. Code such as the following could be improved by some simple pre-processor directives:
public string MyProperty
{
get { return _myProperty; }
set
{
if (value != _myProperty)
{
_myProperty = value;
NotifyPropertyChanged("MyProperty");
// This line above could be improved by replacing the literal string with
// a pre-processor directive like "#Property", which could be translated
// to the string value "MyProperty" This new notify call would be as follows:
// NotifyPropertyChanged(#Property);
}
}
}
Would it be a good idea to write a pre-processor to handle extremely simple cases like this? Steve McConnell wrote in Code Complete (p208):
Write your own preprocessor If a language doesn't include a preprocessor, it's fairly easy to write one...
I am torn. It was a design decision to leave such a flexible pre-processor out of C#. However, an author I highly respect mentions it may be ok in some circumstances.
Should I build a C# pre-processor? Is there one available that does the simple things I want to do?
A:
Should I build a C# pre-processor? Is there one available that does the simple things I want to do?
You can always use the C pre-processor -- C# is close enough, syntax-wise. M4 is also an option.
A: I know a lot of people think short code equals elegant code but that isn't true.
The example you propose is perfectly solved in code, as you have shown so, what do you need a preprocessor directive to? You don't want to "preprocess" your code, you want the compiler to insert some code for you in your properties. It's common code but that's not the purpose of the preprocessor.
With your example, Where do you put the limit? Clearly that satisfies an observer pattern and there's no doubt that will be useful but there are a lot of things that would be useful that are actually done because code provides flexibility where as the preprocessor does not. If you try to implement common patterns through preprocessor directives you'll end with a preprocessor which needs to be as powerful as the language itself. If you want to process your code in a different way the use a preprocessor directive but if you just want a code snippet then find another way because the preprocessor wasn't meant to do that.
A: The main argument agaisnt building a pre-rocessor for C# is integration in Visual Studio: it would take a lot of efforts (if at all possible) to get intellisense and the new background compiling to work seamlessly.
Alternatives are to use a Visual Studio productivity plugin like ReSharper or CodeRush.
The latter has -to the best of my knowledge- an unmatched templating system and comes with an excellent refactoring tool.
Another thing that could be helpful in solving the exact types of problems you are referring to is an AOP framework like PostSharp.
You can then use custom attributes to add common functionality.
A: Using a C++-style preprocessor, the OP's code could be reduced to this one line:
OBSERVABLE_PROPERTY(string, MyProperty)
OBSERVABLE_PROPERTY would look more or less like this:
#define OBSERVABLE_PROPERTY(propType, propName) \
private propType _##propName; \
public propType propName \
{ \
get { return _##propName; } \
set \
{ \
if (value != _##propName) \
{ \
_##propName = value; \
NotifyPropertyChanged(#propName); \
} \
} \
}
If you have 100 properties to deal with, that's ~1,200 lines of code vs. ~100. Which is easier to read and understand? Which is easier to write?
With C#, assuming you cut-and-paste to create each property, that's 8 pastes per property, 800 total. With the macro, no pasting at all. Which is more likely to contain coding errors? Which is easier to change if you have to add e.g. an IsDirty flag?
Macros are not as helpful when there are likely to be custom variations in a significant number of cases.
Like any tool, macros can be abused, and may even be dangerous in the wrong hands. For some programmers, this is a religious issue, and the merits of one approach over another are irrelevant; if that's you, you should avoid macros. For those of us who regularly, skillfully, and safely use extremely sharp tools, macros can offer not only an immediate productivity gain while coding, but downstream as well during debugging and maintenance.
A: Consider taking a look at an aspect-oriented solution like PostSharp, which injects code after the fact based on custom attributes. It's the opposite of a precompiler but can give you the sort of functionality you're looking for (PropertyChanged notifications etc).
A: To get the name of the currently executed method, you can look at the stack trace:
public static string GetNameOfCurrentMethod()
{
// Skip 1 frame (this method call)
var trace = new System.Diagnostics.StackTrace( 1 );
var frame = trace.GetFrame( 0 );
return frame.GetMethod().Name;
}
When you are in a property set method, the name is set_Property.
Using the same technique, you can also query the source file and line/column info.
However, I did not benchmark this, creating the stacktrace object once for every property set might be a too time consuming operation.
A: I think you're possibly missing one important part of the problem when implementing the INotifyPropertyChanged. Your consumer needs a way of determining the property name. For this reason you should have your property names defined as constants or static readonly strings, this way the consumer does not have to `guess' the property names. If you used a preprocessor, how would the consumer know what the string name of the property is?
public static string MyPropertyPropertyName
public string MyProperty {
get { return _myProperty; }
set {
if (!String.Equals(value, _myProperty)) {
_myProperty = value;
NotifyPropertyChanged(MyPropertyPropertyName);
}
}
}
// in the consumer.
private void MyPropertyChangedHandler(object sender,
PropertyChangedEventArgs args) {
switch (e.PropertyName) {
case MyClass.MyPropertyPropertyName:
// Handle property change.
break;
}
}
A: If I were designing the next version of C#, I'd think about each function having an automatically included local variable holding the name of the class and the name of the function. In most cases, the compiler's optimizer would take it out.
I'm not sure there's much of a demand for that sort of thing though.
A:
@Jorge wrote: If you want to process your code in a different way the use a preprocessor directive but if you just want a code snippet then find another way because the preprocessor wasn't meant to do that.
Interesting. I don't really consider a preprocessor to necessarily work this way. In the example provided, I am doing a simple text substitution, which is in-line with the definition of a preprocessor on Wikipedia.
If this isn't the proper use of a preprocessor, what should we call a simple text replacement, which generally needs to occur before a compilation?
A: At least for the provided scenario, there's a cleaner, type-safe solution than building a pre-processor:
Use generics. Like so:
public static class ObjectExtensions
{
public static string PropertyName<TModel, TProperty>( this TModel @this, Expression<Func<TModel, TProperty>> expr )
{
Type source = typeof(TModel);
MemberExpression member = expr.Body as MemberExpression;
if (member == null)
throw new ArgumentException(String.Format(
"Expression '{0}' refers to a method, not a property",
expr.ToString( )));
PropertyInfo property = member.Member as PropertyInfo;
if (property == null)
throw new ArgumentException(String.Format(
"Expression '{0}' refers to a field, not a property",
expr.ToString( )));
if (source != property.ReflectedType ||
!source.IsSubclassOf(property.ReflectedType) ||
!property.ReflectedType.IsAssignableFrom(source))
throw new ArgumentException(String.Format(
"Expression '{0}' refers to a property that is not a member of type '{1}'.",
expr.ToString( ),
source));
return property.Name;
}
}
This can easily be extended to return a PropertyInfo instead, allowing you to get way more stuff than just the name of the property.
Since it's an Extension method, you can use this method on virtually every object.
Also, this is type-safe.
Can't stress that enough.
(I know its an old question, but I found it lacking a practical solution.)
A: Under VS2019, you do get enhanced ability to precompile, without losing intellisense, when using a generator (see https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/).
For example: if you would be in need to remove readonly keywords (useful when manipulating constructors), then your generator could act as a precompiler to remove these keywords at compile time and generate the actual source that is to be compiled instead.
Your original source would then look like the following (the §RegexReplace macro is to be executed by the Generator and subsequently commented out in the generated source):
#if Precompiled || DEBUG
#if Precompiled
§RegexReplace("((private|internal|public|protected)( static)?) readonly","$1")
#endif
#if !Precompiled && DEBUG
namespace NotPrecompiled
{
#endif
... // your code
#if !Precompiled && DEBUG
}
#endif
#endif // Precompiled || DEBUG
The generated source would then have:
#define Precompiled
at the top and the Generator would have executed the other required changes to the source.
During development, you could thus still have intellisense, but the release version would only have the generated code. Care should be taken to never reference the NotPrecompiled namespace anywhere.
A: While there are plenty of good reflection-based answers here, the most obvious answer is missing and that is to use the compiler, at compile time.
Note that the following method has been supported in C# and .NET since .NET 4.5 and C# 5.
The compiler does in fact have some support for obtaining this information, just in a slightly roundabout way, and that is through the CallerMemberNameAttribute attribute. This allows you to get the compiler to inject the name of the member that is calling a method. There are two sibling attributes as well, but I think an example is easier to understand:
Given this simple class:
public static class Code
{
[MethodImplAttribute(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static string MemberName([CallerMemberName] string name = null) => name;
[MethodImplAttribute(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static string FilePath([CallerFilePathAttribute] string filePath = null) => filePath;
[MethodImplAttribute(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static int LineNumber([CallerLineNumberAttribute] int lineNumber = 0) => lineNumber;
}
of which in the context of this question you actually only need the first method, you can use it like this:
public class Test : INotifyPropertyChanged
{
private string _myProperty;
public string MyProperty
{
get => _myProperty;
set
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Code.MemberName()));
_myProperty = value;
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Now, since this method is only returning the argument back to the caller, chances are that it will be inlined completely which means the actual code at runtime will just grab the string that contains the name of the property.
Example usage:
void Main()
{
var t = new Test();
t.PropertyChanged += (s, e) => Console.WriteLine(e.PropertyName);
t.MyProperty = "Test";
}
output:
MyProperty
The property code actually looks like this when decompiled:
IL_0000 ldarg.0
IL_0001 ldfld Test.PropertyChanged
IL_0006 dup
IL_0007 brtrue.s IL_000C
IL_0009 pop
IL_000A br.s IL_0021
IL_000C ldarg.0
// important bit here
IL_000D ldstr "MyProperty"
IL_0012 call Code.MemberName (String)
// important bit here
IL_0017 newobj PropertyChangedEventArgs..ctor
IL_001C callvirt PropertyChangedEventHandler.Invoke (Object, PropertyChangedEventArgs)
IL_0021 ldarg.0
IL_0022 ldarg.1
IL_0023 stfld Test._myProperty
IL_0028 ret
A: If you are ready to ditch C# you might want to check out the Boo language which has incredibly flexible macro support through AST (Abstract Syntax Tree) manipulations. It really is great stuff if you can ditch the C# language.
For more information on Boo see these related questions:
*
*Non-C++ languages for generative programming?
*https://stackoverflow.com/questions/595593/who-is-using-boo-programming-language
*Boo vs. IronPython
*Good dynamic programming language for .net recommendation
*What can Boo do for you?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: Where does "Change Management" end and "Project Failure" begin? I got into a mini-argument with my boss recently regarding "project failure." After three years, our project to migrate a codebase to a new platform (a project I was on for 1.5 years, but my team lead was on for only a few months) went live. He, along with senior management of both my company and the client (I'm one of those god-awful consultants you hear so much about. My engagement is an "Application Outsourcing") declared the project to be a success. I disagreed, stating that old presentations I had found showed that compared to the original schedule, the delay in deployment was best measured in months and could potentially be measured in years. I explained what I know of project failure, and the studies and statistics behind failure rates. He responded that that was all academia, and that no project he led had failed, thanks to the wonders of change/risk management - what seems to come down to explaining delays and re-evaluating the schedule based on new data.
Maybe consulting like this differs from other projects, but it seems like this is just failure wrapped up in a prettier name to avoid the stigma of having failed to deliver on time, on budget, or with full functionality. The fact that he explained that my company gave away hours of work for free in order to finish the project within the maxed out budget says a lot.
So I ask you this:
*
*What is change management, and how does it apply to a project?
*Where does "change management" end, and "project failure" begin?
@shog9:
I wasn't asking about a blame game with the consultants, especially since in this case I represent the consultants. I was looking for views on when a project should be considered "failed" regardless of if the needed functionality was finally implemented.
I'm looking for the difference between "this is actually a little more complex than we thought, and it's going to be another week" which I'd expect is somewhat typical, and "project failure" - however you want to define failure. Is there even a difference? Does this minor level of schedule slippage constitute statistical "project failure?"
A: I think, most of the time, we developers forget this we all do is, after all, about bussiness.
From that point of view a project is not a failure while the client is willing to pay for it. It all depends on the client, some clients have more patience and understand better the risks of software development, other just won't pay if there's a substantial delay.
Anyway, about your question. Whenever you evolve a project there are risks involved, maybe you schedule the end of the project in a certain date but it will take like six month longer than you expected. In that case you have to balance what you have already spent and what you have to gain against the risks you're taking. There's actually an entire science called "decision making" that studies it at software level, so your boss is not wrong at all.
Let's look at some questions, Is the client willing to wait for the project? Is he willing to assume certain overcosts? Even if he doesn't, Is worth completing the project assuming the extra costs instead of throwing away all the already done work? Can the company assume what's already lost?
The real answer to your problem lies behind that questions. You can't establish a point and say, here, if the project isn't done by this time then it's a failure. As for your specific situation, who knows? Your boss has probably more information that you have so your work is to tell him how is the project going, how much it will take and how much it will cost (in terms hours/man if you wish)
A: Unless the goals were clearly stated in the beginning of the project, there are no clear lines between "success" and "failure." Often, a project would have varying degree of success/failure.
For some, just getting some concepts in code would be a success, while other may measure success as recovering all investments and making profit.
Two well-known modes of failures are schedule slip and quality deterioration, but in real-world, people do not seem to care much about them.
Simple ways to slip the schedule are to let the managers make request whenever they want (features creep) and let the programmers code whatever they feel is right (cowboy coding). Change management process such as sprint planning of scrum and planning game of XP are some of the examples. Theses are some of the attempts for the management and the developers to ship reliable products on time. If either party is not interested in reliable or on-time, then change management would not be useful.
A: I suppose how successful the project is depends on who the client is. If the client were the company directors and they are happy, then the project was successful regardless of the failures along the way.
A: Andy Rutledge has written a pretty interesting article on success. Though the title is Pre-bid Discussions, the article defines having a successful project, which for Andy entails:
*
*Will I or my team be allowed to bring our best work to the final result?
*Is the client prepared to engage in the project appropriately?
*Is the client prepared to begin this project?
*Is the client prepared to invest trust in my or my team’s ideas?
*Am I or is my team prepared to fulfill or exceed the project requirements?
This article was pointed out by Obie Fernandez, a successful consultant, in his Do the Hustle conference about consulting.
A: What is change management, and how does it apply to a project?
Change management is about approving and communicating changes to a project before they happen. If someone on your project (user, sponsor, team member.. whoever) wants to add a feature, the change needs to be documented and analysed for the effect. Any resulting changes to scope, budget and schedule must then be approved before the change is undertaken. These changes are typically approved by your sponsor, your steering committee or your client.
Once the changes have been approved and accepted that is your new plan. It doesn't matter what the original budget or schedule was.
Change Management on projects is all about the principle of "No Surprises". The right people (your Change Control Board) need to approve any changes to Scope, Schedule and Budget before they are acted upon.
One thing to remember is that there may be certain explicit or implicit constraints and tolerances for change. You may be have to deliver your project by a certain date to meet government regulatory requirements. Or your organisation may have a threshold that once a project budget is 30% over the original budget it must go to a "C" level or the project is killed. Investigating and explicitly stating these thresholds and tolerances up front are a good way of having better successful projects.
Where does "change management" end, and "project failure" begin?
If a project delivers on the approved scope, schedule and budget then it is successful.
However it may be still viewed as a failure. Post Implementation Reviews are a good tool to qualify this with your stakeholders (not just your boss). Also Benefit Realisation would be worthwhile looking into to see outside the blackbox of the project and the impact on the business as a whole.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What's the best way to persist data in a Java Desktop Application? I have a large tree of Java Objects in my Desktop Application and am trying to decide on the best way of persisting them as a file to the file system.
Some thoughts I've had were:
*
*Roll my own serializer using DataOutputStream: This would give me the greatest control of what was in the file, but at the cost of micromanaging it.
*Straight old Serialization using ObjectOutputStream and its various related classes: I'm not sold on it though since I find the data brittle. Changing any object's structure breaks the serialized instances of it. So I'm locked in to what seems to be a horrible versioning nightmare.
*XML Serialization: It's not as brittle, but it's significantly slower that straight out serialization. It can be transformed outside of my program.
*JavaDB: I'd considered this since I'm comfortable writing JDBC applications. The difference here is that the database instance would only persist while the file was being opened or saved. It's not pretty but... it does lend itself to migrating to a central server architecture if the need arises later and it introduces the possibility of quering the datamodel in a simpler way.
I'm curious to see what other people think. And I'm hoping that I've missed some obvious, and simpler approach than the ones above.
Here are some more options culled from the answers below:
*
*An Object Database - Has significantly less infrastructure than ORM approaches and performs faster than an XML approach. thanks aku
A: I would go for the your final option JavaDB (Sun's distribution of Derby) and use an object relational layer like Hibernate or iBatis. Using the first three aproaches means you are going to spend more time building a database engine than developing application features.
A: Have a look at Hibernate as a simpler way to interface to a database.
A: In my experience, you're probably better off using an embedded database. SQL, while less than perfect, is usually much easier than designing a file format that performs well and is reliable.
I haven't used JavaDB, but I've had good luck with H2 and SQLite. SQLite is a C library which means a little more work in terms of deployment. However, it has the benefit of storing the entire database in a single, cross-platform library. Basically, it is a pre-packaged, generic file format. SQLite has been so useful that I've even started using it instead of text files in scripts.
Be careful using Hibernate if you're working with a small persistence problem. It adds a lot of complexity and library overhead. Hibernate is really nice if you're working with a large number of tables, but it will probably be cumbersome if you only need a few tables.
A: db4objects might be the best choice
A: XStream from codehaus.org
XML serialization/deserialization largely without coding.
You can use annotations to tweak it.
Working well in two projects where I work.
See my users group presentation at http://cjugaustralia.org/?p=61
A: I think it depends on what you need. Let's see the options:
1) Descarded imediatelly! I'll not even justify. :)
2) If you need a simple, quick, one-method persistence, stick with it. It will persist the complete data graph as it is! Beware of how long you'll be maintaning the persisted objects. As yourself pointed out, versioning can be a problem.
3) Slower than (2), need extra code and can be edited by the user. I would only use it the data is supposed to be used by a client in another language.
4) If you need to query your data in anyway, stick with the DB solution.
Well, I think you had already answered your question :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: SQL Query for Logins What is the SQL query to select all of the MSSQL Server's logins?
Thank you. More than one of you had the answer I was looking for:
SELECT * FROM syslogins
A: Starting with SQL 2008, you should use sys.server_principals instead of sys.syslogins, which has been deprecated.
A: Is this what you're after?
select * from master.syslogins
A: On SQL Azure as of 2012;
logins:
--connecct to master
--logins
SELECT * from sys.sql_logins
--users
SELECT * from sys.sysusers
and users on a specific database:
--connect to database
SELECT * from sys.sysusers
Also note that 'users' on Azure SQL now (2022-11-17) have more 'login' type properties and creating a user on a Azure SQL database with a password is now possible, so it is less likely to require creating logins in 'master'.
A: @allain, @GateKiller your query selects users not logins
To select logins you can use this query:
SELECT name FROM master..sysxlogins WHERE sid IS NOT NULL
In MSSQL2005/2008 syslogins table is used insted of sysxlogins
A: Selecting from sysusers will get you information about users on the selected database, not logins on the server.
A: sp_helplogins will give you the logins along with the DBs and the rights on them.
A: Select * From Master..SysUsers Where IsSqlUser = 1
A: EXEC sp_helplogins
You can also pass an "@LoginNamePattern" parameter to get information about a specific login:
EXEC sp_helplogins @LoginNamePattern='fred'
A: Have a look in the syslogins or sysusers tables in the master schema. Not sure if this still still around in more recent MSSQL versions though. In MSSQL 2005 there are views called sys.syslogins and sys.sysusers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "66"
} |
Q: How to robustly, but minimally, distribute items across a peer-to-peer system If one has a peer-to-peer system that can be queried, one would like to
*
*reduce the total number of queries across the network (by distributing "popular" items widely and "similar" items together)
*avoid excess storage at each node
*assure good availability to even moderately rare items in the face of client downtime, hardware failure, and users leaving (possibly detecting rare items for archivists/historians)
*avoid queries failing to find matches in the event of network partitions
Given these requirements:
*
*Are there any standard approaches? If not, is there any respected, but experimental, research? I'm familiar some with distribution schemes, but I haven't seen anything really address learning for robustness.
*Am I missing any obvious criteria?
*Is anybody interested in working on/solving this problem? (If so, I'm happy to open-source part of a very lame simulator I threw together this weekend, and generally offer unhelpful advice).
@cdv: I've now watched the video and it is very good, and although I don't feel it quite gets to a pluggable distribution strategy, it's definitely 90% of the way there. The questions, however, highlight useful differences with this approach that address some of my further concerns, and gives me some references to follow up on. Thus, I'm provisionally accepting your answer, although I consider the question open.
A: There are multiple systems out there with various aspects of what you seek and each making different compromises, including but not limited to:
Amazon's Dynamo: http://s3.amazonaws.com/AllThingsDistributed/sosp/amazon-dynamo-sosp2007.pdf
Kai: http://www.slideshare.net/takemaru/kai-an-open-source-implementation-of-amazons-dynamo-472179
Hadoop: http://hadoop.apache.org/core/docs/current/hdfs_design.html
Chord: http://pdos.csail.mit.edu/chord/
Beehive: http://www.cs.cornell.edu/People/egs/beehive/
and many others. After building a custom system along those lines, I let some of the building blocks out in open source form as well: http://code.google.com/p/distributerl/
(that's not a whole system, but a few libraries useful in building one)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Xcode equivalent of ' __asm int 3 / DebugBreak() / Halt? What's the instruction to cause a hard-break in Xcode? For example under Visual Studio I could do '_asm int 3' or 'DebugBreak()'. Under some GCC implementations it's asm("break 0") or asm("trap").
I've tried various combos under Xcode without any luck. (inline assembler works fine so it's not a syntax issue).
For reference this is for an assert macro. I don't want to use the definitions in assert.h both for portability, and because they appear to do an abort() in the version XCode provides.
John - Super, cheers. For reference the int 3 syntax is the one required for Intel Macs and iPhone.
Chris - Thanks for your comment but there are many reasons to avoid the standard assert() function for codebases ported to different platforms. If you've gone to the trouble of rolling your own assert it's usually because you have additional functionality (logging, stack unwinding, user-interaction) that you wish to retain.
Your suggestion of attempting to replace the hander via an implementation of '__assert" or similar is not going to be portable. The standard 'assert' is usually a macro and while it may map to __assert on the Mac it doesn't on other platforms.
A: __builtin_trap();
Since Debugger() is depreciated now this should work instead.
https://developer.apple.com/library/mac/technotes/tn2124/_index.html#//apple_ref/doc/uid/DTS10003391-CH1-SECCONTROLLEDCRASH
A: For posterity: I have some code for generating halts at the correct stack frame in the debugger and (optionally) pausing the app so you can attach the debugger just-in-time. Works for simulator and device (and possibly desktop, if you should ever need it). Exhaustively detailed post at http://iphone.m20.nl/wp/2010/10/xcode-iphone-debugger-halt-assertions/
A: http://developer.apple.com/documentation/DeveloperTools/Conceptual/XcodeProjectManagement/090_Running_Programs/chapter_11_section_3.html
asm {trap} ; Halts a program running on PPC32 or PPC64.
__asm {int 3} ; Halts a program running on IA-32.
A: I found the following in an Apple Forum:
Xcode doesn't come with any symbolic breaks built in - but they're
quick to add. Go to the breakpoints window and add:
-[NSException raise]
A: kill(getpid(), SIGINT);
Works in the simulator and the device.
A: You can just insert a call to Debugger() — that will stop your app in the debugger (if it's being run under the debugger), or halt it with an exception if it's not.
Also, do not avoid assert() for "portability reasons" — portability is why it exists! It's part of Standard C, and you'll find it wherever you find a C compiler. What you really want to do is define a new assertion handler that does a debugger break instead of calling abort(); virtually all C compilers offer a mechanism by which you can do this.
Typically this is done by simply implementing a function or macro that follows this prototype:
void __assert(const char *expression, const char *file, int line);
It's called when an assertion expression fails. Usually it, not assert() itself, is what performs "the printf() followed by abort()" that is the default documented behavior. By customizing this function or macro, you can change its behavior.
A: There is also the following function that is available as cross platform straight Halt() alternative:
#include <stdlib.h>
void abort(void);
We use it in our cross platform engine for the iPhone implementation in case of fatal asserts. Cross platform across Nintendo DS/Wii/XBOX 360/iOS etc...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: Font-dependent control positioning I'd like to use Segoe UI 9 pt on Vista, and Tahoma 8 pt on Windows XP/etc. (Actually, I'd settle for Segoe UI on both, but my users probably don't have it installed.) But, these being quite different, they really screw up the layout of my forms. So... is there a good way to deal with this?
An example: I have a Label, with some blank space in the middle, into which I place a NumericUpDown control. If I use Segoe UI, the NumericUpDown is about 5 pixels or so to the left of the blank space, compared to when I use Tahoma. This is a pain; I'm not sure what to do here.
So most specifically, my question would be: how can I place controls in the middle of a blank space in my Labels (or CheckBoxes, etc.)? Most generally: is there a good way to handle varying fonts in Windows Forms?
Edit: I don't think people understood the question. I know how to vary my fonts based on OS. I just don't know how to deal with the layout problems that arise from doing so.
Reply to ajryan, quick_dry: OK, you guys understand the question. I guess MeasureString might work, although I'd be interested in further exploration of better ways to solve this problem.
The problem with splitting the control is most apparent with, say, a CheckBox. There, if the user clicks on the "second half" of the CheckBox (which would be a separate Label control, I guess), the CheckBox doesn't change state.
A: I second the usage of TableLayoutPanel for single-line inline controls.
I usually set each column and the first row to AutoSize and set each child control's Dock property to Fill in the designer. That gets the horizontal layout to display properly.
To make the the text line up between labels/textboxes, set the TextAlign property to MiddleLeft.
If your text flows onto to the next line there's no easy solution. Using Graphics.MeasureString/TextRenderer.MeasureText and some fancy wrapping logic is your best bet :(
A: First of all, you can find out which version of Windows you are using with the OperatingSystem.Platform property in the System library.
Second, it is possible that you may put your font settings in Resource files, and determine which resource file to use depending on certain conditions (e.g., your operating system version).
Personally though, I think it would be nice to let your user determine the fonts that they prefer as opposed to the font that you want for them to use.
Finally, you might want to take a look at WPF as this is one of the problem spaces that it was designed to solve.
A: is the problem working out the placement of controls? i.e. you know font X and Y work on OS A and B, and give the layout you want with the text you're using on those systems?
MeasureString method might help in working out your layout in a way that you weren't tied to specific fonts.
float textWidth = graphics.MeasureString(someString, someFont).Width;
(would a change in text alignment work? I might be misunderstanding the problem too)
A: It's strange to need to layout one control within another. You might be solving an upstream problem wrong. Are you able to split the label into two labels with the updown between and maybe rely on a Windows Forms TableLayout panel?
If it's essential to try to position based on font sizes, you could use Graphics.MeasureString("String before updown", myLabel.Font)
If what you're after is font-dependent control positioning, you should probably retitle the question.
[edit] You can handle the click event of the "second half" part of the label and change the checkbox state on that event. The whole thing seems like a hack though. What is the problem being solved by this weird control layout? Why do you need an up-down in the middle of a label?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Checking the results of a Factory in a unit test I have developed some classes with similar behavior, they all implement the same interface. I implemented a factory that creates the appropriate object and returns the interface. I am writing a unit test for the factory. All you get back is an interface to the object.
What is the best way to test that the factory has worked correctly?
I would like to know the answer in Java, but if there is a solution that crosses languages I would like to know it.
Number 2. in the answer, would be done like the other answer? If so I will mark the other answer accepted as well and reword my question to adress both a factory where an interface is returned and you have no clue what type of concrete class implemented the interface, and the case where you do know what concrete class was used.
A: What you are trying to do is not Unit Testing
If you test whether or not the returned objects are instances of specific concrete classes, you aren't unit testing. You are integration testing. While integration testing is important, it is not the same thing.
In unit testing, you only need to test the object itself. If you assert on the concrete type of the abstract objects returned, you are testing over the implementation of the returned object.
Unit Testing on Objects in general
When unit testing, there are four things, you want to assert:
*
*Return values of queries (non-void methods) are what you expect them to be.
*Side-effects of commands (void methods) modify the object itself as you expect them to.
*Commands send to other objects are received (This is usually done using mocks).
Furthermore, you only want to test what could be observed from an object instance, i.e. the public interface. Otherwise, you tie yourself to a specific set of implementation details. This would require you to change your tests when those details change.
Unit Testing Factories
Unit testing on Factories is really uninteresting, because you are not interested in the behavior of the returned objects of queries. That behavior is (hopefully) tested elsewhere, presumable while unit testing that object itself. You are only really interested in whether or not the returned object has the correct type, which is guaranteed if your program compiles.
As Factories do not change over time (because then they would be "Builders", which is another pattern), there are no commands to test.
Factories are responsible for instantiating objects, so they should not depend on other factories to do this for them. They might depend on a Builder, but even so, we are not supposed to test the Builder's correctness, only whether or not the Builder receives the message.
This means that all you have to test on Factories is whether or not they send the messages to the objects on which they depend. If you use Dependency Injection, this is almost trivial. Just mock the dependencies in your unit tests, and verify that they receive the messages.
Summary of Unit Testing Factories
*
*Do not test the behavior nor the implementation details of the returned objects! Your Factory is not responsible for the implementation of the object instances!
*Test whether or not the commands sent to dependencies are received.
That's it. If there are no dependencies, there is nothing to test. Except maybe to assert that the returned object isn't a null reference.
Integration Testing Factories
If you have a requirement that the returned abstract object type is an instance of a specific concrete type, then this falls under integration testing.
Others here have already answered how to do this using the instanceof operator.
A: Since I don't know how your factory method looks like, all I can advise right now is to
*
*Check to see the object is the correct concrete implementation you were looking for:
IMyInterface fromFactory = factory.create(...);
Assert.assertTrue(fromFactory instanceof MyInterfaceImpl1);
*You can check if the factory setup the concrete instances with valid instance variables.
A: if (myNewObject instanceof CorrectClass)
{
/* pass test */
}
update:
Don't know why this got marked down, so I'll expand it a bit...
public void doTest()
{
MyInterface inst = MyFactory.createAppropriateObject();
if (! inst instanceof ExpectedConcreteClass)
{
/* FAIL */
}
}
A: @cem-catikkas I think it would be more correct to compare the getClass().getName() values. In the case that MyInterfaceImpl1 class is subclassed your test could be broken, as the subclass is instanceof MyInterfaceImpl1. I would rewrite as follow:
IMyInterface fromFactory = factory.create(...);
Assert.assertEquals(fromFactory.getClass().getName(), MyInterfaceImpl1.class.getName());
If you think this could fail in some way (I can't imagine), make the two verifications.
A: If your Factory returns a concrete instance you can use the @Parameters annotation in order to obtain a more flexible automatic unit test.
package it.sorintlab.pxrm.proposition.model.factory.task;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collection;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import static org.junit.Assert.*;
@RunWith(Parameterized.class)
public class TaskFactoryTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ "sas:wp|repe" , WorkPackageAvailabilityFactory.class},
{ "sas:wp|people", WorkPackagePeopleFactory.class},
{ "edu:wp|course", WorkPackageCourseFactory.class},
{ "edu:wp|module", WorkPackageModuleFactory.class},
{ "else", AttachmentTaskDetailFactory.class}
});
}
private String fInput;
private Class<? extends TaskFactory> fExpected;
public TaskFactoryTest(String input, Class<? extends TaskFactory> expected) {
this.fInput = input;
this.fExpected = expected;
}
@Test
public void getFactory() {
assertEquals(fExpected, TaskFactory.getFactory(fInput).getClass());
}
}
This example is made using Junit4. You can notice that with only one line of code you can test all the result of your Factory method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: How do you return the focus to the last used control after clicking a button in a winform app? I'm working on a windows forms application (C#) where a user is entering data in a form. At any point while editing the data in the form the user can click one of the buttons on the form to perform certain actions. By default the focus goes to the clicked button so the user has to click back on to the control they want to edit in order to continue modifying the data on the form. What I need to be able to do is return the focus to the last edited control after the button click event has been processed. Here's a sample screenshot that illustrates what I'm talking about:
The user can be entering data in textbox1, textbox2, textbox3, etc and click the button. I need the button to return the focus back to the control that most recently had the focus before the button was clicked.
I'm wondering if anyone has a better way of implementing this functionality than what I've come up with. Here's what I'm doing right now:
public partial class Form1 : Form
{
Control _lastEnteredControl;
private void textBox_Enter(object sender, EventArgs e)
{
_lastEnteredControl = (Control)sender;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Do something here");
_lastEnteredControl.Focus();
}
}
So basically what we have here is a class variable that points to the last entered control. Each textbox on the form is setup so the textBox_Enter method is fired when the control receives the focus. Then, when the button is clicked focus is returned to the control that had the focus before the button was clicked. Anybody have any more elegant solutions for this?
A: You could do the following
Change the button to a label and make it look like a button. The label will never get focus and you don't have to do all the extra coding.
A: For a bit of 'simplicity' maybe try.
public Form1()
{
InitializeComponent();
foreach (Control ctrl in Controls)
{
if (ctrl is TextBox)
{
ctrl.Enter += delegate(object sender, EventArgs e)
{
_lastEnteredControl = (Control)sender;
};
}
}
}
then you don't have to worry about decorating each textbox manually (or forgetting about one too).
A: I think what you're doing is fine. The only thing I could think of to improve it would be to store each control into a stack as they are accessed. That would give you a complete time line of what was accessed.
A: Your approach looks good. If you want to avoid having to add an the event handler to every control you add, you could create a recursive routine to add a GotFocus listener to every control in your form. This will work for any type of control in your form, however you could adjust it to meet your needs.
private void Form_OnLoad(object obj, EventArgs e)
{
AddGotFocusListener(this);
}
private void AddGotFocusListener(Control ctrl)
{
foreach(Control c in ctrl.Controls)
{
c.GotFocus += new EventHandler(Control_GotFocus);
if(c.Controls.Count > 0)
{
AddGotFocusListener(c);
}
}
}
private void Control_GotFocus(object obj, EventArgs e)
{
// Set focused control here
}
A: Your implementation looks good enough -- what I do want to know is why you want to do this in the first place? Won't it be preferrable for the focus to cycle back to the first entry? Is the data in the last text box so malleable that once they click the button it is "remembered"? Or do you have some sort of operation that the button does to that specifici text box data -- in that case shouldn't the focus go to a subsequent control instead?
I'm interested in finding out why you want to do this in the first place.
A: Yeah, I admit the requirement is a bit unusual. Some of the information that the users will be entering into this application exists in scans of old documents that are in a couple of different repositories. The buttons facilitate finding and opening these old docs. It's difficult to predict where the users will be on the form when they decide to pull up a document with more information to enter on the form. The intent is to make the UI flow well in spite of these funky circumstances.
A: Create a class called CustomTextBox that inherits from TextBox. It has a static variable called stack. When the textbox loses focus push onto the stack. When you want to find the last focused control then just pop the first item from the stack. Make sure to clear the static Stack variable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: What is the syntax for an inner join in LINQ to SQL? I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an ON clause in C#.
How do you represent the following in LINQ to SQL:
select DealerContact.*
from Dealer
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID
A: To extend the expression chain syntax answer by Clever Human:
If you wanted to do things (like filter or select) on fields from both tables being joined together -- instead on just one of those two tables -- you could create a new object in the lambda expression of the final parameter to the Join method incorporating both of those tables, for example:
var dealerInfo = DealerContact.Join(Dealer,
dc => dc.DealerId,
d => d.DealerId,
(dc, d) => new { DealerContact = dc, Dealer = d })
.Where(dc_d => dc_d.Dealer.FirstName == "Glenn"
&& dc_d.DealerContact.City == "Chicago")
.Select(dc_d => new {
dc_d.Dealer.DealerID,
dc_d.Dealer.FirstName,
dc_d.Dealer.LastName,
dc_d.DealerContact.City,
dc_d.DealerContact.State });
The interesting part is the lambda expression in line 4 of that example:
(dc, d) => new { DealerContact = dc, Dealer = d }
...where we construct a new anonymous-type object which has as properties the DealerContact and Dealer records, along with all of their fields.
We can then use fields from those records as we filter and select the results, as demonstrated by the remainder of the example, which uses dc_d as a name for the anonymous object we built which has both the DealerContact and Dealer records as its properties.
A: It goes something like:
from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}
It would be nice to have sensible names and fields for your tables for a better example. :)
Update
I think for your query this might be more appropriate:
var dealercontacts = from contact in DealerContact
join dealer in Dealer on contact.DealerId equals dealer.ID
select contact;
Since you are looking for the contacts, not the dealers.
A: Inner join two tables in linq C#
var result = from q1 in table1
join q2 in table2
on q1.Customer_Id equals q2.Customer_Id
select new { q1.Name, q1.Mobile, q2.Purchase, q2.Dates }
A: var results = from c in db.Companies
join cn in db.Countries on c.CountryID equals cn.ID
join ct in db.Cities on c.CityID equals ct.ID
join sect in db.Sectors on c.SectorID equals sect.ID
where (c.CountryID == cn.ID) && (c.CityID == ct.ID) && (c.SectorID == company.SectorID) && (company.SectorID == sect.ID)
select new { country = cn.Name, city = ct.Name, c.ID, c.Name, c.Address1, c.Address2, c.Address3, c.CountryID, c.CityID, c.Region, c.PostCode, c.Telephone, c.Website, c.SectorID, Status = (ContactStatus)c.StatusID, sector = sect.Name };
return results.ToList();
A: Use LINQ joins to perform Inner Join.
var employeeInfo = from emp in db.Employees
join dept in db.Departments
on emp.Eid equals dept.Eid
select new
{
emp.Ename,
dept.Dname,
emp.Elocation
};
A: Try this :
var data =(from t1 in dataContext.Table1 join
t2 in dataContext.Table2 on
t1.field equals t2.field
orderby t1.Id select t1).ToList();
A: You create a foreign key, and LINQ-to-SQL creates navigation properties for you. Each Dealer will then have a collection of DealerContacts which you can select, filter, and manipulate.
from contact in dealer.DealerContacts select contact
or
context.Dealers.Select(d => d.DealerContacts)
If you're not using navigation properties, you're missing out one of the main benefits on LINQ-to-SQL - the part that maps the object graph.
A: Use Linq Join operator:
var q = from d in Dealer
join dc in DealerConact on d.DealerID equals dc.DealerID
select dc;
A: And because I prefer the expression chain syntax, here is how you do it with that:
var dealerContracts = DealerContact.Join(Dealer,
contact => contact.DealerId,
dealer => dealer.DealerId,
(contact, dealer) => contact);
A: basically LINQ join operator provides no benefit for SQL. I.e. the following query
var r = from dealer in db.Dealers
from contact in db.DealerContact
where dealer.DealerID == contact.DealerID
select dealerContact;
will result in INNER JOIN in SQL
join is useful for IEnumerable<> because it is more efficient:
from contact in db.DealerContact
clause would be re-executed for every dealer
But for IQueryable<> it is not the case. Also join is less flexible.
A: OperationDataContext odDataContext = new OperationDataContext();
var studentInfo = from student in odDataContext.STUDENTs
join course in odDataContext.COURSEs
on student.course_id equals course.course_id
select new { student.student_name, student.student_city, course.course_name, course.course_desc };
Where student and course tables have primary key and foreign key relationship
A: try instead this,
var dealer = from d in Dealer
join dc in DealerContact on d.DealerID equals dc.DealerID
select d;
A: Actually, often it is better not to join, in linq that is. When there are navigation properties a very succinct way to write your linq statement is:
from dealer in db.Dealers
from contact in dealer.DealerContacts
select new { whatever you need from dealer or contact }
It translates to a where clause:
SELECT <columns>
FROM Dealer, DealerContact
WHERE Dealer.DealerID = DealerContact.DealerID
A: var Data= (from dealer in Dealer join dealercontact in DealerContact on dealer.ID equals dealercontact.DealerID
select new{
dealer.Id,
dealercontact.ContactName
}).ToList();
A: var data=(from t in db.your tableName(t1)
join s in db.yourothertablename(t2) on t1.fieldname equals t2.feldname
(where condtion)).tolist();
A: var list = (from u in db.Users join c in db.Customers on u.CustomerId equals c.CustomerId where u.Username == username
select new {u.UserId, u.CustomerId, u.ClientId, u.RoleId, u.Username, u.Email, u.Password, u.Salt, u.Hint1, u.Hint2, u.Hint3, u.Locked, u.Active,c.ProfilePic}).First();
Write table names you want, and initialize the select to get the result of fields.
A: from d1 in DealerContrac join d2 in DealerContrac on d1.dealearid equals d2.dealerid select new {dealercontract.*}
A: One Best example
Table Names : TBL_Emp and TBL_Dep
var result = from emp in TBL_Emp join dep in TBL_Dep on emp.id=dep.id
select new
{
emp.Name;
emp.Address
dep.Department_Name
}
foreach(char item in result)
{ // to do}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "478"
} |
Q: How to deal with "java.lang.OutOfMemoryError: Java heap space" error? I am writing a client-side Swing application (graphical font designer) on Java 5. Recently, I am running into java.lang.OutOfMemoryError: Java heap space error because I am not being conservative on memory usage. The user can open unlimited number of files, and the program keeps the opened objects in the memory. After a quick research I found Ergonomics in the 5.0 Java Virtual Machine and others saying on Windows machine the JVM defaults max heap size as 64MB.
Given this situation, how should I deal with this constraint?
I could increase the max heap size using command line option to java, but that would require figuring out available RAM and writing some launching program or script. Besides, increasing to some finite max does not ultimately get rid of the issue.
I could rewrite some of my code to persist objects to file system frequently (using database is the same thing) to free up the memory. It could work, but it's probably a lot work too.
If you could point me to details of above ideas or some alternatives like automatic virtual memory, extending heap size dynamically, that will be great.
A: I read somewhere else that you can try - catch java.lang.OutOfMemoryError and on the catch block, you can free all resources that you know might use a lot of memory, close connections and so forth, then do a System.gc() then re-try whatever you were going to do.
Another way is this although, i don't know whether this would work, but I am currently testing whether it will work on my application.
The Idea is to do Garbage collection by calling System.gc() which is known to increase free memory. You can keep checking this after a memory gobbling code executes.
//Mimimum acceptable free memory you think your app needs
long minRunningMemory = (1024*1024);
Runtime runtime = Runtime.getRuntime();
if(runtime.freeMemory()<minRunningMemory)
System.gc();
A: Easy way to solve OutOfMemoryError in java is to increase the maximum heap size by using JVM options -Xmx512M, this will immediately solve your OutOfMemoryError. This is my preferred solution when I get OutOfMemoryError in Eclipse, Maven or ANT while building project because based upon size of project you can easily ran out of Memory.
Here is an example of increasing maximum heap size of JVM, Also its better to keep -Xmx to -Xms ration either 1:1 or 1:1.5 if you are setting heap size in your java application.
export JVM_ARGS="-Xms1024m -Xmx1024m"
Reference Link
A: If you came here to search this issue from REACT NATIVE.
Then i guess you should do this
cd android/ && ./gradlew clean && cd ..
A: Add this line to your gradle.properties file
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
It should work. You can change MaxPermSize accordingly to fix your heap problem
A: Increasing the heap size is not a "fix" it is a "plaster", 100% temporary. It will crash again in somewhere else. To avoid these issues, write high performance code.
*
*Use local variables wherever possible.
*Make sure you select the correct object (EX: Selection between String, StringBuffer and StringBuilder)
*Use a good code system for your program(EX: Using static variables VS non static variables)
*Other stuff which could work on your code.
*Try to move with multy THREADING
A: If you need to monitor your memory usage at runtime, the java.lang.management package offers MBeans that can be used to monitor the memory pools in your VM (eg, eden space, tenured generation etc), and also garbage collection behaviour.
The free heap space reported by these MBeans will vary greatly depending on GC behaviour, particularly if your application generates a lot of objects which are later GC-ed. One possible approach is to monitor the free heap space after each full-GC, which you may be able to use to make a decision on freeing up memory by persisting objects.
Ultimately, your best bet is to limit your memory retention as far as possible whilst performance remains acceptable. As a previous comment noted, memory is always limited, but your app should have a strategy for dealing with memory exhaustion.
A: I have faced same problem from java heap size.
I have two solutions if you are using java 5(1.5).
*
*just install jdk1.6 and go to the preferences of eclipse and set the jre path of jav1 1.6 as you have installed.
*Check your VM argument and let it be whatever it is.
just add one line below of all the arguments present in VM arguments as
-Xms512m -Xmx512m -XX:MaxPermSize=...m(192m).
I think it will work...
A: In android studio add/change this line at the end of gradle.properties (Global Properties):
...
org.gradle.jvmargs=-XX\:MaxHeapSize\=1024m -Xmx1024m
if it doesn't work you can retry with bigger than 1024 heap size.
A: add the below code inside android/gradle.properties:
org.gradle.jvmargs=-Xmx4096m -XX:MaxPermSize=4096m -XX:+HeapDumpOnOutOfMemoryError
org.gradle.daemon=true
org.gradle.parallel=true
org.gradle.configureondemand=true
A: Note that if you need this in a deployment situation, consider using Java WebStart (with an "ondisk" version, not the network one - possible in Java 6u10 and later) as it allows you to specify the various arguments to the JVM in a cross platform way.
Otherwise you will need an operating system specific launcher which sets the arguments you need.
A: In my case it solved by assigning more memory to Shared build process heap size in intellij settings.
Go to intellij settings > Compiler > Shared build process heap size
A: Big caveat ---- at my office, we were finding that (on some windows machines) we could not allocate more than 512m for Java heap. This turned out to be due to the Kaspersky anti-virus product installed on some of those machines. After uninstalling that AV product, we found we could allocate at least 1.6gb, i.e, -Xmx1600m (m is mandatory other wise it will lead to another error "Too small initial heap") works.
No idea if this happens with other AV products but presumably this is happening because the AV program is reserving a small block of memory in every address space, thereby preventing a single really large allocation.
A: Regarding to netbeans, you could set max heap size to solve the problem.
Go to 'Run', then --> 'Set Project Configuration' --> 'Customise' --> 'run' of its popped up window --> 'VM Option' --> fill in '-Xms2048m -Xmx2048m'.
A: If you are using Android Studio just add these lines with gradle.properties file
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
A: Ultimately you always have a finite max of heap to use no matter what platform you are running on. In Windows 32 bit this is around 2GB (not specifically heap but total amount of memory per process). It just happens that Java chooses to make the default smaller (presumably so that the programmer can't create programs that have runaway memory allocation without running into this problem and having to examine exactly what they are doing).
So this given there are several approaches you could take to either determine what amount of memory you need or to reduce the amount of memory you are using. One common mistake with garbage collected languages such as Java or C# is to keep around references to objects that you no longer are using, or allocating many objects when you could reuse them instead. As long as objects have a reference to them they will continue to use heap space as the garbage collector will not delete them.
In this case you can use a Java memory profiler to determine what methods in your program are allocating large number of objects and then determine if there is a way to make sure they are no longer referenced, or to not allocate them in the first place. One option which I have used in the past is "JMP" http://www.khelekore.org/jmp/.
If you determine that you are allocating these objects for a reason and you need to keep around references (depending on what you are doing this might be the case), you will just need to increase the max heap size when you start the program. However, once you do the memory profiling and understand how your objects are getting allocated you should have a better idea about how much memory you need.
In general if you can't guarantee that your program will run in some finite amount of memory (perhaps depending on input size) you will always run into this problem. Only after exhausting all of this will you need to look into caching objects out to disk etc. At this point you should have a very good reason to say "I need Xgb of memory" for something and you can't work around it by improving your algorithms or memory allocation patterns. Generally this will only usually be the case for algorithms operating on large datasets (like a database or some scientific analysis program) and then techniques like caching and memory mapped IO become useful.
A: VM arguments worked for me in eclipse. If you are using eclipse version 3.4, do the following
go to Run --> Run Configurations --> then select the project under maven build --> then select the tab "JRE" --> then enter -Xmx1024m.
Alternatively you could do Run --> Run Configurations --> select the "JRE" tab --> then enter -Xmx1024m
This should increase the memory heap for all the builds/projects. The above memory size is 1 GB. You can optimize the way you want.
A: I would like to add recommendations from oracle trouble shooting article.
Exception in thread thread_name: java.lang.OutOfMemoryError: Java heap space
The detail message Java heap space indicates object could not be allocated in the Java heap. This error does not necessarily imply a memory leak
Possible causes:
*
*Simple configuration issue, where the specified heap size is insufficient for the application.
*Application is unintentionally holding references to objects, and this prevents the objects from being garbage collected.
*Excessive use of finalizers.
One other potential source of this error arises with applications that make excessive use of finalizers. If a class has a finalize method, then objects of that type do not have their space reclaimed at garbage collection time
After garbage collection, the objects are queued for finalization, which occurs at a later time. finalizers are executed by a daemon thread that services the finalization queue. If the finalizer thread cannot keep up with the finalization queue, then the Java heap could fill up and this type of OutOfMemoryError exception would be thrown.
One scenario that can cause this situation is when an application creates high-priority threads that cause the finalization queue to increase at a rate that is faster than the rate at which the finalizer thread is servicing that queue.
A: Yes, with -Xmx you can configure more memory for your JVM.
To be sure that you don't leak or waste memory. Take a heap dump and use the Eclipse Memory Analyzer to analyze your memory consumption.
A: Android Studio
File -> Invalidate Caches and Restart solved it for me :)
A: Run Java with the command-line option -Xmx, which sets the maximum size of the heap.
See here for details.
A: Follow below steps:
*
*Open catalina.sh from tomcat/bin.
*Change JAVA_OPTS to
JAVA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 -server -Xms1536m
-Xmx1536m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"
*Restart your tomcat
A: You could specify per project how much heap space your project wants
Following is for Eclipse Helios/Juno/Kepler:
Right mouse click on
Run As - Run Configuration - Arguments - Vm Arguments,
then add this
-Xmx2048m
A: By default for development JVM uses small size and small config for other performance related features. But for production you can tune e.g. (In addition it Application Server specific config can exist) -> (If there still isn't enough memory to satisfy the request and the heap has already reached the maximum size, an OutOfMemoryError will occur)
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
-XX:ParallelGCThreads=8
-XX:+CMSClassUnloadingEnabled
-XX:InitiatingHeapOccupancyPercent=70
-XX:+UnlockDiagnosticVMOptions
-XX:+UseConcMarkSweepGC
-Xms512m
-Xmx8192m
-XX:MaxPermSize=256m (in java 8 optional)
For example: On linux Platform for production mode preferable settings.
After downloading and configuring server with this way http://www.ehowstuff.com/how-to-install-and-setup-apache-tomcat-8-on-centos-7-1-rhel-7/
1.create setenv.sh file on folder /opt/tomcat/bin/
touch /opt/tomcat/bin/setenv.sh
2.Open and write this params for setting preferable mode.
nano /opt/tomcat/bin/setenv.sh
export CATALINA_OPTS="$CATALINA_OPTS -XX:ParallelGCThreads=8"
export CATALINA_OPTS="$CATALINA_OPTS -XX:+CMSClassUnloadingEnabled"
export CATALINA_OPTS="$CATALINA_OPTS -XX:InitiatingHeapOccupancyPercent=70"
export CATALINA_OPTS="$CATALINA_OPTS -XX:+UnlockDiagnosticVMOptions"
export CATALINA_OPTS="$CATALINA_OPTS -XX:+UseConcMarkSweepGC"
export CATALINA_OPTS="$CATALINA_OPTS -Xms512m"
export CATALINA_OPTS="$CATALINA_OPTS -Xmx8192m"
export CATALINA_OPTS="$CATALINA_OPTS -XX:MaxMetaspaceSize=256M"
3.service tomcat restart
Note that the JVM uses more memory than just the heap. For example
Java methods, thread stacks and native handles are allocated in memory
separate from the heap, as well as JVM internal data structures.
A: If you keep on allocating & keeping references to object, you will fill up any amount of memory you have.
One option is to do a transparent file close & open when they switch tabs (you only keep a pointer to the file, and when the user switches tab, you close & clean all the objects... it'll make the file change slower... but...), and maybe keep only 3 or 4 files on memory.
Other thing you should do is, when the user opens a file, load it, and intercept any OutOfMemoryError, then (as it is not possible to open the file) close that file, clean its objects and warn the user that he should close unused files.
Your idea of dynamically extending virtual memory doesn't solve the issue, for the machine is limited on resources, so you should be carefull & handle memory issues (or at least, be carefull with them).
A couple of hints i've seen with memory leaks is:
--> Keep on mind that if you put something into a collection and afterwards forget about it, you still have a strong reference to it, so nullify the collection, clean it or do something with it... if not you will find a memory leak difficult to find.
--> Maybe, using collections with weak references (weakhashmap...) can help with memory issues, but you must be carefull with it, for you might find that the object you look for has been collected.
--> Another idea i've found is to develope a persistent collection that stored on database objects least used and transparently loaded. This would probably be the best approach...
A: If this issue is happening in Wildfly 8 and JDK1.8,then we need to specify MaxMetaSpace settings instead of PermGen settings.
For example we need to add below configuration in setenv.sh file of wildfly.
JAVA_OPTS="$JAVA_OPTS -XX:MaxMetaspaceSize=256M"
For more information, please check Wildfly Heap Issue
A: Java OOM Heap space issue can also arise when your DB connection pool got full.
I faced this issue because of my Hikari Connection pool (when upgraded to Spring boot 2.4.*) was full and not able to provide connections anymore (all active connections are still pending to fetch results from database).
Issue is some of our native queries in JPA Repositories contain ORDER BY ?#{#pageable} which takes a very long time to get results when upgraded.
Removed ORDER BY ?#{#pageable} from all the native queries in JPA repositories and OOM heap space issue along with connection pool issue got resolved.
A: If this error occurs right after execution of your junit tests, then you should execute Build -> Rebuild Project.
A: If this error comes up during APK generation in react-native, cd into the android folder in your project and do:
./gradlew clean
then
./gradlew assembleRelease
If error persists, then, restart your machine.
A: If everything else fails, in addition to increasing the max heap size try also increasing the swap size. For Linux, as of now, relevant instructions can be found in https://linuxize.com/post/create-a-linux-swap-file/.
This can help if you're e.g. compiling something big in an embedded platform.
A: if you got this error when you launch eclipse birt
1- you will go in the file of the eclipse configuration
2- you must open eclipse.init
3- modified the RAM memory, you can increase this, i give an example.
my old information was :
-Xmx128m
-XX:MaxPermSize=128m
the new modification that i opered :
-Xmx512m
-XX:MaxPermSize=512m
this modification will permit me to resolve java heap space when i launch my report in my browser.
Thanks
A: In Intellij, it worked for me just by giving the "Build Project"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "551"
} |
Q: Wordpress MediaWiki Cookie Integration I have my Wordpress install and MediaWiki sharing the same login information. Unfortunately, users need to log into both separately, but at least they use the same credentials.
What I would like to do is cause a successful login on the Wordpress blog to also cause a login for MediaWiki (ideally both directions). There are two ways this could happen:
*
*Logging in causes a login on the other application (writes the cookie and creates the session in the DB)
*Accessing an application checks for the cookie of the other and then automatically logs in.
Since the usernames are shared it seems like the latter should be pretty easy to do. Any tips would be great.
A: The primary problem you are going to run into is that you'll have two login forms, and two logout methods. What you need to do is pick one of the login forms as the default, and redirect the other one over to it.
I've been able to successfully integrate bbPress + MediaWiki + WordPress + WordPress MU, but I wrote a lot of custom code to do it.
I'm using the bbPress login page as the default (and .htaccess rewrite to /login/), and then I created my own MediaWiki authentication plugin (which looks a lot like the one you are using), except my plugin checks the WordPress/bbPress cookie for the login information and automatically logs the user in.
I created a customized /logout/ link that runs the bbPress logout, and also kills the MediaWiki cookies at the same time.
Then the last step was to redirect all of the other logout / login links for bbpress, mediawiki, etc, over to my consolidated one. I used .htaccess rewrites for this rather than mess with core code.
Still a work in progress, but it works fairly well.
A: You could consider some kind of single-sign-on software. I am unaware of any that are free and I've only ever used SiteMinder which is neither free nor good. Crowd may be better (but is again not free).
A: I've seen a setup going through Invision Power Board, using IpbWiki and a Wordpress integration mod. Mind you, it's expensive and excessive.
A: They both support OpenId now.
*
*MediaWiki's extension
*WordPress's plugin
There are probably other options for using OpenId, but I think that is the best solution available.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why can't a forward declaration be used for a std::vector? If I create a class like so:
// B.h
#ifndef _B_H_
#define _B_H_
class B
{
private:
int x;
int y;
};
#endif // _B_H_
and use it like this:
// main.cpp
#include <iostream>
#include <vector>
class B; // Forward declaration.
class A
{
public:
A() {
std::cout << v.size() << std::endl;
}
private:
std::vector<B> v;
};
int main()
{
A a;
}
The compiler fails when compiling main.cpp. Now the solution I know is to #include "B.h", but I'm curious as to why it fails. Neither g++ or cl's error messages were very enlightening in this matter.
A: To instantiate A::v, the compiler needs to know the concrete type of B.
If you're trying to minimize the amount of #included baggage to improve compile times, there are two things you can do, which are really variations of each other:
*
*Use a pointer to B
*Use a lightweight proxy to B
A: In fact your example would build if A's constructor were implemented in a compile unit that knows the type of B.
An std::vector instance has a fixed size, no matter what T is, since it contains, as others said before, only a pointer to T. But the vector's constructor depends on the concrete type. Your example doesn't compile because A() tries to call the vector's ctor, which can't be generated without knowing B. Here's what would work:
A's declaration:
// A.h
#include <vector>
class B; // Forward declaration.
class A
{
public:
A(); // only declare, don't implement here
private:
std::vector<B> v;
};
A's implementation:
// A.cpp
#include "A.h"
#include "B.h"
A::A() // this implicitly calls vector<B>'s constructor
{
std::cout << v.size() << std::endl;
}
Now a user of A needs to know only A, not B:
// main.cpp
#include "A.h"
int main()
{
A a; // compiles OK
}
A: The compiler needs to know how big "B" is before it can generate the appropriate layout information. If instead, you said std::vector<B*>, then the compiler wouldn't need to know how big B is because it knows how big a pointer is.
A: It's more than just the size of B that's needed. Modern compilers will have fancy tricks to speed up vector copies using memcpy where possible, for instance. This is commonly achieved by partially specializing on the POD-ness of the element type. You can't tell if B is a POD from a forward declaration.
A: Just like fyzix said, the reason your forward declaration is not working is because of your inline constructor. Even an empty constructor might contain lots of code, like the construction of non-POD members. In your case, you have a vector to initialize, which you can't do without defining its template type completely.
The same goes for destructors. The vector needs the template type definition to tell what destructor to call when destroying the instances it holds.
To get rid of this problem, just don't inline constructors and destructors. Define them separately somewhere after B is completely defined.
For more information,
http://www.chromium.org/developers/coding-style/cpp-dos-and-donts
A: This doesn't matter whether you use a vector or just try to instantiate one B. Instantiation requires the full definition of an object.
A: Man, you're instancing std::vector with an incomplete type. Don't touch the forward declaration, just move the constructor's definition to the .cpp file.
A: The reason you can't use a forward declaration is because the size of B is unknown.
There's no reason in your example that you can't include B.h inside of A.h, so what problem are you really trying to solve?
Edit: There's another way to solve this problem, too: stop using C/C++! It's so 1970s... ;)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: How do you implement caching in Linq to SQL? We've just started using LINQ to SQL at work for our DAL & we haven't really come up with a standard for out caching model. Previously we had being using a base 'DAL' class that implemented a cache manager property that all our DAL classes inherited from, but now we don't have that. I'm wondering if anyone has come up with a 'standard' approach to caching LINQ to SQL results?
We're working in a web environment (IIS) if that makes a difference. I know this may well end up being a subjective question, but I still think the info would be valuable.
EDIT: To clarify, I'm not talking about caching an individual result, I'm after more of an architecture solution, as in how do you set up caching so that all your link methods use the same caching architecture.
A: It's right under your nose:
List<TableItem> myResult = (from t in db.Table select t).ToList();
Now, just cache myResult as you would have cached your old DAL's returned data.
A: My LINQ query result cache is probably just what you're looking for.
var q = from c in context.Customers
where c.City == "London"
select new { c.Name, c.Phone };
var result = q.Take(10).FromCache();
Pete.
A: A quick answer: Use the Repository pattern (see Domain Driven Design by Evans) to fetch your entities. Each repository will cache the things it will hold, ideally by letting each instance of the repository access a singleton cache (each thread/request will instantiate a new repository but there can be only one cache).
The above answer works on one machine only. To be able to use this on many machines, use memcached as your caching solution. Good luck!
A: I found this post, which offers an extension method as a means of caching the LINQ objects.
I've been banging my head against the wall for weaks now trying to figure out a good caching solution for Linq2SQL, an must admit that I'm really struggling to find a one-size fits all...
The repository pattern tends to limit the usefullness of Linq, since (without reimplementing IQueryable) caching must bge performed outside of Linq statement.
Moreover, deferred loading and object tracking are both big no-nos if you're going to cache your objects, which makes performing updates somewhat trickier.
Anyone who's managed to solve this problem in the wild within a highly concurrent web project, please chime in and save the world! :)
A: I understand this is perhaps a bit late answer... Non the less, you can give a try to the LinqToCache project. It hooks a SqlDepdency on an arbitrary LINQ query, if possible, and provides active cache invalidation via the server side Query Notifications. The queries must be valid queries for notifications, see Creating a Query for Notification. Most Linq-to-sql queries conform to these restrictions, as long as the tables are specified using two-part names (dbo.Table, not only Table).
A: See the 'GetReferenceData' method in the 'ReferenceData' class in this article:
http://blog.huagati.com/res/index.php/2008/06/23/application-architecture-part-2-data-access-layer-dynamic-linq/
It uses the asp.net page cache for caching data retrieved using L2S.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: How do I unit test a WCF service? We have a whole bunch of DLLs that give us access to our database and other applications and services.
We've wrapped these DLLs with a thin WCF service layer which our clients then consume.
I'm a little unsure on how to write unit tests that only test the WCF service layer. Should I just write unit tests for the DLLs, and integration tests for the WCF services? I'd appreciate any wisdom... I know that if my unit tests actually go to the database they won't actually be true unit tests. I also understand that I don't really need to test the WCF service host in a unit test.
So, I'm confused about exactly what to test and how.
A: If you want to unit test your WCF service classes make sure you design them with loose coupling in mind so you can mock out each dependancy as you only want to test the logic inside the service class itself.
For example, in the below service I break out my data access repository using "Poor Man's Dependency Injection".
Public Class ProductService
Implements IProductService
Private mRepository As IProductRepository
Public Sub New()
mRepository = New ProductRepository()
End Sub
Public Sub New(ByVal repository As IProductRepository)
mRepository = repository
End Sub
Public Function GetProducts() As System.Collections.Generic.List(Of Product) Implements IProductService.GetProducts
Return mRepository.GetProducts()
End Function
End Class
On the client you can mock the WCF service itself using the interface of the service contract.
<TestMethod()> _
Public Sub ShouldPopulateProductsListOnViewLoadWhenPostBackIsFalse()
mMockery = New MockRepository()
mView = DirectCast(mMockery.Stub(Of IProductView)(), IProductView)
mProductService = DirectCast(mMockery.DynamicMock(Of IProductService)(), IProductService)
mPresenter = New ProductPresenter(mView, mProductService)
Dim ProductList As New List(Of Product)()
ProductList.Add(New Product)
Using mMockery.Record()
SetupResult.For(mView.PageIsPostBack).Return(False).Repeat.Once()
Expect.Call(mProductService.GetProducts()).Return(ProductList).Repeat.Once()
End Using
Using mMockery.Playback()
mPresenter.OnViewLoad()
End Using
'Verify that we hit the service dependency during the method when postback is false
Assert.AreEqual(1, mView.Products.Count)
mMockery.VerifyAll()
End Sub
A: It depends on what the thin WCF service does. If it's really thin and there's no interesting code there, don't bother unit testing it. Don't be afraid to not unit test something if there's no real code there. If the test cannot be at least one level simpler then the code under the test, don't bother. If the code is dumb, the test will also be dumb. You don't want to have more dumb code to maintain.
If you can have tests that go all the way to the db then great! It's even better. It's not a "true unit test?" Not a problem at all.
A: The consumer of your service doesn't care what's underneath your service.
To really test your service layer, I think your layer needs to go down to DLLs and the database and write at least CRUD test.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: How to convince my co-workers not to use datasets for enterprise development (.NET 2.0+) Everyone I work with is obsessed with the data-centric approach to enterprise development and hates the idea of using custom collections/objects. What is the best way to convince them otherwise?
A:
Remember to consider the possibility that they're onto something you've missed. Being part of a team means taking turns learning & teaching.
Seconded. The whole idea that "enterprise development" is somehow distinct from (and usually the implication is 'more important than') normal development really irks me.
If there really is a benefit for using some technology, then you'll need to come up with a considered list of all the pros and cons that would occur if you switched.
Present this list to your co workers along with explanations and examples for each one.
You have to be realistic when creating this list. You can't just say "Saves us lots of time!!! WIN!!" without addressing the fact that sometimes it is going to take MORE time, will require X months to come up to speed on the new tech, etc. You have to show concrete examples where it will save time, and exactly how.
Likewise you can't just skirt over the cons as if they don't matter, your co-workers will call you on it.
If you don't do these things, or come across as just pushing what you personally like, nobody is going to take you seriously, and you'll just get a reputation for being the guy who's full of enthusiasm and energy but has no idea about anything.
BTW. Look out for this particular con. It will trump everything, unless you have a lot of strong cases for all your other stuff:
*
*Requires 12+ months work porting our existing code. You lose.
A: Of course, "it depends" on the situation. Sometimes DataSets or DataTables are more suited, like if it really is pretty light business logic, flat hierarchy of entities/records, or featuring some versioning capabilities.
Custom object collections shine when you want to implement a deep hierarchy/graph of objects that cannot be efficiently represented in flat 2D tables. What you can demonstrate is a large graph of objects and getting certain events to propagate down the correct branches without invoking inappropriate objects in other branches. That way it is not necessary to loop or Select through each and every DataTable just to get the child records.
For example, in a project I got involved in two and half years ago, there was a UI module that is supposed to display questions and answer controls in a single WinForms DataGrid (to be more specific, it was Infragistics' UltraGrid). Some more tricky requirements
*
*The answer control for a question can be anything - text box, check box options, radio button options, drop-down lists, or even to pop up a custom dialog box that may pull more data from a web service.
*Depending on what the user answered, it can trigger more sub-questions to appear directly under the parent question. If a different answer is given later, it should expose another set of sub-questions (if any) related to that answer.
The original implementation was written entirely in DataSets, DataTables, and arrays. The amount of looping through the hundreds of rows for multiple tables was purely mind-bending. It did not help the programmer came from a C++ background attempting to ref everything (hello, objects living in the heap use reference variables, like pointers!). Nobody, not even the originally programmer, could explain why the code is doing what it does. I came into the scene more than six months after this, and it was stil flooded with bugs. No wonder the 2nd-generation developer I took over from decided to quit.
Two months of tying to fix the chaotic mess, I took it upon myself to redesign the entire module into an object-oriented graph to solve this problem. yeap, complete with abstract classes (to render different answer control on a grid cell depending on question type), delegates and eventing. The end result was a 2D dataGrid binded to a deep hierarchy of questions, naturally sorted according to the parent-child arrangement. When a parent question's answer changed, it would raise an event to the children questions and they would automatically show/hide their rows in the grid according to the parent's answer. Only question objects down that path were affected. The UI responsiveness of this solution compared to the old method was by orders of magnitude.
A: Ironically, I wanted to post a question that was the exact opposite of this. Most of the programmers I've worked with have gone with the custom data objects/collections approach. It breaks my heart to watch someone with their SQL Server table definition open on one monitor, slowly typing up a matching row-wrapper class in Visual Studio in another monitor (complete with private properties and getters-setters for each column). It's especially painful if they're also prone to creating 60-column tables. I know there are ORM systems that can build these classes automagically, but I've seen the manual approach used much more frequently.
Engineering choices always involve trade-offs between the pros and cons of the available options. The DataSet-centric approach has its advantages (db-table-like in-memory representation of actual db data, classes written by people who know what they're doing, familiar to large pool of developers etc.), as do custom data objects (compile-type checking, users don't need to learn SQL etc.). If everyone else at your company is going the DataSet route, it's at least technically possible that DataSets are the best choice for what they're doing.
A: Datasets/tables aren't so bad are they?
Best advise I can give is to use it as much as you can in your own code, and hopefully through peer reviews and bugfixes, the other developers will see how code becomes more readable. (make sure to push the point when these occurrences happen).
Ultimately if the code works, then the rest is semantics is my view.
A: Do it by example and tread lightly. Anything stronger will just alienate you from the rest of the team.
Remember to consider the possibility that they're onto something you've missed. Being part of a team means taking turns learning & teaching.
No single person has all the answers.
A: I guess you can trying selling the idea of O/R mapping and mapper tools. The benefit of treating rows as objects is pretty powerful.
A: I think you should focus on the performance. If you can create an application that shows the performance difference when using DataSets vs Custom Entities. Also, try to show them Domain Driven Design principles and how it fits with entity frameworks.
A: Don't make it a religion or faith discussion. Those are hard to win (and is not what you want anyway)
Don't frame it the way you just did in your question. The issue is not getting anyone to agree that this way or that way is the general way they should work. You should talk about how each one needs to think in order to make the right choice at any given time. give an example for when to use dataSet, and when not to.
I had developers using dataTables to store data they fetched from the database and then have business logic code using that dataTable... And I showed them how I reduced the time to load a page from taking 7 seconds of 100% CPU (on the web server) to not being able to see the CPU line move at all.. by changing the memory object from dataTable to Hash table.
So take an example or case that you thing is better implemented differently, and win that battle. Don't fight the a high level war...
A: If Interoperability is/will be a concern down the line, DataSet is definitely not the right direction to go in. You CAN expose DataSets/DataTables over a service but whether you SHOULD or is debatable. If you are talking .NET->.NET you're probably Ok, otherwise you are going to have a very unhappy client developer from the other side of the fence consuming your service
A: If you are working on legacy code (e.g., apps ported from .NET 1.x to 2.0 or 3.5) then it would be a bad idea to depart from datasets. Why change something that already works?
If you are, however, creating a new apps, there a few things that you can cite:
*
*Appeal to experiencing pain in maintaining apps that stick with DataSets
*Cite performance benefits for your new approach
*Bait them with a good middle-ground. Move to .NET 3.5, and promote LINQ to SQL, for instance: while still sticking to data-driven architecture, is a huge, huge departure to string-indexed data sets, and enforces... voila! Custom collections -- in a manner that is hidden from them.
What is important is that whatever approach you use you remain consistent, and you are completely honest with the pros and cons of your approaches.
If all else fails (e.g., you have a development team that utterly refuses to budge from old practices and is skeptical of learning new things), this is a very, very clear sign that you've outgrown your team it's time to leave your company!
A: You can't convince them otherwise. Pick a smaller challenge or move to a different organization. If your manager respects you see if you can do a project in the domain-driven style as a sort of technology trial.
A: If you can profile, just Do it and profile. Datasets are heavier then a simple Collection<T>
DataReaders are faster then using Adapters...
Changing behavior in an objects is much easier than massaging a dataset
Anyway: Just Do It, ask for forgiveness not permission.
A: Most programmers don't like to stray out of their comfort zones (note that the intersection of the 'most programmers' set and the 'Stack Overflow' set is the probably the empty set). "If it worked before (or even just worked) then keep on doing it". The project I'm currently on required a lot of argument to get the older programmers to use XML/schemas/data sets instead of just CSV files (the previous version of the software used CSV's). It's not perfect, the schemas aren't robust enough at validating the data. But it's a step in the right direction. The code I develop uses OO abstractions on the data sets rather than passing data set objects around. Generally, it's best to teach by example, one small step at a time.
A: There is already some very good advice here but you'll still have a job to convince your colleagues if all you have to back you up is a few supportive comments on stackoverflow.
And, if they are as sceptical as they sound, you are going to need more ammo.
First, get a copy of Martin Fowler's "Patterns of Enterprise Architecture" which contains a detailed analysis of a variety of data access techniques.
Read it.
Then force them all to read it.
Job done.
A: data-centric means less code-complexity.
custom objects means potentially hundreds of additional objects to organize, maintain, and generally live with. It's also going to be a bit faster.
I think it's really a code-complexity vs performance question, which can be answered by the needs of your app.
A: Start small. Is there a utility app you can use to illustrate your point?
For instance, at a place where I worked, the main application had a complicated build process, involving changing config files, installing a service, etc.
So I wrote an app to automate the build process. It had a rudimentary WinForms UI. But since we were moving towards WPF, I changed it to a WPF UI, while keeping the WinForms UI as well, thanks to Model-View-Presenter. For those who weren't familiar with Model-View-Presenter, it was an easily-comprehensible example they could refer to.
Similarly, find something small where you can show them what a non-DataSet app would look like without having to make a major development investment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.