instruction
stringlengths 0
30k
⌀ |
---|
|oop|architecture|theory|
|
I'm trying to boil down the concepts of coupling and cohesion to a concise definition. Can someone give me a short and understandable explanation (shorter than the definitions on Wikipedia [here](http://twurl.cc/4cx) and [here](http://twurl.cc/4cw))? How do they interact?
Thanks.
Anybody have a good, short example?
|
Well, I don't think that there is something like that in js. You can always use eval instead of locals(). Like this:
eval(s+"()");
You just have to know that actually function *foo* exists.
|
Well, I don't think that there is something like that in js. You can always use eval instead of locals(). Like this:
eval(s+"()");
You just have to know that actually function *foo* exists.
**Edit:**
Don't use eval:) Use:
var functionName="myFunctionName";
window[functionName]();
|
AFAIK, no. If you just want to check the existence of a given variable, you can do it by testing for it, something like this:
if (foo) foo();
|
group_concat query performance
|
|mysql|sql|performance|
|
i am having serious performance problems (queries up to 55 seconds) while running a mysql query since i added a group_concat clause.
my query looks like:
select ... group_concat(distinct category.name) .... from page where
left outer join page_category on page.id = story_category.page_id
left outer join category on page_category.category_id = category.id
....
group by page.id
As mentioned in the query, among others, my application has three tables page, category and page_category. A page can be associated with none or multiple categories. Currently page, page_category and category have 9,460, 20,241 and 10 entries each.
Can anyone help me to improve my query to avoid such performance problems?
|
|visual-studio|vbscript|
|
How two merge two projects in Mercurial.
|
|mercurial|
|
I have two separate mercurial repositories. At this point it makes sense that they "become one" because I want to work on the two projects simultaneously.
I'd really like the two projects to each be a subdirectory in the new repository.
1. How do I merge the two projects?
2. Is this a good idea, or should I
keep them separate?
|
I have two separate mercurial repositories. At this point it makes sense that they "become one" because I want to work on the two projects simultaneously.
I'd really like the two projects to each be a subdirectory in the new repository.
1. How do I merge the two projects?
2. Is this a good idea, or should I
keep them separate?
It seems I ought to be able to push from one repository to the other... Maybe this is really straight forward?
|
How two combine two projects in Mercurial?
|
How to combine two projects in Mercurial?
|
Take a look at [memcached][1]. It is a really cool, fast and lightweight distributed caching system. There are APIs for several of the most popular languages, including C#. It may not serve well on the client side (unless of course the client is obtaining the cached data from a server of some kind), but if you abstract your usage of memcached to a specific interface, you could then implement the interface with another caching system.
[1]: http://www.danga.com/memcached/
|
We actually just released some classes that help with exactly this kind of thing:
[http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16449][1]
Specifically, check out the DatabaseImage sample.
[1]: http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16449
|
Add a 'Generic Handler' to your web project, name it something like Image.ashx. Implement it like this:
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
using(Image image = GetImage(context.Request.QueryString["ID"]))
{
context.Response.ContentType = "image/jpeg";
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
public bool IsReusable
{
get
{
return true;
}
}
}
Now just implement the GetImage method to load the image with the given ID, and you can use
<asp:Image runat="server" ImageUrl="~/Image.ashx?ID=myImageId" />
to display it. You might want to think about implementing some form of caching in the handler too. And remember if you want to change the image format to PNG, you need to use an intermediate MemoryStream (because PNGs require a seekable stream to be saved).
|
Add the code to a handler to return the image bytes with the appropriate mime-type. Then you can just add the url to your handler like it is an image. For example:
<img src="myhandler.ashx?imageid=5">
Make sense?
|
[@Clayton][1]: Do what? I can't believe, at this point, that your answer has 2 up-votes, considering you cannot overload operators in current, common browser-based implementations of JavaScript interpreters (i.e. neither you nor those that have up-voted your response know JavaScript very well).
To answer the original question, one way you could do this, and mind you, this is a bit of a hack, and simply [serialize the two arrays to JSON][2] and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to *each* of the objects within the arrays as well to see which ones were different.
Another option is to use a library which has some nice facilities for comparing objects - I use and recommend [**MochiKit**][3].
[1]: http://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript#27038
[2]: http://www.json.org/json2.js
[3]: http://www.mochikit.com/
|
[@Clayton][1]: Do what? I can't believe, at this point, that your answer has 2 up-votes, considering you cannot overload operators in current, common browser-based implementations of JavaScript interpreters (i.e. neither you nor those that have up-voted your response know JavaScript very well).
To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply [serialize the two arrays to JSON][2] and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to *each* of the objects within the arrays as well to see which ones were different.
Another option is to use a library which has some nice facilities for comparing objects - I use and recommend [**MochiKit**][3].
[1]: http://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript#27038
[2]: http://www.json.org/json2.js
[3]: http://www.mochikit.com/
|
[@Clayton][1]: Do what? I can't believe, at this point, that your answer has 2 up-votes, considering you cannot overload operators in current, common browser-based implementations of JavaScript interpreters (i.e. neither you nor those that have up-voted your response know JavaScript very well).
To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply [serialize the two arrays to JSON][2] and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to *each* of the objects within the arrays as well to see which ones were different.
Another option is to use a library which has some nice facilities for comparing objects - I use and recommend [**MochiKit**][3].
----------
**EDIT:** [The answer kamens gave][4] deserves consideration as well, since a single function to compare two given objects would be much smaller than any library to do what I suggest (although my suggestion would certainly work well enough).
Here is a naïve implemenation that may do just enough for you - be aware that there are potential problems with this implementation:
function objectsAreSame(x, y) {
var objectsAreSame = true;
for(var propertyName in x) {
if(x[propertyName] !== y[propertyName]) {
objectsAreSame = false;
break;
}
}
return objectsAreSame;
}
The assumption is that both objects have the same exact list of properties.
Oh, and it is probably obvious that, for better or worse, I belong to the only-one-return-point camp. :)
[1]: http://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript#27038
[2]: http://www.json.org/json2.js
[3]: http://www.mochikit.com/
[4]: http://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript#27932
|
Clean the data before you store it. Generally you shouldn't be preforming **ANY** SQL actions without first cleaning up input. You don't want to subject yourself to a SQL injection attack.
I sort of follow these basic rules.
1. Only do modifying SQL actions, such as, INSERT, UPDATE, DELETE through POST. Never GET.
2. Escape everything.
3. If you are expecting user input to be something make sure you check that it is that something. For example, you are requesting an number, then make sure it is a number. Use validations.
4. Use filters. Clean up unwanted characters.
|
Users are evil!
Well perhaps not always, but my approach is to always sanatize immediately to ensure nothing risky goes anywhere near my backend.
The added benefit is that you can provide feed back to the user if you sanitize at point of input.
|
I also found that this will work too.
System.Collections.IDictionaryEnumerator enumerator = hashTable.GetEnumerator();
while (enumerator.MoveNext())
{
string key = enumerator.Key.ToString();
string value = enumerator.Value.ToString();
Console.WriteLine(("Key = '{0}'; Value = '{0}'", key, value);
}
Thanks for the help.
|
Do you actually have the single quotes in your command? I don't think they are necessary. Plus, I think you also need <code>--no-auth-cache</code> and <code>--non-interactive</code>
Here is what I use (no single quotes)
<pre>
--non-interactive --no-auth-cache --username XXXX --password YYYY
</pre>
See the <a href="http://svnbook.red-bean.com/en/1.4/svn.serverconfig.netmodel.html#svn.serverconfig.netmodel.credcache"><b>Client Credentials Caching</b> documentation in the svnbook</a> for more information.
|
I don't know if this is allowed but the best approximation I can find is:
Establish a fixed period of time to open each box and a precise order for opening them. That means, the prissioner will open the first 50 boxes, opening one box every minute. If the next prisioner have to come in at minute 13, then the previous prisioner opened the 13th box.
Repeat the algorithm for every prissioner taking into account the previosly found boxes.
That way you ensure every prissioner doesn't open a box which is known to be assigned to another prissioner who has already found it.
|
I don't know if this is allowed but the best approximation I can find is:
EDIT: Ok, I think this makes it. Of course I'm treating this as a computing problem, I don't think any prisioner will be able to perform this, although is pretty straight forward if you don't.
Find the first 50 primes, let's asume we hold them in an array called primes.
- The first prissioner enters room B and opens the first box and finds the number m.
- Wait primes[1]^m (that would be 3^m)
- Open box 2 and read the number --> n
- Wait (primes[2]^n - 1) * primes[1]^m, that would be (5^n - 1) * 3^m and the total time he has been waiting would be 3^n * 5^n
Repeat. After the first prisioner the total time for him would be:
3^m * 5^n * 7^p ... = X
Before the second prisioner enters the room factorize X. You know beforehand the prime numbers that have been used so the factorization is trivial. Doing so you obtain m, n, p, etc so the second prisioner knows every box/number combination the previous prisioner used.
The probability of the first one getting everybody killed is 1/2, the second one will have a 50 / (100 - n) (being n the numbers of attemps of the first one) the third one will have 50 / (100 - n - m) (if n + m = 100 then all positions are known) and so on.
I don't know what's the exact possibility as it dependes on how many choices they have to do but I'd say it's pretty high.
|
Is something like [Gears][1] acceptable. This will let you store data locally to limit re-requests.
[1]: http://gears.google.com/
|
Is something like [Gears][1] acceptable. This will let you store data locally to limit re-requests.
I would also stay away from flash and silverlight and go straight to javascript/AJAX. JQuery is a ton-O-fun.
[1]: http://gears.google.com/
|
Why is pagination so resource-expensive?
|
|pagination|
|
It's one of those things that seems to have an odd curve where the more I think about it, the more it makes sense. To a certain extent, of course. And then it doesn't make sense to me at all.
Care to enlighten me?
|
|pagination|
|
|performance|pagination|
|
[Lubos](http://stackoverflow.com/questions/29580/why-is-pagination-so-resource-expensive#29588) is right, the problem is not the fact that you are paging (which takes a HUGE amount of data off the wire), but that you need to figure out what is actually going on the page..
The fact that you need to page implies there is a lot of data. A lot of data takes a long time to sort :)
|
[Peter's answer](http://stackoverflow.com/questions/29004/parsing-xml-using-unix-terminal#29023) is correct, but it outputs a trailing line feed.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text"/>
<xsl:template match="root">
<xsl:for-each select="myel">
<xsl:value-of select="@name"/>
<xsl:text>,</xsl:text>
<xsl:if test="not(position() = last())">
<xsl:text>
</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Just run e.g.
xsltproc stylesheet.xsl source.xml
to generate the CSV results into standard output.
|
If you have no choice but to use MSTest, learn the keyboard shortcuts. They'll make your life a little easier.
Test in Current Context: CTRL+R, T
All Tests in Solution: CTRL+R, A
Debug Tests in Current Context: CTRL+R, CTRL+T
Debug All Tests in Solution: CTRL+R, CTRL+A
|
The view state only lasts for [multiple requests for the same page][1]. Changing the query string in the URL is requesting a new page, thus clearing the view state.
Is it possible to remove the reliance on the view state by adding more query string parameters? You can then build a new URL and Response.Redirect to it.
Another option is to use the [Action property][2] on the form to clear the query string so at least the query string does not contradict what's displayed on the page after the user selects a different report.
Form.Action = Request.Path;
[1]: http://msdn.microsoft.com/en-us/library/540y83hx.aspx
[2]: http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlform.action.aspx
|
I recommend checking out the book referenced by jko:
> a book from The Pragmatic Bookshelf called [Stripes: ...and Java web development is fun again][1]
Whilst still in 'beta' the book covers everything very well.
Another good place to start is [this ONJava article][2].
I have used Stripes on a few projects now and have liked it a lot.
It may sound crazy but the Stripes quickstart and sample application documentation on [the website][3] does a pretty good job of covering the bases.
This is helped by the fact there is little to Stripes, probably because it is relatively new and not trying to be all things to all people. I would say give the quick-start a try and if by the end of it you are unsatisfied look elsewhere. At the end of the day you and your company have to be happy (and productive) with what you are using irrespective of how many people are using it.
[1]: http://www.pragprog.com/titles/fdstr/stripes
[2]: http://www.onjava.com/pub/a/onjava/2007/01/24/java-web-development-with-stripes.html
[3]: http://www.stripesframework.org/display/stripes/Sample+Application
|
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 appendix A of the subversion book: [Subversion for CVS Users][1]
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
[1]: http://svnbook.red-bean.com/en/1.1/apa.html
|
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:
- Appendix A of the subversion book: [Subversion for CVS Users][1]
- [Subversion update command reference][2]
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
[1]: http://svnbook.red-bean.com/en/1.1/apa.html
[2]: http://svnbook.red-bean.com/en/1.1/re28.html
|
**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][2]
- Appendix A of the subversion book: [Subversion for CVS Users][1]
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
[1]: http://svnbook.red-bean.com/en/1.1/apa.html
[2]: http://svnbook.red-bean.com/en/1.1/re28.html
|
**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][2]
- Appendix A of the subversion book: [Subversion for CVS Users][1]
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.
[1]: http://svnbook.red-bean.com/en/1.1/apa.html
[2]: http://svnbook.red-bean.com/en/1.1/re28.html
|
What's the best way to implement an 'enum' in Python?
|
|python|enums|
|
I'm mainly a C# developer, but I'm currently working on a project in Python.
What's the best way to implement the equivalent of an enum in Python?
|
EDIT: You cannot overload operators in current, common browser-based implementations of JavaScript interpreters.
To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply [serialize the two arrays to JSON][2] and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to *each* of the objects within the arrays as well to see which ones were different.
Another option is to use a library which has some nice facilities for comparing objects - I use and recommend [**MochiKit**][3].
----------
**EDIT:** [The answer kamens gave][4] deserves consideration as well, since a single function to compare two given objects would be much smaller than any library to do what I suggest (although my suggestion would certainly work well enough).
Here is a naïve implemenation that may do just enough for you - be aware that there are potential problems with this implementation:
function objectsAreSame(x, y) {
var objectsAreSame = true;
for(var propertyName in x) {
if(x[propertyName] !== y[propertyName]) {
objectsAreSame = false;
break;
}
}
return objectsAreSame;
}
The assumption is that both objects have the same exact list of properties.
Oh, and it is probably obvious that, for better or worse, I belong to the only-one-return-point camp. :)
[1]: http://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript#27038
[2]: http://www.json.org/json2.js
[3]: http://www.mochikit.com/
[4]: http://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript#27932
|
@[Darren][1], Upon further examination, I've come to the conclusion that one assumption I had about *needing* Read permissions was incorrect.
SOAP web services only need the "Run scripts" permission enabled because the .wsdl apparently comes from the web service in the form of a script execution response. So the minimum required for a SOAP3.0 web service's directory is **Run scripts**; thanks for your input on this!
[1]: http://stackoverflow.com/questions/30712/what-is-the-proper-virtual-directory-access-permission-level-required-for-a-soa#30758
|
if you have phpMyAdmin installed, it is a nobrainer: Run the query (haven't got a copy loaded, so I can't tell you the details, but it really is easy) and check neer bottom for export options. CSV will be listed, but I think you can also have SQL if you like :)
phpMyAdmin will give CSV in Excels dialect, which is probably what you want...
|
You could also consider [Grails][1] ("Groovy on Rails") which gives you the benefits of a Rails framework and the use of the Java VM.
[1]: http://grails.org/
|
>>In addition to allowing full control to "Everyone" does the location also allow processes with a medium integrity level to write?
>How do I check that ? I am new to Vista, I don't like it too much, it's too slow inside a VM for daily work and for VStudio usage inside a Virtual Machine, it doesn't bring anything new.
From a command prompt to you can execute:
icacls C:\Folder
If you see a line such as "Mandatory Label\High Mandatory Level" then the folder is only accessible to a high integrity process. If there is no such line then medium integrity processes can access it provided there are no other ACLs denying access (based on user for example).
EDIT: Forgot to mention you can use the /setintegritylevel switch to actually change the required integrity level for accessing the object.
|
Crop MP3 to first 30 seconds
|
|mp3|
|
**Original Question**
I want to be able to generate a new (fully valid) MP3 file from an existing MP3 file to be used as a preview -- try-before-you-buy style. The new file should only contain the first *n* seconds of the track.
Now, I know I could just "chop the stream" at *n* seconds (calculating from the bitrate and header size) when delivering the file, but this is a bit dirty and a real PITA on a VBR track. I'd like to be able to generate a proper MP3 file.
Anyone any ideas?
**Answers**
Both mp3split and ffmpeg are both good solutions. I chose ffmpeg as it is commonly installed on linux servers and is also [easily available for windows][2]. Here's some more good command line parameters for generating previews with ffmpeg
- **`-t <seconds>`** chop after specified number of seconds
- **`-y`** force file overwrite
- **`-ab <bitrate>`** set bitrate e.g. *-ab 96k*
- **`-ar <rate Hz>`** set sampling rate e.g. *-ar 22050* for 22.05kHz
- **`-map_meta_data <outfile>:<infile>`** copy track metadata from infile to outfile
[1]: http://getid3.sourceforge.net/
[2]: http://sourceforge.net/project/showfiles.php?group_id=205275&package_id=248632
|
|mp3|ffmpeg|
|
**Original Question**
I want to be able to generate a new (fully valid) MP3 file from an existing MP3 file to be used as a preview -- try-before-you-buy style. The new file should only contain the first *n* seconds of the track.
Now, I know I could just "chop the stream" at *n* seconds (calculating from the bitrate and header size) when delivering the file, but this is a bit dirty and a real PITA on a VBR track. I'd like to be able to generate a proper MP3 file.
Anyone any ideas?
**Answers**
Both mp3split and ffmpeg are both good solutions. I chose ffmpeg as it is commonly installed on linux servers and is also [easily available for windows][2]. Here's some more good command line parameters for generating previews with ffmpeg
- **`-t <seconds>`** chop after specified number of seconds
- **`-y`** force file overwrite
- **`-ab <bitrate>`** set bitrate e.g. *-ab 96k*
- **`-ar <rate Hz>`** set sampling rate e.g. *-ar 22050* for 22.05kHz
- **`-map_meta_data <outfile>:<infile>`** copy track metadata from infile to outfile
instead of setting -ab and -ar, you can copy the original track settings, as Tim Farley suggests, with:
- **`-acodec copy`**
[1]: http://getid3.sourceforge.net/
[2]: http://sourceforge.net/project/showfiles.php?group_id=205275&package_id=248632
|
Do you want the decimal or not?
if not use
select ceiling(@value),floor(@value)
if you do with 0 the do a round
select round(@value,2)
|
You're worrying too much about internal implementation details. Don't pre-optimize.
Go with VARCHAR(500)
|
Can I put an ASP.Net session ID in a hidden form field?
|
|asp.net|session|yui|
|
|asp.net|hacking|session|yui|
|
I don't know if this is allowed but the best approximation I can find is:
EDIT: Ok, I think this makes it. Of course I'm treating this as a computing problem, I don't think any prisioner will be able to perform this, although is pretty straight forward if you don't.
Find the first 50 primes, let's asume we hold them in an array called primes.
- The first prissioner enters room B and opens the first box and finds the number m.
- Wait primes[1]^m (that would be 3^m)
- Open box 2 and read the number --> n
- Wait (primes[2]^n - 1) * primes[1]^m, that would be (5^n - 1) * 3^m and the total time he has been waiting would be 3^n * 5^n
Repeat. After the first prisioner the total time for him would be:
3^m * 5^n * 7^p ... = X
Before the second prisioner enters the room factorize X. You know beforehand the prime numbers that have been used so the factorization is trivial. Doing so you obtain m, n, p, etc so the second prisioner knows every box/number combination the previous prisioner used.
The probability of the first one getting everybody killed is 1/2, the second one will have a 50 / (100 - n) (being n the numbers of attemps of the first one) the third one will have 50 / (100 - n - m) (if n + m = 100 then all positions are known) and so on.
Obviously the next prissioner must skip the already known boxes (except for the last choice if the box which contains his number is already known)
I don't know what's the exact possibility as it dependes on how many choices they have to do but I'd say it's pretty high.
|
I don't know if this is allowed but the best approximation I can find is:
EDIT: Ok, I think this makes it. Of course I'm treating this as a computing problem, I don't think any prisioner will be able to perform this, although is pretty straight forward if you don't.
Find the first 50 primes, let's asume we hold them in an array called primes.
- The first prissioner enters room B and opens the first box and finds the number m.
- Wait primes[1]^m (that would be 3^m)
- Open box 2 and read the number --> n
- Wait (primes[2]^n - 1) * primes[1]^m, that would be (5^n - 1) * 3^m and the total time he has been waiting would be 3^n * 5^n
Repeat. After the first prisioner the total time for him would be:
3^m * 5^n * 7^p ... = X
Before the second prisioner enters the room factorize X. You know beforehand the prime numbers that have been used so the factorization is trivial. Doing so you obtain m, n, p, etc so the second prisioner knows every box/number combination the previous prisioner used.
The probability of the first one getting everybody killed is 1/2, the second one will have a 50 / (100 - n) (being n the numbers of attemps of the first one) the third one will have 50 / (100 - n - m) (if n + m = 100 then all positions are known) and so on.
Obviously the next prissioner must skip the already known boxes (except for the last choice if the box which contains his number is already known)
I don't know what's the exact possibility as it dependes on how many choices they have to do but I'd say it's pretty high.
EDIT: Rereading, if the prissioner does not have to stop when he obtains his number then the probability for the whole group is vastly improved, exactly 50%.
|
I don't know if this is allowed but the best approximation I can find is:
EDIT: Ok, I think this makes it. Of course I'm treating this as a computing problem, I don't think any prisioner will be able to perform this, although is pretty straight forward if you don't.
Find the first 50 primes, let's asume we hold them in an array called primes.
- The first prissioner enters room B and opens the first box and finds the number m.
- Wait primes[1]^m (that would be 3^m)
- Open box 2 and read the number --> n
- Wait (primes[2]^n - 1) * primes[1]^m, that would be (5^n - 1) * 3^m and the total time he has been waiting would be 3^n * 5^n
Repeat. After the first prisioner the total time for him would be:
3^m * 5^n * 7^p ... = X
Before the second prisioner enters the room factorize X. You know beforehand the prime numbers that have been used so the factorization is trivial. Doing so you obtain m, n, p, etc so the second prisioner knows every box/number combination the previous prisioner used.
The probability of the first one getting everybody killed is 1/2, the second one will have a 50 / (100 - n) (being n the numbers of attemps of the first one) the third one will have 50 / (100 - n - m) (if n + m = 100 then all positions are known) and so on.
Obviously the next prissioner must skip the already known boxes (except for the last choice if the box which contains his number is already known)
I don't know what's the exact possibility as it dependes on how many choices they have to do but I'd say it's pretty high.
EDIT: Rereading, if the prissioner does not have to stop when he obtains his number then the probability for the whole group is vastly improved, exactly 50%.
EDIT2: @OysterD see it this way. If the first prisioner can open 50 boxes then the second one know if its number is in any of that boxes. If it is, then he can open other 49 (and by doing so learning the box/number comination of the 100 boxes) and finally open his one. So if the first prissioner succeds then everyone succeds. Remember that each prisioner provides a way for the other to know exactly the boxes/number combination for every box he opens.
|
What is a 'closure'?
|
|functional-programming|terms|computer-science|
|
I asked a question about Currying and closures where mentioned.
What is a closure? How does it relate to currying?
|
What is a 'Closure'?
|
|functional-programming-t|computer-science|
|
|functional-programming|terms|computer-science|
|
|functional-programming|computer-science|programming-terms|
|
|functional-programming|computer-science|programming-terms|glossary|
|
|functional-programming|computer-science|glossary|programming-terms|
|
I asked a question about Currying and closures where mentioned.
What is a closure? How does it relate to currying?
Additional:
Kyle's answer is great but to my poor procedural/OO mind Ben Childs answer is really useful.
|
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.
|
OK my verdict :-) : I have used successfully zend without mod_rewrite and it's as you've all said site/index.php/controller/action. I knew that before posting this. I've also found out around the net a technique that "pushes" 404 pages to index.php therefore what is not a resource (eg. CSS, image, etc) gets there, with one exception: POST values.
So I decided that the next time an application has to be made in the specific server, to ask politely for mod_rewrite. If administrator can not provide it, talk with my boss or if it is for me, switch provider.
Generally it is a shame some times that PHP market is so much fragmented (php4, php5, php6, mod_rewrite, mod_auth, mod_whatever), but this is another story...
|
You will want to wire your URL to the Django [create_object generic view][1], and pass it either "model" (the model you want to create) or "form_class" (a customized [ModelForm][2] class). There are a number of [other arguments][1] 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.
[1]: http://docs.djangoproject.com/en/dev/ref/generic-views/#django-views-generic-create-update-create-object
[2]: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#topics-forms-modelforms
|
Yes, with --slave-skip-errors=xxx in my.cnf, where xxx is 'all' or a comma sep list of error codes.
|
Be aware that TFS does not support sharing files between different projects, as VSS does. If you have any such shared files the link between them will be broken during the migration, resulting in initially identical, but now distinct files in each project. Updates to one of these files in TFS will no longer propagate to the copies in the other projects.
|
something like this?
var myList = new List<string> { "a","b","c" };
var items = from item in db.Items
where myList.Contains(item.Name)
select item;
that would create a sql statement like
SELECT * FROM Items [t0] where Name IN ('a','b','c')
|
Good Mercurial repository viewer for Mac
|
|mercurial|
|
Is there a good, native Mac tool to view Mercurial repositories, similar to gitnub for Git?
|
Use [a symbolic link][1]. :)
[1]: http://tinyurl.com/63z9hp
|
I would suggest you start by removing the UpdatePanels at first, and make sure your control orgy is working correctly with postbacks. Once you have that working, try adding the UpdatePanels back in from the bottom up.
|
Supposing you can create a common repository for all your projects (a common folder in your source control tree, for example), you could add the master pages as links by using relative paths.
However, IIRC, Visual Studio makes local copies of files added from external paths. You might have to text-edit the solution/project file to add the linked files.
This, of course, is assuming you use "Web Application" format. Older VS "Web Sites" do not have project files and rely on having all files within the site folder.
|
This site looks promising: http://snipplr.com/view/6889/regular-expressions-for-uri-validationparsing/
They propose following regex:
/^([a-z0-9+.-]+):(?://(?:((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*)@)?((?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*)(?::(\d*))?(/(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?|(/?(?:[a-z0-9-._~!$&'()*+,;=:@]|%[0-9A-F]{2})+(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?)(?:\?((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*))?(?:#((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*))?$/i
|
Performance vs Readability
|
|performance|
|
Reading [this question][1] I found this as (note the quotation marks) "code" to solve the problem (that's perl by the way).
100,{)..3%!'Fizz'*\5%!'Buzz'*+\or}%n*
Obviously this is an intelectual example without real (I hope to never see that in real code in my life) implications but, when you have to make the choice, when do you sacrifice code readability for performance? Do you apply just common sense, do you do it always as a last resort? What are your strategies?
[1]: http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem
|
|performance|fix-typo|
|
The best place to start with getting control of your email is definitely Merlin Mann's excellent [Inbox Zero][1] series. In particular his [Google Tech Talk video][2] is a great talk.
[1]: http://www.43folders.com/izero
[2]: http://video.google.com/videoplay?docid=973149761529535925&hl=en
|
Maybe try a parallelizing utility instead rewriting the loop? I'm a big fan of xjobs. I use xjobs all the time to mass copy files across our network, usually when setting up a new database server.
<http://www.maier-komor.de/xjobs.html>
|
If you don't want to actually clear out your inbox, you could use a good search utility like Google Desktop, Yahoo Desktop Search (is that what it's called) or my current favorite, Xobni.
With these tools you don't have to worry about where you put the mails you saved. Just save them all and let the tools find it.
|
Instead of a plain bash, use a Makefile, then specify number of simultaneous jobs with `make -jX` where X is the number of jobs to run at once.
|
Instead of a plain bash, use a Makefile, then specify number of simultaneous jobs with `make -jX` where X is the number of jobs to run at once.
Or you can use `wait` ("`man wait`"): launch several child processes, call `wait` - it will exit when the child processes finish.
maxjobs = 10
foreach line in `cat file.txt` {
jobsrunning = 0
while jobsrunning < maxjobs {
do job &
jobsrunning += 1
}
wait
}
job ( ){
...
}
If you need to store the job's result, then assign their result to a variable. After `wait` you just check what the variable contains.
|
How do I unit test a WCF service?
|
|wcf|unit-testing|
|
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, but I'm unsure on how to mock stuff in this scenario.
Thanks in advance!
|