instruction stringlengths 0 30k ⌀ |
|---|
<a href="http://www.stack.nl/~dimitri/doxygen/">Doxygen</a> is really excellent for this, although you will need to install <a href="http://www.graphviz.org/">GraphViz</a> to get the the graphs to draw.
Once you've got everything installed, it's really rather simple to draw the graphs. Make sure you set <a href="http://www.stack.nl/~dimitri/doxygen/config.html#cfg_extract_all">EXTRACT_ALL</a> and <a href="http://www.stack.nl/~dimitri/doxygen/config.html#cfg_call_graph">CALL_GRAPH</a> to true and you should be good to go.
The full documentation on this function for Doxygen is <a href="http://www.stack.nl/~dimitri/doxygen/diagrams.html">here</a>, and it also has a useful <a href="http://www.stack.nl/~dimitri/doxygen/examples/diagrams/html/index.html">example</a>. |
Have a look at [FLTK][1] which supports X11 and Windows.
[1]: http://fltk.org/index.php |
G'day,
As you're talking about integration testing my big (obvious) tip would be to make the test server built and configured as close as possible to the deployment environment as possible.
</thebloodyobvious> (-:
cheers,
Rob |
For all solutions about the back button, none of them are "automatic". With every single one you are going to have to do some work to persist the state of the page. So no, there isn't a way to "trick" the browser, but there are some great libraries out there that help you with the back button. |
If the program has to email you directly, it has to get that information somehow, so a determined attacker could gain that information as well.
Have you considered hosting a simple http form or web service somewhere, so that you could post the information you need there from the application (no authentication required), and either save it to manually look at later, or send the email from that server? |
As long as your account is on gmail.com, set up **gmail-smtp-in.l.google.com** as the outgoing SMTP-server in your program. You do not need to provide a password to send email to gmail-accounts when using that server. |
I would create a webservice to connect to. This webservice should send the email based on the data your program provide. All sensitive access-data is kept on the webservice side, so it's safer.
|
Try running
lsof | grep /mnt/data
That should list any process that is accessing /mnt/data that would prevent it from being unmounted. |
How are you adding the environment variable?
Without using any external tools, you can [add it to the registry][1]. Then, your test of opening a new command window will reflect your change.
[1]: http://www.windowsnetworking.com/kbase/WindowsTips/WindowsNT/AdminTips/Miscellaneous/SetEnvManipulateNTEnvironmentalVariables.html |
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. |
This is a very interesting question. I (vaguely) remember an assignment very similar in college 17 years ago. We had to create an array of pipes, where our code would get filehandles for the input/output of each pipe. Then the code would fork and close the unused filehandles.
I'm thinking you could do something similar with named pipes in bash. Use mknod or mkfifo to create a set of pipes with unique names you can reference then fork your program. |
Microsoft hired one fo the kids from A List Apart to whip some out. The .Net projects are free of charge for download.
http://msdn.microsoft.com/en-us/asp.net/aa336613.aspx
peace|dewde
http://dewde.com |
Free ASP.Net and/or CSS Themes |
|free|asp.net-themes|css-themes| |
Where can I get some decent looking free ASP.Net or CSS themes? |
|asp.net|css|free|themes| |
Unless C: is not the drive that windows booted from.<br />Parse the %SystemRoot% variable, it contains the location of the windows folder (i.e. c:\windows). |
VSJ, I find it a great mag :) [http://www.vsj.co.uk/](http://www.vsj.co.uk/)
###Edit
This is NOT off-topic! It directly relates to programming! |
First, this is MUCH easier if both the server and your workstation are on the same domain (the server needs access to connect to your machine). In your C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\Remote Debugger\x86 (or x64, or ia64) directory are the files you need to copy to your server. There are different versions between Visual Studio versions, so make sure they match on the client and server side. On the server, fire up msvsmon. It will say something like "Msvsmon started a new server named xxx@yyyy". This is the name you'll use in Visual Studio to connect to this server. You can go into Tools > Options to set the server name and to set the authentication mode (hopefully Windows Authentication) - BTW No Authentication doesn't work for managed code.
On the client side, open up Visual Studio and load the solution you're going to debug. Then go to Debug > Attach to Process. In the "Qualifier" field enter the name of the server as you saw it appear earlier. Click on the Select button and select the type of code you want to debug, then hit OK. Hopefully you'll see a list of the processes on the server that you can attach to (you should also see on the server that the debugging monitor just said you connected). Find the process to attach to (start up the app if necessary). If it's an ASP.NET website, you'd select w3wp.exe, then hit Attach. Set your breakpoints and hopefully you're now remotely debugging the code.
AFAIK - the VMWare option lets you start up code inside of a VM but debug it from your workstation. |
I'm trying to come up with a design for a thread pool with a lot of design requirements for my job. This is a real problem for working software, and it's a difficult task. I have a working implementation but I'd like to throw this out to SO and see what interesting ideas people can come up with, so that I can compare to my implementation and see how it stacks up. I've tried to be as specific to the requirements as I can.
The thread pool needs to execute a series of tasks. The tasks can be short running (<1sec) or long running (hours or days). Each task has an associated priority (from 1 = very low to 5 = very high). Tasks can arrive at any time while the other tasks are running, so as they arrive the thread pool needs to pick these up and schedule them as threads become available.
The task priority is completely independant of the task length. In fact it is impossible to tell how long a task could take to run without just running it.
Some tasks are CPU bound while some are greatly IO bound. It is impossible to tell beforehand what a given task would be (although I guess it might be possible to detect while the tasks are running).
The primary goal of the thread pool is to maximise throughput. The thread pool should effectively use the resources of the computer. Ideally, for CPU bound tasks, the number of active threads would be equal to the number of CPUs. For IO bound tasks, more threads should be allocated than there are CPUs so that blocking does not overly affect throughput. Minimising the use of locks and using thread safe/fast containers is important.
In general, you should run higher priority tasks with a higher CPU priority (ref: SetThreadPriority). Lower priority tasks should not "block" higher priority tasks from running, so if a higher priority task comes along while all low priority tasks are running, the higher priority task will get to run.
The tasks have a "max running tasks" parameter associated with them. Each type of task is only allowed to run at most this many concurrent instances of the task at a time. For example, we might have the following tasks in the queue:
- A - 1000 instances - low priority - max tasks 1
- B - 1000 instances - low priority - max tasks 1
- C - 1000 instances - low priority - max tasks 1
A working implementation could only run (at most) 1 A, 1 B and 1 C at the same time.
It needs to run on Windows XP, Server 2003, Vista and Server 2008 (latest service packs).
----------
For reference, we might use the following interface:
namespace ThreadPool
{
class Task
{
public:
Task();
void run();
};
class ThreadPool
{
public:
ThreadPool();
~ThreadPool();
void run(Task *inst);
void stop();
};
} |
The principal framework for audio development in Mac OS X is Core Audio; it's the basis for all audio I/O. There are layers on top of it like Audio Toolbox, Audio Queue Services, QuickTime, and QTKit that you can use if you want a simplified API for common tasks.
To just pull a stream of samples, you'd probably want to use [Audio Queue Services][1]; the [`AudioQueueNewInput`][2] function will set up recording of PCM data and pass it to a callback you supply.
On your Mac there's a set of Core Audio examples in [`/Developer/Examples/CoreAudio/SimpleSDK`][3] that includes a use (AQRecord in AudioQueueTools) of the Audio Queue Services recording APIs.
[1]: http://developer.apple.com/documentation/MusicAudio/Reference/AudioQueueReference/Reference/reference.html "Audio Queue Services Reference"
[2]: http://developer.apple.com/documentation/MusicAudio/Reference/AudioQueueReference/Reference/reference.html#//apple_ref/c/func/AudioQueueNewInput
[3]: file:///Developer/Examples/CoreAudio/SimpleSDK |
|svn|version-control|tfs|teamfoundationserver| |
|svn|version-control|tfs| |
As you are sure about needing to represent the *presentational* side of things, it may be worth looking at the [XSL-FO][1] W3C Recommendation. This is a full-blown page description language and the (deeply unfashionable) other half of the better-known XSLT.
Clearly the whole thing is anything but "lightwight", but if you just incorporated a
very limited subset - which could even just be (to match your spec of "paragraph tags, font selection, font size & decoration") [fo:block][2] and the [common font properties][3], something like:
<yourcontainer xmlns:fo="http://www.w3.org/1999/XSL/Format">
<fo:block font-family="Arial, sans-serif" font-weight="bold"
font-size="16pt">Example Heading</fo:block>
<fo:block font-family="Times, serif"
font-size="12pt">Paragraph text here etc etc...</fo:block>
</yourcontainer>
This would perhaps have a few advantages over just rolling your own. There's an open specification to work from, and all that implies. It reuses CSS properties as XML attributes (in a similar manner to SVG), so many of the formatting details will seem somewhat familiar. You'd have an upgrade path if you later decided that, say, intelligent paging was a must-have feature - including more sections of the spec as they become relevant to your application.
There's one other thing you might get from investigating XSL-FO - seeing how even just-doing-paragraphs-and-fonts can be horrendously complicated. Trying to do text layout and line breaking 'The Right Way' for various different languages and use cases seems very daunting to me.
[1]: http://www.w3.org/TR/xsl/
[2]: http://www.w3.org/TR/xsl/#fo_block
[3]: http://www.w3.org/TR/xsl/#common-font-properties |
Might be a kludge (and may not even work) but on your Login page see if `Request.QueryString["ReturnUrl"] != null` and if so set `Response.StatusCode = 401`.
Bear in mind that you'll still need to get your console app to authenticate somehow. You don't get HTTP basic auth for free: you have to roll your own, but there are plenty of implementations about. |
How do I change my workstation in Team Foundation Server 2k5 and 2k8? |
|teamfoundationserver|workstations| |
I've got multiple projects in a couple different workstations. However, it seems like I can never figure out how to change my current workstation. The result is that files that I have checked out on my machine are shown to be checked out by somebody else and are not accessible. |
How do I change my workspace in Team Foundation Server 2k5 and 2k8? |
I've got multiple projects in a couple different workspaces. However, it seems like I can never figure out how to change my current workspace. The result is that files that I have checked out on my machine are shown to be checked out by somebody else and are not accessible.
**Edit**: Workspaces. |
|tfs|workstations| |
We just did a large AIR app that used PDF quite a bit - make sure you save yourself some heartache and write some code to check the acrobat version or that it's even installed - if they don't have it you won't get an error, just a blank HTML control.
I know, it sounds obvious, but still... |
It's called [alpha blending](http://en.wikipedia.org/wiki/Alpha_compositing).
In psuedocode, assuming the background color (blend) always has 255 alpha. Also assumes alpha is 0-255.
alpha=argb.alpha()
r = (alpha/255)*argb.r() + (1 - alpha/255)*blend.r()
g = (alpha/255)*argb.g() + (1 - alpha/255)*blend.g()
b = (alpha/255)*argb.b() + (1 - alpha/255)*blend.b()
*note: you probably need to be a bit (more) careful about floating-point/int math and rounding issues, depending on language. Cast intermediates accordingly* |
It's called [alpha blending](http://en.wikipedia.org/wiki/Alpha_compositing).
In psuedocode, assuming the background color (blend) always has 255 alpha. Also assumes alpha is 0-255.
alpha=argb.alpha()
r = (alpha/255)*argb.r() + (1 - alpha/255)*blend.r()
g = (alpha/255)*argb.g() + (1 - alpha/255)*blend.g()
b = (alpha/255)*argb.b() + (1 - alpha/255)*blend.b()
*note: you probably need to be a bit (more) careful about floating-point/int math and rounding issues, depending on language. Cast intermediates accordingly*
**Edited to add:**
If you don't have a background color with an alpha of 255, the algebra gets alot more complicated. I've done it before and it's a fun exercise left to the reader (if you really need to know, ask another question :).
In other words, what color C blends into some background the same as blending A, then blending B. This is sort of like calculating A+B (which isn't the same as B+A). |
I bounce about between Mac, Windows and Ubuntu and while Emacs used to be my editor of choice, I'm finding that in my old age I prefer to something GUI-based (using command-line for the shell is still fine by me). My preferred editor is [Komodo Edit][1], which the advantages of:
* Being free (as in beer)
* Available for Mac, Windows and Linux
* Syntax highlighting for a boatload of languages, including C++ and PHP (I'm using it for Ruby, Python and PHP myself)
* Code completion, even for classes I defined myself
* Ability to "remote save" via FTP, SFTP or SCP
* Support for organizing your files into projects
* Tabs and other interface niceties
I'm not sure how lightweight it is, but it certainly feels snappier than Eclipse!
[1]: http://www.activestate.com/Products/komodo_ide/komodo_edit.mhtml "Komodo Edit" |
Choosing a static code analysis tool |
|c|testing|unix| |
I'm working on a project where I'm coding in C in a UNIX environment. I've been using the lint tool to check my source code. Lint has been around a long time (since 1979), can anyone suggest a more recent code analysis tool I could use ? Preferably a tool that is free. |
I find [Ghost Doc][1] to be very useful.
> GhostDoc is a free add-in for Visual Studio that automatically generates XML
documentation comments for C#. Either by using existing documentation inherited
from base classes or implemented interfaces, or by deducing comments from
name and type of e.g. methods, properties or parameters.
[1]: http://www.roland-weigelt.de/ghostdoc/ |
And here's what works...
curl -s --cookie soba=. http://stackoverflow.com/users |
@Chris I have found that Visual Studio is the best IDE for developing against .NET -- I think the best way to target Mono is really just to develop and build in Visual Studio under Windows then just run those binaries directly on Linux (or whatever other Mono platform you are using). There are free versions of Visual Studio if licensing is a concern. If you are developing under Linux, the best software is probably Eclipse with a Mono plugin (see [The Mono Handbook - Eclipse][1] for installation instructions) but keep in mind it doesn't have near the amount of features or language integration Visual Studio has.
@modesty Mono is a 3rd party open source implementation of the .NET framework which allows you to run .NET applications on platforms other than Windows.
[1]: http://www.gotmono.com/docs/ide/eclipse.html "The Mono Handbook - Eclipse" |
Best practices for building Flash video player |
|flash|video| |
We have a custom-built Flash-based video player that I maintain, and it needs to support preroll ads and ideally both progressive video playback and streaming depending on a server switch.
I've been working with the flvPlayback component but am finding myself a little out of my depth. Are there any good tutorials or resources for understanding the difference between netstream and flvPlayback? Or is one part of the other? Have googled without success.
For the preroll ads we'll probably use DART In-Stream, which is part of the reason I feel I'm losing a grip on the best way to structure this thing.
Any help with best practices or links most appreciated - ta! |
[GeoTools][1] has code to transform to and from about any coordinate system you could imagine, and among them also Google Map's. It's also open source. However, it should also be pointed out that GeoTools is a <strong>large</strong> library, so if you're looking something small, quick and easy, it's likely not the way to go.
I would highly recommend it though if you're going to do other GIS/coordinate transformations, etc. as well.
If you use GeoTools or something similar, you might also be interested in knowing that the Google Map coordinate system is called EPSG 3785.
[1]: http://geotools.codehaus.org/ |
Test serialization encoding |
|java|xml|string|serialization|encoding| |
What is the best way to verify/test that a text string is serialized to a byte array with a certain encoding?
In my case, I want to verify that an XML structure is serialized to a byte array with the UTF-8 encoding which is of variable character length. As an example, my current ugly procedure is to inject a character known to require two bytes into the structure before serializing, then replacing the two-byte character with an ASCII character and comparing the serialized array lengths. This should yield two serialized arrays where the array containing the two-byte characters should have length +1.
Plus if the solution is elegant for Java.
I can't think of any elegant way to seek for a byte sequence in a byte array. (Could be used to seek for a known byte sequence representing the desired character representation in UTF-8.) |
My opinions on these are:
1) No, table names should be singular.
While it appears to make sense for the simple selection (`select * from Orders`) it makes less sense for the OO equivalent (`Orders x = new Orders`).
A table in a DB is really the set of that entity, it makes more sense once you're using set-logic:
select Orders.*
from Orders inner join Products
on Orders.Key = Products.Key
That last line, the actual logic of the join, looks confusing with plural table names.
I'm not sure about always using an alias (as Matt suggests) clears that up.
2) No, they only hold 1 property
3) Never, if the column name is ambiguous (as above where they both have a column called [Key]) the name of the table (or its alias) can distinguish them well enough. You want queries to be quick to type and simple - prefixes add unnecessary complexity.
4) Whatever you want, I'd suggest CapitalCase
I don't think there's one set of absolute guidelines on any of these.
As long as whatever you pick is consistent across the application or DB I don't think it really matters. |
>OpenID of course doesn't solve that problem. For example, if I use OpenID to sign in to StackOverflow, it doesn't mean I don't need to sign in to another website again using the same openID. -- tj9991
It can mean that, though. If your sign-on on the OpenID site is rememberd (for example, through cookies), you would effectively only need to sign on once per browser session (or once per week, once per month...) for all OpenID sites you visit.
Browser support and an API could even do away with the password prompt and the page redirect. Great idea!
|
WCF push to client through firewall? |
|.net|wcf|firewall|push|duplex| |
I need to use push-technology with WCF through client firewalls. This must be a common problem, and I know for a fact it works in theory (see links below), but I have failed to get it working, and I haven't been able to find a code sample that demonstrates it.
Requirements:
- WCF
- Clients connects to server through tcp port 80 (netTcpBinding).
- Server pushes back information at irregular intervals (1 min to several hours).
- Users should not have to configure their firewalls, server pushes must pass through firewalls that have all inbound ports closed. TCP duplex on the same connection is needed for this, a dual binding does not work since a port has to be opened on the client firewall.
- Clients sends heartbeats to server at regular intervals (perhaps every 15 mins) so server knows client is still alive.
- Server is IIS7 with WAS.
The solution seems to be duplex netTcpBinding. Based on this information:
[WCF through firewalls and NATs][1]
[Keeping connections open in IIS][2]
But I have yet to find a code sample that works.. I've tried combining the "Duplex" and "TcpActivation" samples from Microsoft's WCF Samples without any luck. Please can someone point me to example code that works, or build a small sample app. Thanks a lot!
[1]: http://blogs.msdn.com/drnick/archive/2006/05/01/configuring-wcf-for-nats-and-firewalls.aspx
[2]: http://blogs.msdn.com/drnick/archive/2006/10/20/keeping-connections-open-in-iis.aspx |
In each step of the job click on advanced then from there you can log to a file or to a table, this will have all errorcodes and other things why the job failed
You should be able to see this also from the job history.
Right click on the job-->view history, click on the + sign to expand, the click on each step and it will be in the lower panel
To set up notifications you need to set up an operator and the in the job on the notification tab you pick it from the email dropdown |
I encountered a similar scenario a while back. A toolkit I was using did not behave well in a 64-bit environment and I wasn't able to find a way to dynamically force the assemblies to bind as 32 bit.
It is possible to force your assemblies to work in 32 bit mode, but this requires patching the CLR header, (there is a tool that does that in the Framework) and if your assemblies are strongly-named, this does not work out.
I'm afraid you'll need to build and publish two sets of binaries for 32 and 64 bit platforms. |
Your process steps should look like this:
1. [Verify][7] the [filetype][3]
2. Load the image if it is a supported filetype into GD using [imagecreatefrom*][2]
3. Resizing using [imagecopyresize][6] or [imagecopyresampled][5]
4. Save the image using [imagepng($handle, 'filename.png', $quality, $filters)][4]
> ImageMagick is faster, generates better images, is more configurable, and finally is (IMO) much easier to code for.
@[ceejayoz][1] Just wait for the new GD - it's OOP like MySQLi and it's actually nto bad :)
[1]: #22270
[2]: http://www.php.net/manual/en/function.imagecreatefromjpeg.php
[3]: http://www.php.net/manual/en/function.imagetypes.php
[4]: http://www.php.net/manual/en/function.imagepng.php
[5]: http://www.php.net/manual/en/function.imagecopyresampled.php
[6]: http://www.php.net/manual/en/function.imagecopyresized.php
[7]: http://www.php.net/manual/en/function.exif-imagetype.php |
Simple programming practice (Fizz Buzz, Print Primes) |
null |
I want to practice my skills away from a keyboard (i.e. pen and paper) and I'm after simple practice questions like Fizz Buzz, Print the first N primes.
What are your favourite simple programming questions? |
|language-agnostic| |
How to compare html entity with JQuery |
|jquery|entity| |
I have the next html code
<h3 id="headerid"><span onclick="expandCollapse('headerid')">⇑</span>Header title</h3>
I would like to toggle between up arrow and down arrow each time the user clicks the span tag.
function expandCollapse(id) {
var arrow = $("#"+id+" span").html(); // I have tried with .text() too
if(arrow == "⇓") {
$("#"+id+" span").html("⇑");
} else {
$("#"+id+" span").html("⇓");
}
}
My function is going always the else path. If i make a javacript:alert of *arrow* variable i am getting the html entity represented as an arrow. How can i tell jquery to interpret arrow variable as a string and not as html.
Thanks in advanced. |
I think the best plan would be to submit the error information to some service (in the simple case, a web form) running under your control, which could then send an email (or log it in some other appropriate way).
If sending the email is assumed to be of benefit to the end user, another option would be to have the user enter their own SMTP server (and username / password if required) - On Unix systems, you can possibly just use sendmail and rely on the user to have it configured correctly. I used to work on a system which used this approach to send the user reports of the system's scheduled tasks, and that worked quite well. |
MailMessage msg = new MailMessage("someone@foo.com", "someoneelse@bar.com");
msg.Subject = "Check it out!";
msg.Body = "Visit stackoverflow.com!";
SmtpClient client = new SmtpClient("some.smtp.server", 25);
client.Send(msg); |
There are some good examples of simple-ish programming questions in Steve Yegge's article [Five Essential Phone Screen Questions][1] (under Area Number One: Coding). I find these are pretty good for doing on pen and paper. Also, the questions under OOP Design in the same article can be done on pen and paper (or even in your head) and are, I think, good exercises to do.
[1]: http://steve.yegge.googlepages.com/five-essential-phone-screen-questions |
Have you tried:
$("#iFrameId").load(function (){
// do something once the iframe is loaded
}); |
Check out the [.toggle()][1] effect.
[1]: http://docs.jquery.com/Effects/toggle
Here is something similar i was playing with earlier.
HTML:
<div id="inplace">
<div id="myStatic">Hello World!</div>
<div id="myEdit" style="display: none">
<input id="myNewTxt" type="text" />
<input id="myOk" type="button" value="OK" />
<input id="myX" type="button" value="X" />
</div></div>
SCRIPT:
$("#myStatic").bind("click", function(){
$("#myNewTxt").val($("#myStatic").text());
$("#myStatic,#myEdit").toggle();
});
$("#myOk").click(function(){
$("#myStatic").text($("#myNewTxt").val());
$("#myStatic,#myEdit").toggle();
});
$("#myX").click(function(){
$("#myStatic,#myEdit").toggle();
}); |
@Levi Figueira
For one thing, Grails is far more flexible than Rails. Rails is difficult to use with a legacy DB because ActiveRecord has too many design constraints that many legacy DBs didn't follow. Grails, oth, can use standard Hibernate mappings, which can accommodate a much broader range of DB designs. |
I think to answer this question definitively would require knowing the compiler name and version that you are using and the platform (CPU type, OS etc.) that it is compiling for. |
There is no boot.ini on a machine with just Vista installed.
How do you want to identify the drive/partition: by the windows drive letter it is mapped to (eg. c:\, d:\) or by how its hardware signature (which bus, etc).
For the simple case check out [GetSystemDirectory][1]
[1]: http://msdn.microsoft.com/en-us/library/ms724373(VS.85).aspx |
I don't know how well it will do with really large tables, but Visual Studio is much quicker than SQL Management Studio for basic table operations. Open up your database in Server Explorer, right-click on a table, and select either "Open" to just display the data or "New Query" to filter, sort, etc. |
Can I create a value for a missing tag in XPath? |
|xml|xslt|xpath| |
I have an application which extracts data from an XML file using XPath. If a node in that XML source file is missing I want to return the value "N/A" (much like the Oracle NVL function). The trick is that the application doesn't support XSLT; I'd like to do this using XPath and XPath alone.
Is that possible? |
Try HKEY_LOCAL_MACHINE\SYSTEM\Setup\SystemPartition |
Editing raw data is a dangerous no-no. Better to identify the situations where you find yourself doing that and put together an application interface to act as an intermediary that can prevent you from doing stupid things like breaking a foreign key. |
In your case, stick with the constructor. The information belongs in Customer and 4 fields are fine.
In the case you have many required and optional fields the constructor is not the best solution. As @boojiboy said, it's hard to read and it's also hard to write client code.
@contagious suggested using the default pattern and setters for optional attributs. That mandates that the fields are mutable, but that's a minor problem.
Joshua Block on Effective Java 2 say that in this case you should consider a builder. An example taken from the book:
public class NutritionFacts {
private final int servingSize;
private final int servings;
private final int calories;
private final int fat;
private final int sodium;
private final int carbohydrate;
public static class Builder {
// required parameters
private final int servingSize;
private final int servings;
// optional parameters
private int calories = 0;
private int fat = 0;
private int carbohydrate = 0;
private int sodium = 0;
public Builder(int servingSize, int servings) {
this.servingSize = servingSize;
this.servings = servings;
}
public Builder calories(int val)
{ calories = val; return this; }
public Builder fat(int val)
{ fat = val; return this; }
public Builder carbohydrate(int val)
{ carbohydrate = val; return this; }
public Builder sodium(int val)
{ sodium = val; return this; }
public NutritionFacts build() {
return new NutritionFacts(this);
}
}
private NutritionFacts(Builder builder) {
servingSize = builder.servingSize;
servings = builder.servings;
calories = builder.calories;
fat = builder.fat;
soduim = builder.sodium;
carbohydrate = builder.carbohydrate;
}
}
And then use it like this:
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).
calories(100).sodium(35).carbohydrate(27).build();
The example above was taken from [Effective Java 2] [1]
And that doesn't only applies to constructor. Citing Kent Beck in [Implementation Patterns][2]:
setOuterBounds(x, y, width, height);
setInnerBounds(x + 2, y + 2, width - 4, height - 4);
Making the rectangle explicit as an object explains the code better:
setOuterBounds(bounds);
setInnerBounds(bounds.expand(-2));
[1]: http://www.amazon.com/Effective-Java-Programming-Language-Guide/dp/0201310058
[2]: http://www.amazon.com/Implementation-Patterns-Addison-Wesley-Signature-Kent/dp/0321413091 |
MVC .net - How actions names effect url |
|asp.net-mvc| |
Using MVC out of the box I found the generated URLs can be misleading and I wanted to know if this can be fixed or if my approach\understanding is wrong.
Suppose I have a CreateEgg page, which has a form on it, and once the form is filled in and submitted the user is taken to a ListEggs page with the new egg in it.
So my egg controller will look some thing like this:
public class EggController :Controller
{
public void Add()
{
//do stuff
RenderView("CreateEgg", viewData);
}
public void Create()
{
//do stuff
RenderView("ListEggs", viewData);
}
}
So my first page will have a url of something like http://localhost/egg/add and the form on the page will have an action of:
using (Html.Form<EggController>(c => c.Create())
Meaning the second page will have a url of http://localhost/Egg/Create, to me this is misleading, the action should be called Create, because im creating the egg, but a list view is being displayed so the url of http://localhost/Egg/List would make more scene. How do i achieve this without making my view or action names misleading? |
ASP.NET MVC - How do action names affect the url? |
Using MVC out of the box I found the generated URLs can be misleading and I wanted to know if this can be fixed or if my approach/understanding is wrong.
Suppose I have a CreateEgg page, which has a form on it, and once the form is filled in and submitted the user is taken to a ListEggs page with the new egg in it.
So my egg controller will look some thing like this:
public class EggController : Controller
{
public void Add()
{
//do stuff
RenderView("CreateEgg", viewData);
}
public void Create()
{
//do stuff
RenderView("ListEggs", viewData);
}
}
So my first page will have a url of something like http://localhost/egg/add and the form on the page will have an action of:
using (Html.Form<EggController>(c => c.Create())
Meaning the second page will have a url of http://localhost/Egg/Create, to me this is misleading, the action should be called Create, because im creating the egg, but a list view is being displayed so the url of http://localhost/Egg/List would make more scene. How do I achieve this without making my view or action names misleading? |
SQL: difference between inner and outer join |
|sql| |
What is the difference between INNER JOIN and OUTER JOIN? |
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. |
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. |
Your process steps should look like this:
1. [Verify][7] the [filetype][3]
2. Load the image if it is a supported filetype into GD using [imagecreatefrom*][2]
3. Resizing using [imagecopyresize][6] or [imagecopyresampled][5]
4. Save the image using [imagepng($handle, 'filename.png', $quality, $filters)][4]
> ImageMagick is faster, generates better images, is more configurable, and finally is (IMO) much easier to code for.
@[ceejayoz][1] Just wait for the new GD - it's OOP like MySQLi and it's actually not bad :)
[1]: #22270
[2]: http://www.php.net/manual/en/function.imagecreatefromjpeg.php
[3]: http://www.php.net/manual/en/function.imagetypes.php
[4]: http://www.php.net/manual/en/function.imagepng.php
[5]: http://www.php.net/manual/en/function.imagecopyresampled.php
[6]: http://www.php.net/manual/en/function.imagecopyresized.php
[7]: http://www.php.net/manual/en/function.exif-imagetype.php |
It depends on what you mean by 'better'. You are already using the simplest and easiest way of doing it.
|
View function should only contain display helpers or display logic. View functions should never access the model itself, but should take parameters of model data. It is important to separate the model from the view. So if the function handles accessing the database or database objects, it belongs in the model. If the function handles formatting display, it belongs in the view. |
Remoting server discovery. |
|.net|remoting|udp|broadcast|networking| |
I have a client/server application that communicates with .Net remoting. I need my clients to be able to find the server(s) on the network without requiring client-side configuration.
As far as I know, there is no support for discovery in remoting. I am prepared to implement a UDP solution where the clients will be able to find the servers via broadcast messages.
I want to hear the collective SO wisdom before I go ahead. Is this the best way? Any other suggestions? |
Remoting server auto-discovery. Broadcast or not? |
|.net|networking|remoting|udp|broadcast| |
How can I develop for iPhone using a Windows development machine? |
|iphone| |
Is there any way to tinker with the iPhone SDK on a Windows machine? Is there plans for an iPhone SDK version for Windows?
The only other way I can think of doing this is to run a Mac VM image on VMWare server running on Windows, although I'm not too sure how legal this is. |
I'm a PHP developer so I'll share what I know from PHP. I'm sure .NET will include something similar.
In PHP you can get timezone differences for the server time - as you've suggested you'd send the emails at different times on the server.
Every time you add a user save their time offset from the server time (or their timezone in case the server timezone changes).
Then when you specify an update, have an automated task (Cron for LAMP people) that runs each hour checking to see if an email needs to be sent. Do this until there are no emails left to send. |